9 struct custom_read_userdata {
14 ssize_t custom_read(void* userdata, uint8_t* buf, size_t count)
16 struct custom_read_userdata* ud = (struct custom_read_userdata*)userdata;
17 size_t num_to_read = (ud->bytes_left > count ? count : ud->bytes_left);
18 memcpy(buf, ud->bytes, num_to_read);
19 ud->bytes += num_to_read;
20 ud->bytes_left -= num_to_read;
24 ssize_t custom_read_slow(void* userdata, uint8_t* buf, size_t count)
26 struct custom_read_userdata* ud = (struct custom_read_userdata*)userdata;
27 size_t num_to_read = ((count > 0 && ud->bytes_left > 0) ? 1 : 0);
28 memcpy(buf, ud->bytes, num_to_read);
29 ud->bytes += num_to_read;
30 ud->bytes_left -= num_to_read;
34 // Read 6 bits at a time. We should get 0b101010 every time.
35 void test_basic_reading()
37 uint8_t bytes[] = { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa };
38 struct custom_read_userdata ud;
40 ud.bytes_left = sizeof(bytes);
42 struct bit_source source;
43 init_bit_source(&source, custom_read, &ud);
45 for (unsigned i = 0; i < sizeof(bytes) * 8 / 6; ++i) {
46 possibly_refill(&source, 6);
47 unsigned ret = read_bits(&source, 6);
51 assert(ud.bytes_left == 0);
54 // Same, but with an input source that gives back only one byte at a time.
55 void test_slow_source()
57 uint8_t bytes[] = { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa };
58 struct custom_read_userdata ud;
60 ud.bytes_left = sizeof(bytes);
62 struct bit_source source;
63 init_bit_source(&source, custom_read_slow, &ud);
65 for (unsigned i = 0; i < sizeof(bytes) * 8 / 6; ++i) {
66 possibly_refill(&source, 6);
67 unsigned ret = read_bits(&source, 6);
71 assert(ud.bytes_left == 0);
74 // Read a few different bit sizes.
75 void test_variable_size()
77 uint8_t bytes[] = { 0x12, 0x34, 0x56, 0x78, 0xff };
78 struct custom_read_userdata ud;
80 ud.bytes_left = sizeof(bytes);
82 struct bit_source source;
83 init_bit_source(&source, custom_read, &ud);
86 possibly_refill(&source, 4);
87 unsigned ret = read_bits(&source, 1);
89 ret = read_bits(&source, 1);
91 ret = read_bits(&source, 1);
93 ret = read_bits(&source, 1);
97 possibly_refill(&source, 4);
98 unsigned ret = read_bits(&source, 4);
102 possibly_refill(&source, 12);
103 unsigned ret = read_bits(&source, 12);
104 assert(ret == 0x345);
107 possibly_refill(&source, 20);
108 unsigned ret = read_bits(&source, 16);
109 assert(ret == 0x678f);
110 ret = read_bits(&source, 4);
114 assert(ud.bytes_left == 0);
119 printf("test_basic_reading()\n");
120 test_basic_reading();
122 printf("test_slow_source()\n");
125 printf("test_variable_size()\n");
126 test_variable_size();
128 printf("All tests pass.\n");