imx: imx8qxp: update fdt_file according to m4 state
[oweals/u-boot.git] / lib / zstd / fse.h
1 /* 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)
34 FSE_PUBLIC_API unsigned FSE_versionNumber(void); /**< library version number; to be used when checking dll version */
35
36 /*-*****************************************
37 *  Tool functions
38 ******************************************/
39 FSE_PUBLIC_API size_t FSE_compressBound(size_t size); /* maximum compressed size */
40
41 /* Error Management */
42 FSE_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 /*!
48 FSE_compress() does the following:
49 1. count symbol occurrence from source[] into table count[]
50 2. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog)
51 3. save normalized counters to memory buffer using writeNCount()
52 4. build encoding table 'CTable' from normalized counters
53 5. encode the data stream using encoding table 'CTable'
54
55 FSE_decompress() does the following:
56 1. read normalized counters with readNCount()
57 2. build decoding table 'DTable' from normalized counters
58 3. decode the data stream using decoding table 'DTable'
59
60 The following API allows targeting specific sub-functions for advanced tasks.
61 For example, it's possible to compress several blocks using the same 'CTable',
62 or 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') */
70 FSE_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() */
77 FSE_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. */
82 FSE_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(). */
88 FSE_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' */
92 typedef 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() */
99 FSE_PUBLIC_API size_t FSE_compress_usingCTable(void *dst, size_t dstCapacity, const void *src, size_t srcSize, const FSE_CTable *ct);
100
101 /*!
102 Tutorial :
103 ----------
104 The first step is to count all symbols. FSE_count() does this job very fast.
105 Result 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]
107 maxSymbolValuePtr[0] will be updated, with its real value (necessarily <= original value)
108 FSE_count() will return the number of occurrence of the most frequent symbol.
109 This can be used to know if there is a single symbol within 'src', and to quickly evaluate its compressibility.
110 If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).
111
112 The next step is to normalize the frequencies.
113 FSE_normalizeCount() will ensure that sum of frequencies is == 2 ^'tableLog'.
114 It also guarantees a minimum of 1 to any Symbol with frequency >= 1.
115 You can use 'tableLog'==0 to mean "use default tableLog value".
116 If you are unsure of which tableLog value to use, you can ask FSE_optimalTableLog(),
117 which will provide the optimal valid tableLog given sourceSize, maxSymbolValue, and a user-defined maximum (0 means "default").
118
119 The result of FSE_normalizeCount() will be saved into a table,
120 called 'normalizedCounter', which is a table of signed short.
121 'normalizedCounter' must be already allocated, and have at least 'maxSymbolValue+1' cells.
122 The return value is tableLog if everything proceeded as expected.
123 It is 0 if there is a single symbol within distribution.
124 If 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.
128 For guaranteed success, buffer size must be at least FSE_headerBound().
129 The result of the function is the number of bytes written into 'buffer'.
130 If 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'.
133 The space required by 'CTable' must be already allocated, using FSE_createCTable().
134 You can then use FSE_buildCTable() to fill 'CTable'.
135 If 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().
138 Similar to FSE_count(), the convention is that 'src' is assumed to be a table of char of size 'srcSize'
139 The function returns the size of compressed data (without header), necessarily <= `dstCapacity`.
140 If it returns '0', compressed data could not fit into 'dst'.
141 If 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 */
151 FSE_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' */
155 typedef 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() */
160 FSE_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() */
167 FSE_PUBLIC_API size_t FSE_decompress_usingDTable(void *dst, size_t dstCapacity, const void *cSrc, size_t cSrcSize, const FSE_DTable *dt);
168
169 /*!
170 Tutorial :
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
176 The first step is to obtain the normalized frequencies of symbols.
177 This 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.
179 In practice, that means it's necessary to know 'maxSymbolValue' beforehand,
180 or size the table to handle worst case situations (typically 256).
181 FSE_readNCount() will provide 'tableLog' and 'maxSymbolValue'.
182 The result of FSE_readNCount() is the number of bytes read from 'rBuffer'.
183 Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that.
184 If there is an error, the function will return an error code, which can be tested using FSE_isError().
185
186 The next step is to build the decompression tables 'FSE_DTable' from 'normalizedCounter'.
187 This is performed by the function FSE_buildDTable().
188 The space required by 'FSE_DTable' must be already allocated using FSE_createDTable().
189 If 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.
193 FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`).
194 If 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  */
219 size_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  */
225 size_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 */
231 size_t FSE_count_simple(unsigned *count, unsigned *maxSymbolValuePtr, const void *src, size_t srcSize);
232
233 unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus);
234 /**< same as FSE_optimalTableLog(), which used `minus==2` */
235
236 size_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
239 size_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  */
246 size_t FSE_buildCTable_wksp(FSE_CTable *ct, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void *workSpace, size_t wkspSize);
247
248 size_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
251 size_t FSE_buildDTable_rle(FSE_DTable *dt, unsigned char symbolValue);
252 /**< build a fake FSE_DTable, designed to always generate the same symbolValue */
253
254 size_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 */
264 typedef struct {
265         ptrdiff_t value;
266         const void *stateTable;
267         const void *symbolTT;
268         unsigned stateLog;
269 } FSE_CState_t;
270
271 static void FSE_initCState(FSE_CState_t *CStatePtr, const FSE_CTable *ct);
272
273 static void FSE_encodeSymbol(BIT_CStream_t *bitC, FSE_CState_t *CStatePtr, unsigned symbol);
274
275 static void FSE_flushCState(BIT_CStream_t *bitC, const FSE_CState_t *CStatePtr);
276
277 /**<
278 These functions are inner components of FSE_compress_usingCTable().
279 They allow the creation of custom streams, mixing multiple tables and bit sources.
280
281 A key property to keep in mind is that encoding and decoding are done **in reverse direction**.
282 So the first symbol you will encode is the last you will decode, like a LIFO stack.
283
284 You will need a few variables to track your CStream. They are :
285
286 FSE_CTable    ct;         // Provided by FSE_buildCTable()
287 BIT_CStream_t bitStream;  // bitStream tracking structure
288 FSE_CState_t  state;      // State tracking structure (can have several)
289
290
291 The 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
295 Note that BIT_initCStream() can produce an error code, so its result should be tested, using FSE_isError();
296 You can then encode your input data, byte after byte.
297 FSE_encodeSymbol() outputs a maximum of 'tableLog' bits at a time.
298 Remember decoding will be done in reverse direction.
299         FSE_encodeByte(&bitStream, &state, symbol);
300
301 At any time, you can also add any bit sequence.
302 Note : maximum allowed nbBits is 25, for compatibility with 32-bits decoders
303         BIT_addBits(&bitStream, bitField, nbBits);
304
305 The above methods don't commit data to memory, they just store it into local register, for speed.
306 Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
307 Writing data to memory is a manual operation, performed by the flushBits function.
308         BIT_flushBits(&bitStream);
309
310 Your last FSE encoding operation shall be to flush your last state value(s).
311         FSE_flushState(&bitStream, &state);
312
313 Finally, you must close the bitStream.
314 The function returns the size of CStream in bytes.
315 If data couldn't fit into dstBuffer, it will return a 0 ( == not compressible)
316 If 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 *******************************************/
323 typedef struct {
324         size_t state;
325         const void *table; /* precise table may vary, depending on U16 */
326 } FSE_DState_t;
327
328 static void FSE_initDState(FSE_DState_t *DStatePtr, BIT_DStream_t *bitD, const FSE_DTable *dt);
329
330 static unsigned char FSE_decodeSymbol(FSE_DState_t *DStatePtr, BIT_DStream_t *bitD);
331
332 static unsigned FSE_endOfDState(const FSE_DState_t *DStatePtr);
333
334 /**<
335 Let's now decompose FSE_decompress_usingDTable() into its unitary components.
336 You will decode FSE-encoded symbols from the bitStream,
337 and also any other bitFields you put in, **in reverse order**.
338
339 You will need a few variables to track your bitStream. They are :
340
341 BIT_DStream_t DStream;    // Stream context
342 FSE_DState_t  DState;     // State context. Multiple ones are possible
343 FSE_DTable*   DTablePtr;  // Decoding table, provided by FSE_buildDTable()
344
345 The first thing to do is to init the bitStream.
346         errorCode = BIT_initDStream(&DStream, srcBuffer, srcSize);
347
348 You 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
352 You can then decode your data, symbol after symbol.
353 For information the maximum number of bits read by FSE_decodeSymbol() is 'tableLog'.
354 Keep 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
357 You can retrieve any bitfield you eventually stored into the bitStream (in reverse order)
358 Note : maximum allowed nbBits is 25, for 32-bits compatibility
359         size_t bitField = BIT_readBits(&DStream, nbBits);
360
361 All above operations only read from local register (which size depends on size_t).
362 Refueling the register from memory is manually performed by the reload method.
363         endSignal = FSE_reloadDStream(&DStream);
364
365 BIT_reloadDStream() result tells if there is still some more data to read from DStream.
366 BIT_DStream_unfinished : there is still some data left into the DStream.
367 BIT_DStream_endOfBuffer : Dstream reached end of buffer. Its container may no longer be completely filled.
368 BIT_DStream_completed : Dstream reached its exact end, corresponding in general to decompression completed.
369 BIT_DStream_tooFar : Dstream went too far. Decompression result is corrupted.
370
371 When reaching end of buffer (BIT_DStream_endOfBuffer), progress slowly, notably if you decode multiple symbols per loop,
372 to properly detect the exact end of stream.
373 After each decoded symbol, check if DStream is fully consumed using this simple test :
374         BIT_reloadDStream(&DStream) >= BIT_DStream_completed
375
376 When it's done, verify decompression is fully completed, by checking both DStream and the relevant states.
377 Checking if DStream has reached its end is performed by :
378         BIT_endOfDStream(&DStream);
379 Check 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 *******************************************/
386 static 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 *******************************************/
392 typedef struct {
393         int deltaFindState;
394         U32 deltaNbBits;
395 } FSE_symbolCompressionTransform; /* total 8 bytes */
396
397 ZSTD_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 */
411 ZSTD_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
423 ZSTD_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
432 ZSTD_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
440 typedef struct {
441         U16 tableLog;
442         U16 fastMode;
443 } FSE_DTableHeader; /* sizeof U32 */
444
445 typedef struct {
446         unsigned short newState;
447         unsigned char symbol;
448         unsigned char nbBits;
449 } FSE_decode_t; /* size == U32 */
450
451 ZSTD_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
460 ZSTD_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
466 ZSTD_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
474 ZSTD_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% */
487 ZSTD_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
498 ZSTD_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 */