-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpack.c
122 lines (94 loc) · 3.21 KB
/
pack.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <assert.h>
#include "pack.h"
bool packBits(const uint8_t *str, const size_t len, uint8_t *const out, size_t *const pOutLen, uint8_t bits)
{
size_t packLen = 0;
uint8_t carryBitsCount = 0;
uint8_t carryBits = 0;
const size_t maxOutLen = *pOutLen;
const uint8_t valueMask = ((0x01U << bits) - 1U);
assert(bits > 0 && bits <= 8);
if (bits == 0 || bits > 8)
return false;
assert(((len * bits) / 8) <= maxOutLen);
if (((len * bits) / 8) > maxOutLen)
return false;
for(size_t i = 0; i < len; ++i) {
const uint8_t byte = (str[i] & valueMask);
const uint8_t mask = (0x01U << carryBitsCount) - 1U;
uint8_t remainingBitsCount = 0;
carryBits = (byte << carryBitsCount) | (carryBits & mask);
if (carryBitsCount + bits < 8) {
remainingBitsCount = 0;
carryBitsCount += bits;
} else {
remainingBitsCount = carryBitsCount + bits - 8;
carryBitsCount = 0;
out[packLen++] = carryBits;
if (remainingBitsCount > 0) {
const uint8_t lshBits = (bits - remainingBitsCount);
carryBits = (byte >> lshBits);
carryBitsCount = remainingBitsCount;
}
}
}
if (carryBitsCount > 0) {
out[packLen++] = carryBits;
}
*pOutLen = packLen;
return true;
}
bool unpackBits(const uint8_t *packedStr, size_t len, uint8_t *out, size_t *pOutLen, uint8_t bits)
{
size_t unpackLen = 0;
uint8_t carryBitsCount = 0;
uint8_t carryBits = 0;
uint8_t byte = 0;
const size_t maxOutLen = *pOutLen;
const uint8_t valueMask = ((1U << bits) - 1U);
assert(bits > 0 && bits <= 8);
if (bits == 0 || bits > 8)
return false;
size_t i = 0;
while (i < len) {
uint8_t remainingBitsCount = 0;
if (carryBitsCount < bits) {
const uint8_t mask = 0xFFU >> (8 - carryBitsCount);
byte = packedStr[i++];
carryBits &= mask;
carryBits |= byte << carryBitsCount;
remainingBitsCount = carryBitsCount;
carryBitsCount = 8;
} else {
remainingBitsCount = 0;
}
out[unpackLen++] = (carryBits & valueMask);
carryBits >>= bits;
carryBitsCount -= bits;
if (remainingBitsCount == 0) {
} else if (remainingBitsCount < bits) {
const uint8_t mask = 0xFFU >> (8 - carryBitsCount);
carryBits &= mask;
carryBits |= (byte >> (8 - remainingBitsCount)) << carryBitsCount;
carryBitsCount += remainingBitsCount;
} else {
assert(0);
return false;
}
}
while(carryBitsCount > 0) {
if (unpackLen < maxOutLen)
out[unpackLen++] = carryBits & valueMask;
if (carryBitsCount >= bits) {
carryBitsCount -= bits;
carryBits >>= bits;
}
else
carryBitsCount = 0;
}
*pOutLen = unpackLen;
assert(unpackLen <= maxOutLen);
if (unpackLen > maxOutLen)
return false;
return true;
}