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