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