-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitbuffer.c
More file actions
80 lines (62 loc) · 1.71 KB
/
bitbuffer.c
File metadata and controls
80 lines (62 loc) · 1.71 KB
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
// Bitbuffer implementation
// TSullivan
#ifndef BITBUFFER
#define BITBUFFER
#define BB_WRITE 0
#define BB_READ 1
#define BB_PEEK 2
#define BB_ASCIIBITS 7
typedef struct _BitBuffer {
unsigned char* chunks;
unsigned int r, w;
unsigned char mode;
} BB;
void BBWrite(BB* buff, void* value, int bits) {
unsigned short head, result;
unsigned char* chunks, * v;
int i, u;
u = buff->w & 0x07;
i = buff->w >> 3;
v = (unsigned char*)value;
chunks = buff->chunks + i;
head = *chunks & ((1 << u) - 1);
result = head | ((unsigned short)(*v & ((1 << bits) - 1)) << u);
*chunks++ = (unsigned char)result;
*chunks = (*chunks & ~(((1 << (u + bits)) - 1) >> 8)) | (unsigned char)(result >> 8);
buff->w += bits;
}
void BBPeek(BB* buff, void* value, int bits) {
unsigned short head;
unsigned char* v;
int u;
u = buff->r & 0x07;
v = buff->chunks + (buff->r >> 3);
head = *v | ((unsigned short)*(v + 1) << 8);
*(v = value) = (unsigned char)((head & (((1 << bits) - 1) << u)) >> u);
}
void BBRead(BB* b, void* val, int bits) {
BBPeek(b, val, bits);
b->r += bits;
}
int BBLength(unsigned int rw) {
return ((rw - 1) >> 3) + 1;
}
typedef void(*BBOp)(BB*, void*, int);
BBOp bufferOps[] = {
BBWrite, BBRead, BBPeek
};
void BBProcess(BB* b, void* val, unsigned char bytes) {
unsigned char* v = val;
for (v += bytes - 1; bytes--; bufferOps[b->mode](b, v--, 8));
}
void BBProcessBits(BB* b, void* val, unsigned char bits) {
unsigned char* v = val, n;
v += (bits >> 3) + ((((bits & 7) + 7) & ~7) >> 3) - 1;
if (n = bits & 7) bufferOps[b->mode](b, v--, n);
for (bits -= n; bits; bits -= 8) bufferOps[b->mode](b, v--, 8);
}
void BBProcessStr(BB* b, char* s) {
do bufferOps[b->mode](b, s, BB_ASCIIBITS);
while (*s++);
}
#endif