8 #define MARKER_CHAR 0xff
9 #define STUFF_MARKER 0x00
11 void init_bit_source(struct bit_source* source, input_func_t* input_func, void* userdata)
13 memset(source, 0, sizeof(*source));
14 source->bytes = (uint8_t*)malloc(BYTERESERVOIR_SIZE);
15 source->byte_read_ptr = source->bytes;
16 source->input_func = input_func;
17 source->userdata = userdata;
20 void possibly_refill_slow_path(struct bit_source* source, unsigned num_bits)
22 // First, move out the data we already read.
23 assert(source->bytes_available <= BYTERESERVOIR_SIZE);
24 assert(source->byte_read_ptr >= source->bytes);
25 memmove(source->bytes, source->byte_read_ptr, source->bytes_available);
26 source->byte_read_ptr = source->bytes;
28 // Then, make sure there's stuff in the byte reservoir if we can.
29 // Read data from the source until we have enough to satisfy the request.
30 while (source->bits_available + 8 * source->bytes_available < num_bits) {
31 const size_t bytes_to_read = BYTERESERVOIR_SIZE - source->bytes_available;
32 const ssize_t bytes_read =
33 (*source->input_func)(source->userdata,
34 source->bytes + source->bytes_available,
36 assert(bytes_read <= (ssize_t)bytes_to_read);
37 assert(bytes_read >= (ssize_t)-1);
39 // TODO: We need better error handling here. setjmp()/longjmp()
40 // should hopefully do the trick, but we need to take care for
42 if (bytes_read == (ssize_t)-1) {
43 fprintf(stderr, "Input function returned error\n");
46 if (bytes_read == 0) {
47 fprintf(stderr, "Premature EOF\n");
51 source->bytes_available += bytes_read;
54 // Fill the bit reservoir one by one byte until we have enough.
55 while (source->bits_available < num_bits) {
56 assert(source->bytes_available > 0);
57 assert(source->bits_available + 8 <= BITRESERVOIR_SIZE);
58 uint8_t byte = *(source->byte_read_ptr);
59 ++source->byte_read_ptr;
60 --source->bytes_available;
61 source->bits |= ((bitreservoir_t)byte << (BITRESERVOIR_SIZE - source->bits_available - 8));
62 source->bits_available += 8;