bitstream.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /* ******************************************************************
  2. * bitstream
  3. * Part of FSE library
  4. * Copyright (c) Meta Platforms, Inc. and affiliates.
  5. *
  6. * You can contact the author at :
  7. * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  8. *
  9. * This source code is licensed under both the BSD-style license (found in the
  10. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  11. * in the COPYING file in the root directory of this source tree).
  12. * You may select, at your option, one of the above-listed licenses.
  13. ****************************************************************** */
  14. #ifndef BITSTREAM_H_MODULE
  15. #define BITSTREAM_H_MODULE
  16. /*
  17. * This API consists of small unitary functions, which must be inlined for best performance.
  18. * Since link-time-optimization is not available for all compilers,
  19. * these functions are defined into a .h to be included.
  20. */
  21. /*-****************************************
  22. * Dependencies
  23. ******************************************/
  24. #include "mem.h" /* unaligned access routines */
  25. #include "compiler.h" /* UNLIKELY() */
  26. #include "debug.h" /* assert(), DEBUGLOG(), RAWLOG() */
  27. #include "error_private.h" /* error codes and messages */
  28. #include "bits.h" /* ZSTD_highbit32 */
  29. /*=========================================
  30. * Target specific
  31. =========================================*/
  32. #ifndef ZSTD_NO_INTRINSICS
  33. # if (defined(__BMI__) || defined(__BMI2__)) && defined(__GNUC__)
  34. # include <immintrin.h> /* support for bextr (experimental)/bzhi */
  35. # elif defined(__ICCARM__)
  36. # include <intrinsics.h>
  37. # endif
  38. #endif
  39. #define STREAM_ACCUMULATOR_MIN_32 25
  40. #define STREAM_ACCUMULATOR_MIN_64 57
  41. #define STREAM_ACCUMULATOR_MIN ((U32)(MEM_32bits() ? STREAM_ACCUMULATOR_MIN_32 : STREAM_ACCUMULATOR_MIN_64))
  42. /*-******************************************
  43. * bitStream encoding API (write forward)
  44. ********************************************/
  45. typedef size_t BitContainerType;
  46. /* bitStream can mix input from multiple sources.
  47. * A critical property of these streams is that they encode and decode in **reverse** direction.
  48. * So the first bit sequence you add will be the last to be read, like a LIFO stack.
  49. */
  50. typedef struct {
  51. BitContainerType bitContainer;
  52. unsigned bitPos;
  53. char* startPtr;
  54. char* ptr;
  55. char* endPtr;
  56. } BIT_CStream_t;
  57. MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, void* dstBuffer, size_t dstCapacity);
  58. MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, BitContainerType value, unsigned nbBits);
  59. MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC);
  60. MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC);
  61. /* Start with initCStream, providing the size of buffer to write into.
  62. * bitStream will never write outside of this buffer.
  63. * `dstCapacity` must be >= sizeof(bitD->bitContainer), otherwise @return will be an error code.
  64. *
  65. * bits are first added to a local register.
  66. * Local register is BitContainerType, 64-bits on 64-bits systems, or 32-bits on 32-bits systems.
  67. * Writing data into memory is an explicit operation, performed by the flushBits function.
  68. * Hence keep track how many bits are potentially stored into local register to avoid register overflow.
  69. * After a flushBits, a maximum of 7 bits might still be stored into local register.
  70. *
  71. * Avoid storing elements of more than 24 bits if you want compatibility with 32-bits bitstream readers.
  72. *
  73. * Last operation is to close the bitStream.
  74. * The function returns the final size of CStream in bytes.
  75. * If data couldn't fit into `dstBuffer`, it will return a 0 ( == not storable)
  76. */
  77. /*-********************************************
  78. * bitStream decoding API (read backward)
  79. **********************************************/
  80. typedef struct {
  81. BitContainerType bitContainer;
  82. unsigned bitsConsumed;
  83. const char* ptr;
  84. const char* start;
  85. const char* limitPtr;
  86. } BIT_DStream_t;
  87. typedef enum { BIT_DStream_unfinished = 0, /* fully refilled */
  88. BIT_DStream_endOfBuffer = 1, /* still some bits left in bitstream */
  89. BIT_DStream_completed = 2, /* bitstream entirely consumed, bit-exact */
  90. BIT_DStream_overflow = 3 /* user requested more bits than present in bitstream */
  91. } BIT_DStream_status; /* result of BIT_reloadDStream() */
  92. MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
  93. MEM_STATIC BitContainerType BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits);
  94. MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD);
  95. MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD);
  96. /* Start by invoking BIT_initDStream().
  97. * A chunk of the bitStream is then stored into a local register.
  98. * Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (BitContainerType).
  99. * You can then retrieve bitFields stored into the local register, **in reverse order**.
  100. * Local register is explicitly reloaded from memory by the BIT_reloadDStream() method.
  101. * A reload guarantee a minimum of ((8*sizeof(bitD->bitContainer))-7) bits when its result is BIT_DStream_unfinished.
  102. * Otherwise, it can be less than that, so proceed accordingly.
  103. * Checking if DStream has reached its end can be performed with BIT_endOfDStream().
  104. */
  105. /*-****************************************
  106. * unsafe API
  107. ******************************************/
  108. MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, BitContainerType value, unsigned nbBits);
  109. /* faster, but works only if value is "clean", meaning all high bits above nbBits are 0 */
  110. MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC);
  111. /* unsafe version; does not check buffer overflow */
  112. MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits);
  113. /* faster, but works only if nbBits >= 1 */
  114. /*===== Local Constants =====*/
  115. static const unsigned BIT_mask[] = {
  116. 0, 1, 3, 7, 0xF, 0x1F,
  117. 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF,
  118. 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0x1FFFF,
  119. 0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF,
  120. 0xFFFFFF, 0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF, 0x1FFFFFFF,
  121. 0x3FFFFFFF, 0x7FFFFFFF}; /* up to 31 bits */
  122. #define BIT_MASK_SIZE (sizeof(BIT_mask) / sizeof(BIT_mask[0]))
  123. /*-**************************************************************
  124. * bitStream encoding
  125. ****************************************************************/
  126. /*! BIT_initCStream() :
  127. * `dstCapacity` must be > sizeof(size_t)
  128. * @return : 0 if success,
  129. * otherwise an error code (can be tested using ERR_isError()) */
  130. MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC,
  131. void* startPtr, size_t dstCapacity)
  132. {
  133. bitC->bitContainer = 0;
  134. bitC->bitPos = 0;
  135. bitC->startPtr = (char*)startPtr;
  136. bitC->ptr = bitC->startPtr;
  137. bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer);
  138. if (dstCapacity <= sizeof(bitC->bitContainer)) return ERROR(dstSize_tooSmall);
  139. return 0;
  140. }
  141. FORCE_INLINE_TEMPLATE BitContainerType BIT_getLowerBits(BitContainerType bitContainer, U32 const nbBits)
  142. {
  143. #if STATIC_BMI2 && !defined(ZSTD_NO_INTRINSICS)
  144. # if (defined(__x86_64__) || defined(_M_X64)) && !defined(__ILP32__)
  145. return _bzhi_u64(bitContainer, nbBits);
  146. # else
  147. DEBUG_STATIC_ASSERT(sizeof(bitContainer) == sizeof(U32));
  148. return _bzhi_u32(bitContainer, nbBits);
  149. # endif
  150. #else
  151. assert(nbBits < BIT_MASK_SIZE);
  152. return bitContainer & BIT_mask[nbBits];
  153. #endif
  154. }
  155. /*! BIT_addBits() :
  156. * can add up to 31 bits into `bitC`.
  157. * Note : does not check for register overflow ! */
  158. MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC,
  159. BitContainerType value, unsigned nbBits)
  160. {
  161. DEBUG_STATIC_ASSERT(BIT_MASK_SIZE == 32);
  162. assert(nbBits < BIT_MASK_SIZE);
  163. assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8);
  164. bitC->bitContainer |= BIT_getLowerBits(value, nbBits) << bitC->bitPos;
  165. bitC->bitPos += nbBits;
  166. }
  167. /*! BIT_addBitsFast() :
  168. * works only if `value` is _clean_,
  169. * meaning all high bits above nbBits are 0 */
  170. MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC,
  171. BitContainerType value, unsigned nbBits)
  172. {
  173. assert((value>>nbBits) == 0);
  174. assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8);
  175. bitC->bitContainer |= value << bitC->bitPos;
  176. bitC->bitPos += nbBits;
  177. }
  178. /*! BIT_flushBitsFast() :
  179. * assumption : bitContainer has not overflowed
  180. * unsafe version; does not check buffer overflow */
  181. MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC)
  182. {
  183. size_t const nbBytes = bitC->bitPos >> 3;
  184. assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8);
  185. assert(bitC->ptr <= bitC->endPtr);
  186. MEM_writeLEST(bitC->ptr, bitC->bitContainer);
  187. bitC->ptr += nbBytes;
  188. bitC->bitPos &= 7;
  189. bitC->bitContainer >>= nbBytes*8;
  190. }
  191. /*! BIT_flushBits() :
  192. * assumption : bitContainer has not overflowed
  193. * safe version; check for buffer overflow, and prevents it.
  194. * note : does not signal buffer overflow.
  195. * overflow will be revealed later on using BIT_closeCStream() */
  196. MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC)
  197. {
  198. size_t const nbBytes = bitC->bitPos >> 3;
  199. assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8);
  200. assert(bitC->ptr <= bitC->endPtr);
  201. MEM_writeLEST(bitC->ptr, bitC->bitContainer);
  202. bitC->ptr += nbBytes;
  203. if (bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr;
  204. bitC->bitPos &= 7;
  205. bitC->bitContainer >>= nbBytes*8;
  206. }
  207. /*! BIT_closeCStream() :
  208. * @return : size of CStream, in bytes,
  209. * or 0 if it could not fit into dstBuffer */
  210. MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC)
  211. {
  212. BIT_addBitsFast(bitC, 1, 1); /* endMark */
  213. BIT_flushBits(bitC);
  214. if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */
  215. return (size_t)(bitC->ptr - bitC->startPtr) + (bitC->bitPos > 0);
  216. }
  217. /*-********************************************************
  218. * bitStream decoding
  219. **********************************************************/
  220. /*! BIT_initDStream() :
  221. * Initialize a BIT_DStream_t.
  222. * `bitD` : a pointer to an already allocated BIT_DStream_t structure.
  223. * `srcSize` must be the *exact* size of the bitStream, in bytes.
  224. * @return : size of stream (== srcSize), or an errorCode if a problem is detected
  225. */
  226. MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
  227. {
  228. if (srcSize < 1) { ZSTD_memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }
  229. bitD->start = (const char*)srcBuffer;
  230. bitD->limitPtr = bitD->start + sizeof(bitD->bitContainer);
  231. if (srcSize >= sizeof(bitD->bitContainer)) { /* normal case */
  232. bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(bitD->bitContainer);
  233. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  234. { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
  235. bitD->bitsConsumed = lastByte ? 8 - ZSTD_highbit32(lastByte) : 0; /* ensures bitsConsumed is always set */
  236. if (lastByte == 0) return ERROR(GENERIC); /* endMark not present */ }
  237. } else {
  238. bitD->ptr = bitD->start;
  239. bitD->bitContainer = *(const BYTE*)(bitD->start);
  240. switch(srcSize)
  241. {
  242. case 7: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16);
  243. ZSTD_FALLTHROUGH;
  244. case 6: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24);
  245. ZSTD_FALLTHROUGH;
  246. case 5: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32);
  247. ZSTD_FALLTHROUGH;
  248. case 4: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[3]) << 24;
  249. ZSTD_FALLTHROUGH;
  250. case 3: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[2]) << 16;
  251. ZSTD_FALLTHROUGH;
  252. case 2: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[1]) << 8;
  253. ZSTD_FALLTHROUGH;
  254. default: break;
  255. }
  256. { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
  257. bitD->bitsConsumed = lastByte ? 8 - ZSTD_highbit32(lastByte) : 0;
  258. if (lastByte == 0) return ERROR(corruption_detected); /* endMark not present */
  259. }
  260. bitD->bitsConsumed += (U32)(sizeof(bitD->bitContainer) - srcSize)*8;
  261. }
  262. return srcSize;
  263. }
  264. FORCE_INLINE_TEMPLATE BitContainerType BIT_getUpperBits(BitContainerType bitContainer, U32 const start)
  265. {
  266. return bitContainer >> start;
  267. }
  268. FORCE_INLINE_TEMPLATE BitContainerType BIT_getMiddleBits(BitContainerType bitContainer, U32 const start, U32 const nbBits)
  269. {
  270. U32 const regMask = sizeof(bitContainer)*8 - 1;
  271. /* if start > regMask, bitstream is corrupted, and result is undefined */
  272. assert(nbBits < BIT_MASK_SIZE);
  273. /* x86 transform & ((1 << nbBits) - 1) to bzhi instruction, it is better
  274. * than accessing memory. When bmi2 instruction is not present, we consider
  275. * such cpus old (pre-Haswell, 2013) and their performance is not of that
  276. * importance.
  277. */
  278. #if defined(__x86_64__) || defined(_M_X64)
  279. return (bitContainer >> (start & regMask)) & ((((U64)1) << nbBits) - 1);
  280. #else
  281. return (bitContainer >> (start & regMask)) & BIT_mask[nbBits];
  282. #endif
  283. }
  284. /*! BIT_lookBits() :
  285. * Provides next n bits from local register.
  286. * local register is not modified.
  287. * On 32-bits, maxNbBits==24.
  288. * On 64-bits, maxNbBits==56.
  289. * @return : value extracted */
  290. FORCE_INLINE_TEMPLATE BitContainerType BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits)
  291. {
  292. /* arbitrate between double-shift and shift+mask */
  293. #if 1
  294. /* if bitD->bitsConsumed + nbBits > sizeof(bitD->bitContainer)*8,
  295. * bitstream is likely corrupted, and result is undefined */
  296. return BIT_getMiddleBits(bitD->bitContainer, (sizeof(bitD->bitContainer)*8) - bitD->bitsConsumed - nbBits, nbBits);
  297. #else
  298. /* this code path is slower on my os-x laptop */
  299. U32 const regMask = sizeof(bitD->bitContainer)*8 - 1;
  300. return ((bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> 1) >> ((regMask-nbBits) & regMask);
  301. #endif
  302. }
  303. /*! BIT_lookBitsFast() :
  304. * unsafe version; only works if nbBits >= 1 */
  305. MEM_STATIC BitContainerType BIT_lookBitsFast(const BIT_DStream_t* bitD, U32 nbBits)
  306. {
  307. U32 const regMask = sizeof(bitD->bitContainer)*8 - 1;
  308. assert(nbBits >= 1);
  309. return (bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> (((regMask+1)-nbBits) & regMask);
  310. }
  311. FORCE_INLINE_TEMPLATE void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits)
  312. {
  313. bitD->bitsConsumed += nbBits;
  314. }
  315. /*! BIT_readBits() :
  316. * Read (consume) next n bits from local register and update.
  317. * Pay attention to not read more than nbBits contained into local register.
  318. * @return : extracted value. */
  319. FORCE_INLINE_TEMPLATE BitContainerType BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits)
  320. {
  321. BitContainerType const value = BIT_lookBits(bitD, nbBits);
  322. BIT_skipBits(bitD, nbBits);
  323. return value;
  324. }
  325. /*! BIT_readBitsFast() :
  326. * unsafe version; only works if nbBits >= 1 */
  327. MEM_STATIC BitContainerType BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits)
  328. {
  329. BitContainerType const value = BIT_lookBitsFast(bitD, nbBits);
  330. assert(nbBits >= 1);
  331. BIT_skipBits(bitD, nbBits);
  332. return value;
  333. }
  334. /*! BIT_reloadDStream_internal() :
  335. * Simple variant of BIT_reloadDStream(), with two conditions:
  336. * 1. bitstream is valid : bitsConsumed <= sizeof(bitD->bitContainer)*8
  337. * 2. look window is valid after shifted down : bitD->ptr >= bitD->start
  338. */
  339. MEM_STATIC BIT_DStream_status BIT_reloadDStream_internal(BIT_DStream_t* bitD)
  340. {
  341. assert(bitD->bitsConsumed <= sizeof(bitD->bitContainer)*8);
  342. bitD->ptr -= bitD->bitsConsumed >> 3;
  343. assert(bitD->ptr >= bitD->start);
  344. bitD->bitsConsumed &= 7;
  345. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  346. return BIT_DStream_unfinished;
  347. }
  348. /*! BIT_reloadDStreamFast() :
  349. * Similar to BIT_reloadDStream(), but with two differences:
  350. * 1. bitsConsumed <= sizeof(bitD->bitContainer)*8 must hold!
  351. * 2. Returns BIT_DStream_overflow when bitD->ptr < bitD->limitPtr, at this
  352. * point you must use BIT_reloadDStream() to reload.
  353. */
  354. MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast(BIT_DStream_t* bitD)
  355. {
  356. if (UNLIKELY(bitD->ptr < bitD->limitPtr))
  357. return BIT_DStream_overflow;
  358. return BIT_reloadDStream_internal(bitD);
  359. }
  360. /*! BIT_reloadDStream() :
  361. * Refill `bitD` from buffer previously set in BIT_initDStream() .
  362. * This function is safe, it guarantees it will not never beyond src buffer.
  363. * @return : status of `BIT_DStream_t` internal register.
  364. * when status == BIT_DStream_unfinished, internal register is filled with at least 25 or 57 bits */
  365. FORCE_INLINE_TEMPLATE BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD)
  366. {
  367. /* note : once in overflow mode, a bitstream remains in this mode until it's reset */
  368. if (UNLIKELY(bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8))) {
  369. static const BitContainerType zeroFilled = 0;
  370. bitD->ptr = (const char*)&zeroFilled; /* aliasing is allowed for char */
  371. /* overflow detected, erroneous scenario or end of stream: no update */
  372. return BIT_DStream_overflow;
  373. }
  374. assert(bitD->ptr >= bitD->start);
  375. if (bitD->ptr >= bitD->limitPtr) {
  376. return BIT_reloadDStream_internal(bitD);
  377. }
  378. if (bitD->ptr == bitD->start) {
  379. /* reached end of bitStream => no update */
  380. if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer;
  381. return BIT_DStream_completed;
  382. }
  383. /* start < ptr < limitPtr => cautious update */
  384. { U32 nbBytes = bitD->bitsConsumed >> 3;
  385. BIT_DStream_status result = BIT_DStream_unfinished;
  386. if (bitD->ptr - nbBytes < bitD->start) {
  387. nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
  388. result = BIT_DStream_endOfBuffer;
  389. }
  390. bitD->ptr -= nbBytes;
  391. bitD->bitsConsumed -= nbBytes*8;
  392. bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD->bitContainer), otherwise bitD->ptr == bitD->start */
  393. return result;
  394. }
  395. }
  396. /*! BIT_endOfDStream() :
  397. * @return : 1 if DStream has _exactly_ reached its end (all bits consumed).
  398. */
  399. MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream)
  400. {
  401. return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
  402. }
  403. #endif /* BITSTREAM_H_MODULE */