]> git.sesse.net Git - fjl/blobdiff - bitsource.c
Add optional padding data at the end to the bit source (is that the right place?...
[fjl] / bitsource.c
index 6cc627c70b08b462b0d0c9c7e0a4ec3d25cdceed..7a4ea4a0ca3c553e276be095932061313e833441 100644 (file)
@@ -8,12 +8,14 @@
 #define MARKER_CHAR 0xff
 #define STUFF_MARKER 0x00
 
-void init_bit_source(struct bit_source* source, input_func_t* input_func, void* userdata)
+void init_bit_source(struct bit_source* source, input_func_t* input_func,
+                     unsigned padding_bytes, void* userdata)
 {
        memset(source, 0, sizeof(*source));
        source->bytes = (uint8_t*)malloc(BYTERESERVOIR_SIZE);
        source->byte_read_ptr = source->bytes;
        source->input_func = input_func;
+       source->padding_bytes_available = padding_bytes;
        source->userdata = userdata;
 }
 
@@ -43,12 +45,20 @@ void possibly_refill_slow_path(struct bit_source* source, unsigned num_bits)
                        fprintf(stderr, "Input function returned error\n");
                        exit(1);
                }
-               if (bytes_read == 0) {
+               if (bytes_read == 0 && source->padding_bytes_available > 0) {
+                       unsigned padding_to_add = source->padding_bytes_available;
+                       if (padding_to_add > bytes_to_read) {
+                               padding_to_add = bytes_to_read;
+                       }
+                       memset(source->bytes + source->bytes_available, 0, padding_to_add);
+                       source->padding_bytes_available -= padding_to_add;
+                       source->bytes_available += padding_to_add;
+               } else if (bytes_read == 0) {
                        fprintf(stderr, "Premature EOF\n");
                        exit(1);
+               } else {
+                       source->bytes_available += bytes_read;
                }
-               
-               source->bytes_available += bytes_read;
        }
 
        // Fill the bit reservoir one by one byte until we have enough.