| 1 | /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ |
| 2 | /* If you are missing that file, acquire a complete release at teeworlds.com. */ |
| 3 | #ifndef ENGINE_SHARED_COMPRESSION_H |
| 4 | #define ENGINE_SHARED_COMPRESSION_H |
| 5 | |
| 6 | // variable int packing |
| 7 | class CVariableInt |
| 8 | { |
| 9 | public: |
| 10 | enum |
| 11 | { |
| 12 | MAX_BYTES_PACKED = 5, // maximum number of bytes in a packed int |
| 13 | }; |
| 14 | |
| 15 | // Format: ESDDDDDD EDDDDDDD EDD... Extended, Data, Sign |
| 16 | // Defined here so that callers packing many ints in a row do not pay a call per int. |
| 17 | static unsigned char *Pack(unsigned char *pDst, int i, int DstSize) |
| 18 | { |
| 19 | if(DstSize <= 0) |
| 20 | return nullptr; |
| 21 | |
| 22 | DstSize--; |
| 23 | *pDst = 0; |
| 24 | if(i < 0) |
| 25 | { |
| 26 | *pDst |= 0x40; // set sign bit |
| 27 | i = ~i; |
| 28 | } |
| 29 | |
| 30 | *pDst |= i & 0x3F; // pack 6bit into dst |
| 31 | i >>= 6; // discard 6 bits |
| 32 | while(i) |
| 33 | { |
| 34 | if(DstSize <= 0) |
| 35 | return nullptr; |
| 36 | *pDst |= 0x80; // set extend bit |
| 37 | DstSize--; |
| 38 | pDst++; |
| 39 | *pDst = i & 0x7F; // pack 7bit |
| 40 | i >>= 7; // discard 7 bits |
| 41 | } |
| 42 | |
| 43 | pDst++; |
| 44 | return pDst; |
| 45 | } |
| 46 | |
| 47 | static const unsigned char *Unpack(const unsigned char *pSrc, int *pInOut, int SrcSize); |
| 48 | |
| 49 | static long Compress(const void *pSrc, int SrcSize, void *pDst, int DstSize); |
| 50 | static long Decompress(const void *pSrc, int SrcSize, void *pDst, int DstSize); |
| 51 | }; |
| 52 | |
| 53 | #endif |
| 54 | |