-
Notifications
You must be signed in to change notification settings - Fork 2
/
bio.c
112 lines (83 loc) · 1.66 KB
/
bio.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
#include "bio.h"
#include <assert.h>
void bio_open(struct bio *bio, void *ptr, void *end, int mode)
{
assert(bio != NULL);
bio->ptr = ptr;
bio->end = (char *)end - 3;
if (mode == BIO_MODE_READ) {
bio->c = 32;
} else {
bio->b = 0;
bio->c = 0;
}
}
static void bio_flush_buffer(struct bio *bio)
{
assert(bio != NULL);
assert(bio->ptr != NULL);
*(bio->ptr++) = bio->b;
bio->b = 0;
bio->c = 0;
}
static void bio_reload_buffer(struct bio *bio)
{
assert(bio != NULL);
assert(bio->ptr != NULL);
if ((void *)bio->ptr < bio->end) {
bio->b = *(bio->ptr++);
} else {
bio->b = 0x80000000;
}
bio->c = 0;
}
static size_t minsize(size_t a, size_t b)
{
return a < b ? a : b;
}
void bio_write_bits(struct bio *bio, uint32_t b, size_t n)
{
assert(n <= 32);
for (int i = 0; i < 2; ++i) {
assert(bio->c < 32);
size_t m = minsize(32 - bio->c, n);
bio->b |= (b & (((uint32_t)1 << m) - 1)) << bio->c;
bio->c += m;
if (bio->c == 32) {
bio_flush_buffer(bio);
}
b >>= m;
n -= m;
if (n == 0) {
return;
}
}
}
uint32_t bio_read_bits(struct bio *bio, size_t n)
{
if (bio->c == 32) {
bio_reload_buffer(bio);
}
/* get the avail. least-significant bits */
size_t s = minsize(32 - bio->c, n);
uint32_t w = bio->b & (((uint32_t)1 << s) - 1);
bio->b >>= s;
bio->c += s;
n -= s;
/* need more bits? reload & get the most-significant bits */
if (n > 0) {
assert(bio->c == 32);
bio_reload_buffer(bio);
w |= (bio->b & (((uint32_t)1 << n) - 1)) << s;
bio->b >>= n;
bio->c += n;
}
return w;
}
void bio_close(struct bio *bio, int mode)
{
assert(bio != NULL);
if (mode == BIO_MODE_WRITE && bio->c > 0) {
bio_flush_buffer(bio);
}
}