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;
38 /*-----------------------------------------------------
39 * bitstream_peek - fetch the requested number of bits
40 * but don't advance the input pointer
41 *-----------------------------------------------------
44 uint32_t bitstream_peek(struct bitstream* bitstream, int numbits)
49 /* fetch data if we need more */
50 if (numbits > bitstream->bits)
52 while (bitstream->bits <= 24)
54 if (bitstream->doffset < bitstream->dlength)
55 bitstream->buffer |= bitstream->read[bitstream->doffset] << (24 - bitstream->bits);
62 return bitstream->buffer >> (32 - numbits);
66 /*-----------------------------------------------------
67 * bitstream_remove - advance the input pointer by the
68 * specified number of bits
69 *-----------------------------------------------------
72 void bitstream_remove(struct bitstream* bitstream, int numbits)
74 bitstream->buffer <<= numbits;
75 bitstream->bits -= numbits;
79 /*-----------------------------------------------------
80 * bitstream_read - fetch the requested number of bits
81 *-----------------------------------------------------
84 uint32_t bitstream_read(struct bitstream* bitstream, int numbits)
86 uint32_t result = bitstream_peek(bitstream, numbits);
87 bitstream_remove(bitstream, numbits);
92 /*-------------------------------------------------
93 * read_offset - return the current read offset
94 *-------------------------------------------------
97 uint32_t bitstream_read_offset(struct bitstream* bitstream)
99 uint32_t result = bitstream->doffset;
100 int bits = bitstream->bits;
110 /*-------------------------------------------------
111 * flush - flush to the nearest byte
112 *-------------------------------------------------
115 uint32_t bitstream_flush(struct bitstream* bitstream)
117 while (bitstream->bits >= 8)
119 bitstream->doffset--;
120 bitstream->bits -= 8;
122 bitstream->bits = bitstream->buffer = 0;
123 return bitstream->doffset;