| 1 |
/* |
| 2 |
* This is a mimic of the Bitstream class in SPERR: |
| 3 |
* https://github.com/NCAR/SPERR/blob/main/include/Bitstream.h |
| 4 |
* |
| 5 |
* The most significant difference is that bitstream here doesn't manage |
| 6 |
* any memory; it reads a bit sequence from a user-provided memory buffer, |
| 7 |
* or writes a bit sequence to a user-provided memory buffer. |
| 8 |
* |
| 9 |
* The "object" is named `icecream` and all functions operating on it |
| 10 |
* are named with a prefix `icecream`. |
| 11 |
*/ |
| 12 |
|
| 13 |
#ifndef ICECREAM_H |
| 14 |
#define ICECREAM_H |
| 15 |
|
| 16 |
#include <stdlib.h> |
| 17 |
#include <stdint.h> |
| 18 |
#include <assert.h> |
| 19 |
|
| 20 |
#ifndef NDEBUG |
| 21 |
#include <stdio.h> |
| 22 |
#endif |
| 23 |
|
| 24 |
#ifdef __cplusplus |
| 25 |
extern "C" { |
| 26 |
#endif |
| 27 |
|
| 28 |
typedef struct { |
| 29 |
uint64_t* begin; /* begin of the stream */ |
| 30 |
uint64_t* ptr; /* pointer to the next word to be read/written */ |
| 31 |
uint64_t buffer; /* incoming/outgoing bits */ |
| 32 |
int bits; /* number of buffered bits (0 <= bits < 64) */ |
| 33 |
} icecream; |
| 34 |
|
| 35 |
/* |
| 36 |
* Specify a bitstream to use memory provided by users. |
| 37 |
* NOTE: the memory length (in bytes) have to be a multiplier of 8, |
| 38 |
* because the icecream class writes/reads in 64-bit integers. |
| 39 |
*/ |
| 40 |
void icecream_use_mem(icecream* s, void* mem, size_t bytes); |
| 41 |
|
| 42 |
/* Position the bitstream for reading or writing at the beginning. */ |
| 43 |
void icecream_rewind(icecream* s); |
| 44 |
|
| 45 |
/* Read a bit. Please don't read beyond the end of the stream. */ |
| 46 |
int icecream_rbit(icecream* s); |
| 47 |
|
| 48 |
/* Write a bit (0 or 1). Please don't write beyond the end of the stream. */ |
| 49 |
void icecream_wbit(icecream* s, int bit); |
| 50 |
|
| 51 |
/* Return the bit offset to the next bit to be read. */ |
| 52 |
size_t icecream_rtell(icecream* s); |
| 53 |
|
| 54 |
/* Return the bit offset to the next bit to be written. */ |
| 55 |
size_t icecream_wtell(icecream* s); |
| 56 |
|
| 57 |
/* Write any remaining buffered bits and align stream on next word boundary. */ |
| 58 |
void icecream_flush(icecream* s); |
| 59 |
|
| 60 |
#ifdef __cplusplus |
| 61 |
} |
| 62 |
#endif |
| 63 |
|
| 64 |
#endif |