1 /* |
|
2 * skulltag::BitWriter class - Enables writing arbitrary bit lengths of data. |
|
3 * |
|
4 * Copyright 2009 Timothy Landers |
|
5 * email: code.vortexcortex@gmail.com |
|
6 * |
|
7 * Permission is hereby granted, free of charge, to any person obtaining a copy |
|
8 * of this software and associated documentation files (the "Software"), to deal |
|
9 * in the Software without restriction, including without limitation the rights |
|
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
|
11 * copies of the Software, and to permit persons to whom the Software is |
|
12 * furnished to do so, subject to the following conditions: |
|
13 * |
|
14 * The above copyright notice and this permission notice shall be included in |
|
15 * all copies or substantial portions of the Software. |
|
16 * |
|
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
|
23 * THE SOFTWARE. |
|
24 */ |
|
25 |
|
26 #include "bitwriter.h" |
|
27 |
|
28 /* The internal buffer of bits is an int which is initiallized to zero. |
|
29 * The Bit Buffer: [00000000000000000000000000000000] - 0 bits stored. |
|
30 * |
|
31 * Bits stored in the bit buffer occupy the most significant bits available. |
|
32 * When bits are stored their order is preserved. |
|
33 * Storing the 5 bits 01011 into the bit buffer would result in: |
|
34 * The Bit Buffer: [01011000000000000000000000000000] - 5 bits stored. |
|
35 * |
|
36 * Additionally storing 0x12f3 (13 bits) would result in: |
|
37 * The Bit Buffer: [01011100101111001100000000000000] - 18 bits stored. |
|
38 * |
|
39 * Data is stored via any of the put(...) functions. |
|
40 * |
|
41 * To retrieve bytes (chars) of data from the bit buffer and empty the bit buffer: flush(); |
|
42 * Flushing the bit buffer takes groups of 8 bits (octets) and stores them in the |
|
43 * output buffer at the current byte position. Calling flush() would cause output |
|
44 * to receive 2 bytes (0x5c, 0xbc) == (01011100, 10111100) and the remaining bits would |
|
45 * be moved to the most significant bit positions. |
|
46 * The Bit Buffer: [11000000000000000000000000000000] - 2 bits stored. |
|
47 * Note: The empty bits of the bit buffer must be zero to avoid additional masking operations. |
|
48 * flush() is called automatically if the bit buffer is too full during a call to put(...) |
|
49 * |
|
50 * When the bit storage operation is complete call finish(...). Finish will flush as many full |
|
51 * bytes of data into the output buffer as possible, the remaining bits will be padded out |
|
52 * to a full octet with zeros (on their less significant side), then written to the output |
|
53 * buffer. finish( bytesStored, padding ) passes by reference the number of bytes stored |
|
54 * and number of padding bits added (0 to 7) to the last stored byte. |
|
55 * |
|
56 * Bits are not added one at a time, they are masked, shifted and bitwise OR'ed into |
|
57 * the buffer in as large a group as possible. This allows the BitWriter to add multiple bits in a single |
|
58 * operation instead of calling a function for each 1 bit added. |
|
59 * |
|
60 * Normal usage: |
|
61 * |
|
62 * char * dataArray = new char[ max_output_size ]; |
|
63 * BitWriter * buffer = new BitWriter( dataArray, max_output_size ); |
|
64 * ... |
|
65 * // various calls to put(...); |
|
66 * ... |
|
67 * int numBytesOutput, paddedBits; |
|
68 * buffer->finish( numBytesOutput, paddedBits ); |
|
69 * ... |
|
70 * // do something with dataArray |
|
71 * ... |
|
72 * delete buffer; |
|
73 * delete dataArray; |
|
74 * |
|
75 * */ |
|
76 |
|
77 /** Prevents naming convention problems via encapsulation. */ |
|
78 namespace skulltag { |
|
79 |
|
80 // Static variable initially set to zero as a signal for init() |
|
81 int BitWriter::intSize = 0; |
|
82 int BitWriter::mask[32]; |
|
83 |
|
84 /** Initializes this BitWriter. */ |
|
85 void BitWriter::init(){ |
|
86 |
|
87 // initialize static variables if not initialized yet. |
|
88 if ( intSize == 0 ){ |
|
89 intSize = sizeof maximumBytes; |
|
90 mask[0] = 0; |
|
91 |
|
92 // fill mask such that m = { 0, 1, 3, 7, 15, etc. } |
|
93 for ( int i = 1; i < 32; i++ ) mask[i] = (mask[i-1] << 1) | 1; |
|
94 } |
|
95 |
|
96 // initialize member variables. |
|
97 bitsAvailable = 0; |
|
98 bytesAvailable = 0; |
|
99 bufferBits = 0; |
|
100 currentByte = 0; |
|
101 maximumBytes = 0; |
|
102 bitsLeft = intSize << 3; |
|
103 } |
|
104 |
|
105 /** Creates a new BitWriter. */ |
|
106 BitWriter::BitWriter(){ |
|
107 init(); |
|
108 } |
|
109 |
|
110 /** Creates a new BitWriter. |
|
111 * @param output Destination that bits will be written to. |
|
112 * @param max Maximum number of chars to output. */ |
|
113 BitWriter::BitWriter( unsigned char * const output, int const &max ){ |
|
114 outputBuffer( output, max ); |
|
115 } |
|
116 |
|
117 /** Sets the output buffer that bytes will be written to. |
|
118 * @param output Destination that bits will be written to. |
|
119 * @param max Maximum number of chars to output. |
|
120 * @return true if successful, false otherwise. */ |
|
121 bool BitWriter::outputBuffer( unsigned char * const output, int const &max ){ |
|
122 init(); // zero the vars. |
|
123 currentByte = output; |
|
124 if ( output == 0 ) return false; |
|
125 if ( max < 1 ) return false; |
|
126 bytesAvailable = max; |
|
127 bitsAvailable = max << 3; |
|
128 maximumBytes = max; |
|
129 return true; |
|
130 } |
|
131 |
|
132 /** Appends a char worth of bits to the buffer. |
|
133 * @param bits the bits to append. |
|
134 * @return true if successful, false otherwise. */ |
|
135 bool BitWriter::put( unsigned char const &bits ){ |
|
136 return put( (int)bits, 8 ); |
|
137 } |
|
138 |
|
139 /** Appends a short worth of bits to the buffer. |
|
140 * @param bits the bits to append. |
|
141 * @return true if successful, false otherwise. */ |
|
142 bool BitWriter::put( short const &bits ){ |
|
143 static int shortBitSize = (sizeof bits) << 3; |
|
144 return put( (int)bits, shortBitSize ); |
|
145 } |
|
146 /** Appends an int worth of bits to the buffer. |
|
147 * @param bits the bits to append. |
|
148 * @return true if successful, false otherwise. */ |
|
149 bool BitWriter::put( int const &bits ){ |
|
150 static int intBitSize = intSize << 3; |
|
151 return put( bits, intBitSize); |
|
152 } |
|
153 |
|
154 /** Appends multiple chars from a buffer to this BitWriter. |
|
155 * @param inputBuffer pointer to char data |
|
156 * @param count number of chars to read |
|
157 * @return true if successful, false otherwise. */ |
|
158 bool BitWriter::put( unsigned char const * const inputBuffer, int count ){ |
|
159 int i = 0; |
|
160 |
|
161 // Read in 4 bytes at a time and send all at once to the bit buffer. |
|
162 while ( (i + 3) < count ){ |
|
163 if ( !put( |
|
164 ((int)inputBuffer[ i ] << 24) | |
|
165 ((int)inputBuffer[i+1] << 16) | |
|
166 ((int)inputBuffer[i+2] << 8) | |
|
167 (int)inputBuffer[i+3], 32 |
|
168 ) ) return false; |
|
169 i+=4; |
|
170 } |
|
171 |
|
172 // If any bytes remain, output them one at a time. |
|
173 while ( i < count ){ |
|
174 if ( !put( (int)inputBuffer[ i ], 8 ) ) return false; |
|
175 i++; |
|
176 } |
|
177 |
|
178 return true; |
|
179 } |
|
180 |
|
181 /** Appends a specified number of bits from an int to the buffer. |
|
182 * @param bits the bits to append. <br> |
|
183 * The bits should be stored in the least significant portion of the int. |
|
184 * @param count the number of bits to append. |
|
185 * @return true if successful, false otherwise. */ |
|
186 bool BitWriter::put( int const &bits, int count ){ |
|
187 if ( count > bitsAvailable ) return false; |
|
188 if ( (bitsLeft < 1) && (!flush()) ) return false; |
|
189 if ( count > bitsLeft ){ |
|
190 // not enough space in buffer, fill buffer with top end of input bits then flush. |
|
191 bufferBits |= mask[bitsLeft] & (bits >> (count - bitsLeft)); |
|
192 count -= bitsLeft; |
|
193 bitsAvailable -= bitsLeft; |
|
194 bitsLeft = 0; |
|
195 |
|
196 // Buffer's full, needs flushing. |
|
197 if (!flush()) return false; |
|
198 } |
|
199 |
|
200 // if there are still bits of input... |
|
201 if ( count > 0 ){ |
|
202 |
|
203 // shift the input bits up to the end of the bit buffer. |
|
204 bufferBits |= (mask[count] & bits) << (bitsLeft - count); |
|
205 bitsAvailable -= count; |
|
206 bitsLeft -= count; |
|
207 } |
|
208 return true; |
|
209 } |
|
210 |
|
211 /** Writes any full chars of data stored in this BitWriter to the output char buffer. |
|
212 * @return true if successful, false if an error occurs. */ |
|
213 bool BitWriter::flush(){ |
|
214 // static var to hold how many bits are in an int. |
|
215 static int intBitSize = intSize << 3; |
|
216 if ( currentByte == 0 ) return false; |
|
217 int numBits = intBitSize - bitsLeft; |
|
218 |
|
219 // while there's at least one octet of data in the buffer. |
|
220 while ( numBits > 7 ){ |
|
221 |
|
222 // fail if no bytes can be written. |
|
223 if ( bytesAvailable <= 0 ) return false; |
|
224 |
|
225 // get a byte off the top end of the buffer. |
|
226 *currentByte = (bufferBits >> (intBitSize - 8)) & mask[8]; |
|
227 |
|
228 // Set variables to reflect the change. |
|
229 currentByte++; |
|
230 bytesAvailable--; |
|
231 bufferBits = bufferBits << 8; |
|
232 bitsLeft += 8; |
|
233 numBits -= 8; |
|
234 } |
|
235 return true; |
|
236 } |
|
237 |
|
238 /** Flushes this BitWriter then outputs any partial chars by padding them with zeros. <br> |
|
239 * After calling finish() all other calls to update the BitWriter will fail until a buffer is set via outputBuffer(). |
|
240 * @param bytesWritten out: the number of bytes written to the output buffer. |
|
241 * @param paddingBits out: the number of padding bits used in the final byte of output. |
|
242 * @return true if successful, false if an error occurs. */ |
|
243 bool BitWriter::finish( int &bytesWritten, int &paddingBits ){ |
|
244 static int intBitSize = intSize << 3; |
|
245 // set meaningful return values even if flush() fails. |
|
246 bytesWritten = maximumBytes - bytesAvailable; |
|
247 paddingBits = 0; |
|
248 if ( flush() ){ |
|
249 // use a temp var to avoid setting paddingBits to invalid value on failure. |
|
250 int pad = (8 - (intBitSize - bitsLeft)) & 7; |
|
251 if ( pad > 0 ){ |
|
252 // all empty bits should be zero. Artificially extend by the number of bits needed. |
|
253 bitsLeft -= pad; |
|
254 if ( !flush() ){ |
|
255 // Prevent futher use even on failure. |
|
256 init(); |
|
257 return false; |
|
258 } |
|
259 // return the temp bit padding value. |
|
260 paddingBits = pad; |
|
261 } |
|
262 bytesWritten = maximumBytes - bytesAvailable; |
|
263 init(); // set initial state -- no further writing can occur. |
|
264 return true; |
|
265 } |
|
266 // Prevents futher use even on failure. |
|
267 init(); |
|
268 return false; |
|
269 } |
|
270 |
|
271 } |
|