blob: 42f80ff73ec8168e8cdcb46e70fb1acc51f5ace4 [file] [log] [blame]
Marek BehĂșn8509f222019-04-29 22:40:44 +02001/* SPDX-License-Identifier: (GPL-2.0 or BSD-2-Clause) */
2/*
3 * FSE : Finite State Entropy codec
4 * Public Prototypes declaration
5 * Copyright (C) 2013-2016, Yann Collet.
6 *
7 * You can contact the author at :
8 * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
9 */
10#ifndef FSE_H
11#define FSE_H
12
13/*-*****************************************
14* Dependencies
15******************************************/
16#include <linux/types.h> /* size_t, ptrdiff_t */
17
18/*-*****************************************
19* FSE_PUBLIC_API : control library symbols visibility
20******************************************/
21#define FSE_PUBLIC_API
22
23/*------ Version ------*/
24#define FSE_VERSION_MAJOR 0
25#define FSE_VERSION_MINOR 9
26#define FSE_VERSION_RELEASE 0
27
28#define FSE_LIB_VERSION FSE_VERSION_MAJOR.FSE_VERSION_MINOR.FSE_VERSION_RELEASE
29#define FSE_QUOTE(str) #str
30#define FSE_EXPAND_AND_QUOTE(str) FSE_QUOTE(str)
31#define FSE_VERSION_STRING FSE_EXPAND_AND_QUOTE(FSE_LIB_VERSION)
32
33#define FSE_VERSION_NUMBER (FSE_VERSION_MAJOR * 100 * 100 + FSE_VERSION_MINOR * 100 + FSE_VERSION_RELEASE)
34FSE_PUBLIC_API unsigned FSE_versionNumber(void); /**< library version number; to be used when checking dll version */
35
36/*-*****************************************
37* Tool functions
38******************************************/
39FSE_PUBLIC_API size_t FSE_compressBound(size_t size); /* maximum compressed size */
40
41/* Error Management */
42FSE_PUBLIC_API unsigned FSE_isError(size_t code); /* tells if a return value is an error code */
43
44/*-*****************************************
45* FSE detailed API
46******************************************/
47/*!
48FSE_compress() does the following:
491. count symbol occurrence from source[] into table count[]
502. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog)
513. save normalized counters to memory buffer using writeNCount()
524. build encoding table 'CTable' from normalized counters
535. encode the data stream using encoding table 'CTable'
54
55FSE_decompress() does the following:
561. read normalized counters with readNCount()
572. build decoding table 'DTable' from normalized counters
583. decode the data stream using decoding table 'DTable'
59
60The following API allows targeting specific sub-functions for advanced tasks.
61For example, it's possible to compress several blocks using the same 'CTable',
62or to save and provide normalized distribution using external method.
63*/
64
65/* *** COMPRESSION *** */
66/*! FSE_optimalTableLog():
67 dynamically downsize 'tableLog' when conditions are met.
68 It saves CPU time, by using smaller tables, while preserving or even improving compression ratio.
69 @return : recommended tableLog (necessarily <= 'maxTableLog') */
70FSE_PUBLIC_API unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue);
71
72/*! FSE_normalizeCount():
73 normalize counts so that sum(count[]) == Power_of_2 (2^tableLog)
74 'normalizedCounter' is a table of short, of minimum size (maxSymbolValue+1).
75 @return : tableLog,
76 or an errorCode, which can be tested using FSE_isError() */
77FSE_PUBLIC_API size_t FSE_normalizeCount(short *normalizedCounter, unsigned tableLog, const unsigned *count, size_t srcSize, unsigned maxSymbolValue);
78
79/*! FSE_NCountWriteBound():
80 Provides the maximum possible size of an FSE normalized table, given 'maxSymbolValue' and 'tableLog'.
81 Typically useful for allocation purpose. */
82FSE_PUBLIC_API size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog);
83
84/*! FSE_writeNCount():
85 Compactly save 'normalizedCounter' into 'buffer'.
86 @return : size of the compressed table,
87 or an errorCode, which can be tested using FSE_isError(). */
88FSE_PUBLIC_API size_t FSE_writeNCount(void *buffer, size_t bufferSize, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
89
90/*! Constructor and Destructor of FSE_CTable.
91 Note that FSE_CTable size depends on 'tableLog' and 'maxSymbolValue' */
92typedef unsigned FSE_CTable; /* don't allocate that. It's only meant to be more restrictive than void* */
93
94/*! FSE_compress_usingCTable():
95 Compress `src` using `ct` into `dst` which must be already allocated.
96 @return : size of compressed data (<= `dstCapacity`),
97 or 0 if compressed data could not fit into `dst`,
98 or an errorCode, which can be tested using FSE_isError() */
99FSE_PUBLIC_API size_t FSE_compress_usingCTable(void *dst, size_t dstCapacity, const void *src, size_t srcSize, const FSE_CTable *ct);
100
101/*!
102Tutorial :
103----------
104The first step is to count all symbols. FSE_count() does this job very fast.
105Result will be saved into 'count', a table of unsigned int, which must be already allocated, and have 'maxSymbolValuePtr[0]+1' cells.
106'src' is a table of bytes of size 'srcSize'. All values within 'src' MUST be <= maxSymbolValuePtr[0]
107maxSymbolValuePtr[0] will be updated, with its real value (necessarily <= original value)
108FSE_count() will return the number of occurrence of the most frequent symbol.
109This can be used to know if there is a single symbol within 'src', and to quickly evaluate its compressibility.
110If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).
111
112The next step is to normalize the frequencies.
113FSE_normalizeCount() will ensure that sum of frequencies is == 2 ^'tableLog'.
114It also guarantees a minimum of 1 to any Symbol with frequency >= 1.
115You can use 'tableLog'==0 to mean "use default tableLog value".
116If you are unsure of which tableLog value to use, you can ask FSE_optimalTableLog(),
117which will provide the optimal valid tableLog given sourceSize, maxSymbolValue, and a user-defined maximum (0 means "default").
118
119The result of FSE_normalizeCount() will be saved into a table,
120called 'normalizedCounter', which is a table of signed short.
121'normalizedCounter' must be already allocated, and have at least 'maxSymbolValue+1' cells.
122The return value is tableLog if everything proceeded as expected.
123It is 0 if there is a single symbol within distribution.
124If there is an error (ex: invalid tableLog value), the function will return an ErrorCode (which can be tested using FSE_isError()).
125
126'normalizedCounter' can be saved in a compact manner to a memory area using FSE_writeNCount().
127'buffer' must be already allocated.
128For guaranteed success, buffer size must be at least FSE_headerBound().
129The result of the function is the number of bytes written into 'buffer'.
130If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError(); ex : buffer size too small).
131
132'normalizedCounter' can then be used to create the compression table 'CTable'.
133The space required by 'CTable' must be already allocated, using FSE_createCTable().
134You can then use FSE_buildCTable() to fill 'CTable'.
135If there is an error, both functions will return an ErrorCode (which can be tested using FSE_isError()).
136
137'CTable' can then be used to compress 'src', with FSE_compress_usingCTable().
138Similar to FSE_count(), the convention is that 'src' is assumed to be a table of char of size 'srcSize'
139The function returns the size of compressed data (without header), necessarily <= `dstCapacity`.
140If it returns '0', compressed data could not fit into 'dst'.
141If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).
142*/
143
144/* *** DECOMPRESSION *** */
145
146/*! FSE_readNCount():
147 Read compactly saved 'normalizedCounter' from 'rBuffer'.
148 @return : size read from 'rBuffer',
149 or an errorCode, which can be tested using FSE_isError().
150 maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */
151FSE_PUBLIC_API size_t FSE_readNCount(short *normalizedCounter, unsigned *maxSymbolValuePtr, unsigned *tableLogPtr, const void *rBuffer, size_t rBuffSize);
152
153/*! Constructor and Destructor of FSE_DTable.
154 Note that its size depends on 'tableLog' */
155typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */
156
157/*! FSE_buildDTable():
158 Builds 'dt', which must be already allocated, using FSE_createDTable().
159 return : 0, or an errorCode, which can be tested using FSE_isError() */
160FSE_PUBLIC_API size_t FSE_buildDTable_wksp(FSE_DTable *dt, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void *workspace, size_t workspaceSize);
161
162/*! FSE_decompress_usingDTable():
163 Decompress compressed source `cSrc` of size `cSrcSize` using `dt`
164 into `dst` which must be already allocated.
165 @return : size of regenerated data (necessarily <= `dstCapacity`),
166 or an errorCode, which can be tested using FSE_isError() */
167FSE_PUBLIC_API size_t FSE_decompress_usingDTable(void *dst, size_t dstCapacity, const void *cSrc, size_t cSrcSize, const FSE_DTable *dt);
168
169/*!
170Tutorial :
171----------
172(Note : these functions only decompress FSE-compressed blocks.
173 If block is uncompressed, use memcpy() instead
174 If block is a single repeated byte, use memset() instead )
175
176The first step is to obtain the normalized frequencies of symbols.
177This can be performed by FSE_readNCount() if it was saved using FSE_writeNCount().
178'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short.
179In practice, that means it's necessary to know 'maxSymbolValue' beforehand,
180or size the table to handle worst case situations (typically 256).
181FSE_readNCount() will provide 'tableLog' and 'maxSymbolValue'.
182The result of FSE_readNCount() is the number of bytes read from 'rBuffer'.
183Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that.
184If there is an error, the function will return an error code, which can be tested using FSE_isError().
185
186The next step is to build the decompression tables 'FSE_DTable' from 'normalizedCounter'.
187This is performed by the function FSE_buildDTable().
188The space required by 'FSE_DTable' must be already allocated using FSE_createDTable().
189If there is an error, the function will return an error code, which can be tested using FSE_isError().
190
191`FSE_DTable` can then be used to decompress `cSrc`, with FSE_decompress_usingDTable().
192`cSrcSize` must be strictly correct, otherwise decompression will fail.
193FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`).
194If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small)
195*/
196
197/* *** Dependency *** */
198#include "bitstream.h"
199
200/* *****************************************
201* Static allocation
202*******************************************/
203/* FSE buffer bounds */
204#define FSE_NCOUNTBOUND 512
205#define FSE_BLOCKBOUND(size) (size + (size >> 7))
206#define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size)) /* Macro version, useful for static allocation */
207
208/* It is possible to statically allocate FSE CTable/DTable as a table of FSE_CTable/FSE_DTable using below macros */
209#define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) (1 + (1 << (maxTableLog - 1)) + ((maxSymbolValue + 1) * 2))
210#define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1 << maxTableLog))
211
212/* *****************************************
213* FSE advanced API
214*******************************************/
215/* FSE_count_wksp() :
216 * Same as FSE_count(), but using an externally provided scratch buffer.
217 * `workSpace` size must be table of >= `1024` unsigned
218 */
219size_t FSE_count_wksp(unsigned *count, unsigned *maxSymbolValuePtr, const void *source, size_t sourceSize, unsigned *workSpace);
220
221/* FSE_countFast_wksp() :
222 * Same as FSE_countFast(), but using an externally provided scratch buffer.
223 * `workSpace` must be a table of minimum `1024` unsigned
224 */
225size_t FSE_countFast_wksp(unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize, unsigned *workSpace);
226
227/*! FSE_count_simple
228 * Same as FSE_countFast(), but does not use any additional memory (not even on stack).
229 * This function is unsafe, and will segfault if any value within `src` is `> *maxSymbolValuePtr` (presuming it's also the size of `count`).
230*/
231size_t FSE_count_simple(unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize);
232
233unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus);
234/**< same as FSE_optimalTableLog(), which used `minus==2` */
235
236size_t FSE_buildCTable_raw(FSE_CTable *ct, unsigned nbBits);
237/**< build a fake FSE_CTable, designed for a flat distribution, where each symbol uses nbBits */
238
239size_t FSE_buildCTable_rle(FSE_CTable *ct, unsigned char symbolValue);
240/**< build a fake FSE_CTable, designed to compress always the same symbolValue */
241
242/* FSE_buildCTable_wksp() :
243 * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
244 * `wkspSize` must be >= `(1<<tableLog)`.
245 */
246size_t FSE_buildCTable_wksp(FSE_CTable *ct, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void *workSpace, size_t wkspSize);
247
248size_t FSE_buildDTable_raw(FSE_DTable *dt, unsigned nbBits);
249/**< build a fake FSE_DTable, designed to read a flat distribution where each symbol uses nbBits */
250
251size_t FSE_buildDTable_rle(FSE_DTable *dt, unsigned char symbolValue);
252/**< build a fake FSE_DTable, designed to always generate the same symbolValue */
253
254size_t FSE_decompress_wksp(void *dst, size_t dstCapacity, const void *cSrc, size_t cSrcSize, unsigned maxLog, void *workspace, size_t workspaceSize);
255/**< same as FSE_decompress(), using an externally allocated `workSpace` produced with `FSE_DTABLE_SIZE_U32(maxLog)` */
256
257/* *****************************************
258* FSE symbol compression API
259*******************************************/
260/*!
261 This API consists of small unitary functions, which highly benefit from being inlined.
262 Hence their body are included in next section.
263*/
264typedef struct {
265 ptrdiff_t value;
266 const void *stateTable;
267 const void *symbolTT;
268 unsigned stateLog;
269} FSE_CState_t;
270
271static void FSE_initCState(FSE_CState_t *CStatePtr, const FSE_CTable *ct);
272
273static void FSE_encodeSymbol(BIT_CStream_t *bitC, FSE_CState_t *CStatePtr, unsigned symbol);
274
275static void FSE_flushCState(BIT_CStream_t *bitC, const FSE_CState_t *CStatePtr);
276
277/**<
278These functions are inner components of FSE_compress_usingCTable().
279They allow the creation of custom streams, mixing multiple tables and bit sources.
280
281A key property to keep in mind is that encoding and decoding are done **in reverse direction**.
282So the first symbol you will encode is the last you will decode, like a LIFO stack.
283
284You will need a few variables to track your CStream. They are :
285
286FSE_CTable ct; // Provided by FSE_buildCTable()
287BIT_CStream_t bitStream; // bitStream tracking structure
288FSE_CState_t state; // State tracking structure (can have several)
289
290
291The first thing to do is to init bitStream and state.
292 size_t errorCode = BIT_initCStream(&bitStream, dstBuffer, maxDstSize);
293 FSE_initCState(&state, ct);
294
295Note that BIT_initCStream() can produce an error code, so its result should be tested, using FSE_isError();
296You can then encode your input data, byte after byte.
297FSE_encodeSymbol() outputs a maximum of 'tableLog' bits at a time.
298Remember decoding will be done in reverse direction.
299 FSE_encodeByte(&bitStream, &state, symbol);
300
301At any time, you can also add any bit sequence.
302Note : maximum allowed nbBits is 25, for compatibility with 32-bits decoders
303 BIT_addBits(&bitStream, bitField, nbBits);
304
305The above methods don't commit data to memory, they just store it into local register, for speed.
306Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
307Writing data to memory is a manual operation, performed by the flushBits function.
308 BIT_flushBits(&bitStream);
309
310Your last FSE encoding operation shall be to flush your last state value(s).
311 FSE_flushState(&bitStream, &state);
312
313Finally, you must close the bitStream.
314The function returns the size of CStream in bytes.
315If data couldn't fit into dstBuffer, it will return a 0 ( == not compressible)
316If there is an error, it returns an errorCode (which can be tested using FSE_isError()).
317 size_t size = BIT_closeCStream(&bitStream);
318*/
319
320/* *****************************************
321* FSE symbol decompression API
322*******************************************/
323typedef struct {
324 size_t state;
325 const void *table; /* precise table may vary, depending on U16 */
326} FSE_DState_t;
327
328static void FSE_initDState(FSE_DState_t *DStatePtr, BIT_DStream_t *bitD, const FSE_DTable *dt);
329
330static unsigned char FSE_decodeSymbol(FSE_DState_t *DStatePtr, BIT_DStream_t *bitD);
331
332static unsigned FSE_endOfDState(const FSE_DState_t *DStatePtr);
333
334/**<
335Let's now decompose FSE_decompress_usingDTable() into its unitary components.
336You will decode FSE-encoded symbols from the bitStream,
337and also any other bitFields you put in, **in reverse order**.
338
339You will need a few variables to track your bitStream. They are :
340
341BIT_DStream_t DStream; // Stream context
342FSE_DState_t DState; // State context. Multiple ones are possible
343FSE_DTable* DTablePtr; // Decoding table, provided by FSE_buildDTable()
344
345The first thing to do is to init the bitStream.
346 errorCode = BIT_initDStream(&DStream, srcBuffer, srcSize);
347
348You should then retrieve your initial state(s)
349(in reverse flushing order if you have several ones) :
350 errorCode = FSE_initDState(&DState, &DStream, DTablePtr);
351
352You can then decode your data, symbol after symbol.
353For information the maximum number of bits read by FSE_decodeSymbol() is 'tableLog'.
354Keep in mind that symbols are decoded in reverse order, like a LIFO stack (last in, first out).
355 unsigned char symbol = FSE_decodeSymbol(&DState, &DStream);
356
357You can retrieve any bitfield you eventually stored into the bitStream (in reverse order)
358Note : maximum allowed nbBits is 25, for 32-bits compatibility
359 size_t bitField = BIT_readBits(&DStream, nbBits);
360
361All above operations only read from local register (which size depends on size_t).
362Refueling the register from memory is manually performed by the reload method.
363 endSignal = FSE_reloadDStream(&DStream);
364
365BIT_reloadDStream() result tells if there is still some more data to read from DStream.
366BIT_DStream_unfinished : there is still some data left into the DStream.
367BIT_DStream_endOfBuffer : Dstream reached end of buffer. Its container may no longer be completely filled.
368BIT_DStream_completed : Dstream reached its exact end, corresponding in general to decompression completed.
369BIT_DStream_tooFar : Dstream went too far. Decompression result is corrupted.
370
371When reaching end of buffer (BIT_DStream_endOfBuffer), progress slowly, notably if you decode multiple symbols per loop,
372to properly detect the exact end of stream.
373After each decoded symbol, check if DStream is fully consumed using this simple test :
374 BIT_reloadDStream(&DStream) >= BIT_DStream_completed
375
376When it's done, verify decompression is fully completed, by checking both DStream and the relevant states.
377Checking if DStream has reached its end is performed by :
378 BIT_endOfDStream(&DStream);
379Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible.
380 FSE_endOfDState(&DState);
381*/
382
383/* *****************************************
384* FSE unsafe API
385*******************************************/
386static unsigned char FSE_decodeSymbolFast(FSE_DState_t *DStatePtr, BIT_DStream_t *bitD);
387/* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */
388
389/* *****************************************
390* Implementation of inlined functions
391*******************************************/
392typedef struct {
393 int deltaFindState;
394 U32 deltaNbBits;
395} FSE_symbolCompressionTransform; /* total 8 bytes */
396
397ZSTD_STATIC void FSE_initCState(FSE_CState_t *statePtr, const FSE_CTable *ct)
398{
399 const void *ptr = ct;
400 const U16 *u16ptr = (const U16 *)ptr;
401 const U32 tableLog = ZSTD_read16(ptr);
402 statePtr->value = (ptrdiff_t)1 << tableLog;
403 statePtr->stateTable = u16ptr + 2;
404 statePtr->symbolTT = ((const U32 *)ct + 1 + (tableLog ? (1 << (tableLog - 1)) : 1));
405 statePtr->stateLog = tableLog;
406}
407
408/*! FSE_initCState2() :
409* Same as FSE_initCState(), but the first symbol to include (which will be the last to be read)
410* uses the smallest state value possible, saving the cost of this symbol */
411ZSTD_STATIC void FSE_initCState2(FSE_CState_t *statePtr, const FSE_CTable *ct, U32 symbol)
412{
413 FSE_initCState(statePtr, ct);
414 {
415 const FSE_symbolCompressionTransform symbolTT = ((const FSE_symbolCompressionTransform *)(statePtr->symbolTT))[symbol];
416 const U16 *stateTable = (const U16 *)(statePtr->stateTable);
417 U32 nbBitsOut = (U32)((symbolTT.deltaNbBits + (1 << 15)) >> 16);
418 statePtr->value = (nbBitsOut << 16) - symbolTT.deltaNbBits;
419 statePtr->value = stateTable[(statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
420 }
421}
422
423ZSTD_STATIC void FSE_encodeSymbol(BIT_CStream_t *bitC, FSE_CState_t *statePtr, U32 symbol)
424{
425 const FSE_symbolCompressionTransform symbolTT = ((const FSE_symbolCompressionTransform *)(statePtr->symbolTT))[symbol];
426 const U16 *const stateTable = (const U16 *)(statePtr->stateTable);
427 U32 nbBitsOut = (U32)((statePtr->value + symbolTT.deltaNbBits) >> 16);
428 BIT_addBits(bitC, statePtr->value, nbBitsOut);
429 statePtr->value = stateTable[(statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
430}
431
432ZSTD_STATIC void FSE_flushCState(BIT_CStream_t *bitC, const FSE_CState_t *statePtr)
433{
434 BIT_addBits(bitC, statePtr->value, statePtr->stateLog);
435 BIT_flushBits(bitC);
436}
437
438/* ====== Decompression ====== */
439
440typedef struct {
441 U16 tableLog;
442 U16 fastMode;
443} FSE_DTableHeader; /* sizeof U32 */
444
445typedef struct {
446 unsigned short newState;
447 unsigned char symbol;
448 unsigned char nbBits;
449} FSE_decode_t; /* size == U32 */
450
451ZSTD_STATIC void FSE_initDState(FSE_DState_t *DStatePtr, BIT_DStream_t *bitD, const FSE_DTable *dt)
452{
453 const void *ptr = dt;
454 const FSE_DTableHeader *const DTableH = (const FSE_DTableHeader *)ptr;
455 DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
456 BIT_reloadDStream(bitD);
457 DStatePtr->table = dt + 1;
458}
459
460ZSTD_STATIC BYTE FSE_peekSymbol(const FSE_DState_t *DStatePtr)
461{
462 FSE_decode_t const DInfo = ((const FSE_decode_t *)(DStatePtr->table))[DStatePtr->state];
463 return DInfo.symbol;
464}
465
466ZSTD_STATIC void FSE_updateState(FSE_DState_t *DStatePtr, BIT_DStream_t *bitD)
467{
468 FSE_decode_t const DInfo = ((const FSE_decode_t *)(DStatePtr->table))[DStatePtr->state];
469 U32 const nbBits = DInfo.nbBits;
470 size_t const lowBits = BIT_readBits(bitD, nbBits);
471 DStatePtr->state = DInfo.newState + lowBits;
472}
473
474ZSTD_STATIC BYTE FSE_decodeSymbol(FSE_DState_t *DStatePtr, BIT_DStream_t *bitD)
475{
476 FSE_decode_t const DInfo = ((const FSE_decode_t *)(DStatePtr->table))[DStatePtr->state];
477 U32 const nbBits = DInfo.nbBits;
478 BYTE const symbol = DInfo.symbol;
479 size_t const lowBits = BIT_readBits(bitD, nbBits);
480
481 DStatePtr->state = DInfo.newState + lowBits;
482 return symbol;
483}
484
485/*! FSE_decodeSymbolFast() :
486 unsafe, only works if no symbol has a probability > 50% */
487ZSTD_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t *DStatePtr, BIT_DStream_t *bitD)
488{
489 FSE_decode_t const DInfo = ((const FSE_decode_t *)(DStatePtr->table))[DStatePtr->state];
490 U32 const nbBits = DInfo.nbBits;
491 BYTE const symbol = DInfo.symbol;
492 size_t const lowBits = BIT_readBitsFast(bitD, nbBits);
493
494 DStatePtr->state = DInfo.newState + lowBits;
495 return symbol;
496}
497
498ZSTD_STATIC unsigned FSE_endOfDState(const FSE_DState_t *DStatePtr) { return DStatePtr->state == 0; }
499
500/* **************************************************************
501* Tuning parameters
502****************************************************************/
503/*!MEMORY_USAGE :
504* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
505* Increasing memory usage improves compression ratio
506* Reduced memory usage can improve speed, due to cache effect
507* Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
508#ifndef FSE_MAX_MEMORY_USAGE
509#define FSE_MAX_MEMORY_USAGE 14
510#endif
511#ifndef FSE_DEFAULT_MEMORY_USAGE
512#define FSE_DEFAULT_MEMORY_USAGE 13
513#endif
514
515/*!FSE_MAX_SYMBOL_VALUE :
516* Maximum symbol value authorized.
517* Required for proper stack allocation */
518#ifndef FSE_MAX_SYMBOL_VALUE
519#define FSE_MAX_SYMBOL_VALUE 255
520#endif
521
522/* **************************************************************
523* template functions type & suffix
524****************************************************************/
525#define FSE_FUNCTION_TYPE BYTE
526#define FSE_FUNCTION_EXTENSION
527#define FSE_DECODE_TYPE FSE_decode_t
528
529/* ***************************************************************
530* Constants
531*****************************************************************/
532#define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE - 2)
533#define FSE_MAX_TABLESIZE (1U << FSE_MAX_TABLELOG)
534#define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE - 1)
535#define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE - 2)
536#define FSE_MIN_TABLELOG 5
537
538#define FSE_TABLELOG_ABSOLUTE_MAX 15
539#if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
540#error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
541#endif
542
543#define FSE_TABLESTEP(tableSize) ((tableSize >> 1) + (tableSize >> 3) + 3)
544
545#endif /* FSE_H */