1 /* license:BSD-3-Clause
2 * copyright-holders:Aaron Giles
3 ***************************************************************************
7 Helper classes for reading/writing at the bit level.
9 ***************************************************************************/
12 #include <libchdr/bitstream.h>
14 /***************************************************************************
16 ***************************************************************************
19 int bitstream_overflow(struct bitstream* bitstream) { return ((bitstream->doffset - bitstream->bits / 8) > bitstream->dlength); }
21 /*-------------------------------------------------
22 * create_bitstream - constructor
23 *-------------------------------------------------
26 struct bitstream* create_bitstream(const void *src, uint32_t srclength)
28 struct bitstream* bitstream = (struct bitstream*)malloc(sizeof(struct bitstream));
29 bitstream->buffer = 0;
31 bitstream->read = (const uint8_t*)src;
32 bitstream->doffset = 0;
33 bitstream->dlength = srclength;
37 /*-----------------------------------------------------
38 * bitstream_peek - fetch the requested number of bits
39 * but don't advance the input pointer
40 *-----------------------------------------------------
43 uint32_t bitstream_peek(struct bitstream* bitstream, int numbits)
48 /* fetch data if we need more */
49 if (numbits > bitstream->bits)
51 while (bitstream->bits <= 24)
53 if (bitstream->doffset < bitstream->dlength)
54 bitstream->buffer |= bitstream->read[bitstream->doffset] << (24 - bitstream->bits);
61 return bitstream->buffer >> (32 - numbits);
64 /*-----------------------------------------------------
65 * bitstream_remove - advance the input pointer by the
66 * specified number of bits
67 *-----------------------------------------------------
70 void bitstream_remove(struct bitstream* bitstream, int numbits)
72 bitstream->buffer <<= numbits;
73 bitstream->bits -= numbits;
76 /*-----------------------------------------------------
77 * bitstream_read - fetch the requested number of bits
78 *-----------------------------------------------------
81 uint32_t bitstream_read(struct bitstream* bitstream, int numbits)
83 uint32_t result = bitstream_peek(bitstream, numbits);
84 bitstream_remove(bitstream, numbits);
88 /*-------------------------------------------------
89 * read_offset - return the current read offset
90 *-------------------------------------------------
93 uint32_t bitstream_read_offset(struct bitstream* bitstream)
95 uint32_t result = bitstream->doffset;
96 int bits = bitstream->bits;
105 /*-------------------------------------------------
106 * flush - flush to the nearest byte
107 *-------------------------------------------------
110 uint32_t bitstream_flush(struct bitstream* bitstream)
112 while (bitstream->bits >= 8)
114 bitstream->doffset--;
115 bitstream->bits -= 8;
117 bitstream->bits = bitstream->buffer = 0;
118 return bitstream->doffset;