1 /* ******************************************************************
4 header file (to include)
5 Copyright (C) 2013-2017, Yann Collet.
7 BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
9 Redistribution and use in source and binary forms, with or without
10 modification, are permitted provided that the following conditions are
13 * Redistributions of source code must retain the above copyright
14 notice, this list of conditions and the following disclaimer.
15 * Redistributions in binary form must reproduce the above
16 copyright notice, this list of conditions and the following disclaimer
17 in the documentation and/or other materials provided with the
20 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 You can contact the author at :
33 - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
34 ****************************************************************** */
35 #ifndef BITSTREAM_H_MODULE
36 #define BITSTREAM_H_MODULE
38 #if defined (__cplusplus)
43 * This API consists of small unitary functions, which must be inlined for best performance.
44 * Since link-time-optimization is not available for all compilers,
45 * these functions are defined into a .h to be included.
48 /*-****************************************
50 ******************************************/
51 #include "mem.h" /* unaligned access routines */
52 #include "error_private.h" /* error codes and messages */
55 /*-*************************************
57 ***************************************/
58 #if defined(BIT_DEBUG) && (BIT_DEBUG>=1)
62 # define assert(condition) ((void)0)
67 /*=========================================
69 =========================================*/
70 #if defined(__BMI__) && defined(__GNUC__)
71 # include <immintrin.h> /* support for bextr (experimental) */
74 #define STREAM_ACCUMULATOR_MIN_32 25
75 #define STREAM_ACCUMULATOR_MIN_64 57
76 #define STREAM_ACCUMULATOR_MIN ((U32)(MEM_32bits() ? STREAM_ACCUMULATOR_MIN_32 : STREAM_ACCUMULATOR_MIN_64))
79 /*-******************************************
80 * bitStream encoding API (write forward)
81 ********************************************/
82 /* bitStream can mix input from multiple sources.
83 * A critical property of these streams is that they encode and decode in **reverse** direction.
84 * So the first bit sequence you add will be the last to be read, like a LIFO stack.
95 MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, void* dstBuffer, size_t dstCapacity);
96 MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, size_t value, unsigned nbBits);
97 MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC);
98 MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC);
100 /* Start with initCStream, providing the size of buffer to write into.
101 * bitStream will never write outside of this buffer.
102 * `dstCapacity` must be >= sizeof(bitD->bitContainer), otherwise @return will be an error code.
104 * bits are first added to a local register.
105 * Local register is size_t, hence 64-bits on 64-bits systems, or 32-bits on 32-bits systems.
106 * Writing data into memory is an explicit operation, performed by the flushBits function.
107 * Hence keep track how many bits are potentially stored into local register to avoid register overflow.
108 * After a flushBits, a maximum of 7 bits might still be stored into local register.
110 * Avoid storing elements of more than 24 bits if you want compatibility with 32-bits bitstream readers.
112 * Last operation is to close the bitStream.
113 * The function returns the final size of CStream in bytes.
114 * If data couldn't fit into `dstBuffer`, it will return a 0 ( == not storable)
118 /*-********************************************
119 * bitStream decoding API (read backward)
120 **********************************************/
124 unsigned bitsConsumed;
127 const char* limitPtr;
130 typedef enum { BIT_DStream_unfinished = 0,
131 BIT_DStream_endOfBuffer = 1,
132 BIT_DStream_completed = 2,
133 BIT_DStream_overflow = 3 } BIT_DStream_status; /* result of BIT_reloadDStream() */
134 /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */
136 MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
137 MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits);
138 MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD);
139 MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD);
142 /* Start by invoking BIT_initDStream().
143 * A chunk of the bitStream is then stored into a local register.
144 * Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
145 * You can then retrieve bitFields stored into the local register, **in reverse order**.
146 * Local register is explicitly reloaded from memory by the BIT_reloadDStream() method.
147 * A reload guarantee a minimum of ((8*sizeof(bitD->bitContainer))-7) bits when its result is BIT_DStream_unfinished.
148 * Otherwise, it can be less than that, so proceed accordingly.
149 * Checking if DStream has reached its end can be performed with BIT_endOfDStream().
153 /*-****************************************
155 ******************************************/
156 MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, size_t value, unsigned nbBits);
157 /* faster, but works only if value is "clean", meaning all high bits above nbBits are 0 */
159 MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC);
160 /* unsafe version; does not check buffer overflow */
162 MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits);
163 /* faster, but works only if nbBits >= 1 */
167 /*-**************************************************************
169 ****************************************************************/
170 MEM_STATIC unsigned BIT_highbit32 (register U32 val)
172 # if defined(_MSC_VER) /* Visual */
174 _BitScanReverse ( &r, val );
176 # elif defined(__GNUC__) && (__GNUC__ >= 3) /* Use GCC Intrinsic */
177 return 31 - __builtin_clz (val);
178 # else /* Software version */
179 static const unsigned DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29,
180 11, 14, 16, 18, 22, 25, 3, 30,
181 8, 12, 20, 28, 15, 17, 24, 7,
182 19, 27, 23, 6, 26, 5, 4, 31 };
189 return DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
193 /*===== Local Constants =====*/
194 static const unsigned BIT_mask[] = { 0, 1, 3, 7, 0xF, 0x1F, 0x3F, 0x7F,
195 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF,
196 0xFFFF, 0x1FFFF, 0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF,
197 0xFFFFFF, 0x1FFFFFF, 0x3FFFFFF }; /* up to 26 bits */
200 /*-**************************************************************
202 ****************************************************************/
203 /*! BIT_initCStream() :
204 * `dstCapacity` must be > sizeof(size_t)
205 * @return : 0 if success,
206 otherwise an error code (can be tested using ERR_isError() ) */
207 MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC,
208 void* startPtr, size_t dstCapacity)
210 bitC->bitContainer = 0;
212 bitC->startPtr = (char*)startPtr;
213 bitC->ptr = bitC->startPtr;
214 bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer);
215 if (dstCapacity <= sizeof(bitC->bitContainer)) return ERROR(dstSize_tooSmall);
220 can add up to 26 bits into `bitC`.
221 Does not check for register overflow ! */
222 MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC,
223 size_t value, unsigned nbBits)
225 bitC->bitContainer |= (value & BIT_mask[nbBits]) << bitC->bitPos;
226 bitC->bitPos += nbBits;
229 /*! BIT_addBitsFast() :
230 * works only if `value` is _clean_, meaning all high bits above nbBits are 0 */
231 MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC,
232 size_t value, unsigned nbBits)
234 assert((value>>nbBits) == 0);
235 bitC->bitContainer |= value << bitC->bitPos;
236 bitC->bitPos += nbBits;
239 /*! BIT_flushBitsFast() :
240 * assumption : bitContainer has not overflowed
241 * unsafe version; does not check buffer overflow */
242 MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC)
244 size_t const nbBytes = bitC->bitPos >> 3;
245 assert( bitC->bitPos <= (sizeof(bitC->bitContainer)*8) );
246 MEM_writeLEST(bitC->ptr, bitC->bitContainer);
247 bitC->ptr += nbBytes;
248 assert(bitC->ptr <= bitC->endPtr);
250 bitC->bitContainer >>= nbBytes*8;
253 /*! BIT_flushBits() :
254 * assumption : bitContainer has not overflowed
255 * safe version; check for buffer overflow, and prevents it.
256 * note : does not signal buffer overflow.
257 * overflow will be revealed later on using BIT_closeCStream() */
258 MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC)
260 size_t const nbBytes = bitC->bitPos >> 3;
261 assert( bitC->bitPos <= (sizeof(bitC->bitContainer)*8) );
262 MEM_writeLEST(bitC->ptr, bitC->bitContainer);
263 bitC->ptr += nbBytes;
264 if (bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr;
266 bitC->bitContainer >>= nbBytes*8;
269 /*! BIT_closeCStream() :
270 * @return : size of CStream, in bytes,
271 or 0 if it could not fit into dstBuffer */
272 MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC)
274 BIT_addBitsFast(bitC, 1, 1); /* endMark */
276 if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */
277 return (bitC->ptr - bitC->startPtr) + (bitC->bitPos > 0);
281 /*-********************************************************
283 **********************************************************/
284 /*! BIT_initDStream() :
285 * Initialize a BIT_DStream_t.
286 * `bitD` : a pointer to an already allocated BIT_DStream_t structure.
287 * `srcSize` must be the *exact* size of the bitStream, in bytes.
288 * @return : size of stream (== srcSize) or an errorCode if a problem is detected
290 MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
292 if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }
294 bitD->start = (const char*)srcBuffer;
295 bitD->limitPtr = bitD->start + sizeof(bitD->bitContainer);
297 if (srcSize >= sizeof(bitD->bitContainer)) { /* normal case */
298 bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(bitD->bitContainer);
299 bitD->bitContainer = MEM_readLEST(bitD->ptr);
300 { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
301 bitD->bitsConsumed = lastByte ? 8 - BIT_highbit32(lastByte) : 0; /* ensures bitsConsumed is always set */
302 if (lastByte == 0) return ERROR(GENERIC); /* endMark not present */ }
304 bitD->ptr = bitD->start;
305 bitD->bitContainer = *(const BYTE*)(bitD->start);
308 case 7: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16);
311 case 6: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24);
314 case 5: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32);
317 case 4: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[3]) << 24;
320 case 3: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[2]) << 16;
323 case 2: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[1]) << 8;
328 { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
329 bitD->bitsConsumed = lastByte ? 8 - BIT_highbit32(lastByte) : 0;
330 if (lastByte == 0) return ERROR(GENERIC); /* endMark not present */ }
331 bitD->bitsConsumed += (U32)(sizeof(bitD->bitContainer) - srcSize)*8;
337 MEM_STATIC size_t BIT_getUpperBits(size_t bitContainer, U32 const start)
339 return bitContainer >> start;
342 MEM_STATIC size_t BIT_getMiddleBits(size_t bitContainer, U32 const start, U32 const nbBits)
344 #if defined(__BMI__) && defined(__GNUC__) && __GNUC__*1000+__GNUC_MINOR__ >= 4008 /* experimental */
345 # if defined(__x86_64__)
346 if (sizeof(bitContainer)==8)
347 return _bextr_u64(bitContainer, start, nbBits);
350 return _bextr_u32(bitContainer, start, nbBits);
352 return (bitContainer >> start) & BIT_mask[nbBits];
356 MEM_STATIC size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits)
358 return bitContainer & BIT_mask[nbBits];
362 * Provides next n bits from local register.
363 * local register is not modified.
364 * On 32-bits, maxNbBits==24.
365 * On 64-bits, maxNbBits==56.
366 * @return : value extracted
368 MEM_STATIC size_t BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits)
370 #if defined(__BMI__) && defined(__GNUC__) /* experimental; fails if bitD->bitsConsumed + nbBits > sizeof(bitD->bitContainer)*8 */
371 return BIT_getMiddleBits(bitD->bitContainer, (sizeof(bitD->bitContainer)*8) - bitD->bitsConsumed - nbBits, nbBits);
373 U32 const regMask = sizeof(bitD->bitContainer)*8 - 1;
374 return ((bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> 1) >> ((regMask-nbBits) & regMask);
378 /*! BIT_lookBitsFast() :
379 * unsafe version; only works if nbBits >= 1 */
380 MEM_STATIC size_t BIT_lookBitsFast(const BIT_DStream_t* bitD, U32 nbBits)
382 U32 const regMask = sizeof(bitD->bitContainer)*8 - 1;
384 return (bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> (((regMask+1)-nbBits) & regMask);
387 MEM_STATIC void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits)
389 bitD->bitsConsumed += nbBits;
393 * Read (consume) next n bits from local register and update.
394 * Pay attention to not read more than nbBits contained into local register.
395 * @return : extracted value.
397 MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, U32 nbBits)
399 size_t const value = BIT_lookBits(bitD, nbBits);
400 BIT_skipBits(bitD, nbBits);
404 /*! BIT_readBitsFast() :
405 * unsafe version; only works only if nbBits >= 1 */
406 MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, U32 nbBits)
408 size_t const value = BIT_lookBitsFast(bitD, nbBits);
410 BIT_skipBits(bitD, nbBits);
414 /*! BIT_reloadDStream() :
415 * Refill `bitD` from buffer previously set in BIT_initDStream() .
416 * This function is safe, it guarantees it will not read beyond src buffer.
417 * @return : status of `BIT_DStream_t` internal register.
418 if status == BIT_DStream_unfinished, internal register is filled with >= (sizeof(bitD->bitContainer)*8 - 7) bits */
419 MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD)
421 if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* overflow detected, like end of stream */
422 return BIT_DStream_overflow;
424 if (bitD->ptr >= bitD->limitPtr) {
425 bitD->ptr -= bitD->bitsConsumed >> 3;
426 bitD->bitsConsumed &= 7;
427 bitD->bitContainer = MEM_readLEST(bitD->ptr);
428 return BIT_DStream_unfinished;
430 if (bitD->ptr == bitD->start) {
431 if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer;
432 return BIT_DStream_completed;
434 /* start < ptr < limitPtr */
435 { U32 nbBytes = bitD->bitsConsumed >> 3;
436 BIT_DStream_status result = BIT_DStream_unfinished;
437 if (bitD->ptr - nbBytes < bitD->start) {
438 nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
439 result = BIT_DStream_endOfBuffer;
441 bitD->ptr -= nbBytes;
442 bitD->bitsConsumed -= nbBytes*8;
443 bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD->bitContainer), otherwise bitD->ptr == bitD->start */
448 /*! BIT_endOfDStream() :
449 * @return Tells if DStream has exactly reached its end (all bits consumed).
451 MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream)
453 return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
456 #if defined (__cplusplus)
460 #endif /* BITSTREAM_H_MODULE */