1 // license:BSD-3-Clause
2 // copyright-holders:Aaron Giles
3 /***************************************************************************
7 Helper classes for reading/writing at the bit level.
9 ***************************************************************************/
11 #include "bitstream.h"
14 //**************************************************************************
16 //**************************************************************************
18 int bitstream_overflow(struct bitstream* bitstream) { return ((bitstream->doffset - bitstream->bits / 8) > bitstream->dlength); }
20 //-------------------------------------------------
21 // create_bitstream - constructor
22 //-------------------------------------------------
24 struct bitstream* create_bitstream(const void *src, uint32_t srclength)
26 struct bitstream* bitstream = (struct bitstream*)malloc(sizeof(struct bitstream));
27 bitstream->buffer = 0;
29 bitstream->read = (const uint8_t*)src;
30 bitstream->doffset = 0;
31 bitstream->dlength = srclength;
36 //-----------------------------------------------------
37 // bitstream_peek - fetch the requested number of bits
38 // but don't advance the input pointer
39 //-----------------------------------------------------
41 uint32_t bitstream_peek(struct bitstream* bitstream, int numbits)
46 // fetch data if we need more
47 if (numbits > bitstream->bits)
49 while (bitstream->bits <= 24)
51 if (bitstream->doffset < bitstream->dlength)
52 bitstream->buffer |= bitstream->read[bitstream->doffset] << (24 - bitstream->bits);
59 return bitstream->buffer >> (32 - numbits);
63 //-----------------------------------------------------
64 // bitstream_remove - advance the input pointer by the
65 // specified number of bits
66 //-----------------------------------------------------
68 void bitstream_remove(struct bitstream* bitstream, int numbits)
70 bitstream->buffer <<= numbits;
71 bitstream->bits -= numbits;
75 //-----------------------------------------------------
76 // bitstream_read - fetch the requested number of bits
77 //-----------------------------------------------------
79 uint32_t bitstream_read(struct bitstream* bitstream, int numbits)
81 uint32_t result = bitstream_peek(bitstream, numbits);
82 bitstream_remove(bitstream, numbits);
87 //-------------------------------------------------
88 // read_offset - return the current read offset
89 //-------------------------------------------------
91 uint32_t bitstream_read_offset(struct bitstream* bitstream)
93 uint32_t result = bitstream->doffset;
94 int bits = bitstream->bits;
104 //-------------------------------------------------
105 // flush - flush to the nearest byte
106 //-------------------------------------------------
108 uint32_t bitstream_flush(struct bitstream* bitstream)
110 while (bitstream->bits >= 8)
112 bitstream->doffset--;
113 bitstream->bits -= 8;
115 bitstream->bits = bitstream->buffer = 0;
116 return bitstream->doffset;