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#include "compression.h"
4
5#include <base/dbg.h>
6
7#include <iterator> // std::size
8
9const unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut, int SrcSize)
10{
11 if(SrcSize <= 0)
12 return nullptr;
13
14 const int Sign = (*pSrc >> 6) & 1;
15 *pInOut = *pSrc & 0x3F;
16 SrcSize--;
17
18 static const int s_aMasks[] = {0x7F, 0x7F, 0x7F, 0x0F};
19 static const int s_aShifts[] = {6, 6 + 7, 6 + 7 + 7, 6 + 7 + 7 + 7};
20
21 for(unsigned i = 0; i < std::size(s_aMasks); i++)
22 {
23 if(!(*pSrc & 0x80))
24 break;
25 if(SrcSize <= 0)
26 return nullptr;
27 SrcSize--;
28 pSrc++;
29 *pInOut |= (*pSrc & s_aMasks[i]) << s_aShifts[i];
30 }
31
32 pSrc++;
33 *pInOut ^= -Sign; // if(sign) *i = ~(*i)
34 return pSrc;
35}
36
37long CVariableInt::Decompress(const void *pSrc, int SrcSize, void *pDst, int DstSize)
38{
39 dbg_assert(DstSize % sizeof(int) == 0, "invalid bounds");
40
41 const unsigned char *pCharSrc = (unsigned char *)pSrc;
42 const unsigned char *pCharSrcEnd = pCharSrc + SrcSize;
43 int *pIntDst = (int *)pDst;
44 const int *pIntDstEnd = pIntDst + DstSize / sizeof(int); // NOLINT(bugprone-sizeof-expression)
45 while(pCharSrc < pCharSrcEnd)
46 {
47 if(pIntDst >= pIntDstEnd)
48 return -1;
49 pCharSrc = CVariableInt::Unpack(pSrc: pCharSrc, pInOut: pIntDst, SrcSize: pCharSrcEnd - pCharSrc);
50 if(!pCharSrc)
51 return -1;
52 pIntDst++;
53 }
54 return (long)((unsigned char *)pIntDst - (unsigned char *)pDst);
55}
56
57long CVariableInt::Compress(const void *pSrc, int SrcSize, void *pDst, int DstSize)
58{
59 dbg_assert(SrcSize % sizeof(int) == 0, "invalid bounds");
60
61 const int *pIntSrc = (int *)pSrc;
62 unsigned char *pCharDst = (unsigned char *)pDst;
63 const unsigned char *pCharDstEnd = pCharDst + DstSize;
64 SrcSize /= sizeof(int);
65 while(SrcSize)
66 {
67 pCharDst = CVariableInt::Pack(pDst: pCharDst, i: *pIntSrc, DstSize: pCharDstEnd - pCharDst);
68 if(!pCharDst)
69 return -1;
70 SrcSize--;
71 pIntSrc++;
72 }
73 return (long)(pCharDst - (unsigned char *)pDst);
74}
75