xref: /aosp_15_r20/external/zstd/lib/legacy/zstd_v06.c (revision 01826a4963a0d8a59bc3812d29bdf0fb76416722)
1*01826a49SYabin Cui /*
2*01826a49SYabin Cui  * Copyright (c) Yann Collet, Meta Platforms, Inc. and affiliates.
3*01826a49SYabin Cui  * All rights reserved.
4*01826a49SYabin Cui  *
5*01826a49SYabin Cui  * This source code is licensed under both the BSD-style license (found in the
6*01826a49SYabin Cui  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7*01826a49SYabin Cui  * in the COPYING file in the root directory of this source tree).
8*01826a49SYabin Cui  * You may select, at your option, one of the above-listed licenses.
9*01826a49SYabin Cui  */
10*01826a49SYabin Cui 
11*01826a49SYabin Cui 
12*01826a49SYabin Cui /*- Dependencies -*/
13*01826a49SYabin Cui #include "zstd_v06.h"
14*01826a49SYabin Cui #include <stddef.h>    /* size_t, ptrdiff_t */
15*01826a49SYabin Cui #include <string.h>    /* memcpy */
16*01826a49SYabin Cui #include <stdlib.h>    /* malloc, free, qsort */
17*01826a49SYabin Cui #include "../common/compiler.h"
18*01826a49SYabin Cui #include "../common/error_private.h"
19*01826a49SYabin Cui 
20*01826a49SYabin Cui 
21*01826a49SYabin Cui 
22*01826a49SYabin Cui /* ******************************************************************
23*01826a49SYabin Cui    mem.h
24*01826a49SYabin Cui    low-level memory access routines
25*01826a49SYabin Cui    Copyright (C) 2013-2015, Yann Collet.
26*01826a49SYabin Cui 
27*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
28*01826a49SYabin Cui 
29*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
30*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
31*01826a49SYabin Cui    met:
32*01826a49SYabin Cui 
33*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
34*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
35*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
36*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
37*01826a49SYabin Cui    in the documentation and/or other materials provided with the
38*01826a49SYabin Cui    distribution.
39*01826a49SYabin Cui 
40*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
41*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
42*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
43*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
44*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
46*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
47*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
48*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
49*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
50*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
51*01826a49SYabin Cui 
52*01826a49SYabin Cui     You can contact the author at :
53*01826a49SYabin Cui     - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
54*01826a49SYabin Cui     - Public forum : https://groups.google.com/forum/#!forum/lz4c
55*01826a49SYabin Cui ****************************************************************** */
56*01826a49SYabin Cui #ifndef MEM_H_MODULE
57*01826a49SYabin Cui #define MEM_H_MODULE
58*01826a49SYabin Cui 
59*01826a49SYabin Cui #if defined (__cplusplus)
60*01826a49SYabin Cui extern "C" {
61*01826a49SYabin Cui #endif
62*01826a49SYabin Cui 
63*01826a49SYabin Cui 
64*01826a49SYabin Cui /*-****************************************
65*01826a49SYabin Cui *  Compiler specifics
66*01826a49SYabin Cui ******************************************/
67*01826a49SYabin Cui #if defined(_MSC_VER)   /* Visual Studio */
68*01826a49SYabin Cui #   include <stdlib.h>  /* _byteswap_ulong */
69*01826a49SYabin Cui #   include <intrin.h>  /* _byteswap_* */
70*01826a49SYabin Cui #endif
71*01826a49SYabin Cui 
72*01826a49SYabin Cui 
73*01826a49SYabin Cui /*-**************************************************************
74*01826a49SYabin Cui *  Basic Types
75*01826a49SYabin Cui *****************************************************************/
76*01826a49SYabin Cui #if  !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
77*01826a49SYabin Cui # if defined(_AIX)
78*01826a49SYabin Cui #  include <inttypes.h>
79*01826a49SYabin Cui # else
80*01826a49SYabin Cui #  include <stdint.h> /* intptr_t */
81*01826a49SYabin Cui # endif
82*01826a49SYabin Cui   typedef  uint8_t BYTE;
83*01826a49SYabin Cui   typedef uint16_t U16;
84*01826a49SYabin Cui   typedef  int16_t S16;
85*01826a49SYabin Cui   typedef uint32_t U32;
86*01826a49SYabin Cui   typedef  int32_t S32;
87*01826a49SYabin Cui   typedef uint64_t U64;
88*01826a49SYabin Cui   typedef  int64_t S64;
89*01826a49SYabin Cui #else
90*01826a49SYabin Cui   typedef unsigned char       BYTE;
91*01826a49SYabin Cui   typedef unsigned short      U16;
92*01826a49SYabin Cui   typedef   signed short      S16;
93*01826a49SYabin Cui   typedef unsigned int        U32;
94*01826a49SYabin Cui   typedef   signed int        S32;
95*01826a49SYabin Cui   typedef unsigned long long  U64;
96*01826a49SYabin Cui   typedef   signed long long  S64;
97*01826a49SYabin Cui #endif
98*01826a49SYabin Cui 
99*01826a49SYabin Cui 
100*01826a49SYabin Cui /*-**************************************************************
101*01826a49SYabin Cui *  Memory I/O
102*01826a49SYabin Cui *****************************************************************/
103*01826a49SYabin Cui 
MEM_32bits(void)104*01826a49SYabin Cui MEM_STATIC unsigned MEM_32bits(void) { return sizeof(size_t)==4; }
MEM_64bits(void)105*01826a49SYabin Cui MEM_STATIC unsigned MEM_64bits(void) { return sizeof(size_t)==8; }
106*01826a49SYabin Cui 
MEM_isLittleEndian(void)107*01826a49SYabin Cui MEM_STATIC unsigned MEM_isLittleEndian(void)
108*01826a49SYabin Cui {
109*01826a49SYabin Cui     const union { U32 u; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental  */
110*01826a49SYabin Cui     return one.c[0];
111*01826a49SYabin Cui }
112*01826a49SYabin Cui 
MEM_read16(const void * memPtr)113*01826a49SYabin Cui MEM_STATIC U16 MEM_read16(const void* memPtr)
114*01826a49SYabin Cui {
115*01826a49SYabin Cui     U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
116*01826a49SYabin Cui }
117*01826a49SYabin Cui 
MEM_read32(const void * memPtr)118*01826a49SYabin Cui MEM_STATIC U32 MEM_read32(const void* memPtr)
119*01826a49SYabin Cui {
120*01826a49SYabin Cui     U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
121*01826a49SYabin Cui }
122*01826a49SYabin Cui 
MEM_read64(const void * memPtr)123*01826a49SYabin Cui MEM_STATIC U64 MEM_read64(const void* memPtr)
124*01826a49SYabin Cui {
125*01826a49SYabin Cui     U64 val; memcpy(&val, memPtr, sizeof(val)); return val;
126*01826a49SYabin Cui }
127*01826a49SYabin Cui 
MEM_write16(void * memPtr,U16 value)128*01826a49SYabin Cui MEM_STATIC void MEM_write16(void* memPtr, U16 value)
129*01826a49SYabin Cui {
130*01826a49SYabin Cui     memcpy(memPtr, &value, sizeof(value));
131*01826a49SYabin Cui }
132*01826a49SYabin Cui 
MEM_swap32(U32 in)133*01826a49SYabin Cui MEM_STATIC U32 MEM_swap32(U32 in)
134*01826a49SYabin Cui {
135*01826a49SYabin Cui #if defined(_MSC_VER)     /* Visual Studio */
136*01826a49SYabin Cui     return _byteswap_ulong(in);
137*01826a49SYabin Cui #elif defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)
138*01826a49SYabin Cui     return __builtin_bswap32(in);
139*01826a49SYabin Cui #else
140*01826a49SYabin Cui     return  ((in << 24) & 0xff000000 ) |
141*01826a49SYabin Cui             ((in <<  8) & 0x00ff0000 ) |
142*01826a49SYabin Cui             ((in >>  8) & 0x0000ff00 ) |
143*01826a49SYabin Cui             ((in >> 24) & 0x000000ff );
144*01826a49SYabin Cui #endif
145*01826a49SYabin Cui }
146*01826a49SYabin Cui 
MEM_swap64(U64 in)147*01826a49SYabin Cui MEM_STATIC U64 MEM_swap64(U64 in)
148*01826a49SYabin Cui {
149*01826a49SYabin Cui #if defined(_MSC_VER)     /* Visual Studio */
150*01826a49SYabin Cui     return _byteswap_uint64(in);
151*01826a49SYabin Cui #elif defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)
152*01826a49SYabin Cui     return __builtin_bswap64(in);
153*01826a49SYabin Cui #else
154*01826a49SYabin Cui     return  ((in << 56) & 0xff00000000000000ULL) |
155*01826a49SYabin Cui             ((in << 40) & 0x00ff000000000000ULL) |
156*01826a49SYabin Cui             ((in << 24) & 0x0000ff0000000000ULL) |
157*01826a49SYabin Cui             ((in << 8)  & 0x000000ff00000000ULL) |
158*01826a49SYabin Cui             ((in >> 8)  & 0x00000000ff000000ULL) |
159*01826a49SYabin Cui             ((in >> 24) & 0x0000000000ff0000ULL) |
160*01826a49SYabin Cui             ((in >> 40) & 0x000000000000ff00ULL) |
161*01826a49SYabin Cui             ((in >> 56) & 0x00000000000000ffULL);
162*01826a49SYabin Cui #endif
163*01826a49SYabin Cui }
164*01826a49SYabin Cui 
165*01826a49SYabin Cui 
166*01826a49SYabin Cui /*=== Little endian r/w ===*/
167*01826a49SYabin Cui 
MEM_readLE16(const void * memPtr)168*01826a49SYabin Cui MEM_STATIC U16 MEM_readLE16(const void* memPtr)
169*01826a49SYabin Cui {
170*01826a49SYabin Cui     if (MEM_isLittleEndian())
171*01826a49SYabin Cui         return MEM_read16(memPtr);
172*01826a49SYabin Cui     else {
173*01826a49SYabin Cui         const BYTE* p = (const BYTE*)memPtr;
174*01826a49SYabin Cui         return (U16)(p[0] + (p[1]<<8));
175*01826a49SYabin Cui     }
176*01826a49SYabin Cui }
177*01826a49SYabin Cui 
MEM_writeLE16(void * memPtr,U16 val)178*01826a49SYabin Cui MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val)
179*01826a49SYabin Cui {
180*01826a49SYabin Cui     if (MEM_isLittleEndian()) {
181*01826a49SYabin Cui         MEM_write16(memPtr, val);
182*01826a49SYabin Cui     } else {
183*01826a49SYabin Cui         BYTE* p = (BYTE*)memPtr;
184*01826a49SYabin Cui         p[0] = (BYTE)val;
185*01826a49SYabin Cui         p[1] = (BYTE)(val>>8);
186*01826a49SYabin Cui     }
187*01826a49SYabin Cui }
188*01826a49SYabin Cui 
MEM_readLE32(const void * memPtr)189*01826a49SYabin Cui MEM_STATIC U32 MEM_readLE32(const void* memPtr)
190*01826a49SYabin Cui {
191*01826a49SYabin Cui     if (MEM_isLittleEndian())
192*01826a49SYabin Cui         return MEM_read32(memPtr);
193*01826a49SYabin Cui     else
194*01826a49SYabin Cui         return MEM_swap32(MEM_read32(memPtr));
195*01826a49SYabin Cui }
196*01826a49SYabin Cui 
197*01826a49SYabin Cui 
MEM_readLE64(const void * memPtr)198*01826a49SYabin Cui MEM_STATIC U64 MEM_readLE64(const void* memPtr)
199*01826a49SYabin Cui {
200*01826a49SYabin Cui     if (MEM_isLittleEndian())
201*01826a49SYabin Cui         return MEM_read64(memPtr);
202*01826a49SYabin Cui     else
203*01826a49SYabin Cui         return MEM_swap64(MEM_read64(memPtr));
204*01826a49SYabin Cui }
205*01826a49SYabin Cui 
206*01826a49SYabin Cui 
MEM_readLEST(const void * memPtr)207*01826a49SYabin Cui MEM_STATIC size_t MEM_readLEST(const void* memPtr)
208*01826a49SYabin Cui {
209*01826a49SYabin Cui     if (MEM_32bits())
210*01826a49SYabin Cui         return (size_t)MEM_readLE32(memPtr);
211*01826a49SYabin Cui     else
212*01826a49SYabin Cui         return (size_t)MEM_readLE64(memPtr);
213*01826a49SYabin Cui }
214*01826a49SYabin Cui 
215*01826a49SYabin Cui 
216*01826a49SYabin Cui 
217*01826a49SYabin Cui #if defined (__cplusplus)
218*01826a49SYabin Cui }
219*01826a49SYabin Cui #endif
220*01826a49SYabin Cui 
221*01826a49SYabin Cui #endif /* MEM_H_MODULE */
222*01826a49SYabin Cui 
223*01826a49SYabin Cui /*
224*01826a49SYabin Cui     zstd - standard compression library
225*01826a49SYabin Cui     Header File for static linking only
226*01826a49SYabin Cui     Copyright (C) 2014-2016, Yann Collet.
227*01826a49SYabin Cui 
228*01826a49SYabin Cui     BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
229*01826a49SYabin Cui 
230*01826a49SYabin Cui     Redistribution and use in source and binary forms, with or without
231*01826a49SYabin Cui     modification, are permitted provided that the following conditions are
232*01826a49SYabin Cui     met:
233*01826a49SYabin Cui     * Redistributions of source code must retain the above copyright
234*01826a49SYabin Cui     notice, this list of conditions and the following disclaimer.
235*01826a49SYabin Cui     * Redistributions in binary form must reproduce the above
236*01826a49SYabin Cui     copyright notice, this list of conditions and the following disclaimer
237*01826a49SYabin Cui     in the documentation and/or other materials provided with the
238*01826a49SYabin Cui     distribution.
239*01826a49SYabin Cui     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
240*01826a49SYabin Cui     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
241*01826a49SYabin Cui     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
242*01826a49SYabin Cui     A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
243*01826a49SYabin Cui     OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
244*01826a49SYabin Cui     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
245*01826a49SYabin Cui     LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
246*01826a49SYabin Cui     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
247*01826a49SYabin Cui     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
248*01826a49SYabin Cui     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
249*01826a49SYabin Cui     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
250*01826a49SYabin Cui 
251*01826a49SYabin Cui     You can contact the author at :
252*01826a49SYabin Cui     - zstd homepage : https://facebook.github.io/zstd
253*01826a49SYabin Cui */
254*01826a49SYabin Cui #ifndef ZSTDv06_STATIC_H
255*01826a49SYabin Cui #define ZSTDv06_STATIC_H
256*01826a49SYabin Cui 
257*01826a49SYabin Cui /* The prototypes defined within this file are considered experimental.
258*01826a49SYabin Cui  * They should not be used in the context DLL as they may change in the future.
259*01826a49SYabin Cui  * Prefer static linking if you need them, to control breaking version changes issues.
260*01826a49SYabin Cui  */
261*01826a49SYabin Cui 
262*01826a49SYabin Cui #if defined (__cplusplus)
263*01826a49SYabin Cui extern "C" {
264*01826a49SYabin Cui #endif
265*01826a49SYabin Cui 
266*01826a49SYabin Cui 
267*01826a49SYabin Cui 
268*01826a49SYabin Cui /*- Advanced Decompression functions -*/
269*01826a49SYabin Cui 
270*01826a49SYabin Cui /*! ZSTDv06_decompress_usingPreparedDCtx() :
271*01826a49SYabin Cui *   Same as ZSTDv06_decompress_usingDict, but using a reference context `preparedDCtx`, where dictionary has been loaded.
272*01826a49SYabin Cui *   It avoids reloading the dictionary each time.
273*01826a49SYabin Cui *   `preparedDCtx` must have been properly initialized using ZSTDv06_decompressBegin_usingDict().
274*01826a49SYabin Cui *   Requires 2 contexts : 1 for reference (preparedDCtx), which will not be modified, and 1 to run the decompression operation (dctx) */
275*01826a49SYabin Cui ZSTDLIBv06_API size_t ZSTDv06_decompress_usingPreparedDCtx(
276*01826a49SYabin Cui                                            ZSTDv06_DCtx* dctx, const ZSTDv06_DCtx* preparedDCtx,
277*01826a49SYabin Cui                                            void* dst, size_t dstCapacity,
278*01826a49SYabin Cui                                      const void* src, size_t srcSize);
279*01826a49SYabin Cui 
280*01826a49SYabin Cui 
281*01826a49SYabin Cui 
282*01826a49SYabin Cui #define ZSTDv06_FRAMEHEADERSIZE_MAX 13    /* for static allocation */
283*01826a49SYabin Cui static const size_t ZSTDv06_frameHeaderSize_min = 5;
284*01826a49SYabin Cui static const size_t ZSTDv06_frameHeaderSize_max = ZSTDv06_FRAMEHEADERSIZE_MAX;
285*01826a49SYabin Cui 
286*01826a49SYabin Cui ZSTDLIBv06_API size_t ZSTDv06_decompressBegin(ZSTDv06_DCtx* dctx);
287*01826a49SYabin Cui 
288*01826a49SYabin Cui /*
289*01826a49SYabin Cui   Streaming decompression, direct mode (bufferless)
290*01826a49SYabin Cui 
291*01826a49SYabin Cui   A ZSTDv06_DCtx object is required to track streaming operations.
292*01826a49SYabin Cui   Use ZSTDv06_createDCtx() / ZSTDv06_freeDCtx() to manage it.
293*01826a49SYabin Cui   A ZSTDv06_DCtx object can be re-used multiple times.
294*01826a49SYabin Cui 
295*01826a49SYabin Cui   First optional operation is to retrieve frame parameters, using ZSTDv06_getFrameParams(), which doesn't consume the input.
296*01826a49SYabin Cui   It can provide the minimum size of rolling buffer required to properly decompress data,
297*01826a49SYabin Cui   and optionally the final size of uncompressed content.
298*01826a49SYabin Cui   (Note : content size is an optional info that may not be present. 0 means : content size unknown)
299*01826a49SYabin Cui   Frame parameters are extracted from the beginning of compressed frame.
300*01826a49SYabin Cui   The amount of data to read is variable, from ZSTDv06_frameHeaderSize_min to ZSTDv06_frameHeaderSize_max (so if `srcSize` >= ZSTDv06_frameHeaderSize_max, it will always work)
301*01826a49SYabin Cui   If `srcSize` is too small for operation to succeed, function will return the minimum size it requires to produce a result.
302*01826a49SYabin Cui   Result : 0 when successful, it means the ZSTDv06_frameParams structure has been filled.
303*01826a49SYabin Cui           >0 : means there is not enough data into `src`. Provides the expected size to successfully decode header.
304*01826a49SYabin Cui            errorCode, which can be tested using ZSTDv06_isError()
305*01826a49SYabin Cui 
306*01826a49SYabin Cui   Start decompression, with ZSTDv06_decompressBegin() or ZSTDv06_decompressBegin_usingDict().
307*01826a49SYabin Cui   Alternatively, you can copy a prepared context, using ZSTDv06_copyDCtx().
308*01826a49SYabin Cui 
309*01826a49SYabin Cui   Then use ZSTDv06_nextSrcSizeToDecompress() and ZSTDv06_decompressContinue() alternatively.
310*01826a49SYabin Cui   ZSTDv06_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTDv06_decompressContinue().
311*01826a49SYabin Cui   ZSTDv06_decompressContinue() requires this exact amount of bytes, or it will fail.
312*01826a49SYabin Cui   ZSTDv06_decompressContinue() needs previous data blocks during decompression, up to (1 << windowlog).
313*01826a49SYabin Cui   They should preferably be located contiguously, prior to current block. Alternatively, a round buffer is also possible.
314*01826a49SYabin Cui 
315*01826a49SYabin Cui   @result of ZSTDv06_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity)
316*01826a49SYabin Cui   It can be zero, which is not an error; it just means ZSTDv06_decompressContinue() has decoded some header.
317*01826a49SYabin Cui 
318*01826a49SYabin Cui   A frame is fully decoded when ZSTDv06_nextSrcSizeToDecompress() returns zero.
319*01826a49SYabin Cui   Context can then be reset to start a new decompression.
320*01826a49SYabin Cui */
321*01826a49SYabin Cui 
322*01826a49SYabin Cui 
323*01826a49SYabin Cui /* **************************************
324*01826a49SYabin Cui *  Block functions
325*01826a49SYabin Cui ****************************************/
326*01826a49SYabin Cui /*! Block functions produce and decode raw zstd blocks, without frame metadata.
327*01826a49SYabin Cui     User will have to take in charge required information to regenerate data, such as compressed and content sizes.
328*01826a49SYabin Cui 
329*01826a49SYabin Cui     A few rules to respect :
330*01826a49SYabin Cui     - Uncompressed block size must be <= ZSTDv06_BLOCKSIZE_MAX (128 KB)
331*01826a49SYabin Cui     - Compressing or decompressing requires a context structure
332*01826a49SYabin Cui       + Use ZSTDv06_createCCtx() and ZSTDv06_createDCtx()
333*01826a49SYabin Cui     - It is necessary to init context before starting
334*01826a49SYabin Cui       + compression : ZSTDv06_compressBegin()
335*01826a49SYabin Cui       + decompression : ZSTDv06_decompressBegin()
336*01826a49SYabin Cui       + variants _usingDict() are also allowed
337*01826a49SYabin Cui       + copyCCtx() and copyDCtx() work too
338*01826a49SYabin Cui     - When a block is considered not compressible enough, ZSTDv06_compressBlock() result will be zero.
339*01826a49SYabin Cui       In which case, nothing is produced into `dst`.
340*01826a49SYabin Cui       + User must test for such outcome and deal directly with uncompressed data
341*01826a49SYabin Cui       + ZSTDv06_decompressBlock() doesn't accept uncompressed data as input !!
342*01826a49SYabin Cui */
343*01826a49SYabin Cui 
344*01826a49SYabin Cui #define ZSTDv06_BLOCKSIZE_MAX (128 * 1024)   /* define, for static allocation */
345*01826a49SYabin Cui ZSTDLIBv06_API size_t ZSTDv06_decompressBlock(ZSTDv06_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
346*01826a49SYabin Cui 
347*01826a49SYabin Cui 
348*01826a49SYabin Cui 
349*01826a49SYabin Cui #if defined (__cplusplus)
350*01826a49SYabin Cui }
351*01826a49SYabin Cui #endif
352*01826a49SYabin Cui 
353*01826a49SYabin Cui #endif  /* ZSTDv06_STATIC_H */
354*01826a49SYabin Cui /*
355*01826a49SYabin Cui     zstd_internal - common functions to include
356*01826a49SYabin Cui     Header File for include
357*01826a49SYabin Cui     Copyright (C) 2014-2016, Yann Collet.
358*01826a49SYabin Cui 
359*01826a49SYabin Cui     BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
360*01826a49SYabin Cui 
361*01826a49SYabin Cui     Redistribution and use in source and binary forms, with or without
362*01826a49SYabin Cui     modification, are permitted provided that the following conditions are
363*01826a49SYabin Cui     met:
364*01826a49SYabin Cui     * Redistributions of source code must retain the above copyright
365*01826a49SYabin Cui     notice, this list of conditions and the following disclaimer.
366*01826a49SYabin Cui     * Redistributions in binary form must reproduce the above
367*01826a49SYabin Cui     copyright notice, this list of conditions and the following disclaimer
368*01826a49SYabin Cui     in the documentation and/or other materials provided with the
369*01826a49SYabin Cui     distribution.
370*01826a49SYabin Cui     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
371*01826a49SYabin Cui     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
372*01826a49SYabin Cui     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
373*01826a49SYabin Cui     A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
374*01826a49SYabin Cui     OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
375*01826a49SYabin Cui     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
376*01826a49SYabin Cui     LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
377*01826a49SYabin Cui     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
378*01826a49SYabin Cui     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
379*01826a49SYabin Cui     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
380*01826a49SYabin Cui     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
381*01826a49SYabin Cui 
382*01826a49SYabin Cui     You can contact the author at :
383*01826a49SYabin Cui     - zstd homepage : https://www.zstd.net
384*01826a49SYabin Cui */
385*01826a49SYabin Cui #ifndef ZSTDv06_CCOMMON_H_MODULE
386*01826a49SYabin Cui #define ZSTDv06_CCOMMON_H_MODULE
387*01826a49SYabin Cui 
388*01826a49SYabin Cui 
389*01826a49SYabin Cui /*-*************************************
390*01826a49SYabin Cui *  Common macros
391*01826a49SYabin Cui ***************************************/
392*01826a49SYabin Cui #define MIN(a,b) ((a)<(b) ? (a) : (b))
393*01826a49SYabin Cui #define MAX(a,b) ((a)>(b) ? (a) : (b))
394*01826a49SYabin Cui 
395*01826a49SYabin Cui 
396*01826a49SYabin Cui /*-*************************************
397*01826a49SYabin Cui *  Common constants
398*01826a49SYabin Cui ***************************************/
399*01826a49SYabin Cui #define ZSTDv06_DICT_MAGIC  0xEC30A436
400*01826a49SYabin Cui 
401*01826a49SYabin Cui #define ZSTDv06_REP_NUM    3
402*01826a49SYabin Cui #define ZSTDv06_REP_INIT   ZSTDv06_REP_NUM
403*01826a49SYabin Cui #define ZSTDv06_REP_MOVE   (ZSTDv06_REP_NUM-1)
404*01826a49SYabin Cui 
405*01826a49SYabin Cui #define KB *(1 <<10)
406*01826a49SYabin Cui #define MB *(1 <<20)
407*01826a49SYabin Cui #define GB *(1U<<30)
408*01826a49SYabin Cui 
409*01826a49SYabin Cui #define BIT7 128
410*01826a49SYabin Cui #define BIT6  64
411*01826a49SYabin Cui #define BIT5  32
412*01826a49SYabin Cui #define BIT4  16
413*01826a49SYabin Cui #define BIT1   2
414*01826a49SYabin Cui #define BIT0   1
415*01826a49SYabin Cui 
416*01826a49SYabin Cui #define ZSTDv06_WINDOWLOG_ABSOLUTEMIN 12
417*01826a49SYabin Cui static const size_t ZSTDv06_fcs_fieldSize[4] = { 0, 1, 2, 8 };
418*01826a49SYabin Cui 
419*01826a49SYabin Cui #define ZSTDv06_BLOCKHEADERSIZE 3   /* because C standard does not allow a static const value to be defined using another static const value .... :( */
420*01826a49SYabin Cui static const size_t ZSTDv06_blockHeaderSize = ZSTDv06_BLOCKHEADERSIZE;
421*01826a49SYabin Cui typedef enum { bt_compressed, bt_raw, bt_rle, bt_end } blockType_t;
422*01826a49SYabin Cui 
423*01826a49SYabin Cui #define MIN_SEQUENCES_SIZE 1 /* nbSeq==0 */
424*01826a49SYabin Cui #define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */ + MIN_SEQUENCES_SIZE /* nbSeq==0 */)   /* for a non-null block */
425*01826a49SYabin Cui 
426*01826a49SYabin Cui #define ZSTD_HUFFDTABLE_CAPACITY_LOG 12
427*01826a49SYabin Cui 
428*01826a49SYabin Cui #define IS_HUF 0
429*01826a49SYabin Cui #define IS_PCH 1
430*01826a49SYabin Cui #define IS_RAW 2
431*01826a49SYabin Cui #define IS_RLE 3
432*01826a49SYabin Cui 
433*01826a49SYabin Cui #define LONGNBSEQ 0x7F00
434*01826a49SYabin Cui 
435*01826a49SYabin Cui #define MINMATCH 3
436*01826a49SYabin Cui #define EQUAL_READ32 4
437*01826a49SYabin Cui #define REPCODE_STARTVALUE 1
438*01826a49SYabin Cui 
439*01826a49SYabin Cui #define Litbits  8
440*01826a49SYabin Cui #define MaxLit ((1<<Litbits) - 1)
441*01826a49SYabin Cui #define MaxML  52
442*01826a49SYabin Cui #define MaxLL  35
443*01826a49SYabin Cui #define MaxOff 28
444*01826a49SYabin Cui #define MaxSeq MAX(MaxLL, MaxML)   /* Assumption : MaxOff < MaxLL,MaxML */
445*01826a49SYabin Cui #define MLFSELog    9
446*01826a49SYabin Cui #define LLFSELog    9
447*01826a49SYabin Cui #define OffFSELog   8
448*01826a49SYabin Cui 
449*01826a49SYabin Cui #define FSEv06_ENCODING_RAW     0
450*01826a49SYabin Cui #define FSEv06_ENCODING_RLE     1
451*01826a49SYabin Cui #define FSEv06_ENCODING_STATIC  2
452*01826a49SYabin Cui #define FSEv06_ENCODING_DYNAMIC 3
453*01826a49SYabin Cui 
454*01826a49SYabin Cui #define ZSTD_CONTENTSIZE_ERROR   (0ULL - 2)
455*01826a49SYabin Cui 
456*01826a49SYabin Cui static const U32 LL_bits[MaxLL+1] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
457*01826a49SYabin Cui                                       1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9,10,11,12,
458*01826a49SYabin Cui                                      13,14,15,16 };
459*01826a49SYabin Cui static const S16 LL_defaultNorm[MaxLL+1] = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1,
460*01826a49SYabin Cui                                              2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1,
461*01826a49SYabin Cui                                             -1,-1,-1,-1 };
462*01826a49SYabin Cui static const U32 LL_defaultNormLog = 6;
463*01826a49SYabin Cui 
464*01826a49SYabin Cui static const U32 ML_bits[MaxML+1] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
465*01826a49SYabin Cui                                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
466*01826a49SYabin Cui                                       1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9,10,11,
467*01826a49SYabin Cui                                      12,13,14,15,16 };
468*01826a49SYabin Cui static const S16 ML_defaultNorm[MaxML+1] = { 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
469*01826a49SYabin Cui                                              1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
470*01826a49SYabin Cui                                              1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-1,-1,
471*01826a49SYabin Cui                                             -1,-1,-1,-1,-1 };
472*01826a49SYabin Cui static const U32 ML_defaultNormLog = 6;
473*01826a49SYabin Cui 
474*01826a49SYabin Cui static const S16 OF_defaultNorm[MaxOff+1] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
475*01826a49SYabin Cui                                               1, 1, 1, 1, 1, 1, 1, 1,-1,-1,-1,-1,-1 };
476*01826a49SYabin Cui static const U32 OF_defaultNormLog = 5;
477*01826a49SYabin Cui 
478*01826a49SYabin Cui 
479*01826a49SYabin Cui /*-*******************************************
480*01826a49SYabin Cui *  Shared functions to include for inlining
481*01826a49SYabin Cui *********************************************/
ZSTDv06_copy8(void * dst,const void * src)482*01826a49SYabin Cui static void ZSTDv06_copy8(void* dst, const void* src) { memcpy(dst, src, 8); }
483*01826a49SYabin Cui #define COPY8(d,s) { ZSTDv06_copy8(d,s); d+=8; s+=8; }
484*01826a49SYabin Cui 
485*01826a49SYabin Cui /*! ZSTDv06_wildcopy() :
486*01826a49SYabin Cui *   custom version of memcpy(), can copy up to 7 bytes too many (8 bytes if length==0) */
487*01826a49SYabin Cui #define WILDCOPY_OVERLENGTH 8
ZSTDv06_wildcopy(void * dst,const void * src,ptrdiff_t length)488*01826a49SYabin Cui MEM_STATIC void ZSTDv06_wildcopy(void* dst, const void* src, ptrdiff_t length)
489*01826a49SYabin Cui {
490*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
491*01826a49SYabin Cui     BYTE* op = (BYTE*)dst;
492*01826a49SYabin Cui     BYTE* const oend = op + length;
493*01826a49SYabin Cui     do
494*01826a49SYabin Cui         COPY8(op, ip)
495*01826a49SYabin Cui     while (op < oend);
496*01826a49SYabin Cui }
497*01826a49SYabin Cui 
498*01826a49SYabin Cui 
499*01826a49SYabin Cui 
500*01826a49SYabin Cui /*-*******************************************
501*01826a49SYabin Cui *  Private interfaces
502*01826a49SYabin Cui *********************************************/
503*01826a49SYabin Cui typedef struct {
504*01826a49SYabin Cui     U32 off;
505*01826a49SYabin Cui     U32 len;
506*01826a49SYabin Cui } ZSTDv06_match_t;
507*01826a49SYabin Cui 
508*01826a49SYabin Cui typedef struct {
509*01826a49SYabin Cui     U32 price;
510*01826a49SYabin Cui     U32 off;
511*01826a49SYabin Cui     U32 mlen;
512*01826a49SYabin Cui     U32 litlen;
513*01826a49SYabin Cui     U32 rep[ZSTDv06_REP_INIT];
514*01826a49SYabin Cui } ZSTDv06_optimal_t;
515*01826a49SYabin Cui 
516*01826a49SYabin Cui typedef struct { U32  unused; } ZSTDv06_stats_t;
517*01826a49SYabin Cui 
518*01826a49SYabin Cui typedef struct {
519*01826a49SYabin Cui     void* buffer;
520*01826a49SYabin Cui     U32*  offsetStart;
521*01826a49SYabin Cui     U32*  offset;
522*01826a49SYabin Cui     BYTE* offCodeStart;
523*01826a49SYabin Cui     BYTE* litStart;
524*01826a49SYabin Cui     BYTE* lit;
525*01826a49SYabin Cui     U16*  litLengthStart;
526*01826a49SYabin Cui     U16*  litLength;
527*01826a49SYabin Cui     BYTE* llCodeStart;
528*01826a49SYabin Cui     U16*  matchLengthStart;
529*01826a49SYabin Cui     U16*  matchLength;
530*01826a49SYabin Cui     BYTE* mlCodeStart;
531*01826a49SYabin Cui     U32   longLengthID;   /* 0 == no longLength; 1 == Lit.longLength; 2 == Match.longLength; */
532*01826a49SYabin Cui     U32   longLengthPos;
533*01826a49SYabin Cui     /* opt */
534*01826a49SYabin Cui     ZSTDv06_optimal_t* priceTable;
535*01826a49SYabin Cui     ZSTDv06_match_t* matchTable;
536*01826a49SYabin Cui     U32* matchLengthFreq;
537*01826a49SYabin Cui     U32* litLengthFreq;
538*01826a49SYabin Cui     U32* litFreq;
539*01826a49SYabin Cui     U32* offCodeFreq;
540*01826a49SYabin Cui     U32  matchLengthSum;
541*01826a49SYabin Cui     U32  matchSum;
542*01826a49SYabin Cui     U32  litLengthSum;
543*01826a49SYabin Cui     U32  litSum;
544*01826a49SYabin Cui     U32  offCodeSum;
545*01826a49SYabin Cui     U32  log2matchLengthSum;
546*01826a49SYabin Cui     U32  log2matchSum;
547*01826a49SYabin Cui     U32  log2litLengthSum;
548*01826a49SYabin Cui     U32  log2litSum;
549*01826a49SYabin Cui     U32  log2offCodeSum;
550*01826a49SYabin Cui     U32  factor;
551*01826a49SYabin Cui     U32  cachedPrice;
552*01826a49SYabin Cui     U32  cachedLitLength;
553*01826a49SYabin Cui     const BYTE* cachedLiterals;
554*01826a49SYabin Cui     ZSTDv06_stats_t stats;
555*01826a49SYabin Cui } seqStore_t;
556*01826a49SYabin Cui 
557*01826a49SYabin Cui void ZSTDv06_seqToCodes(const seqStore_t* seqStorePtr, size_t const nbSeq);
558*01826a49SYabin Cui 
559*01826a49SYabin Cui 
560*01826a49SYabin Cui #endif   /* ZSTDv06_CCOMMON_H_MODULE */
561*01826a49SYabin Cui /* ******************************************************************
562*01826a49SYabin Cui    FSE : Finite State Entropy codec
563*01826a49SYabin Cui    Public Prototypes declaration
564*01826a49SYabin Cui    Copyright (C) 2013-2016, Yann Collet.
565*01826a49SYabin Cui 
566*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
567*01826a49SYabin Cui 
568*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
569*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
570*01826a49SYabin Cui    met:
571*01826a49SYabin Cui 
572*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
573*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
574*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
575*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
576*01826a49SYabin Cui    in the documentation and/or other materials provided with the
577*01826a49SYabin Cui    distribution.
578*01826a49SYabin Cui 
579*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
580*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
581*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
582*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
583*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
584*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
585*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
586*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
587*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
588*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
589*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
590*01826a49SYabin Cui 
591*01826a49SYabin Cui    You can contact the author at :
592*01826a49SYabin Cui    - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
593*01826a49SYabin Cui ****************************************************************** */
594*01826a49SYabin Cui #ifndef FSEv06_H
595*01826a49SYabin Cui #define FSEv06_H
596*01826a49SYabin Cui 
597*01826a49SYabin Cui #if defined (__cplusplus)
598*01826a49SYabin Cui extern "C" {
599*01826a49SYabin Cui #endif
600*01826a49SYabin Cui 
601*01826a49SYabin Cui 
602*01826a49SYabin Cui 
603*01826a49SYabin Cui /*-****************************************
604*01826a49SYabin Cui *  FSE simple functions
605*01826a49SYabin Cui ******************************************/
606*01826a49SYabin Cui /*! FSEv06_decompress():
607*01826a49SYabin Cui     Decompress FSE data from buffer 'cSrc', of size 'cSrcSize',
608*01826a49SYabin Cui     into already allocated destination buffer 'dst', of size 'dstCapacity'.
609*01826a49SYabin Cui     @return : size of regenerated data (<= maxDstSize),
610*01826a49SYabin Cui               or an error code, which can be tested using FSEv06_isError() .
611*01826a49SYabin Cui 
612*01826a49SYabin Cui     ** Important ** : FSEv06_decompress() does not decompress non-compressible nor RLE data !!!
613*01826a49SYabin Cui     Why ? : making this distinction requires a header.
614*01826a49SYabin Cui     Header management is intentionally delegated to the user layer, which can better manage special cases.
615*01826a49SYabin Cui */
616*01826a49SYabin Cui size_t FSEv06_decompress(void* dst,  size_t dstCapacity,
617*01826a49SYabin Cui                 const void* cSrc, size_t cSrcSize);
618*01826a49SYabin Cui 
619*01826a49SYabin Cui 
620*01826a49SYabin Cui /*-*****************************************
621*01826a49SYabin Cui *  Tool functions
622*01826a49SYabin Cui ******************************************/
623*01826a49SYabin Cui size_t FSEv06_compressBound(size_t size);       /* maximum compressed size */
624*01826a49SYabin Cui 
625*01826a49SYabin Cui /* Error Management */
626*01826a49SYabin Cui unsigned    FSEv06_isError(size_t code);        /* tells if a return value is an error code */
627*01826a49SYabin Cui const char* FSEv06_getErrorName(size_t code);   /* provides error code string (useful for debugging) */
628*01826a49SYabin Cui 
629*01826a49SYabin Cui 
630*01826a49SYabin Cui 
631*01826a49SYabin Cui /*-*****************************************
632*01826a49SYabin Cui *  FSE detailed API
633*01826a49SYabin Cui ******************************************/
634*01826a49SYabin Cui /*!
635*01826a49SYabin Cui 
636*01826a49SYabin Cui FSEv06_decompress() does the following:
637*01826a49SYabin Cui 1. read normalized counters with readNCount()
638*01826a49SYabin Cui 2. build decoding table 'DTable' from normalized counters
639*01826a49SYabin Cui 3. decode the data stream using decoding table 'DTable'
640*01826a49SYabin Cui 
641*01826a49SYabin Cui The following API allows targeting specific sub-functions for advanced tasks.
642*01826a49SYabin Cui For example, it's possible to compress several blocks using the same 'CTable',
643*01826a49SYabin Cui or to save and provide normalized distribution using external method.
644*01826a49SYabin Cui */
645*01826a49SYabin Cui 
646*01826a49SYabin Cui 
647*01826a49SYabin Cui /* *** DECOMPRESSION *** */
648*01826a49SYabin Cui 
649*01826a49SYabin Cui /*! FSEv06_readNCount():
650*01826a49SYabin Cui     Read compactly saved 'normalizedCounter' from 'rBuffer'.
651*01826a49SYabin Cui     @return : size read from 'rBuffer',
652*01826a49SYabin Cui               or an errorCode, which can be tested using FSEv06_isError().
653*01826a49SYabin Cui               maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */
654*01826a49SYabin Cui size_t FSEv06_readNCount (short* normalizedCounter, unsigned* maxSymbolValuePtr, unsigned* tableLogPtr, const void* rBuffer, size_t rBuffSize);
655*01826a49SYabin Cui 
656*01826a49SYabin Cui /*! Constructor and Destructor of FSEv06_DTable.
657*01826a49SYabin Cui     Note that its size depends on 'tableLog' */
658*01826a49SYabin Cui typedef unsigned FSEv06_DTable;   /* don't allocate that. It's just a way to be more restrictive than void* */
659*01826a49SYabin Cui FSEv06_DTable* FSEv06_createDTable(unsigned tableLog);
660*01826a49SYabin Cui void        FSEv06_freeDTable(FSEv06_DTable* dt);
661*01826a49SYabin Cui 
662*01826a49SYabin Cui /*! FSEv06_buildDTable():
663*01826a49SYabin Cui     Builds 'dt', which must be already allocated, using FSEv06_createDTable().
664*01826a49SYabin Cui     return : 0, or an errorCode, which can be tested using FSEv06_isError() */
665*01826a49SYabin Cui size_t FSEv06_buildDTable (FSEv06_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
666*01826a49SYabin Cui 
667*01826a49SYabin Cui /*! FSEv06_decompress_usingDTable():
668*01826a49SYabin Cui     Decompress compressed source `cSrc` of size `cSrcSize` using `dt`
669*01826a49SYabin Cui     into `dst` which must be already allocated.
670*01826a49SYabin Cui     @return : size of regenerated data (necessarily <= `dstCapacity`),
671*01826a49SYabin Cui               or an errorCode, which can be tested using FSEv06_isError() */
672*01826a49SYabin Cui size_t FSEv06_decompress_usingDTable(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, const FSEv06_DTable* dt);
673*01826a49SYabin Cui 
674*01826a49SYabin Cui /*!
675*01826a49SYabin Cui Tutorial :
676*01826a49SYabin Cui ----------
677*01826a49SYabin Cui (Note : these functions only decompress FSE-compressed blocks.
678*01826a49SYabin Cui  If block is uncompressed, use memcpy() instead
679*01826a49SYabin Cui  If block is a single repeated byte, use memset() instead )
680*01826a49SYabin Cui 
681*01826a49SYabin Cui The first step is to obtain the normalized frequencies of symbols.
682*01826a49SYabin Cui This can be performed by FSEv06_readNCount() if it was saved using FSEv06_writeNCount().
683*01826a49SYabin Cui 'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short.
684*01826a49SYabin Cui In practice, that means it's necessary to know 'maxSymbolValue' beforehand,
685*01826a49SYabin Cui or size the table to handle worst case situations (typically 256).
686*01826a49SYabin Cui FSEv06_readNCount() will provide 'tableLog' and 'maxSymbolValue'.
687*01826a49SYabin Cui The result of FSEv06_readNCount() is the number of bytes read from 'rBuffer'.
688*01826a49SYabin Cui Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that.
689*01826a49SYabin Cui If there is an error, the function will return an error code, which can be tested using FSEv06_isError().
690*01826a49SYabin Cui 
691*01826a49SYabin Cui The next step is to build the decompression tables 'FSEv06_DTable' from 'normalizedCounter'.
692*01826a49SYabin Cui This is performed by the function FSEv06_buildDTable().
693*01826a49SYabin Cui The space required by 'FSEv06_DTable' must be already allocated using FSEv06_createDTable().
694*01826a49SYabin Cui If there is an error, the function will return an error code, which can be tested using FSEv06_isError().
695*01826a49SYabin Cui 
696*01826a49SYabin Cui `FSEv06_DTable` can then be used to decompress `cSrc`, with FSEv06_decompress_usingDTable().
697*01826a49SYabin Cui `cSrcSize` must be strictly correct, otherwise decompression will fail.
698*01826a49SYabin Cui FSEv06_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`).
699*01826a49SYabin Cui If there is an error, the function will return an error code, which can be tested using FSEv06_isError(). (ex: dst buffer too small)
700*01826a49SYabin Cui */
701*01826a49SYabin Cui 
702*01826a49SYabin Cui 
703*01826a49SYabin Cui #if defined (__cplusplus)
704*01826a49SYabin Cui }
705*01826a49SYabin Cui #endif
706*01826a49SYabin Cui 
707*01826a49SYabin Cui #endif  /* FSEv06_H */
708*01826a49SYabin Cui /* ******************************************************************
709*01826a49SYabin Cui    bitstream
710*01826a49SYabin Cui    Part of FSE library
711*01826a49SYabin Cui    header file (to include)
712*01826a49SYabin Cui    Copyright (C) 2013-2016, Yann Collet.
713*01826a49SYabin Cui 
714*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
715*01826a49SYabin Cui 
716*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
717*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
718*01826a49SYabin Cui    met:
719*01826a49SYabin Cui 
720*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
721*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
722*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
723*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
724*01826a49SYabin Cui    in the documentation and/or other materials provided with the
725*01826a49SYabin Cui    distribution.
726*01826a49SYabin Cui 
727*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
728*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
729*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
730*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
731*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
732*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
733*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
734*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
735*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
736*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
737*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
738*01826a49SYabin Cui 
739*01826a49SYabin Cui    You can contact the author at :
740*01826a49SYabin Cui    - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
741*01826a49SYabin Cui ****************************************************************** */
742*01826a49SYabin Cui #ifndef BITSTREAM_H_MODULE
743*01826a49SYabin Cui #define BITSTREAM_H_MODULE
744*01826a49SYabin Cui 
745*01826a49SYabin Cui #if defined (__cplusplus)
746*01826a49SYabin Cui extern "C" {
747*01826a49SYabin Cui #endif
748*01826a49SYabin Cui 
749*01826a49SYabin Cui 
750*01826a49SYabin Cui /*
751*01826a49SYabin Cui *  This API consists of small unitary functions, which must be inlined for best performance.
752*01826a49SYabin Cui *  Since link-time-optimization is not available for all compilers,
753*01826a49SYabin Cui *  these functions are defined into a .h to be included.
754*01826a49SYabin Cui */
755*01826a49SYabin Cui 
756*01826a49SYabin Cui 
757*01826a49SYabin Cui /*=========================================
758*01826a49SYabin Cui *  Target specific
759*01826a49SYabin Cui =========================================*/
760*01826a49SYabin Cui #if defined(__BMI__) && defined(__GNUC__)
761*01826a49SYabin Cui #  include <immintrin.h>   /* support for bextr (experimental) */
762*01826a49SYabin Cui #endif
763*01826a49SYabin Cui 
764*01826a49SYabin Cui 
765*01826a49SYabin Cui 
766*01826a49SYabin Cui /*-********************************************
767*01826a49SYabin Cui *  bitStream decoding API (read backward)
768*01826a49SYabin Cui **********************************************/
769*01826a49SYabin Cui typedef struct
770*01826a49SYabin Cui {
771*01826a49SYabin Cui     size_t   bitContainer;
772*01826a49SYabin Cui     unsigned bitsConsumed;
773*01826a49SYabin Cui     const char* ptr;
774*01826a49SYabin Cui     const char* start;
775*01826a49SYabin Cui } BITv06_DStream_t;
776*01826a49SYabin Cui 
777*01826a49SYabin Cui typedef enum { BITv06_DStream_unfinished = 0,
778*01826a49SYabin Cui                BITv06_DStream_endOfBuffer = 1,
779*01826a49SYabin Cui                BITv06_DStream_completed = 2,
780*01826a49SYabin Cui                BITv06_DStream_overflow = 3 } BITv06_DStream_status;  /* result of BITv06_reloadDStream() */
781*01826a49SYabin Cui                /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */
782*01826a49SYabin Cui 
783*01826a49SYabin Cui MEM_STATIC size_t   BITv06_initDStream(BITv06_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
784*01826a49SYabin Cui MEM_STATIC size_t   BITv06_readBits(BITv06_DStream_t* bitD, unsigned nbBits);
785*01826a49SYabin Cui MEM_STATIC BITv06_DStream_status BITv06_reloadDStream(BITv06_DStream_t* bitD);
786*01826a49SYabin Cui MEM_STATIC unsigned BITv06_endOfDStream(const BITv06_DStream_t* bitD);
787*01826a49SYabin Cui 
788*01826a49SYabin Cui 
789*01826a49SYabin Cui 
790*01826a49SYabin Cui /*-****************************************
791*01826a49SYabin Cui *  unsafe API
792*01826a49SYabin Cui ******************************************/
793*01826a49SYabin Cui MEM_STATIC size_t BITv06_readBitsFast(BITv06_DStream_t* bitD, unsigned nbBits);
794*01826a49SYabin Cui /* faster, but works only if nbBits >= 1 */
795*01826a49SYabin Cui 
796*01826a49SYabin Cui 
797*01826a49SYabin Cui 
798*01826a49SYabin Cui /*-**************************************************************
799*01826a49SYabin Cui *  Internal functions
800*01826a49SYabin Cui ****************************************************************/
BITv06_highbit32(U32 val)801*01826a49SYabin Cui MEM_STATIC unsigned BITv06_highbit32 ( U32 val)
802*01826a49SYabin Cui {
803*01826a49SYabin Cui #   if defined(_MSC_VER)   /* Visual */
804*01826a49SYabin Cui     unsigned long r;
805*01826a49SYabin Cui     return _BitScanReverse(&r, val) ? (unsigned)r : 0;
806*01826a49SYabin Cui #   elif defined(__GNUC__) && (__GNUC__ >= 3)   /* Use GCC Intrinsic */
807*01826a49SYabin Cui     return __builtin_clz (val) ^ 31;
808*01826a49SYabin Cui #   else   /* Software version */
809*01826a49SYabin Cui     static const unsigned DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 };
810*01826a49SYabin Cui     U32 v = val;
811*01826a49SYabin Cui     unsigned r;
812*01826a49SYabin Cui     v |= v >> 1;
813*01826a49SYabin Cui     v |= v >> 2;
814*01826a49SYabin Cui     v |= v >> 4;
815*01826a49SYabin Cui     v |= v >> 8;
816*01826a49SYabin Cui     v |= v >> 16;
817*01826a49SYabin Cui     r = DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
818*01826a49SYabin Cui     return r;
819*01826a49SYabin Cui #   endif
820*01826a49SYabin Cui }
821*01826a49SYabin Cui 
822*01826a49SYabin Cui 
823*01826a49SYabin Cui 
824*01826a49SYabin Cui /*-********************************************************
825*01826a49SYabin Cui * bitStream decoding
826*01826a49SYabin Cui **********************************************************/
827*01826a49SYabin Cui /*! BITv06_initDStream() :
828*01826a49SYabin Cui *   Initialize a BITv06_DStream_t.
829*01826a49SYabin Cui *   `bitD` : a pointer to an already allocated BITv06_DStream_t structure.
830*01826a49SYabin Cui *   `srcSize` must be the *exact* size of the bitStream, in bytes.
831*01826a49SYabin Cui *   @return : size of stream (== srcSize) or an errorCode if a problem is detected
832*01826a49SYabin Cui */
BITv06_initDStream(BITv06_DStream_t * bitD,const void * srcBuffer,size_t srcSize)833*01826a49SYabin Cui MEM_STATIC size_t BITv06_initDStream(BITv06_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
834*01826a49SYabin Cui {
835*01826a49SYabin Cui     if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }
836*01826a49SYabin Cui 
837*01826a49SYabin Cui     if (srcSize >=  sizeof(bitD->bitContainer)) {  /* normal case */
838*01826a49SYabin Cui         bitD->start = (const char*)srcBuffer;
839*01826a49SYabin Cui         bitD->ptr   = (const char*)srcBuffer + srcSize - sizeof(bitD->bitContainer);
840*01826a49SYabin Cui         bitD->bitContainer = MEM_readLEST(bitD->ptr);
841*01826a49SYabin Cui         { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
842*01826a49SYabin Cui           if (lastByte == 0) return ERROR(GENERIC);   /* endMark not present */
843*01826a49SYabin Cui           bitD->bitsConsumed = 8 - BITv06_highbit32(lastByte); }
844*01826a49SYabin Cui     } else {
845*01826a49SYabin Cui         bitD->start = (const char*)srcBuffer;
846*01826a49SYabin Cui         bitD->ptr   = bitD->start;
847*01826a49SYabin Cui         bitD->bitContainer = *(const BYTE*)(bitD->start);
848*01826a49SYabin Cui         switch(srcSize)
849*01826a49SYabin Cui         {
850*01826a49SYabin Cui             case 7: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16);/* fall-through */
851*01826a49SYabin Cui             case 6: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24);/* fall-through */
852*01826a49SYabin Cui             case 5: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32);/* fall-through */
853*01826a49SYabin Cui             case 4: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[3]) << 24; /* fall-through */
854*01826a49SYabin Cui             case 3: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[2]) << 16; /* fall-through */
855*01826a49SYabin Cui             case 2: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[1]) <<  8; /* fall-through */
856*01826a49SYabin Cui             default: break;
857*01826a49SYabin Cui         }
858*01826a49SYabin Cui         { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
859*01826a49SYabin Cui           if (lastByte == 0) return ERROR(GENERIC);   /* endMark not present */
860*01826a49SYabin Cui           bitD->bitsConsumed = 8 - BITv06_highbit32(lastByte); }
861*01826a49SYabin Cui         bitD->bitsConsumed += (U32)(sizeof(bitD->bitContainer) - srcSize)*8;
862*01826a49SYabin Cui     }
863*01826a49SYabin Cui 
864*01826a49SYabin Cui     return srcSize;
865*01826a49SYabin Cui }
866*01826a49SYabin Cui 
867*01826a49SYabin Cui 
BITv06_lookBits(const BITv06_DStream_t * bitD,U32 nbBits)868*01826a49SYabin Cui  MEM_STATIC size_t BITv06_lookBits(const BITv06_DStream_t* bitD, U32 nbBits)
869*01826a49SYabin Cui {
870*01826a49SYabin Cui     U32 const bitMask = sizeof(bitD->bitContainer)*8 - 1;
871*01826a49SYabin Cui     return ((bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> 1) >> ((bitMask-nbBits) & bitMask);
872*01826a49SYabin Cui }
873*01826a49SYabin Cui 
874*01826a49SYabin Cui /*! BITv06_lookBitsFast() :
875*01826a49SYabin Cui *   unsafe version; only works if nbBits >= 1 */
BITv06_lookBitsFast(const BITv06_DStream_t * bitD,U32 nbBits)876*01826a49SYabin Cui MEM_STATIC size_t BITv06_lookBitsFast(const BITv06_DStream_t* bitD, U32 nbBits)
877*01826a49SYabin Cui {
878*01826a49SYabin Cui     U32 const bitMask = sizeof(bitD->bitContainer)*8 - 1;
879*01826a49SYabin Cui     return (bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> (((bitMask+1)-nbBits) & bitMask);
880*01826a49SYabin Cui }
881*01826a49SYabin Cui 
BITv06_skipBits(BITv06_DStream_t * bitD,U32 nbBits)882*01826a49SYabin Cui MEM_STATIC void BITv06_skipBits(BITv06_DStream_t* bitD, U32 nbBits)
883*01826a49SYabin Cui {
884*01826a49SYabin Cui     bitD->bitsConsumed += nbBits;
885*01826a49SYabin Cui }
886*01826a49SYabin Cui 
BITv06_readBits(BITv06_DStream_t * bitD,U32 nbBits)887*01826a49SYabin Cui MEM_STATIC size_t BITv06_readBits(BITv06_DStream_t* bitD, U32 nbBits)
888*01826a49SYabin Cui {
889*01826a49SYabin Cui     size_t const value = BITv06_lookBits(bitD, nbBits);
890*01826a49SYabin Cui     BITv06_skipBits(bitD, nbBits);
891*01826a49SYabin Cui     return value;
892*01826a49SYabin Cui }
893*01826a49SYabin Cui 
894*01826a49SYabin Cui /*! BITv06_readBitsFast() :
895*01826a49SYabin Cui *   unsafe version; only works if nbBits >= 1 */
BITv06_readBitsFast(BITv06_DStream_t * bitD,U32 nbBits)896*01826a49SYabin Cui MEM_STATIC size_t BITv06_readBitsFast(BITv06_DStream_t* bitD, U32 nbBits)
897*01826a49SYabin Cui {
898*01826a49SYabin Cui     size_t const value = BITv06_lookBitsFast(bitD, nbBits);
899*01826a49SYabin Cui     BITv06_skipBits(bitD, nbBits);
900*01826a49SYabin Cui     return value;
901*01826a49SYabin Cui }
902*01826a49SYabin Cui 
BITv06_reloadDStream(BITv06_DStream_t * bitD)903*01826a49SYabin Cui MEM_STATIC BITv06_DStream_status BITv06_reloadDStream(BITv06_DStream_t* bitD)
904*01826a49SYabin Cui {
905*01826a49SYabin Cui     if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8))  /* should never happen */
906*01826a49SYabin Cui         return BITv06_DStream_overflow;
907*01826a49SYabin Cui 
908*01826a49SYabin Cui     if (bitD->ptr >= bitD->start + sizeof(bitD->bitContainer)) {
909*01826a49SYabin Cui         bitD->ptr -= bitD->bitsConsumed >> 3;
910*01826a49SYabin Cui         bitD->bitsConsumed &= 7;
911*01826a49SYabin Cui         bitD->bitContainer = MEM_readLEST(bitD->ptr);
912*01826a49SYabin Cui         return BITv06_DStream_unfinished;
913*01826a49SYabin Cui     }
914*01826a49SYabin Cui     if (bitD->ptr == bitD->start) {
915*01826a49SYabin Cui         if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BITv06_DStream_endOfBuffer;
916*01826a49SYabin Cui         return BITv06_DStream_completed;
917*01826a49SYabin Cui     }
918*01826a49SYabin Cui     {   U32 nbBytes = bitD->bitsConsumed >> 3;
919*01826a49SYabin Cui         BITv06_DStream_status result = BITv06_DStream_unfinished;
920*01826a49SYabin Cui         if (bitD->ptr - nbBytes < bitD->start) {
921*01826a49SYabin Cui             nbBytes = (U32)(bitD->ptr - bitD->start);  /* ptr > start */
922*01826a49SYabin Cui             result = BITv06_DStream_endOfBuffer;
923*01826a49SYabin Cui         }
924*01826a49SYabin Cui         bitD->ptr -= nbBytes;
925*01826a49SYabin Cui         bitD->bitsConsumed -= nbBytes*8;
926*01826a49SYabin Cui         bitD->bitContainer = MEM_readLEST(bitD->ptr);   /* reminder : srcSize > sizeof(bitD) */
927*01826a49SYabin Cui         return result;
928*01826a49SYabin Cui     }
929*01826a49SYabin Cui }
930*01826a49SYabin Cui 
931*01826a49SYabin Cui /*! BITv06_endOfDStream() :
932*01826a49SYabin Cui *   @return Tells if DStream has exactly reached its end (all bits consumed).
933*01826a49SYabin Cui */
BITv06_endOfDStream(const BITv06_DStream_t * DStream)934*01826a49SYabin Cui MEM_STATIC unsigned BITv06_endOfDStream(const BITv06_DStream_t* DStream)
935*01826a49SYabin Cui {
936*01826a49SYabin Cui     return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
937*01826a49SYabin Cui }
938*01826a49SYabin Cui 
939*01826a49SYabin Cui #if defined (__cplusplus)
940*01826a49SYabin Cui }
941*01826a49SYabin Cui #endif
942*01826a49SYabin Cui 
943*01826a49SYabin Cui #endif /* BITSTREAM_H_MODULE */
944*01826a49SYabin Cui /* ******************************************************************
945*01826a49SYabin Cui    FSE : Finite State Entropy coder
946*01826a49SYabin Cui    header file for static linking (only)
947*01826a49SYabin Cui    Copyright (C) 2013-2015, Yann Collet
948*01826a49SYabin Cui 
949*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
950*01826a49SYabin Cui 
951*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
952*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
953*01826a49SYabin Cui    met:
954*01826a49SYabin Cui 
955*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
956*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
957*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
958*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
959*01826a49SYabin Cui    in the documentation and/or other materials provided with the
960*01826a49SYabin Cui    distribution.
961*01826a49SYabin Cui 
962*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
963*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
964*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
965*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
966*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
967*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
968*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
969*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
970*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
971*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
972*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
973*01826a49SYabin Cui 
974*01826a49SYabin Cui    You can contact the author at :
975*01826a49SYabin Cui    - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
976*01826a49SYabin Cui    - Public forum : https://groups.google.com/forum/#!forum/lz4c
977*01826a49SYabin Cui ****************************************************************** */
978*01826a49SYabin Cui #ifndef FSEv06_STATIC_H
979*01826a49SYabin Cui #define FSEv06_STATIC_H
980*01826a49SYabin Cui 
981*01826a49SYabin Cui #if defined (__cplusplus)
982*01826a49SYabin Cui extern "C" {
983*01826a49SYabin Cui #endif
984*01826a49SYabin Cui 
985*01826a49SYabin Cui 
986*01826a49SYabin Cui /* *****************************************
987*01826a49SYabin Cui *  Static allocation
988*01826a49SYabin Cui *******************************************/
989*01826a49SYabin Cui /* FSE buffer bounds */
990*01826a49SYabin Cui #define FSEv06_NCOUNTBOUND 512
991*01826a49SYabin Cui #define FSEv06_BLOCKBOUND(size) (size + (size>>7))
992*01826a49SYabin Cui #define FSEv06_COMPRESSBOUND(size) (FSEv06_NCOUNTBOUND + FSEv06_BLOCKBOUND(size))   /* Macro version, useful for static allocation */
993*01826a49SYabin Cui 
994*01826a49SYabin Cui /* It is possible to statically allocate FSE CTable/DTable as a table of unsigned using below macros */
995*01826a49SYabin Cui #define FSEv06_DTABLE_SIZE_U32(maxTableLog)                   (1 + (1<<maxTableLog))
996*01826a49SYabin Cui 
997*01826a49SYabin Cui 
998*01826a49SYabin Cui /* *****************************************
999*01826a49SYabin Cui *  FSE advanced API
1000*01826a49SYabin Cui *******************************************/
1001*01826a49SYabin Cui size_t FSEv06_countFast(unsigned* count, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize);
1002*01826a49SYabin Cui /* same as FSEv06_count(), but blindly trusts that all byte values within src are <= *maxSymbolValuePtr  */
1003*01826a49SYabin Cui 
1004*01826a49SYabin Cui size_t FSEv06_buildDTable_raw (FSEv06_DTable* dt, unsigned nbBits);
1005*01826a49SYabin Cui /* build a fake FSEv06_DTable, designed to read an uncompressed bitstream where each symbol uses nbBits */
1006*01826a49SYabin Cui 
1007*01826a49SYabin Cui size_t FSEv06_buildDTable_rle (FSEv06_DTable* dt, unsigned char symbolValue);
1008*01826a49SYabin Cui /* build a fake FSEv06_DTable, designed to always generate the same symbolValue */
1009*01826a49SYabin Cui 
1010*01826a49SYabin Cui 
1011*01826a49SYabin Cui /* *****************************************
1012*01826a49SYabin Cui *  FSE symbol decompression API
1013*01826a49SYabin Cui *******************************************/
1014*01826a49SYabin Cui typedef struct
1015*01826a49SYabin Cui {
1016*01826a49SYabin Cui     size_t      state;
1017*01826a49SYabin Cui     const void* table;   /* precise table may vary, depending on U16 */
1018*01826a49SYabin Cui } FSEv06_DState_t;
1019*01826a49SYabin Cui 
1020*01826a49SYabin Cui 
1021*01826a49SYabin Cui static void     FSEv06_initDState(FSEv06_DState_t* DStatePtr, BITv06_DStream_t* bitD, const FSEv06_DTable* dt);
1022*01826a49SYabin Cui 
1023*01826a49SYabin Cui static unsigned char FSEv06_decodeSymbol(FSEv06_DState_t* DStatePtr, BITv06_DStream_t* bitD);
1024*01826a49SYabin Cui 
1025*01826a49SYabin Cui 
1026*01826a49SYabin Cui /* *****************************************
1027*01826a49SYabin Cui *  FSE unsafe API
1028*01826a49SYabin Cui *******************************************/
1029*01826a49SYabin Cui static unsigned char FSEv06_decodeSymbolFast(FSEv06_DState_t* DStatePtr, BITv06_DStream_t* bitD);
1030*01826a49SYabin Cui /* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */
1031*01826a49SYabin Cui 
1032*01826a49SYabin Cui 
1033*01826a49SYabin Cui /* *****************************************
1034*01826a49SYabin Cui *  Implementation of inlined functions
1035*01826a49SYabin Cui *******************************************/
1036*01826a49SYabin Cui 
1037*01826a49SYabin Cui 
1038*01826a49SYabin Cui /* ======    Decompression    ====== */
1039*01826a49SYabin Cui 
1040*01826a49SYabin Cui typedef struct {
1041*01826a49SYabin Cui     U16 tableLog;
1042*01826a49SYabin Cui     U16 fastMode;
1043*01826a49SYabin Cui } FSEv06_DTableHeader;   /* sizeof U32 */
1044*01826a49SYabin Cui 
1045*01826a49SYabin Cui typedef struct
1046*01826a49SYabin Cui {
1047*01826a49SYabin Cui     unsigned short newState;
1048*01826a49SYabin Cui     unsigned char  symbol;
1049*01826a49SYabin Cui     unsigned char  nbBits;
1050*01826a49SYabin Cui } FSEv06_decode_t;   /* size == U32 */
1051*01826a49SYabin Cui 
FSEv06_initDState(FSEv06_DState_t * DStatePtr,BITv06_DStream_t * bitD,const FSEv06_DTable * dt)1052*01826a49SYabin Cui MEM_STATIC void FSEv06_initDState(FSEv06_DState_t* DStatePtr, BITv06_DStream_t* bitD, const FSEv06_DTable* dt)
1053*01826a49SYabin Cui {
1054*01826a49SYabin Cui     const void* ptr = dt;
1055*01826a49SYabin Cui     const FSEv06_DTableHeader* const DTableH = (const FSEv06_DTableHeader*)ptr;
1056*01826a49SYabin Cui     DStatePtr->state = BITv06_readBits(bitD, DTableH->tableLog);
1057*01826a49SYabin Cui     BITv06_reloadDStream(bitD);
1058*01826a49SYabin Cui     DStatePtr->table = dt + 1;
1059*01826a49SYabin Cui }
1060*01826a49SYabin Cui 
FSEv06_peekSymbol(const FSEv06_DState_t * DStatePtr)1061*01826a49SYabin Cui MEM_STATIC BYTE FSEv06_peekSymbol(const FSEv06_DState_t* DStatePtr)
1062*01826a49SYabin Cui {
1063*01826a49SYabin Cui     FSEv06_decode_t const DInfo = ((const FSEv06_decode_t*)(DStatePtr->table))[DStatePtr->state];
1064*01826a49SYabin Cui     return DInfo.symbol;
1065*01826a49SYabin Cui }
1066*01826a49SYabin Cui 
FSEv06_updateState(FSEv06_DState_t * DStatePtr,BITv06_DStream_t * bitD)1067*01826a49SYabin Cui MEM_STATIC void FSEv06_updateState(FSEv06_DState_t* DStatePtr, BITv06_DStream_t* bitD)
1068*01826a49SYabin Cui {
1069*01826a49SYabin Cui     FSEv06_decode_t const DInfo = ((const FSEv06_decode_t*)(DStatePtr->table))[DStatePtr->state];
1070*01826a49SYabin Cui     U32 const nbBits = DInfo.nbBits;
1071*01826a49SYabin Cui     size_t const lowBits = BITv06_readBits(bitD, nbBits);
1072*01826a49SYabin Cui     DStatePtr->state = DInfo.newState + lowBits;
1073*01826a49SYabin Cui }
1074*01826a49SYabin Cui 
FSEv06_decodeSymbol(FSEv06_DState_t * DStatePtr,BITv06_DStream_t * bitD)1075*01826a49SYabin Cui MEM_STATIC BYTE FSEv06_decodeSymbol(FSEv06_DState_t* DStatePtr, BITv06_DStream_t* bitD)
1076*01826a49SYabin Cui {
1077*01826a49SYabin Cui     FSEv06_decode_t const DInfo = ((const FSEv06_decode_t*)(DStatePtr->table))[DStatePtr->state];
1078*01826a49SYabin Cui     U32 const nbBits = DInfo.nbBits;
1079*01826a49SYabin Cui     BYTE const symbol = DInfo.symbol;
1080*01826a49SYabin Cui     size_t const lowBits = BITv06_readBits(bitD, nbBits);
1081*01826a49SYabin Cui 
1082*01826a49SYabin Cui     DStatePtr->state = DInfo.newState + lowBits;
1083*01826a49SYabin Cui     return symbol;
1084*01826a49SYabin Cui }
1085*01826a49SYabin Cui 
1086*01826a49SYabin Cui /*! FSEv06_decodeSymbolFast() :
1087*01826a49SYabin Cui     unsafe, only works if no symbol has a probability > 50% */
FSEv06_decodeSymbolFast(FSEv06_DState_t * DStatePtr,BITv06_DStream_t * bitD)1088*01826a49SYabin Cui MEM_STATIC BYTE FSEv06_decodeSymbolFast(FSEv06_DState_t* DStatePtr, BITv06_DStream_t* bitD)
1089*01826a49SYabin Cui {
1090*01826a49SYabin Cui     FSEv06_decode_t const DInfo = ((const FSEv06_decode_t*)(DStatePtr->table))[DStatePtr->state];
1091*01826a49SYabin Cui     U32 const nbBits = DInfo.nbBits;
1092*01826a49SYabin Cui     BYTE const symbol = DInfo.symbol;
1093*01826a49SYabin Cui     size_t const lowBits = BITv06_readBitsFast(bitD, nbBits);
1094*01826a49SYabin Cui 
1095*01826a49SYabin Cui     DStatePtr->state = DInfo.newState + lowBits;
1096*01826a49SYabin Cui     return symbol;
1097*01826a49SYabin Cui }
1098*01826a49SYabin Cui 
1099*01826a49SYabin Cui 
1100*01826a49SYabin Cui 
1101*01826a49SYabin Cui #ifndef FSEv06_COMMONDEFS_ONLY
1102*01826a49SYabin Cui 
1103*01826a49SYabin Cui /* **************************************************************
1104*01826a49SYabin Cui *  Tuning parameters
1105*01826a49SYabin Cui ****************************************************************/
1106*01826a49SYabin Cui /*!MEMORY_USAGE :
1107*01826a49SYabin Cui *  Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
1108*01826a49SYabin Cui *  Increasing memory usage improves compression ratio
1109*01826a49SYabin Cui *  Reduced memory usage can improve speed, due to cache effect
1110*01826a49SYabin Cui *  Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
1111*01826a49SYabin Cui #define FSEv06_MAX_MEMORY_USAGE 14
1112*01826a49SYabin Cui #define FSEv06_DEFAULT_MEMORY_USAGE 13
1113*01826a49SYabin Cui 
1114*01826a49SYabin Cui /*!FSEv06_MAX_SYMBOL_VALUE :
1115*01826a49SYabin Cui *  Maximum symbol value authorized.
1116*01826a49SYabin Cui *  Required for proper stack allocation */
1117*01826a49SYabin Cui #define FSEv06_MAX_SYMBOL_VALUE 255
1118*01826a49SYabin Cui 
1119*01826a49SYabin Cui 
1120*01826a49SYabin Cui /* **************************************************************
1121*01826a49SYabin Cui *  template functions type & suffix
1122*01826a49SYabin Cui ****************************************************************/
1123*01826a49SYabin Cui #define FSEv06_FUNCTION_TYPE BYTE
1124*01826a49SYabin Cui #define FSEv06_FUNCTION_EXTENSION
1125*01826a49SYabin Cui #define FSEv06_DECODE_TYPE FSEv06_decode_t
1126*01826a49SYabin Cui 
1127*01826a49SYabin Cui 
1128*01826a49SYabin Cui #endif   /* !FSEv06_COMMONDEFS_ONLY */
1129*01826a49SYabin Cui 
1130*01826a49SYabin Cui 
1131*01826a49SYabin Cui /* ***************************************************************
1132*01826a49SYabin Cui *  Constants
1133*01826a49SYabin Cui *****************************************************************/
1134*01826a49SYabin Cui #define FSEv06_MAX_TABLELOG  (FSEv06_MAX_MEMORY_USAGE-2)
1135*01826a49SYabin Cui #define FSEv06_MAX_TABLESIZE (1U<<FSEv06_MAX_TABLELOG)
1136*01826a49SYabin Cui #define FSEv06_MAXTABLESIZE_MASK (FSEv06_MAX_TABLESIZE-1)
1137*01826a49SYabin Cui #define FSEv06_DEFAULT_TABLELOG (FSEv06_DEFAULT_MEMORY_USAGE-2)
1138*01826a49SYabin Cui #define FSEv06_MIN_TABLELOG 5
1139*01826a49SYabin Cui 
1140*01826a49SYabin Cui #define FSEv06_TABLELOG_ABSOLUTE_MAX 15
1141*01826a49SYabin Cui #if FSEv06_MAX_TABLELOG > FSEv06_TABLELOG_ABSOLUTE_MAX
1142*01826a49SYabin Cui #error "FSEv06_MAX_TABLELOG > FSEv06_TABLELOG_ABSOLUTE_MAX is not supported"
1143*01826a49SYabin Cui #endif
1144*01826a49SYabin Cui 
1145*01826a49SYabin Cui #define FSEv06_TABLESTEP(tableSize) ((tableSize>>1) + (tableSize>>3) + 3)
1146*01826a49SYabin Cui 
1147*01826a49SYabin Cui 
1148*01826a49SYabin Cui #if defined (__cplusplus)
1149*01826a49SYabin Cui }
1150*01826a49SYabin Cui #endif
1151*01826a49SYabin Cui 
1152*01826a49SYabin Cui #endif  /* FSEv06_STATIC_H */
1153*01826a49SYabin Cui /*
1154*01826a49SYabin Cui    Common functions of New Generation Entropy library
1155*01826a49SYabin Cui    Copyright (C) 2016, Yann Collet.
1156*01826a49SYabin Cui 
1157*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
1158*01826a49SYabin Cui 
1159*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
1160*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
1161*01826a49SYabin Cui    met:
1162*01826a49SYabin Cui 
1163*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
1164*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
1165*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
1166*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
1167*01826a49SYabin Cui    in the documentation and/or other materials provided with the
1168*01826a49SYabin Cui    distribution.
1169*01826a49SYabin Cui 
1170*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1171*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1172*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1173*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1174*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1175*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1176*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1177*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1178*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1179*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1180*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1181*01826a49SYabin Cui 
1182*01826a49SYabin Cui     You can contact the author at :
1183*01826a49SYabin Cui     - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
1184*01826a49SYabin Cui     - Public forum : https://groups.google.com/forum/#!forum/lz4c
1185*01826a49SYabin Cui *************************************************************************** */
1186*01826a49SYabin Cui 
1187*01826a49SYabin Cui 
1188*01826a49SYabin Cui /*-****************************************
1189*01826a49SYabin Cui *  FSE Error Management
1190*01826a49SYabin Cui ******************************************/
FSEv06_isError(size_t code)1191*01826a49SYabin Cui unsigned FSEv06_isError(size_t code) { return ERR_isError(code); }
1192*01826a49SYabin Cui 
FSEv06_getErrorName(size_t code)1193*01826a49SYabin Cui const char* FSEv06_getErrorName(size_t code) { return ERR_getErrorName(code); }
1194*01826a49SYabin Cui 
1195*01826a49SYabin Cui 
1196*01826a49SYabin Cui /* **************************************************************
1197*01826a49SYabin Cui *  HUF Error Management
1198*01826a49SYabin Cui ****************************************************************/
HUFv06_isError(size_t code)1199*01826a49SYabin Cui static unsigned HUFv06_isError(size_t code) { return ERR_isError(code); }
1200*01826a49SYabin Cui 
1201*01826a49SYabin Cui 
1202*01826a49SYabin Cui /*-**************************************************************
1203*01826a49SYabin Cui *  FSE NCount encoding-decoding
1204*01826a49SYabin Cui ****************************************************************/
FSEv06_abs(short a)1205*01826a49SYabin Cui static short FSEv06_abs(short a) { return a<0 ? -a : a; }
1206*01826a49SYabin Cui 
FSEv06_readNCount(short * normalizedCounter,unsigned * maxSVPtr,unsigned * tableLogPtr,const void * headerBuffer,size_t hbSize)1207*01826a49SYabin Cui size_t FSEv06_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
1208*01826a49SYabin Cui                  const void* headerBuffer, size_t hbSize)
1209*01826a49SYabin Cui {
1210*01826a49SYabin Cui     const BYTE* const istart = (const BYTE*) headerBuffer;
1211*01826a49SYabin Cui     const BYTE* const iend = istart + hbSize;
1212*01826a49SYabin Cui     const BYTE* ip = istart;
1213*01826a49SYabin Cui     int nbBits;
1214*01826a49SYabin Cui     int remaining;
1215*01826a49SYabin Cui     int threshold;
1216*01826a49SYabin Cui     U32 bitStream;
1217*01826a49SYabin Cui     int bitCount;
1218*01826a49SYabin Cui     unsigned charnum = 0;
1219*01826a49SYabin Cui     int previous0 = 0;
1220*01826a49SYabin Cui 
1221*01826a49SYabin Cui     if (hbSize < 4) return ERROR(srcSize_wrong);
1222*01826a49SYabin Cui     bitStream = MEM_readLE32(ip);
1223*01826a49SYabin Cui     nbBits = (bitStream & 0xF) + FSEv06_MIN_TABLELOG;   /* extract tableLog */
1224*01826a49SYabin Cui     if (nbBits > FSEv06_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
1225*01826a49SYabin Cui     bitStream >>= 4;
1226*01826a49SYabin Cui     bitCount = 4;
1227*01826a49SYabin Cui     *tableLogPtr = nbBits;
1228*01826a49SYabin Cui     remaining = (1<<nbBits)+1;
1229*01826a49SYabin Cui     threshold = 1<<nbBits;
1230*01826a49SYabin Cui     nbBits++;
1231*01826a49SYabin Cui 
1232*01826a49SYabin Cui     while ((remaining>1) && (charnum<=*maxSVPtr)) {
1233*01826a49SYabin Cui         if (previous0) {
1234*01826a49SYabin Cui             unsigned n0 = charnum;
1235*01826a49SYabin Cui             while ((bitStream & 0xFFFF) == 0xFFFF) {
1236*01826a49SYabin Cui                 n0+=24;
1237*01826a49SYabin Cui                 if (ip < iend-5) {
1238*01826a49SYabin Cui                     ip+=2;
1239*01826a49SYabin Cui                     bitStream = MEM_readLE32(ip) >> bitCount;
1240*01826a49SYabin Cui                 } else {
1241*01826a49SYabin Cui                     bitStream >>= 16;
1242*01826a49SYabin Cui                     bitCount+=16;
1243*01826a49SYabin Cui             }   }
1244*01826a49SYabin Cui             while ((bitStream & 3) == 3) {
1245*01826a49SYabin Cui                 n0+=3;
1246*01826a49SYabin Cui                 bitStream>>=2;
1247*01826a49SYabin Cui                 bitCount+=2;
1248*01826a49SYabin Cui             }
1249*01826a49SYabin Cui             n0 += bitStream & 3;
1250*01826a49SYabin Cui             bitCount += 2;
1251*01826a49SYabin Cui             if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
1252*01826a49SYabin Cui             while (charnum < n0) normalizedCounter[charnum++] = 0;
1253*01826a49SYabin Cui             if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
1254*01826a49SYabin Cui                 ip += bitCount>>3;
1255*01826a49SYabin Cui                 bitCount &= 7;
1256*01826a49SYabin Cui                 bitStream = MEM_readLE32(ip) >> bitCount;
1257*01826a49SYabin Cui             }
1258*01826a49SYabin Cui             else
1259*01826a49SYabin Cui                 bitStream >>= 2;
1260*01826a49SYabin Cui         }
1261*01826a49SYabin Cui         {   short const max = (short)((2*threshold-1)-remaining);
1262*01826a49SYabin Cui             short count;
1263*01826a49SYabin Cui 
1264*01826a49SYabin Cui             if ((bitStream & (threshold-1)) < (U32)max) {
1265*01826a49SYabin Cui                 count = (short)(bitStream & (threshold-1));
1266*01826a49SYabin Cui                 bitCount   += nbBits-1;
1267*01826a49SYabin Cui             } else {
1268*01826a49SYabin Cui                 count = (short)(bitStream & (2*threshold-1));
1269*01826a49SYabin Cui                 if (count >= threshold) count -= max;
1270*01826a49SYabin Cui                 bitCount   += nbBits;
1271*01826a49SYabin Cui             }
1272*01826a49SYabin Cui 
1273*01826a49SYabin Cui             count--;   /* extra accuracy */
1274*01826a49SYabin Cui             remaining -= FSEv06_abs(count);
1275*01826a49SYabin Cui             normalizedCounter[charnum++] = count;
1276*01826a49SYabin Cui             previous0 = !count;
1277*01826a49SYabin Cui             while (remaining < threshold) {
1278*01826a49SYabin Cui                 nbBits--;
1279*01826a49SYabin Cui                 threshold >>= 1;
1280*01826a49SYabin Cui             }
1281*01826a49SYabin Cui 
1282*01826a49SYabin Cui             if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
1283*01826a49SYabin Cui                 ip += bitCount>>3;
1284*01826a49SYabin Cui                 bitCount &= 7;
1285*01826a49SYabin Cui             } else {
1286*01826a49SYabin Cui                 bitCount -= (int)(8 * (iend - 4 - ip));
1287*01826a49SYabin Cui                 ip = iend - 4;
1288*01826a49SYabin Cui             }
1289*01826a49SYabin Cui             bitStream = MEM_readLE32(ip) >> (bitCount & 31);
1290*01826a49SYabin Cui     }   }   /* while ((remaining>1) && (charnum<=*maxSVPtr)) */
1291*01826a49SYabin Cui     if (remaining != 1) return ERROR(GENERIC);
1292*01826a49SYabin Cui     *maxSVPtr = charnum-1;
1293*01826a49SYabin Cui 
1294*01826a49SYabin Cui     ip += (bitCount+7)>>3;
1295*01826a49SYabin Cui     if ((size_t)(ip-istart) > hbSize) return ERROR(srcSize_wrong);
1296*01826a49SYabin Cui     return ip-istart;
1297*01826a49SYabin Cui }
1298*01826a49SYabin Cui /* ******************************************************************
1299*01826a49SYabin Cui    FSE : Finite State Entropy decoder
1300*01826a49SYabin Cui    Copyright (C) 2013-2015, Yann Collet.
1301*01826a49SYabin Cui 
1302*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
1303*01826a49SYabin Cui 
1304*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
1305*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
1306*01826a49SYabin Cui    met:
1307*01826a49SYabin Cui 
1308*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
1309*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
1310*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
1311*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
1312*01826a49SYabin Cui    in the documentation and/or other materials provided with the
1313*01826a49SYabin Cui    distribution.
1314*01826a49SYabin Cui 
1315*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1316*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1317*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1318*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1319*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1320*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1321*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1322*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1323*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1324*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1325*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1326*01826a49SYabin Cui 
1327*01826a49SYabin Cui     You can contact the author at :
1328*01826a49SYabin Cui     - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
1329*01826a49SYabin Cui     - Public forum : https://groups.google.com/forum/#!forum/lz4c
1330*01826a49SYabin Cui ****************************************************************** */
1331*01826a49SYabin Cui 
1332*01826a49SYabin Cui 
1333*01826a49SYabin Cui /* **************************************************************
1334*01826a49SYabin Cui *  Compiler specifics
1335*01826a49SYabin Cui ****************************************************************/
1336*01826a49SYabin Cui #ifdef _MSC_VER    /* Visual Studio */
1337*01826a49SYabin Cui #  define FORCE_INLINE static __forceinline
1338*01826a49SYabin Cui #  include <intrin.h>                    /* For Visual 2005 */
1339*01826a49SYabin Cui #  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */
1340*01826a49SYabin Cui #  pragma warning(disable : 4214)        /* disable: C4214: non-int bitfields */
1341*01826a49SYabin Cui #else
1342*01826a49SYabin Cui #  if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
1343*01826a49SYabin Cui #    ifdef __GNUC__
1344*01826a49SYabin Cui #      define FORCE_INLINE static inline __attribute__((always_inline))
1345*01826a49SYabin Cui #    else
1346*01826a49SYabin Cui #      define FORCE_INLINE static inline
1347*01826a49SYabin Cui #    endif
1348*01826a49SYabin Cui #  else
1349*01826a49SYabin Cui #    define FORCE_INLINE static
1350*01826a49SYabin Cui #  endif /* __STDC_VERSION__ */
1351*01826a49SYabin Cui #endif
1352*01826a49SYabin Cui 
1353*01826a49SYabin Cui 
1354*01826a49SYabin Cui /* **************************************************************
1355*01826a49SYabin Cui *  Error Management
1356*01826a49SYabin Cui ****************************************************************/
1357*01826a49SYabin Cui #define FSEv06_isError ERR_isError
1358*01826a49SYabin Cui #define FSEv06_STATIC_ASSERT(c) { enum { FSEv06_static_assert = 1/(int)(!!(c)) }; }   /* use only *after* variable declarations */
1359*01826a49SYabin Cui 
1360*01826a49SYabin Cui 
1361*01826a49SYabin Cui /* **************************************************************
1362*01826a49SYabin Cui *  Complex types
1363*01826a49SYabin Cui ****************************************************************/
1364*01826a49SYabin Cui typedef U32 DTable_max_t[FSEv06_DTABLE_SIZE_U32(FSEv06_MAX_TABLELOG)];
1365*01826a49SYabin Cui 
1366*01826a49SYabin Cui 
1367*01826a49SYabin Cui /* **************************************************************
1368*01826a49SYabin Cui *  Templates
1369*01826a49SYabin Cui ****************************************************************/
1370*01826a49SYabin Cui /*
1371*01826a49SYabin Cui   designed to be included
1372*01826a49SYabin Cui   for type-specific functions (template emulation in C)
1373*01826a49SYabin Cui   Objective is to write these functions only once, for improved maintenance
1374*01826a49SYabin Cui */
1375*01826a49SYabin Cui 
1376*01826a49SYabin Cui /* safety checks */
1377*01826a49SYabin Cui #ifndef FSEv06_FUNCTION_EXTENSION
1378*01826a49SYabin Cui #  error "FSEv06_FUNCTION_EXTENSION must be defined"
1379*01826a49SYabin Cui #endif
1380*01826a49SYabin Cui #ifndef FSEv06_FUNCTION_TYPE
1381*01826a49SYabin Cui #  error "FSEv06_FUNCTION_TYPE must be defined"
1382*01826a49SYabin Cui #endif
1383*01826a49SYabin Cui 
1384*01826a49SYabin Cui /* Function names */
1385*01826a49SYabin Cui #define FSEv06_CAT(X,Y) X##Y
1386*01826a49SYabin Cui #define FSEv06_FUNCTION_NAME(X,Y) FSEv06_CAT(X,Y)
1387*01826a49SYabin Cui #define FSEv06_TYPE_NAME(X,Y) FSEv06_CAT(X,Y)
1388*01826a49SYabin Cui 
1389*01826a49SYabin Cui 
1390*01826a49SYabin Cui /* Function templates */
FSEv06_createDTable(unsigned tableLog)1391*01826a49SYabin Cui FSEv06_DTable* FSEv06_createDTable (unsigned tableLog)
1392*01826a49SYabin Cui {
1393*01826a49SYabin Cui     if (tableLog > FSEv06_TABLELOG_ABSOLUTE_MAX) tableLog = FSEv06_TABLELOG_ABSOLUTE_MAX;
1394*01826a49SYabin Cui     return (FSEv06_DTable*)malloc( FSEv06_DTABLE_SIZE_U32(tableLog) * sizeof (U32) );
1395*01826a49SYabin Cui }
1396*01826a49SYabin Cui 
FSEv06_freeDTable(FSEv06_DTable * dt)1397*01826a49SYabin Cui void FSEv06_freeDTable (FSEv06_DTable* dt)
1398*01826a49SYabin Cui {
1399*01826a49SYabin Cui     free(dt);
1400*01826a49SYabin Cui }
1401*01826a49SYabin Cui 
FSEv06_buildDTable(FSEv06_DTable * dt,const short * normalizedCounter,unsigned maxSymbolValue,unsigned tableLog)1402*01826a49SYabin Cui size_t FSEv06_buildDTable(FSEv06_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
1403*01826a49SYabin Cui {
1404*01826a49SYabin Cui     void* const tdPtr = dt+1;   /* because *dt is unsigned, 32-bits aligned on 32-bits */
1405*01826a49SYabin Cui     FSEv06_DECODE_TYPE* const tableDecode = (FSEv06_DECODE_TYPE*) (tdPtr);
1406*01826a49SYabin Cui     U16 symbolNext[FSEv06_MAX_SYMBOL_VALUE+1];
1407*01826a49SYabin Cui 
1408*01826a49SYabin Cui     U32 const maxSV1 = maxSymbolValue + 1;
1409*01826a49SYabin Cui     U32 const tableSize = 1 << tableLog;
1410*01826a49SYabin Cui     U32 highThreshold = tableSize-1;
1411*01826a49SYabin Cui 
1412*01826a49SYabin Cui     /* Sanity Checks */
1413*01826a49SYabin Cui     if (maxSymbolValue > FSEv06_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
1414*01826a49SYabin Cui     if (tableLog > FSEv06_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
1415*01826a49SYabin Cui 
1416*01826a49SYabin Cui     /* Init, lay down lowprob symbols */
1417*01826a49SYabin Cui     {   FSEv06_DTableHeader DTableH;
1418*01826a49SYabin Cui         DTableH.tableLog = (U16)tableLog;
1419*01826a49SYabin Cui         DTableH.fastMode = 1;
1420*01826a49SYabin Cui         {   S16 const largeLimit= (S16)(1 << (tableLog-1));
1421*01826a49SYabin Cui             U32 s;
1422*01826a49SYabin Cui             for (s=0; s<maxSV1; s++) {
1423*01826a49SYabin Cui                 if (normalizedCounter[s]==-1) {
1424*01826a49SYabin Cui                     tableDecode[highThreshold--].symbol = (FSEv06_FUNCTION_TYPE)s;
1425*01826a49SYabin Cui                     symbolNext[s] = 1;
1426*01826a49SYabin Cui                 } else {
1427*01826a49SYabin Cui                     if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
1428*01826a49SYabin Cui                     symbolNext[s] = normalizedCounter[s];
1429*01826a49SYabin Cui         }   }   }
1430*01826a49SYabin Cui         memcpy(dt, &DTableH, sizeof(DTableH));
1431*01826a49SYabin Cui     }
1432*01826a49SYabin Cui 
1433*01826a49SYabin Cui     /* Spread symbols */
1434*01826a49SYabin Cui     {   U32 const tableMask = tableSize-1;
1435*01826a49SYabin Cui         U32 const step = FSEv06_TABLESTEP(tableSize);
1436*01826a49SYabin Cui         U32 s, position = 0;
1437*01826a49SYabin Cui         for (s=0; s<maxSV1; s++) {
1438*01826a49SYabin Cui             int i;
1439*01826a49SYabin Cui             for (i=0; i<normalizedCounter[s]; i++) {
1440*01826a49SYabin Cui                 tableDecode[position].symbol = (FSEv06_FUNCTION_TYPE)s;
1441*01826a49SYabin Cui                 position = (position + step) & tableMask;
1442*01826a49SYabin Cui                 while (position > highThreshold) position = (position + step) & tableMask;   /* lowprob area */
1443*01826a49SYabin Cui         }   }
1444*01826a49SYabin Cui 
1445*01826a49SYabin Cui         if (position!=0) return ERROR(GENERIC);   /* position must reach all cells once, otherwise normalizedCounter is incorrect */
1446*01826a49SYabin Cui     }
1447*01826a49SYabin Cui 
1448*01826a49SYabin Cui     /* Build Decoding table */
1449*01826a49SYabin Cui     {   U32 u;
1450*01826a49SYabin Cui         for (u=0; u<tableSize; u++) {
1451*01826a49SYabin Cui             FSEv06_FUNCTION_TYPE const symbol = (FSEv06_FUNCTION_TYPE)(tableDecode[u].symbol);
1452*01826a49SYabin Cui             U16 nextState = symbolNext[symbol]++;
1453*01826a49SYabin Cui             tableDecode[u].nbBits = (BYTE) (tableLog - BITv06_highbit32 ((U32)nextState) );
1454*01826a49SYabin Cui             tableDecode[u].newState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
1455*01826a49SYabin Cui     }   }
1456*01826a49SYabin Cui 
1457*01826a49SYabin Cui     return 0;
1458*01826a49SYabin Cui }
1459*01826a49SYabin Cui 
1460*01826a49SYabin Cui 
1461*01826a49SYabin Cui 
1462*01826a49SYabin Cui #ifndef FSEv06_COMMONDEFS_ONLY
1463*01826a49SYabin Cui 
1464*01826a49SYabin Cui /*-*******************************************************
1465*01826a49SYabin Cui *  Decompression (Byte symbols)
1466*01826a49SYabin Cui *********************************************************/
FSEv06_buildDTable_rle(FSEv06_DTable * dt,BYTE symbolValue)1467*01826a49SYabin Cui size_t FSEv06_buildDTable_rle (FSEv06_DTable* dt, BYTE symbolValue)
1468*01826a49SYabin Cui {
1469*01826a49SYabin Cui     void* ptr = dt;
1470*01826a49SYabin Cui     FSEv06_DTableHeader* const DTableH = (FSEv06_DTableHeader*)ptr;
1471*01826a49SYabin Cui     void* dPtr = dt + 1;
1472*01826a49SYabin Cui     FSEv06_decode_t* const cell = (FSEv06_decode_t*)dPtr;
1473*01826a49SYabin Cui 
1474*01826a49SYabin Cui     DTableH->tableLog = 0;
1475*01826a49SYabin Cui     DTableH->fastMode = 0;
1476*01826a49SYabin Cui 
1477*01826a49SYabin Cui     cell->newState = 0;
1478*01826a49SYabin Cui     cell->symbol = symbolValue;
1479*01826a49SYabin Cui     cell->nbBits = 0;
1480*01826a49SYabin Cui 
1481*01826a49SYabin Cui     return 0;
1482*01826a49SYabin Cui }
1483*01826a49SYabin Cui 
1484*01826a49SYabin Cui 
FSEv06_buildDTable_raw(FSEv06_DTable * dt,unsigned nbBits)1485*01826a49SYabin Cui size_t FSEv06_buildDTable_raw (FSEv06_DTable* dt, unsigned nbBits)
1486*01826a49SYabin Cui {
1487*01826a49SYabin Cui     void* ptr = dt;
1488*01826a49SYabin Cui     FSEv06_DTableHeader* const DTableH = (FSEv06_DTableHeader*)ptr;
1489*01826a49SYabin Cui     void* dPtr = dt + 1;
1490*01826a49SYabin Cui     FSEv06_decode_t* const dinfo = (FSEv06_decode_t*)dPtr;
1491*01826a49SYabin Cui     const unsigned tableSize = 1 << nbBits;
1492*01826a49SYabin Cui     const unsigned tableMask = tableSize - 1;
1493*01826a49SYabin Cui     const unsigned maxSV1 = tableMask+1;
1494*01826a49SYabin Cui     unsigned s;
1495*01826a49SYabin Cui 
1496*01826a49SYabin Cui     /* Sanity checks */
1497*01826a49SYabin Cui     if (nbBits < 1) return ERROR(GENERIC);         /* min size */
1498*01826a49SYabin Cui 
1499*01826a49SYabin Cui     /* Build Decoding Table */
1500*01826a49SYabin Cui     DTableH->tableLog = (U16)nbBits;
1501*01826a49SYabin Cui     DTableH->fastMode = 1;
1502*01826a49SYabin Cui     for (s=0; s<maxSV1; s++) {
1503*01826a49SYabin Cui         dinfo[s].newState = 0;
1504*01826a49SYabin Cui         dinfo[s].symbol = (BYTE)s;
1505*01826a49SYabin Cui         dinfo[s].nbBits = (BYTE)nbBits;
1506*01826a49SYabin Cui     }
1507*01826a49SYabin Cui 
1508*01826a49SYabin Cui     return 0;
1509*01826a49SYabin Cui }
1510*01826a49SYabin Cui 
FSEv06_decompress_usingDTable_generic(void * dst,size_t maxDstSize,const void * cSrc,size_t cSrcSize,const FSEv06_DTable * dt,const unsigned fast)1511*01826a49SYabin Cui FORCE_INLINE size_t FSEv06_decompress_usingDTable_generic(
1512*01826a49SYabin Cui           void* dst, size_t maxDstSize,
1513*01826a49SYabin Cui     const void* cSrc, size_t cSrcSize,
1514*01826a49SYabin Cui     const FSEv06_DTable* dt, const unsigned fast)
1515*01826a49SYabin Cui {
1516*01826a49SYabin Cui     BYTE* const ostart = (BYTE*) dst;
1517*01826a49SYabin Cui     BYTE* op = ostart;
1518*01826a49SYabin Cui     BYTE* const omax = op + maxDstSize;
1519*01826a49SYabin Cui     BYTE* const olimit = omax-3;
1520*01826a49SYabin Cui 
1521*01826a49SYabin Cui     BITv06_DStream_t bitD;
1522*01826a49SYabin Cui     FSEv06_DState_t state1;
1523*01826a49SYabin Cui     FSEv06_DState_t state2;
1524*01826a49SYabin Cui 
1525*01826a49SYabin Cui     /* Init */
1526*01826a49SYabin Cui     { size_t const errorCode = BITv06_initDStream(&bitD, cSrc, cSrcSize);   /* replaced last arg by maxCompressed Size */
1527*01826a49SYabin Cui       if (FSEv06_isError(errorCode)) return errorCode; }
1528*01826a49SYabin Cui 
1529*01826a49SYabin Cui     FSEv06_initDState(&state1, &bitD, dt);
1530*01826a49SYabin Cui     FSEv06_initDState(&state2, &bitD, dt);
1531*01826a49SYabin Cui 
1532*01826a49SYabin Cui #define FSEv06_GETSYMBOL(statePtr) fast ? FSEv06_decodeSymbolFast(statePtr, &bitD) : FSEv06_decodeSymbol(statePtr, &bitD)
1533*01826a49SYabin Cui 
1534*01826a49SYabin Cui     /* 4 symbols per loop */
1535*01826a49SYabin Cui     for ( ; (BITv06_reloadDStream(&bitD)==BITv06_DStream_unfinished) && (op<olimit) ; op+=4) {
1536*01826a49SYabin Cui         op[0] = FSEv06_GETSYMBOL(&state1);
1537*01826a49SYabin Cui 
1538*01826a49SYabin Cui         if (FSEv06_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
1539*01826a49SYabin Cui             BITv06_reloadDStream(&bitD);
1540*01826a49SYabin Cui 
1541*01826a49SYabin Cui         op[1] = FSEv06_GETSYMBOL(&state2);
1542*01826a49SYabin Cui 
1543*01826a49SYabin Cui         if (FSEv06_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
1544*01826a49SYabin Cui             { if (BITv06_reloadDStream(&bitD) > BITv06_DStream_unfinished) { op+=2; break; } }
1545*01826a49SYabin Cui 
1546*01826a49SYabin Cui         op[2] = FSEv06_GETSYMBOL(&state1);
1547*01826a49SYabin Cui 
1548*01826a49SYabin Cui         if (FSEv06_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
1549*01826a49SYabin Cui             BITv06_reloadDStream(&bitD);
1550*01826a49SYabin Cui 
1551*01826a49SYabin Cui         op[3] = FSEv06_GETSYMBOL(&state2);
1552*01826a49SYabin Cui     }
1553*01826a49SYabin Cui 
1554*01826a49SYabin Cui     /* tail */
1555*01826a49SYabin Cui     /* note : BITv06_reloadDStream(&bitD) >= FSEv06_DStream_partiallyFilled; Ends at exactly BITv06_DStream_completed */
1556*01826a49SYabin Cui     while (1) {
1557*01826a49SYabin Cui         if (op>(omax-2)) return ERROR(dstSize_tooSmall);
1558*01826a49SYabin Cui 
1559*01826a49SYabin Cui         *op++ = FSEv06_GETSYMBOL(&state1);
1560*01826a49SYabin Cui 
1561*01826a49SYabin Cui         if (BITv06_reloadDStream(&bitD)==BITv06_DStream_overflow) {
1562*01826a49SYabin Cui             *op++ = FSEv06_GETSYMBOL(&state2);
1563*01826a49SYabin Cui             break;
1564*01826a49SYabin Cui         }
1565*01826a49SYabin Cui 
1566*01826a49SYabin Cui         if (op>(omax-2)) return ERROR(dstSize_tooSmall);
1567*01826a49SYabin Cui 
1568*01826a49SYabin Cui         *op++ = FSEv06_GETSYMBOL(&state2);
1569*01826a49SYabin Cui 
1570*01826a49SYabin Cui         if (BITv06_reloadDStream(&bitD)==BITv06_DStream_overflow) {
1571*01826a49SYabin Cui             *op++ = FSEv06_GETSYMBOL(&state1);
1572*01826a49SYabin Cui             break;
1573*01826a49SYabin Cui     }   }
1574*01826a49SYabin Cui 
1575*01826a49SYabin Cui     return op-ostart;
1576*01826a49SYabin Cui }
1577*01826a49SYabin Cui 
1578*01826a49SYabin Cui 
FSEv06_decompress_usingDTable(void * dst,size_t originalSize,const void * cSrc,size_t cSrcSize,const FSEv06_DTable * dt)1579*01826a49SYabin Cui size_t FSEv06_decompress_usingDTable(void* dst, size_t originalSize,
1580*01826a49SYabin Cui                             const void* cSrc, size_t cSrcSize,
1581*01826a49SYabin Cui                             const FSEv06_DTable* dt)
1582*01826a49SYabin Cui {
1583*01826a49SYabin Cui     const void* ptr = dt;
1584*01826a49SYabin Cui     const FSEv06_DTableHeader* DTableH = (const FSEv06_DTableHeader*)ptr;
1585*01826a49SYabin Cui     const U32 fastMode = DTableH->fastMode;
1586*01826a49SYabin Cui 
1587*01826a49SYabin Cui     /* select fast mode (static) */
1588*01826a49SYabin Cui     if (fastMode) return FSEv06_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
1589*01826a49SYabin Cui     return FSEv06_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
1590*01826a49SYabin Cui }
1591*01826a49SYabin Cui 
1592*01826a49SYabin Cui 
FSEv06_decompress(void * dst,size_t maxDstSize,const void * cSrc,size_t cSrcSize)1593*01826a49SYabin Cui size_t FSEv06_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
1594*01826a49SYabin Cui {
1595*01826a49SYabin Cui     const BYTE* const istart = (const BYTE*)cSrc;
1596*01826a49SYabin Cui     const BYTE* ip = istart;
1597*01826a49SYabin Cui     short counting[FSEv06_MAX_SYMBOL_VALUE+1];
1598*01826a49SYabin Cui     DTable_max_t dt;   /* Static analyzer seems unable to understand this table will be properly initialized later */
1599*01826a49SYabin Cui     unsigned tableLog;
1600*01826a49SYabin Cui     unsigned maxSymbolValue = FSEv06_MAX_SYMBOL_VALUE;
1601*01826a49SYabin Cui 
1602*01826a49SYabin Cui     if (cSrcSize<2) return ERROR(srcSize_wrong);   /* too small input size */
1603*01826a49SYabin Cui 
1604*01826a49SYabin Cui     /* normal FSE decoding mode */
1605*01826a49SYabin Cui     {   size_t const NCountLength = FSEv06_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
1606*01826a49SYabin Cui         if (FSEv06_isError(NCountLength)) return NCountLength;
1607*01826a49SYabin Cui         if (NCountLength >= cSrcSize) return ERROR(srcSize_wrong);   /* too small input size */
1608*01826a49SYabin Cui         ip += NCountLength;
1609*01826a49SYabin Cui         cSrcSize -= NCountLength;
1610*01826a49SYabin Cui     }
1611*01826a49SYabin Cui 
1612*01826a49SYabin Cui     { size_t const errorCode = FSEv06_buildDTable (dt, counting, maxSymbolValue, tableLog);
1613*01826a49SYabin Cui       if (FSEv06_isError(errorCode)) return errorCode; }
1614*01826a49SYabin Cui 
1615*01826a49SYabin Cui     return FSEv06_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt);   /* always return, even if it is an error code */
1616*01826a49SYabin Cui }
1617*01826a49SYabin Cui 
1618*01826a49SYabin Cui 
1619*01826a49SYabin Cui 
1620*01826a49SYabin Cui #endif   /* FSEv06_COMMONDEFS_ONLY */
1621*01826a49SYabin Cui /* ******************************************************************
1622*01826a49SYabin Cui    Huffman coder, part of New Generation Entropy library
1623*01826a49SYabin Cui    header file
1624*01826a49SYabin Cui    Copyright (C) 2013-2016, Yann Collet.
1625*01826a49SYabin Cui 
1626*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
1627*01826a49SYabin Cui 
1628*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
1629*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
1630*01826a49SYabin Cui    met:
1631*01826a49SYabin Cui 
1632*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
1633*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
1634*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
1635*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
1636*01826a49SYabin Cui    in the documentation and/or other materials provided with the
1637*01826a49SYabin Cui    distribution.
1638*01826a49SYabin Cui 
1639*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1640*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1641*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1642*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1643*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1644*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1645*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1646*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1647*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1648*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1649*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1650*01826a49SYabin Cui 
1651*01826a49SYabin Cui    You can contact the author at :
1652*01826a49SYabin Cui    - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
1653*01826a49SYabin Cui ****************************************************************** */
1654*01826a49SYabin Cui #ifndef HUFv06_H
1655*01826a49SYabin Cui #define HUFv06_H
1656*01826a49SYabin Cui 
1657*01826a49SYabin Cui #if defined (__cplusplus)
1658*01826a49SYabin Cui extern "C" {
1659*01826a49SYabin Cui #endif
1660*01826a49SYabin Cui 
1661*01826a49SYabin Cui 
1662*01826a49SYabin Cui /* ****************************************
1663*01826a49SYabin Cui *  HUF simple functions
1664*01826a49SYabin Cui ******************************************/
1665*01826a49SYabin Cui size_t HUFv06_decompress(void* dst,  size_t dstSize,
1666*01826a49SYabin Cui                 const void* cSrc, size_t cSrcSize);
1667*01826a49SYabin Cui /*
1668*01826a49SYabin Cui HUFv06_decompress() :
1669*01826a49SYabin Cui     Decompress HUF data from buffer 'cSrc', of size 'cSrcSize',
1670*01826a49SYabin Cui     into already allocated destination buffer 'dst', of size 'dstSize'.
1671*01826a49SYabin Cui     `dstSize` : must be the **exact** size of original (uncompressed) data.
1672*01826a49SYabin Cui     Note : in contrast with FSE, HUFv06_decompress can regenerate
1673*01826a49SYabin Cui            RLE (cSrcSize==1) and uncompressed (cSrcSize==dstSize) data,
1674*01826a49SYabin Cui            because it knows size to regenerate.
1675*01826a49SYabin Cui     @return : size of regenerated data (== dstSize)
1676*01826a49SYabin Cui               or an error code, which can be tested using HUFv06_isError()
1677*01826a49SYabin Cui */
1678*01826a49SYabin Cui 
1679*01826a49SYabin Cui 
1680*01826a49SYabin Cui /* ****************************************
1681*01826a49SYabin Cui *  Tool functions
1682*01826a49SYabin Cui ******************************************/
1683*01826a49SYabin Cui size_t HUFv06_compressBound(size_t size);       /**< maximum compressed size */
1684*01826a49SYabin Cui 
1685*01826a49SYabin Cui 
1686*01826a49SYabin Cui #if defined (__cplusplus)
1687*01826a49SYabin Cui }
1688*01826a49SYabin Cui #endif
1689*01826a49SYabin Cui 
1690*01826a49SYabin Cui #endif   /* HUFv06_H */
1691*01826a49SYabin Cui /* ******************************************************************
1692*01826a49SYabin Cui    Huffman codec, part of New Generation Entropy library
1693*01826a49SYabin Cui    header file, for static linking only
1694*01826a49SYabin Cui    Copyright (C) 2013-2016, Yann Collet
1695*01826a49SYabin Cui 
1696*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
1697*01826a49SYabin Cui 
1698*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
1699*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
1700*01826a49SYabin Cui    met:
1701*01826a49SYabin Cui 
1702*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
1703*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
1704*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
1705*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
1706*01826a49SYabin Cui    in the documentation and/or other materials provided with the
1707*01826a49SYabin Cui    distribution.
1708*01826a49SYabin Cui 
1709*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1710*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1711*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1712*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1713*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1714*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1715*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1716*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1717*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1718*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1719*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1720*01826a49SYabin Cui 
1721*01826a49SYabin Cui    You can contact the author at :
1722*01826a49SYabin Cui    - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
1723*01826a49SYabin Cui ****************************************************************** */
1724*01826a49SYabin Cui #ifndef HUFv06_STATIC_H
1725*01826a49SYabin Cui #define HUFv06_STATIC_H
1726*01826a49SYabin Cui 
1727*01826a49SYabin Cui #if defined (__cplusplus)
1728*01826a49SYabin Cui extern "C" {
1729*01826a49SYabin Cui #endif
1730*01826a49SYabin Cui 
1731*01826a49SYabin Cui 
1732*01826a49SYabin Cui /* ****************************************
1733*01826a49SYabin Cui *  Static allocation
1734*01826a49SYabin Cui ******************************************/
1735*01826a49SYabin Cui /* HUF buffer bounds */
1736*01826a49SYabin Cui #define HUFv06_CTABLEBOUND 129
1737*01826a49SYabin Cui #define HUFv06_BLOCKBOUND(size) (size + (size>>8) + 8)   /* only true if incompressible pre-filtered with fast heuristic */
1738*01826a49SYabin Cui #define HUFv06_COMPRESSBOUND(size) (HUFv06_CTABLEBOUND + HUFv06_BLOCKBOUND(size))   /* Macro version, useful for static allocation */
1739*01826a49SYabin Cui 
1740*01826a49SYabin Cui /* static allocation of HUF's DTable */
1741*01826a49SYabin Cui #define HUFv06_DTABLE_SIZE(maxTableLog)   (1 + (1<<maxTableLog))
1742*01826a49SYabin Cui #define HUFv06_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \
1743*01826a49SYabin Cui         unsigned short DTable[HUFv06_DTABLE_SIZE(maxTableLog)] = { maxTableLog }
1744*01826a49SYabin Cui #define HUFv06_CREATE_STATIC_DTABLEX4(DTable, maxTableLog) \
1745*01826a49SYabin Cui         unsigned int DTable[HUFv06_DTABLE_SIZE(maxTableLog)] = { maxTableLog }
1746*01826a49SYabin Cui #define HUFv06_CREATE_STATIC_DTABLEX6(DTable, maxTableLog) \
1747*01826a49SYabin Cui         unsigned int DTable[HUFv06_DTABLE_SIZE(maxTableLog) * 3 / 2] = { maxTableLog }
1748*01826a49SYabin Cui 
1749*01826a49SYabin Cui 
1750*01826a49SYabin Cui /* ****************************************
1751*01826a49SYabin Cui *  Advanced decompression functions
1752*01826a49SYabin Cui ******************************************/
1753*01826a49SYabin Cui size_t HUFv06_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /* single-symbol decoder */
1754*01826a49SYabin Cui size_t HUFv06_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /* double-symbols decoder */
1755*01826a49SYabin Cui 
1756*01826a49SYabin Cui 
1757*01826a49SYabin Cui 
1758*01826a49SYabin Cui /*!
1759*01826a49SYabin Cui HUFv06_decompress() does the following:
1760*01826a49SYabin Cui 1. select the decompression algorithm (X2, X4, X6) based on pre-computed heuristics
1761*01826a49SYabin Cui 2. build Huffman table from save, using HUFv06_readDTableXn()
1762*01826a49SYabin Cui 3. decode 1 or 4 segments in parallel using HUFv06_decompressSXn_usingDTable
1763*01826a49SYabin Cui */
1764*01826a49SYabin Cui size_t HUFv06_readDTableX2 (unsigned short* DTable, const void* src, size_t srcSize);
1765*01826a49SYabin Cui size_t HUFv06_readDTableX4 (unsigned* DTable, const void* src, size_t srcSize);
1766*01826a49SYabin Cui 
1767*01826a49SYabin Cui size_t HUFv06_decompress4X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const unsigned short* DTable);
1768*01826a49SYabin Cui size_t HUFv06_decompress4X4_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const unsigned* DTable);
1769*01826a49SYabin Cui 
1770*01826a49SYabin Cui 
1771*01826a49SYabin Cui /* single stream variants */
1772*01826a49SYabin Cui size_t HUFv06_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /* single-symbol decoder */
1773*01826a49SYabin Cui size_t HUFv06_decompress1X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /* double-symbol decoder */
1774*01826a49SYabin Cui 
1775*01826a49SYabin Cui size_t HUFv06_decompress1X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const unsigned short* DTable);
1776*01826a49SYabin Cui size_t HUFv06_decompress1X4_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const unsigned* DTable);
1777*01826a49SYabin Cui 
1778*01826a49SYabin Cui 
1779*01826a49SYabin Cui 
1780*01826a49SYabin Cui /* **************************************************************
1781*01826a49SYabin Cui *  Constants
1782*01826a49SYabin Cui ****************************************************************/
1783*01826a49SYabin Cui #define HUFv06_ABSOLUTEMAX_TABLELOG  16   /* absolute limit of HUFv06_MAX_TABLELOG. Beyond that value, code does not work */
1784*01826a49SYabin Cui #define HUFv06_MAX_TABLELOG  12           /* max configured tableLog (for static allocation); can be modified up to HUFv06_ABSOLUTEMAX_TABLELOG */
1785*01826a49SYabin Cui #define HUFv06_DEFAULT_TABLELOG  HUFv06_MAX_TABLELOG   /* tableLog by default, when not specified */
1786*01826a49SYabin Cui #define HUFv06_MAX_SYMBOL_VALUE 255
1787*01826a49SYabin Cui #if (HUFv06_MAX_TABLELOG > HUFv06_ABSOLUTEMAX_TABLELOG)
1788*01826a49SYabin Cui #  error "HUFv06_MAX_TABLELOG is too large !"
1789*01826a49SYabin Cui #endif
1790*01826a49SYabin Cui 
1791*01826a49SYabin Cui 
1792*01826a49SYabin Cui 
1793*01826a49SYabin Cui /*! HUFv06_readStats() :
1794*01826a49SYabin Cui     Read compact Huffman tree, saved by HUFv06_writeCTable().
1795*01826a49SYabin Cui     `huffWeight` is destination buffer.
1796*01826a49SYabin Cui     @return : size read from `src`
1797*01826a49SYabin Cui */
HUFv06_readStats(BYTE * huffWeight,size_t hwSize,U32 * rankStats,U32 * nbSymbolsPtr,U32 * tableLogPtr,const void * src,size_t srcSize)1798*01826a49SYabin Cui MEM_STATIC size_t HUFv06_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
1799*01826a49SYabin Cui                             U32* nbSymbolsPtr, U32* tableLogPtr,
1800*01826a49SYabin Cui                             const void* src, size_t srcSize)
1801*01826a49SYabin Cui {
1802*01826a49SYabin Cui     U32 weightTotal;
1803*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) src;
1804*01826a49SYabin Cui     size_t iSize;
1805*01826a49SYabin Cui     size_t oSize;
1806*01826a49SYabin Cui 
1807*01826a49SYabin Cui     if (!srcSize) return ERROR(srcSize_wrong);
1808*01826a49SYabin Cui     iSize = ip[0];
1809*01826a49SYabin Cui     /* memset(huffWeight, 0, hwSize); */   /* is not necessary, even though some analyzer complain ... */
1810*01826a49SYabin Cui 
1811*01826a49SYabin Cui     if (iSize >= 128)  { /* special header */
1812*01826a49SYabin Cui         if (iSize >= (242)) {  /* RLE */
1813*01826a49SYabin Cui             static U32 l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 };
1814*01826a49SYabin Cui             oSize = l[iSize-242];
1815*01826a49SYabin Cui             memset(huffWeight, 1, hwSize);
1816*01826a49SYabin Cui             iSize = 0;
1817*01826a49SYabin Cui         }
1818*01826a49SYabin Cui         else {   /* Incompressible */
1819*01826a49SYabin Cui             oSize = iSize - 127;
1820*01826a49SYabin Cui             iSize = ((oSize+1)/2);
1821*01826a49SYabin Cui             if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
1822*01826a49SYabin Cui             if (oSize >= hwSize) return ERROR(corruption_detected);
1823*01826a49SYabin Cui             ip += 1;
1824*01826a49SYabin Cui             {   U32 n;
1825*01826a49SYabin Cui                 for (n=0; n<oSize; n+=2) {
1826*01826a49SYabin Cui                     huffWeight[n]   = ip[n/2] >> 4;
1827*01826a49SYabin Cui                     huffWeight[n+1] = ip[n/2] & 15;
1828*01826a49SYabin Cui     }   }   }   }
1829*01826a49SYabin Cui     else  {   /* header compressed with FSE (normal case) */
1830*01826a49SYabin Cui         if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
1831*01826a49SYabin Cui         oSize = FSEv06_decompress(huffWeight, hwSize-1, ip+1, iSize);   /* max (hwSize-1) values decoded, as last one is implied */
1832*01826a49SYabin Cui         if (FSEv06_isError(oSize)) return oSize;
1833*01826a49SYabin Cui     }
1834*01826a49SYabin Cui 
1835*01826a49SYabin Cui     /* collect weight stats */
1836*01826a49SYabin Cui     memset(rankStats, 0, (HUFv06_ABSOLUTEMAX_TABLELOG + 1) * sizeof(U32));
1837*01826a49SYabin Cui     weightTotal = 0;
1838*01826a49SYabin Cui     {   U32 n; for (n=0; n<oSize; n++) {
1839*01826a49SYabin Cui             if (huffWeight[n] >= HUFv06_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
1840*01826a49SYabin Cui             rankStats[huffWeight[n]]++;
1841*01826a49SYabin Cui             weightTotal += (1 << huffWeight[n]) >> 1;
1842*01826a49SYabin Cui     }   }
1843*01826a49SYabin Cui     if (weightTotal == 0) return ERROR(corruption_detected);
1844*01826a49SYabin Cui 
1845*01826a49SYabin Cui     /* get last non-null symbol weight (implied, total must be 2^n) */
1846*01826a49SYabin Cui     {   U32 const tableLog = BITv06_highbit32(weightTotal) + 1;
1847*01826a49SYabin Cui         if (tableLog > HUFv06_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
1848*01826a49SYabin Cui         *tableLogPtr = tableLog;
1849*01826a49SYabin Cui         /* determine last weight */
1850*01826a49SYabin Cui         {   U32 const total = 1 << tableLog;
1851*01826a49SYabin Cui             U32 const rest = total - weightTotal;
1852*01826a49SYabin Cui             U32 const verif = 1 << BITv06_highbit32(rest);
1853*01826a49SYabin Cui             U32 const lastWeight = BITv06_highbit32(rest) + 1;
1854*01826a49SYabin Cui             if (verif != rest) return ERROR(corruption_detected);    /* last value must be a clean power of 2 */
1855*01826a49SYabin Cui             huffWeight[oSize] = (BYTE)lastWeight;
1856*01826a49SYabin Cui             rankStats[lastWeight]++;
1857*01826a49SYabin Cui     }   }
1858*01826a49SYabin Cui 
1859*01826a49SYabin Cui     /* check tree construction validity */
1860*01826a49SYabin Cui     if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected);   /* by construction : at least 2 elts of rank 1, must be even */
1861*01826a49SYabin Cui 
1862*01826a49SYabin Cui     /* results */
1863*01826a49SYabin Cui     *nbSymbolsPtr = (U32)(oSize+1);
1864*01826a49SYabin Cui     return iSize+1;
1865*01826a49SYabin Cui }
1866*01826a49SYabin Cui 
1867*01826a49SYabin Cui 
1868*01826a49SYabin Cui 
1869*01826a49SYabin Cui #if defined (__cplusplus)
1870*01826a49SYabin Cui }
1871*01826a49SYabin Cui #endif
1872*01826a49SYabin Cui 
1873*01826a49SYabin Cui #endif /* HUFv06_STATIC_H */
1874*01826a49SYabin Cui /* ******************************************************************
1875*01826a49SYabin Cui    Huffman decoder, part of New Generation Entropy library
1876*01826a49SYabin Cui    Copyright (C) 2013-2016, Yann Collet.
1877*01826a49SYabin Cui 
1878*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
1879*01826a49SYabin Cui 
1880*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
1881*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
1882*01826a49SYabin Cui    met:
1883*01826a49SYabin Cui 
1884*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
1885*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
1886*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
1887*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
1888*01826a49SYabin Cui    in the documentation and/or other materials provided with the
1889*01826a49SYabin Cui    distribution.
1890*01826a49SYabin Cui 
1891*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1892*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1893*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1894*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1895*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1896*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1897*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1898*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1899*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1900*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1901*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1902*01826a49SYabin Cui 
1903*01826a49SYabin Cui     You can contact the author at :
1904*01826a49SYabin Cui     - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
1905*01826a49SYabin Cui     - Public forum : https://groups.google.com/forum/#!forum/lz4c
1906*01826a49SYabin Cui ****************************************************************** */
1907*01826a49SYabin Cui 
1908*01826a49SYabin Cui /* **************************************************************
1909*01826a49SYabin Cui *  Compiler specifics
1910*01826a49SYabin Cui ****************************************************************/
1911*01826a49SYabin Cui #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
1912*01826a49SYabin Cui /* inline is defined */
1913*01826a49SYabin Cui #elif defined(_MSC_VER)
1914*01826a49SYabin Cui #  define inline __inline
1915*01826a49SYabin Cui #else
1916*01826a49SYabin Cui #  define inline /* disable inline */
1917*01826a49SYabin Cui #endif
1918*01826a49SYabin Cui 
1919*01826a49SYabin Cui 
1920*01826a49SYabin Cui #ifdef _MSC_VER    /* Visual Studio */
1921*01826a49SYabin Cui #  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */
1922*01826a49SYabin Cui #endif
1923*01826a49SYabin Cui 
1924*01826a49SYabin Cui 
1925*01826a49SYabin Cui 
1926*01826a49SYabin Cui /* **************************************************************
1927*01826a49SYabin Cui *  Error Management
1928*01826a49SYabin Cui ****************************************************************/
1929*01826a49SYabin Cui #define HUFv06_STATIC_ASSERT(c) { enum { HUFv06_static_assert = 1/(int)(!!(c)) }; }   /* use only *after* variable declarations */
1930*01826a49SYabin Cui 
1931*01826a49SYabin Cui 
1932*01826a49SYabin Cui 
1933*01826a49SYabin Cui /* *******************************************************
1934*01826a49SYabin Cui *  HUF : Huffman block decompression
1935*01826a49SYabin Cui *********************************************************/
1936*01826a49SYabin Cui typedef struct { BYTE byte; BYTE nbBits; } HUFv06_DEltX2;   /* single-symbol decoding */
1937*01826a49SYabin Cui 
1938*01826a49SYabin Cui typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUFv06_DEltX4;  /* double-symbols decoding */
1939*01826a49SYabin Cui 
1940*01826a49SYabin Cui typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t;
1941*01826a49SYabin Cui 
1942*01826a49SYabin Cui 
1943*01826a49SYabin Cui 
1944*01826a49SYabin Cui /*-***************************/
1945*01826a49SYabin Cui /*  single-symbol decoding   */
1946*01826a49SYabin Cui /*-***************************/
1947*01826a49SYabin Cui 
HUFv06_readDTableX2(U16 * DTable,const void * src,size_t srcSize)1948*01826a49SYabin Cui size_t HUFv06_readDTableX2 (U16* DTable, const void* src, size_t srcSize)
1949*01826a49SYabin Cui {
1950*01826a49SYabin Cui     BYTE huffWeight[HUFv06_MAX_SYMBOL_VALUE + 1];
1951*01826a49SYabin Cui     U32 rankVal[HUFv06_ABSOLUTEMAX_TABLELOG + 1];   /* large enough for values from 0 to 16 */
1952*01826a49SYabin Cui     U32 tableLog = 0;
1953*01826a49SYabin Cui     size_t iSize;
1954*01826a49SYabin Cui     U32 nbSymbols = 0;
1955*01826a49SYabin Cui     U32 n;
1956*01826a49SYabin Cui     U32 nextRankStart;
1957*01826a49SYabin Cui     void* const dtPtr = DTable + 1;
1958*01826a49SYabin Cui     HUFv06_DEltX2* const dt = (HUFv06_DEltX2*)dtPtr;
1959*01826a49SYabin Cui 
1960*01826a49SYabin Cui     HUFv06_STATIC_ASSERT(sizeof(HUFv06_DEltX2) == sizeof(U16));   /* if compilation fails here, assertion is false */
1961*01826a49SYabin Cui     /* memset(huffWeight, 0, sizeof(huffWeight)); */   /* is not necessary, even though some analyzer complain ... */
1962*01826a49SYabin Cui 
1963*01826a49SYabin Cui     iSize = HUFv06_readStats(huffWeight, HUFv06_MAX_SYMBOL_VALUE + 1, rankVal, &nbSymbols, &tableLog, src, srcSize);
1964*01826a49SYabin Cui     if (HUFv06_isError(iSize)) return iSize;
1965*01826a49SYabin Cui 
1966*01826a49SYabin Cui     /* check result */
1967*01826a49SYabin Cui     if (tableLog > DTable[0]) return ERROR(tableLog_tooLarge);   /* DTable is too small */
1968*01826a49SYabin Cui     DTable[0] = (U16)tableLog;   /* maybe should separate sizeof allocated DTable, from used size of DTable, in case of re-use */
1969*01826a49SYabin Cui 
1970*01826a49SYabin Cui     /* Prepare ranks */
1971*01826a49SYabin Cui     nextRankStart = 0;
1972*01826a49SYabin Cui     for (n=1; n<tableLog+1; n++) {
1973*01826a49SYabin Cui         U32 current = nextRankStart;
1974*01826a49SYabin Cui         nextRankStart += (rankVal[n] << (n-1));
1975*01826a49SYabin Cui         rankVal[n] = current;
1976*01826a49SYabin Cui     }
1977*01826a49SYabin Cui 
1978*01826a49SYabin Cui     /* fill DTable */
1979*01826a49SYabin Cui     for (n=0; n<nbSymbols; n++) {
1980*01826a49SYabin Cui         const U32 w = huffWeight[n];
1981*01826a49SYabin Cui         const U32 length = (1 << w) >> 1;
1982*01826a49SYabin Cui         U32 i;
1983*01826a49SYabin Cui         HUFv06_DEltX2 D;
1984*01826a49SYabin Cui         D.byte = (BYTE)n; D.nbBits = (BYTE)(tableLog + 1 - w);
1985*01826a49SYabin Cui         for (i = rankVal[w]; i < rankVal[w] + length; i++)
1986*01826a49SYabin Cui             dt[i] = D;
1987*01826a49SYabin Cui         rankVal[w] += length;
1988*01826a49SYabin Cui     }
1989*01826a49SYabin Cui 
1990*01826a49SYabin Cui     return iSize;
1991*01826a49SYabin Cui }
1992*01826a49SYabin Cui 
1993*01826a49SYabin Cui 
HUFv06_decodeSymbolX2(BITv06_DStream_t * Dstream,const HUFv06_DEltX2 * dt,const U32 dtLog)1994*01826a49SYabin Cui static BYTE HUFv06_decodeSymbolX2(BITv06_DStream_t* Dstream, const HUFv06_DEltX2* dt, const U32 dtLog)
1995*01826a49SYabin Cui {
1996*01826a49SYabin Cui     const size_t val = BITv06_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
1997*01826a49SYabin Cui     const BYTE c = dt[val].byte;
1998*01826a49SYabin Cui     BITv06_skipBits(Dstream, dt[val].nbBits);
1999*01826a49SYabin Cui     return c;
2000*01826a49SYabin Cui }
2001*01826a49SYabin Cui 
2002*01826a49SYabin Cui #define HUFv06_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
2003*01826a49SYabin Cui     *ptr++ = HUFv06_decodeSymbolX2(DStreamPtr, dt, dtLog)
2004*01826a49SYabin Cui 
2005*01826a49SYabin Cui #define HUFv06_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
2006*01826a49SYabin Cui     if (MEM_64bits() || (HUFv06_MAX_TABLELOG<=12)) \
2007*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
2008*01826a49SYabin Cui 
2009*01826a49SYabin Cui #define HUFv06_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
2010*01826a49SYabin Cui     if (MEM_64bits()) \
2011*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
2012*01826a49SYabin Cui 
HUFv06_decodeStreamX2(BYTE * p,BITv06_DStream_t * const bitDPtr,BYTE * const pEnd,const HUFv06_DEltX2 * const dt,const U32 dtLog)2013*01826a49SYabin Cui static inline size_t HUFv06_decodeStreamX2(BYTE* p, BITv06_DStream_t* const bitDPtr, BYTE* const pEnd, const HUFv06_DEltX2* const dt, const U32 dtLog)
2014*01826a49SYabin Cui {
2015*01826a49SYabin Cui     BYTE* const pStart = p;
2016*01826a49SYabin Cui 
2017*01826a49SYabin Cui     /* up to 4 symbols at a time */
2018*01826a49SYabin Cui     while ((BITv06_reloadDStream(bitDPtr) == BITv06_DStream_unfinished) && (p <= pEnd-4)) {
2019*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX2_2(p, bitDPtr);
2020*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX2_1(p, bitDPtr);
2021*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX2_2(p, bitDPtr);
2022*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX2_0(p, bitDPtr);
2023*01826a49SYabin Cui     }
2024*01826a49SYabin Cui 
2025*01826a49SYabin Cui     /* closer to the end */
2026*01826a49SYabin Cui     while ((BITv06_reloadDStream(bitDPtr) == BITv06_DStream_unfinished) && (p < pEnd))
2027*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX2_0(p, bitDPtr);
2028*01826a49SYabin Cui 
2029*01826a49SYabin Cui     /* no more data to retrieve from bitstream, hence no need to reload */
2030*01826a49SYabin Cui     while (p < pEnd)
2031*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX2_0(p, bitDPtr);
2032*01826a49SYabin Cui 
2033*01826a49SYabin Cui     return pEnd-pStart;
2034*01826a49SYabin Cui }
2035*01826a49SYabin Cui 
HUFv06_decompress1X2_usingDTable(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize,const U16 * DTable)2036*01826a49SYabin Cui size_t HUFv06_decompress1X2_usingDTable(
2037*01826a49SYabin Cui           void* dst,  size_t dstSize,
2038*01826a49SYabin Cui     const void* cSrc, size_t cSrcSize,
2039*01826a49SYabin Cui     const U16* DTable)
2040*01826a49SYabin Cui {
2041*01826a49SYabin Cui     BYTE* op = (BYTE*)dst;
2042*01826a49SYabin Cui     BYTE* const oend = op + dstSize;
2043*01826a49SYabin Cui     const U32 dtLog = DTable[0];
2044*01826a49SYabin Cui     const void* dtPtr = DTable;
2045*01826a49SYabin Cui     const HUFv06_DEltX2* const dt = ((const HUFv06_DEltX2*)dtPtr)+1;
2046*01826a49SYabin Cui     BITv06_DStream_t bitD;
2047*01826a49SYabin Cui 
2048*01826a49SYabin Cui     { size_t const errorCode = BITv06_initDStream(&bitD, cSrc, cSrcSize);
2049*01826a49SYabin Cui       if (HUFv06_isError(errorCode)) return errorCode; }
2050*01826a49SYabin Cui 
2051*01826a49SYabin Cui     HUFv06_decodeStreamX2(op, &bitD, oend, dt, dtLog);
2052*01826a49SYabin Cui 
2053*01826a49SYabin Cui     /* check */
2054*01826a49SYabin Cui     if (!BITv06_endOfDStream(&bitD)) return ERROR(corruption_detected);
2055*01826a49SYabin Cui 
2056*01826a49SYabin Cui     return dstSize;
2057*01826a49SYabin Cui }
2058*01826a49SYabin Cui 
HUFv06_decompress1X2(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize)2059*01826a49SYabin Cui size_t HUFv06_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
2060*01826a49SYabin Cui {
2061*01826a49SYabin Cui     HUFv06_CREATE_STATIC_DTABLEX2(DTable, HUFv06_MAX_TABLELOG);
2062*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) cSrc;
2063*01826a49SYabin Cui 
2064*01826a49SYabin Cui     size_t const errorCode = HUFv06_readDTableX2 (DTable, cSrc, cSrcSize);
2065*01826a49SYabin Cui     if (HUFv06_isError(errorCode)) return errorCode;
2066*01826a49SYabin Cui     if (errorCode >= cSrcSize) return ERROR(srcSize_wrong);
2067*01826a49SYabin Cui     ip += errorCode;
2068*01826a49SYabin Cui     cSrcSize -= errorCode;
2069*01826a49SYabin Cui 
2070*01826a49SYabin Cui     return HUFv06_decompress1X2_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
2071*01826a49SYabin Cui }
2072*01826a49SYabin Cui 
2073*01826a49SYabin Cui 
HUFv06_decompress4X2_usingDTable(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize,const U16 * DTable)2074*01826a49SYabin Cui size_t HUFv06_decompress4X2_usingDTable(
2075*01826a49SYabin Cui           void* dst,  size_t dstSize,
2076*01826a49SYabin Cui     const void* cSrc, size_t cSrcSize,
2077*01826a49SYabin Cui     const U16* DTable)
2078*01826a49SYabin Cui {
2079*01826a49SYabin Cui     /* Check */
2080*01826a49SYabin Cui     if (cSrcSize < 10) return ERROR(corruption_detected);  /* strict minimum : jump table + 1 byte per stream */
2081*01826a49SYabin Cui 
2082*01826a49SYabin Cui     {   const BYTE* const istart = (const BYTE*) cSrc;
2083*01826a49SYabin Cui         BYTE* const ostart = (BYTE*) dst;
2084*01826a49SYabin Cui         BYTE* const oend = ostart + dstSize;
2085*01826a49SYabin Cui         const void* const dtPtr = DTable;
2086*01826a49SYabin Cui         const HUFv06_DEltX2* const dt = ((const HUFv06_DEltX2*)dtPtr) +1;
2087*01826a49SYabin Cui         const U32 dtLog = DTable[0];
2088*01826a49SYabin Cui         size_t errorCode;
2089*01826a49SYabin Cui 
2090*01826a49SYabin Cui         /* Init */
2091*01826a49SYabin Cui         BITv06_DStream_t bitD1;
2092*01826a49SYabin Cui         BITv06_DStream_t bitD2;
2093*01826a49SYabin Cui         BITv06_DStream_t bitD3;
2094*01826a49SYabin Cui         BITv06_DStream_t bitD4;
2095*01826a49SYabin Cui         const size_t length1 = MEM_readLE16(istart);
2096*01826a49SYabin Cui         const size_t length2 = MEM_readLE16(istart+2);
2097*01826a49SYabin Cui         const size_t length3 = MEM_readLE16(istart+4);
2098*01826a49SYabin Cui         size_t length4;
2099*01826a49SYabin Cui         const BYTE* const istart1 = istart + 6;  /* jumpTable */
2100*01826a49SYabin Cui         const BYTE* const istart2 = istart1 + length1;
2101*01826a49SYabin Cui         const BYTE* const istart3 = istart2 + length2;
2102*01826a49SYabin Cui         const BYTE* const istart4 = istart3 + length3;
2103*01826a49SYabin Cui         const size_t segmentSize = (dstSize+3) / 4;
2104*01826a49SYabin Cui         BYTE* const opStart2 = ostart + segmentSize;
2105*01826a49SYabin Cui         BYTE* const opStart3 = opStart2 + segmentSize;
2106*01826a49SYabin Cui         BYTE* const opStart4 = opStart3 + segmentSize;
2107*01826a49SYabin Cui         BYTE* op1 = ostart;
2108*01826a49SYabin Cui         BYTE* op2 = opStart2;
2109*01826a49SYabin Cui         BYTE* op3 = opStart3;
2110*01826a49SYabin Cui         BYTE* op4 = opStart4;
2111*01826a49SYabin Cui         U32 endSignal;
2112*01826a49SYabin Cui 
2113*01826a49SYabin Cui         length4 = cSrcSize - (length1 + length2 + length3 + 6);
2114*01826a49SYabin Cui         if (length4 > cSrcSize) return ERROR(corruption_detected);   /* overflow */
2115*01826a49SYabin Cui         errorCode = BITv06_initDStream(&bitD1, istart1, length1);
2116*01826a49SYabin Cui         if (HUFv06_isError(errorCode)) return errorCode;
2117*01826a49SYabin Cui         errorCode = BITv06_initDStream(&bitD2, istart2, length2);
2118*01826a49SYabin Cui         if (HUFv06_isError(errorCode)) return errorCode;
2119*01826a49SYabin Cui         errorCode = BITv06_initDStream(&bitD3, istart3, length3);
2120*01826a49SYabin Cui         if (HUFv06_isError(errorCode)) return errorCode;
2121*01826a49SYabin Cui         errorCode = BITv06_initDStream(&bitD4, istart4, length4);
2122*01826a49SYabin Cui         if (HUFv06_isError(errorCode)) return errorCode;
2123*01826a49SYabin Cui 
2124*01826a49SYabin Cui         /* 16-32 symbols per loop (4-8 symbols per stream) */
2125*01826a49SYabin Cui         endSignal = BITv06_reloadDStream(&bitD1) | BITv06_reloadDStream(&bitD2) | BITv06_reloadDStream(&bitD3) | BITv06_reloadDStream(&bitD4);
2126*01826a49SYabin Cui         for ( ; (endSignal==BITv06_DStream_unfinished) && (op4<(oend-7)) ; ) {
2127*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_2(op1, &bitD1);
2128*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_2(op2, &bitD2);
2129*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_2(op3, &bitD3);
2130*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_2(op4, &bitD4);
2131*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_1(op1, &bitD1);
2132*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_1(op2, &bitD2);
2133*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_1(op3, &bitD3);
2134*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_1(op4, &bitD4);
2135*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_2(op1, &bitD1);
2136*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_2(op2, &bitD2);
2137*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_2(op3, &bitD3);
2138*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_2(op4, &bitD4);
2139*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_0(op1, &bitD1);
2140*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_0(op2, &bitD2);
2141*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_0(op3, &bitD3);
2142*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX2_0(op4, &bitD4);
2143*01826a49SYabin Cui             endSignal = BITv06_reloadDStream(&bitD1) | BITv06_reloadDStream(&bitD2) | BITv06_reloadDStream(&bitD3) | BITv06_reloadDStream(&bitD4);
2144*01826a49SYabin Cui         }
2145*01826a49SYabin Cui 
2146*01826a49SYabin Cui         /* check corruption */
2147*01826a49SYabin Cui         if (op1 > opStart2) return ERROR(corruption_detected);
2148*01826a49SYabin Cui         if (op2 > opStart3) return ERROR(corruption_detected);
2149*01826a49SYabin Cui         if (op3 > opStart4) return ERROR(corruption_detected);
2150*01826a49SYabin Cui         /* note : op4 supposed already verified within main loop */
2151*01826a49SYabin Cui 
2152*01826a49SYabin Cui         /* finish bitStreams one by one */
2153*01826a49SYabin Cui         HUFv06_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
2154*01826a49SYabin Cui         HUFv06_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
2155*01826a49SYabin Cui         HUFv06_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
2156*01826a49SYabin Cui         HUFv06_decodeStreamX2(op4, &bitD4, oend,     dt, dtLog);
2157*01826a49SYabin Cui 
2158*01826a49SYabin Cui         /* check */
2159*01826a49SYabin Cui         endSignal = BITv06_endOfDStream(&bitD1) & BITv06_endOfDStream(&bitD2) & BITv06_endOfDStream(&bitD3) & BITv06_endOfDStream(&bitD4);
2160*01826a49SYabin Cui         if (!endSignal) return ERROR(corruption_detected);
2161*01826a49SYabin Cui 
2162*01826a49SYabin Cui         /* decoded size */
2163*01826a49SYabin Cui         return dstSize;
2164*01826a49SYabin Cui     }
2165*01826a49SYabin Cui }
2166*01826a49SYabin Cui 
2167*01826a49SYabin Cui 
HUFv06_decompress4X2(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize)2168*01826a49SYabin Cui size_t HUFv06_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
2169*01826a49SYabin Cui {
2170*01826a49SYabin Cui     HUFv06_CREATE_STATIC_DTABLEX2(DTable, HUFv06_MAX_TABLELOG);
2171*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) cSrc;
2172*01826a49SYabin Cui 
2173*01826a49SYabin Cui     size_t const errorCode = HUFv06_readDTableX2 (DTable, cSrc, cSrcSize);
2174*01826a49SYabin Cui     if (HUFv06_isError(errorCode)) return errorCode;
2175*01826a49SYabin Cui     if (errorCode >= cSrcSize) return ERROR(srcSize_wrong);
2176*01826a49SYabin Cui     ip += errorCode;
2177*01826a49SYabin Cui     cSrcSize -= errorCode;
2178*01826a49SYabin Cui 
2179*01826a49SYabin Cui     return HUFv06_decompress4X2_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
2180*01826a49SYabin Cui }
2181*01826a49SYabin Cui 
2182*01826a49SYabin Cui 
2183*01826a49SYabin Cui /* *************************/
2184*01826a49SYabin Cui /* double-symbols decoding */
2185*01826a49SYabin Cui /* *************************/
2186*01826a49SYabin Cui 
HUFv06_fillDTableX4Level2(HUFv06_DEltX4 * DTable,U32 sizeLog,const U32 consumed,const U32 * rankValOrigin,const int minWeight,const sortedSymbol_t * sortedSymbols,const U32 sortedListSize,U32 nbBitsBaseline,U16 baseSeq)2187*01826a49SYabin Cui static void HUFv06_fillDTableX4Level2(HUFv06_DEltX4* DTable, U32 sizeLog, const U32 consumed,
2188*01826a49SYabin Cui                            const U32* rankValOrigin, const int minWeight,
2189*01826a49SYabin Cui                            const sortedSymbol_t* sortedSymbols, const U32 sortedListSize,
2190*01826a49SYabin Cui                            U32 nbBitsBaseline, U16 baseSeq)
2191*01826a49SYabin Cui {
2192*01826a49SYabin Cui     HUFv06_DEltX4 DElt;
2193*01826a49SYabin Cui     U32 rankVal[HUFv06_ABSOLUTEMAX_TABLELOG + 1];
2194*01826a49SYabin Cui 
2195*01826a49SYabin Cui     /* get pre-calculated rankVal */
2196*01826a49SYabin Cui     memcpy(rankVal, rankValOrigin, sizeof(rankVal));
2197*01826a49SYabin Cui 
2198*01826a49SYabin Cui     /* fill skipped values */
2199*01826a49SYabin Cui     if (minWeight>1) {
2200*01826a49SYabin Cui         U32 i, skipSize = rankVal[minWeight];
2201*01826a49SYabin Cui         MEM_writeLE16(&(DElt.sequence), baseSeq);
2202*01826a49SYabin Cui         DElt.nbBits   = (BYTE)(consumed);
2203*01826a49SYabin Cui         DElt.length   = 1;
2204*01826a49SYabin Cui         for (i = 0; i < skipSize; i++)
2205*01826a49SYabin Cui             DTable[i] = DElt;
2206*01826a49SYabin Cui     }
2207*01826a49SYabin Cui 
2208*01826a49SYabin Cui     /* fill DTable */
2209*01826a49SYabin Cui     { U32 s; for (s=0; s<sortedListSize; s++) {   /* note : sortedSymbols already skipped */
2210*01826a49SYabin Cui         const U32 symbol = sortedSymbols[s].symbol;
2211*01826a49SYabin Cui         const U32 weight = sortedSymbols[s].weight;
2212*01826a49SYabin Cui         const U32 nbBits = nbBitsBaseline - weight;
2213*01826a49SYabin Cui         const U32 length = 1 << (sizeLog-nbBits);
2214*01826a49SYabin Cui         const U32 start = rankVal[weight];
2215*01826a49SYabin Cui         U32 i = start;
2216*01826a49SYabin Cui         const U32 end = start + length;
2217*01826a49SYabin Cui 
2218*01826a49SYabin Cui         MEM_writeLE16(&(DElt.sequence), (U16)(baseSeq + (symbol << 8)));
2219*01826a49SYabin Cui         DElt.nbBits = (BYTE)(nbBits + consumed);
2220*01826a49SYabin Cui         DElt.length = 2;
2221*01826a49SYabin Cui         do { DTable[i++] = DElt; } while (i<end);   /* since length >= 1 */
2222*01826a49SYabin Cui 
2223*01826a49SYabin Cui         rankVal[weight] += length;
2224*01826a49SYabin Cui     }}
2225*01826a49SYabin Cui }
2226*01826a49SYabin Cui 
2227*01826a49SYabin Cui typedef U32 rankVal_t[HUFv06_ABSOLUTEMAX_TABLELOG][HUFv06_ABSOLUTEMAX_TABLELOG + 1];
2228*01826a49SYabin Cui 
HUFv06_fillDTableX4(HUFv06_DEltX4 * DTable,const U32 targetLog,const sortedSymbol_t * sortedList,const U32 sortedListSize,const U32 * rankStart,rankVal_t rankValOrigin,const U32 maxWeight,const U32 nbBitsBaseline)2229*01826a49SYabin Cui static void HUFv06_fillDTableX4(HUFv06_DEltX4* DTable, const U32 targetLog,
2230*01826a49SYabin Cui                            const sortedSymbol_t* sortedList, const U32 sortedListSize,
2231*01826a49SYabin Cui                            const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight,
2232*01826a49SYabin Cui                            const U32 nbBitsBaseline)
2233*01826a49SYabin Cui {
2234*01826a49SYabin Cui     U32 rankVal[HUFv06_ABSOLUTEMAX_TABLELOG + 1];
2235*01826a49SYabin Cui     const int scaleLog = nbBitsBaseline - targetLog;   /* note : targetLog >= srcLog, hence scaleLog <= 1 */
2236*01826a49SYabin Cui     const U32 minBits  = nbBitsBaseline - maxWeight;
2237*01826a49SYabin Cui     U32 s;
2238*01826a49SYabin Cui 
2239*01826a49SYabin Cui     memcpy(rankVal, rankValOrigin, sizeof(rankVal));
2240*01826a49SYabin Cui 
2241*01826a49SYabin Cui     /* fill DTable */
2242*01826a49SYabin Cui     for (s=0; s<sortedListSize; s++) {
2243*01826a49SYabin Cui         const U16 symbol = sortedList[s].symbol;
2244*01826a49SYabin Cui         const U32 weight = sortedList[s].weight;
2245*01826a49SYabin Cui         const U32 nbBits = nbBitsBaseline - weight;
2246*01826a49SYabin Cui         const U32 start = rankVal[weight];
2247*01826a49SYabin Cui         const U32 length = 1 << (targetLog-nbBits);
2248*01826a49SYabin Cui 
2249*01826a49SYabin Cui         if (targetLog-nbBits >= minBits) {   /* enough room for a second symbol */
2250*01826a49SYabin Cui             U32 sortedRank;
2251*01826a49SYabin Cui             int minWeight = nbBits + scaleLog;
2252*01826a49SYabin Cui             if (minWeight < 1) minWeight = 1;
2253*01826a49SYabin Cui             sortedRank = rankStart[minWeight];
2254*01826a49SYabin Cui             HUFv06_fillDTableX4Level2(DTable+start, targetLog-nbBits, nbBits,
2255*01826a49SYabin Cui                            rankValOrigin[nbBits], minWeight,
2256*01826a49SYabin Cui                            sortedList+sortedRank, sortedListSize-sortedRank,
2257*01826a49SYabin Cui                            nbBitsBaseline, symbol);
2258*01826a49SYabin Cui         } else {
2259*01826a49SYabin Cui             HUFv06_DEltX4 DElt;
2260*01826a49SYabin Cui             MEM_writeLE16(&(DElt.sequence), symbol);
2261*01826a49SYabin Cui             DElt.nbBits = (BYTE)(nbBits);
2262*01826a49SYabin Cui             DElt.length = 1;
2263*01826a49SYabin Cui             {   U32 u;
2264*01826a49SYabin Cui                 const U32 end = start + length;
2265*01826a49SYabin Cui                 for (u = start; u < end; u++) DTable[u] = DElt;
2266*01826a49SYabin Cui         }   }
2267*01826a49SYabin Cui         rankVal[weight] += length;
2268*01826a49SYabin Cui     }
2269*01826a49SYabin Cui }
2270*01826a49SYabin Cui 
HUFv06_readDTableX4(U32 * DTable,const void * src,size_t srcSize)2271*01826a49SYabin Cui size_t HUFv06_readDTableX4 (U32* DTable, const void* src, size_t srcSize)
2272*01826a49SYabin Cui {
2273*01826a49SYabin Cui     BYTE weightList[HUFv06_MAX_SYMBOL_VALUE + 1];
2274*01826a49SYabin Cui     sortedSymbol_t sortedSymbol[HUFv06_MAX_SYMBOL_VALUE + 1];
2275*01826a49SYabin Cui     U32 rankStats[HUFv06_ABSOLUTEMAX_TABLELOG + 1] = { 0 };
2276*01826a49SYabin Cui     U32 rankStart0[HUFv06_ABSOLUTEMAX_TABLELOG + 2] = { 0 };
2277*01826a49SYabin Cui     U32* const rankStart = rankStart0+1;
2278*01826a49SYabin Cui     rankVal_t rankVal;
2279*01826a49SYabin Cui     U32 tableLog, maxW, sizeOfSort, nbSymbols;
2280*01826a49SYabin Cui     const U32 memLog = DTable[0];
2281*01826a49SYabin Cui     size_t iSize;
2282*01826a49SYabin Cui     void* dtPtr = DTable;
2283*01826a49SYabin Cui     HUFv06_DEltX4* const dt = ((HUFv06_DEltX4*)dtPtr) + 1;
2284*01826a49SYabin Cui 
2285*01826a49SYabin Cui     HUFv06_STATIC_ASSERT(sizeof(HUFv06_DEltX4) == sizeof(U32));   /* if compilation fails here, assertion is false */
2286*01826a49SYabin Cui     if (memLog > HUFv06_ABSOLUTEMAX_TABLELOG) return ERROR(tableLog_tooLarge);
2287*01826a49SYabin Cui     /* memset(weightList, 0, sizeof(weightList)); */   /* is not necessary, even though some analyzer complain ... */
2288*01826a49SYabin Cui 
2289*01826a49SYabin Cui     iSize = HUFv06_readStats(weightList, HUFv06_MAX_SYMBOL_VALUE + 1, rankStats, &nbSymbols, &tableLog, src, srcSize);
2290*01826a49SYabin Cui     if (HUFv06_isError(iSize)) return iSize;
2291*01826a49SYabin Cui 
2292*01826a49SYabin Cui     /* check result */
2293*01826a49SYabin Cui     if (tableLog > memLog) return ERROR(tableLog_tooLarge);   /* DTable can't fit code depth */
2294*01826a49SYabin Cui 
2295*01826a49SYabin Cui     /* find maxWeight */
2296*01826a49SYabin Cui     for (maxW = tableLog; rankStats[maxW]==0; maxW--) {}  /* necessarily finds a solution before 0 */
2297*01826a49SYabin Cui 
2298*01826a49SYabin Cui     /* Get start index of each weight */
2299*01826a49SYabin Cui     {   U32 w, nextRankStart = 0;
2300*01826a49SYabin Cui         for (w=1; w<maxW+1; w++) {
2301*01826a49SYabin Cui             U32 current = nextRankStart;
2302*01826a49SYabin Cui             nextRankStart += rankStats[w];
2303*01826a49SYabin Cui             rankStart[w] = current;
2304*01826a49SYabin Cui         }
2305*01826a49SYabin Cui         rankStart[0] = nextRankStart;   /* put all 0w symbols at the end of sorted list*/
2306*01826a49SYabin Cui         sizeOfSort = nextRankStart;
2307*01826a49SYabin Cui     }
2308*01826a49SYabin Cui 
2309*01826a49SYabin Cui     /* sort symbols by weight */
2310*01826a49SYabin Cui     {   U32 s;
2311*01826a49SYabin Cui         for (s=0; s<nbSymbols; s++) {
2312*01826a49SYabin Cui             U32 const w = weightList[s];
2313*01826a49SYabin Cui             U32 const r = rankStart[w]++;
2314*01826a49SYabin Cui             sortedSymbol[r].symbol = (BYTE)s;
2315*01826a49SYabin Cui             sortedSymbol[r].weight = (BYTE)w;
2316*01826a49SYabin Cui         }
2317*01826a49SYabin Cui         rankStart[0] = 0;   /* forget 0w symbols; this is beginning of weight(1) */
2318*01826a49SYabin Cui     }
2319*01826a49SYabin Cui 
2320*01826a49SYabin Cui     /* Build rankVal */
2321*01826a49SYabin Cui     {   U32* const rankVal0 = rankVal[0];
2322*01826a49SYabin Cui         {   int const rescale = (memLog-tableLog) - 1;   /* tableLog <= memLog */
2323*01826a49SYabin Cui             U32 nextRankVal = 0;
2324*01826a49SYabin Cui             U32 w;
2325*01826a49SYabin Cui             for (w=1; w<maxW+1; w++) {
2326*01826a49SYabin Cui                 U32 current = nextRankVal;
2327*01826a49SYabin Cui                 nextRankVal += rankStats[w] << (w+rescale);
2328*01826a49SYabin Cui                 rankVal0[w] = current;
2329*01826a49SYabin Cui         }   }
2330*01826a49SYabin Cui         {   U32 const minBits = tableLog+1 - maxW;
2331*01826a49SYabin Cui             U32 consumed;
2332*01826a49SYabin Cui             for (consumed = minBits; consumed < memLog - minBits + 1; consumed++) {
2333*01826a49SYabin Cui                 U32* const rankValPtr = rankVal[consumed];
2334*01826a49SYabin Cui                 U32 w;
2335*01826a49SYabin Cui                 for (w = 1; w < maxW+1; w++) {
2336*01826a49SYabin Cui                     rankValPtr[w] = rankVal0[w] >> consumed;
2337*01826a49SYabin Cui     }   }   }   }
2338*01826a49SYabin Cui 
2339*01826a49SYabin Cui     HUFv06_fillDTableX4(dt, memLog,
2340*01826a49SYabin Cui                    sortedSymbol, sizeOfSort,
2341*01826a49SYabin Cui                    rankStart0, rankVal, maxW,
2342*01826a49SYabin Cui                    tableLog+1);
2343*01826a49SYabin Cui 
2344*01826a49SYabin Cui     return iSize;
2345*01826a49SYabin Cui }
2346*01826a49SYabin Cui 
2347*01826a49SYabin Cui 
HUFv06_decodeSymbolX4(void * op,BITv06_DStream_t * DStream,const HUFv06_DEltX4 * dt,const U32 dtLog)2348*01826a49SYabin Cui static U32 HUFv06_decodeSymbolX4(void* op, BITv06_DStream_t* DStream, const HUFv06_DEltX4* dt, const U32 dtLog)
2349*01826a49SYabin Cui {
2350*01826a49SYabin Cui     const size_t val = BITv06_lookBitsFast(DStream, dtLog);   /* note : dtLog >= 1 */
2351*01826a49SYabin Cui     memcpy(op, dt+val, 2);
2352*01826a49SYabin Cui     BITv06_skipBits(DStream, dt[val].nbBits);
2353*01826a49SYabin Cui     return dt[val].length;
2354*01826a49SYabin Cui }
2355*01826a49SYabin Cui 
HUFv06_decodeLastSymbolX4(void * op,BITv06_DStream_t * DStream,const HUFv06_DEltX4 * dt,const U32 dtLog)2356*01826a49SYabin Cui static U32 HUFv06_decodeLastSymbolX4(void* op, BITv06_DStream_t* DStream, const HUFv06_DEltX4* dt, const U32 dtLog)
2357*01826a49SYabin Cui {
2358*01826a49SYabin Cui     const size_t val = BITv06_lookBitsFast(DStream, dtLog);   /* note : dtLog >= 1 */
2359*01826a49SYabin Cui     memcpy(op, dt+val, 1);
2360*01826a49SYabin Cui     if (dt[val].length==1) BITv06_skipBits(DStream, dt[val].nbBits);
2361*01826a49SYabin Cui     else {
2362*01826a49SYabin Cui         if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8)) {
2363*01826a49SYabin Cui             BITv06_skipBits(DStream, dt[val].nbBits);
2364*01826a49SYabin Cui             if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
2365*01826a49SYabin Cui                 DStream->bitsConsumed = (sizeof(DStream->bitContainer)*8);   /* ugly hack; works only because it's the last symbol. Note : can't easily extract nbBits from just this symbol */
2366*01826a49SYabin Cui     }   }
2367*01826a49SYabin Cui     return 1;
2368*01826a49SYabin Cui }
2369*01826a49SYabin Cui 
2370*01826a49SYabin Cui 
2371*01826a49SYabin Cui #define HUFv06_DECODE_SYMBOLX4_0(ptr, DStreamPtr) \
2372*01826a49SYabin Cui     ptr += HUFv06_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
2373*01826a49SYabin Cui 
2374*01826a49SYabin Cui #define HUFv06_DECODE_SYMBOLX4_1(ptr, DStreamPtr) \
2375*01826a49SYabin Cui     if (MEM_64bits() || (HUFv06_MAX_TABLELOG<=12)) \
2376*01826a49SYabin Cui         ptr += HUFv06_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
2377*01826a49SYabin Cui 
2378*01826a49SYabin Cui #define HUFv06_DECODE_SYMBOLX4_2(ptr, DStreamPtr) \
2379*01826a49SYabin Cui     if (MEM_64bits()) \
2380*01826a49SYabin Cui         ptr += HUFv06_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
2381*01826a49SYabin Cui 
HUFv06_decodeStreamX4(BYTE * p,BITv06_DStream_t * bitDPtr,BYTE * const pEnd,const HUFv06_DEltX4 * const dt,const U32 dtLog)2382*01826a49SYabin Cui static inline size_t HUFv06_decodeStreamX4(BYTE* p, BITv06_DStream_t* bitDPtr, BYTE* const pEnd, const HUFv06_DEltX4* const dt, const U32 dtLog)
2383*01826a49SYabin Cui {
2384*01826a49SYabin Cui     BYTE* const pStart = p;
2385*01826a49SYabin Cui 
2386*01826a49SYabin Cui     /* up to 8 symbols at a time */
2387*01826a49SYabin Cui     while ((BITv06_reloadDStream(bitDPtr) == BITv06_DStream_unfinished) && (p < pEnd-7)) {
2388*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX4_2(p, bitDPtr);
2389*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX4_1(p, bitDPtr);
2390*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX4_2(p, bitDPtr);
2391*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX4_0(p, bitDPtr);
2392*01826a49SYabin Cui     }
2393*01826a49SYabin Cui 
2394*01826a49SYabin Cui     /* closer to the end */
2395*01826a49SYabin Cui     while ((BITv06_reloadDStream(bitDPtr) == BITv06_DStream_unfinished) && (p <= pEnd-2))
2396*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX4_0(p, bitDPtr);
2397*01826a49SYabin Cui 
2398*01826a49SYabin Cui     while (p <= pEnd-2)
2399*01826a49SYabin Cui         HUFv06_DECODE_SYMBOLX4_0(p, bitDPtr);   /* no need to reload : reached the end of DStream */
2400*01826a49SYabin Cui 
2401*01826a49SYabin Cui     if (p < pEnd)
2402*01826a49SYabin Cui         p += HUFv06_decodeLastSymbolX4(p, bitDPtr, dt, dtLog);
2403*01826a49SYabin Cui 
2404*01826a49SYabin Cui     return p-pStart;
2405*01826a49SYabin Cui }
2406*01826a49SYabin Cui 
2407*01826a49SYabin Cui 
HUFv06_decompress1X4_usingDTable(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize,const U32 * DTable)2408*01826a49SYabin Cui size_t HUFv06_decompress1X4_usingDTable(
2409*01826a49SYabin Cui           void* dst,  size_t dstSize,
2410*01826a49SYabin Cui     const void* cSrc, size_t cSrcSize,
2411*01826a49SYabin Cui     const U32* DTable)
2412*01826a49SYabin Cui {
2413*01826a49SYabin Cui     const BYTE* const istart = (const BYTE*) cSrc;
2414*01826a49SYabin Cui     BYTE* const ostart = (BYTE*) dst;
2415*01826a49SYabin Cui     BYTE* const oend = ostart + dstSize;
2416*01826a49SYabin Cui 
2417*01826a49SYabin Cui     const U32 dtLog = DTable[0];
2418*01826a49SYabin Cui     const void* const dtPtr = DTable;
2419*01826a49SYabin Cui     const HUFv06_DEltX4* const dt = ((const HUFv06_DEltX4*)dtPtr) +1;
2420*01826a49SYabin Cui 
2421*01826a49SYabin Cui     /* Init */
2422*01826a49SYabin Cui     BITv06_DStream_t bitD;
2423*01826a49SYabin Cui     { size_t const errorCode = BITv06_initDStream(&bitD, istart, cSrcSize);
2424*01826a49SYabin Cui       if (HUFv06_isError(errorCode)) return errorCode; }
2425*01826a49SYabin Cui 
2426*01826a49SYabin Cui     /* decode */
2427*01826a49SYabin Cui     HUFv06_decodeStreamX4(ostart, &bitD, oend, dt, dtLog);
2428*01826a49SYabin Cui 
2429*01826a49SYabin Cui     /* check */
2430*01826a49SYabin Cui     if (!BITv06_endOfDStream(&bitD)) return ERROR(corruption_detected);
2431*01826a49SYabin Cui 
2432*01826a49SYabin Cui     /* decoded size */
2433*01826a49SYabin Cui     return dstSize;
2434*01826a49SYabin Cui }
2435*01826a49SYabin Cui 
HUFv06_decompress1X4(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize)2436*01826a49SYabin Cui size_t HUFv06_decompress1X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
2437*01826a49SYabin Cui {
2438*01826a49SYabin Cui     HUFv06_CREATE_STATIC_DTABLEX4(DTable, HUFv06_MAX_TABLELOG);
2439*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) cSrc;
2440*01826a49SYabin Cui 
2441*01826a49SYabin Cui     size_t const hSize = HUFv06_readDTableX4 (DTable, cSrc, cSrcSize);
2442*01826a49SYabin Cui     if (HUFv06_isError(hSize)) return hSize;
2443*01826a49SYabin Cui     if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
2444*01826a49SYabin Cui     ip += hSize;
2445*01826a49SYabin Cui     cSrcSize -= hSize;
2446*01826a49SYabin Cui 
2447*01826a49SYabin Cui     return HUFv06_decompress1X4_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
2448*01826a49SYabin Cui }
2449*01826a49SYabin Cui 
HUFv06_decompress4X4_usingDTable(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize,const U32 * DTable)2450*01826a49SYabin Cui size_t HUFv06_decompress4X4_usingDTable(
2451*01826a49SYabin Cui           void* dst,  size_t dstSize,
2452*01826a49SYabin Cui     const void* cSrc, size_t cSrcSize,
2453*01826a49SYabin Cui     const U32* DTable)
2454*01826a49SYabin Cui {
2455*01826a49SYabin Cui     if (cSrcSize < 10) return ERROR(corruption_detected);   /* strict minimum : jump table + 1 byte per stream */
2456*01826a49SYabin Cui 
2457*01826a49SYabin Cui     {   const BYTE* const istart = (const BYTE*) cSrc;
2458*01826a49SYabin Cui         BYTE* const ostart = (BYTE*) dst;
2459*01826a49SYabin Cui         BYTE* const oend = ostart + dstSize;
2460*01826a49SYabin Cui         const void* const dtPtr = DTable;
2461*01826a49SYabin Cui         const HUFv06_DEltX4* const dt = ((const HUFv06_DEltX4*)dtPtr) +1;
2462*01826a49SYabin Cui         const U32 dtLog = DTable[0];
2463*01826a49SYabin Cui         size_t errorCode;
2464*01826a49SYabin Cui 
2465*01826a49SYabin Cui         /* Init */
2466*01826a49SYabin Cui         BITv06_DStream_t bitD1;
2467*01826a49SYabin Cui         BITv06_DStream_t bitD2;
2468*01826a49SYabin Cui         BITv06_DStream_t bitD3;
2469*01826a49SYabin Cui         BITv06_DStream_t bitD4;
2470*01826a49SYabin Cui         const size_t length1 = MEM_readLE16(istart);
2471*01826a49SYabin Cui         const size_t length2 = MEM_readLE16(istart+2);
2472*01826a49SYabin Cui         const size_t length3 = MEM_readLE16(istart+4);
2473*01826a49SYabin Cui         size_t length4;
2474*01826a49SYabin Cui         const BYTE* const istart1 = istart + 6;  /* jumpTable */
2475*01826a49SYabin Cui         const BYTE* const istart2 = istart1 + length1;
2476*01826a49SYabin Cui         const BYTE* const istart3 = istart2 + length2;
2477*01826a49SYabin Cui         const BYTE* const istart4 = istart3 + length3;
2478*01826a49SYabin Cui         const size_t segmentSize = (dstSize+3) / 4;
2479*01826a49SYabin Cui         BYTE* const opStart2 = ostart + segmentSize;
2480*01826a49SYabin Cui         BYTE* const opStart3 = opStart2 + segmentSize;
2481*01826a49SYabin Cui         BYTE* const opStart4 = opStart3 + segmentSize;
2482*01826a49SYabin Cui         BYTE* op1 = ostart;
2483*01826a49SYabin Cui         BYTE* op2 = opStart2;
2484*01826a49SYabin Cui         BYTE* op3 = opStart3;
2485*01826a49SYabin Cui         BYTE* op4 = opStart4;
2486*01826a49SYabin Cui         U32 endSignal;
2487*01826a49SYabin Cui 
2488*01826a49SYabin Cui         length4 = cSrcSize - (length1 + length2 + length3 + 6);
2489*01826a49SYabin Cui         if (length4 > cSrcSize) return ERROR(corruption_detected);   /* overflow */
2490*01826a49SYabin Cui         errorCode = BITv06_initDStream(&bitD1, istart1, length1);
2491*01826a49SYabin Cui         if (HUFv06_isError(errorCode)) return errorCode;
2492*01826a49SYabin Cui         errorCode = BITv06_initDStream(&bitD2, istart2, length2);
2493*01826a49SYabin Cui         if (HUFv06_isError(errorCode)) return errorCode;
2494*01826a49SYabin Cui         errorCode = BITv06_initDStream(&bitD3, istart3, length3);
2495*01826a49SYabin Cui         if (HUFv06_isError(errorCode)) return errorCode;
2496*01826a49SYabin Cui         errorCode = BITv06_initDStream(&bitD4, istart4, length4);
2497*01826a49SYabin Cui         if (HUFv06_isError(errorCode)) return errorCode;
2498*01826a49SYabin Cui 
2499*01826a49SYabin Cui         /* 16-32 symbols per loop (4-8 symbols per stream) */
2500*01826a49SYabin Cui         endSignal = BITv06_reloadDStream(&bitD1) | BITv06_reloadDStream(&bitD2) | BITv06_reloadDStream(&bitD3) | BITv06_reloadDStream(&bitD4);
2501*01826a49SYabin Cui         for ( ; (endSignal==BITv06_DStream_unfinished) && (op4<(oend-7)) ; ) {
2502*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_2(op1, &bitD1);
2503*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_2(op2, &bitD2);
2504*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_2(op3, &bitD3);
2505*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_2(op4, &bitD4);
2506*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_1(op1, &bitD1);
2507*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_1(op2, &bitD2);
2508*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_1(op3, &bitD3);
2509*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_1(op4, &bitD4);
2510*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_2(op1, &bitD1);
2511*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_2(op2, &bitD2);
2512*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_2(op3, &bitD3);
2513*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_2(op4, &bitD4);
2514*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_0(op1, &bitD1);
2515*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_0(op2, &bitD2);
2516*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_0(op3, &bitD3);
2517*01826a49SYabin Cui             HUFv06_DECODE_SYMBOLX4_0(op4, &bitD4);
2518*01826a49SYabin Cui 
2519*01826a49SYabin Cui             endSignal = BITv06_reloadDStream(&bitD1) | BITv06_reloadDStream(&bitD2) | BITv06_reloadDStream(&bitD3) | BITv06_reloadDStream(&bitD4);
2520*01826a49SYabin Cui         }
2521*01826a49SYabin Cui 
2522*01826a49SYabin Cui         /* check corruption */
2523*01826a49SYabin Cui         if (op1 > opStart2) return ERROR(corruption_detected);
2524*01826a49SYabin Cui         if (op2 > opStart3) return ERROR(corruption_detected);
2525*01826a49SYabin Cui         if (op3 > opStart4) return ERROR(corruption_detected);
2526*01826a49SYabin Cui         /* note : op4 supposed already verified within main loop */
2527*01826a49SYabin Cui 
2528*01826a49SYabin Cui         /* finish bitStreams one by one */
2529*01826a49SYabin Cui         HUFv06_decodeStreamX4(op1, &bitD1, opStart2, dt, dtLog);
2530*01826a49SYabin Cui         HUFv06_decodeStreamX4(op2, &bitD2, opStart3, dt, dtLog);
2531*01826a49SYabin Cui         HUFv06_decodeStreamX4(op3, &bitD3, opStart4, dt, dtLog);
2532*01826a49SYabin Cui         HUFv06_decodeStreamX4(op4, &bitD4, oend,     dt, dtLog);
2533*01826a49SYabin Cui 
2534*01826a49SYabin Cui         /* check */
2535*01826a49SYabin Cui         endSignal = BITv06_endOfDStream(&bitD1) & BITv06_endOfDStream(&bitD2) & BITv06_endOfDStream(&bitD3) & BITv06_endOfDStream(&bitD4);
2536*01826a49SYabin Cui         if (!endSignal) return ERROR(corruption_detected);
2537*01826a49SYabin Cui 
2538*01826a49SYabin Cui         /* decoded size */
2539*01826a49SYabin Cui         return dstSize;
2540*01826a49SYabin Cui     }
2541*01826a49SYabin Cui }
2542*01826a49SYabin Cui 
2543*01826a49SYabin Cui 
HUFv06_decompress4X4(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize)2544*01826a49SYabin Cui size_t HUFv06_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
2545*01826a49SYabin Cui {
2546*01826a49SYabin Cui     HUFv06_CREATE_STATIC_DTABLEX4(DTable, HUFv06_MAX_TABLELOG);
2547*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) cSrc;
2548*01826a49SYabin Cui 
2549*01826a49SYabin Cui     size_t hSize = HUFv06_readDTableX4 (DTable, cSrc, cSrcSize);
2550*01826a49SYabin Cui     if (HUFv06_isError(hSize)) return hSize;
2551*01826a49SYabin Cui     if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
2552*01826a49SYabin Cui     ip += hSize;
2553*01826a49SYabin Cui     cSrcSize -= hSize;
2554*01826a49SYabin Cui 
2555*01826a49SYabin Cui     return HUFv06_decompress4X4_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
2556*01826a49SYabin Cui }
2557*01826a49SYabin Cui 
2558*01826a49SYabin Cui 
2559*01826a49SYabin Cui 
2560*01826a49SYabin Cui 
2561*01826a49SYabin Cui /* ********************************/
2562*01826a49SYabin Cui /* Generic decompression selector */
2563*01826a49SYabin Cui /* ********************************/
2564*01826a49SYabin Cui 
2565*01826a49SYabin Cui typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t;
2566*01826a49SYabin Cui static const algo_time_t algoTime[16 /* Quantization */][3 /* single, double, quad */] =
2567*01826a49SYabin Cui {
2568*01826a49SYabin Cui     /* single, double, quad */
2569*01826a49SYabin Cui     {{0,0}, {1,1}, {2,2}},  /* Q==0 : impossible */
2570*01826a49SYabin Cui     {{0,0}, {1,1}, {2,2}},  /* Q==1 : impossible */
2571*01826a49SYabin Cui     {{  38,130}, {1313, 74}, {2151, 38}},   /* Q == 2 : 12-18% */
2572*01826a49SYabin Cui     {{ 448,128}, {1353, 74}, {2238, 41}},   /* Q == 3 : 18-25% */
2573*01826a49SYabin Cui     {{ 556,128}, {1353, 74}, {2238, 47}},   /* Q == 4 : 25-32% */
2574*01826a49SYabin Cui     {{ 714,128}, {1418, 74}, {2436, 53}},   /* Q == 5 : 32-38% */
2575*01826a49SYabin Cui     {{ 883,128}, {1437, 74}, {2464, 61}},   /* Q == 6 : 38-44% */
2576*01826a49SYabin Cui     {{ 897,128}, {1515, 75}, {2622, 68}},   /* Q == 7 : 44-50% */
2577*01826a49SYabin Cui     {{ 926,128}, {1613, 75}, {2730, 75}},   /* Q == 8 : 50-56% */
2578*01826a49SYabin Cui     {{ 947,128}, {1729, 77}, {3359, 77}},   /* Q == 9 : 56-62% */
2579*01826a49SYabin Cui     {{1107,128}, {2083, 81}, {4006, 84}},   /* Q ==10 : 62-69% */
2580*01826a49SYabin Cui     {{1177,128}, {2379, 87}, {4785, 88}},   /* Q ==11 : 69-75% */
2581*01826a49SYabin Cui     {{1242,128}, {2415, 93}, {5155, 84}},   /* Q ==12 : 75-81% */
2582*01826a49SYabin Cui     {{1349,128}, {2644,106}, {5260,106}},   /* Q ==13 : 81-87% */
2583*01826a49SYabin Cui     {{1455,128}, {2422,124}, {4174,124}},   /* Q ==14 : 87-93% */
2584*01826a49SYabin Cui     {{ 722,128}, {1891,145}, {1936,146}},   /* Q ==15 : 93-99% */
2585*01826a49SYabin Cui };
2586*01826a49SYabin Cui 
2587*01826a49SYabin Cui typedef size_t (*decompressionAlgo)(void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
2588*01826a49SYabin Cui 
HUFv06_decompress(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize)2589*01826a49SYabin Cui size_t HUFv06_decompress (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
2590*01826a49SYabin Cui {
2591*01826a49SYabin Cui     static const decompressionAlgo decompress[3] = { HUFv06_decompress4X2, HUFv06_decompress4X4, NULL };
2592*01826a49SYabin Cui     U32 Dtime[3];   /* decompression time estimation */
2593*01826a49SYabin Cui 
2594*01826a49SYabin Cui     /* validation checks */
2595*01826a49SYabin Cui     if (dstSize == 0) return ERROR(dstSize_tooSmall);
2596*01826a49SYabin Cui     if (cSrcSize > dstSize) return ERROR(corruption_detected);   /* invalid */
2597*01826a49SYabin Cui     if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; }   /* not compressed */
2598*01826a49SYabin Cui     if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; }   /* RLE */
2599*01826a49SYabin Cui 
2600*01826a49SYabin Cui     /* decoder timing evaluation */
2601*01826a49SYabin Cui     {   U32 const Q = (U32)(cSrcSize * 16 / dstSize);   /* Q < 16 since dstSize > cSrcSize */
2602*01826a49SYabin Cui         U32 const D256 = (U32)(dstSize >> 8);
2603*01826a49SYabin Cui         U32 n; for (n=0; n<3; n++)
2604*01826a49SYabin Cui             Dtime[n] = algoTime[Q][n].tableTime + (algoTime[Q][n].decode256Time * D256);
2605*01826a49SYabin Cui     }
2606*01826a49SYabin Cui 
2607*01826a49SYabin Cui     Dtime[1] += Dtime[1] >> 4; Dtime[2] += Dtime[2] >> 3; /* advantage to algorithms using less memory, for cache eviction */
2608*01826a49SYabin Cui 
2609*01826a49SYabin Cui     {   U32 algoNb = 0;
2610*01826a49SYabin Cui         if (Dtime[1] < Dtime[0]) algoNb = 1;
2611*01826a49SYabin Cui         /* if (Dtime[2] < Dtime[algoNb]) algoNb = 2; */   /* current speed of HUFv06_decompress4X6 is not good */
2612*01826a49SYabin Cui         return decompress[algoNb](dst, dstSize, cSrc, cSrcSize);
2613*01826a49SYabin Cui     }
2614*01826a49SYabin Cui 
2615*01826a49SYabin Cui     /* return HUFv06_decompress4X2(dst, dstSize, cSrc, cSrcSize); */   /* multi-streams single-symbol decoding */
2616*01826a49SYabin Cui     /* return HUFv06_decompress4X4(dst, dstSize, cSrc, cSrcSize); */   /* multi-streams double-symbols decoding */
2617*01826a49SYabin Cui     /* return HUFv06_decompress4X6(dst, dstSize, cSrc, cSrcSize); */   /* multi-streams quad-symbols decoding */
2618*01826a49SYabin Cui }
2619*01826a49SYabin Cui /*
2620*01826a49SYabin Cui     Common functions of Zstd compression library
2621*01826a49SYabin Cui     Copyright (C) 2015-2016, Yann Collet.
2622*01826a49SYabin Cui 
2623*01826a49SYabin Cui     BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
2624*01826a49SYabin Cui 
2625*01826a49SYabin Cui     Redistribution and use in source and binary forms, with or without
2626*01826a49SYabin Cui     modification, are permitted provided that the following conditions are
2627*01826a49SYabin Cui     met:
2628*01826a49SYabin Cui     * Redistributions of source code must retain the above copyright
2629*01826a49SYabin Cui     notice, this list of conditions and the following disclaimer.
2630*01826a49SYabin Cui     * Redistributions in binary form must reproduce the above
2631*01826a49SYabin Cui     copyright notice, this list of conditions and the following disclaimer
2632*01826a49SYabin Cui     in the documentation and/or other materials provided with the
2633*01826a49SYabin Cui     distribution.
2634*01826a49SYabin Cui     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2635*01826a49SYabin Cui     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2636*01826a49SYabin Cui     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2637*01826a49SYabin Cui     A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2638*01826a49SYabin Cui     OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2639*01826a49SYabin Cui     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2640*01826a49SYabin Cui     LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2641*01826a49SYabin Cui     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2642*01826a49SYabin Cui     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2643*01826a49SYabin Cui     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2644*01826a49SYabin Cui     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2645*01826a49SYabin Cui 
2646*01826a49SYabin Cui     You can contact the author at :
2647*01826a49SYabin Cui     - zstd homepage : https://facebook.github.io/zstd/
2648*01826a49SYabin Cui */
2649*01826a49SYabin Cui 
2650*01826a49SYabin Cui 
2651*01826a49SYabin Cui /*-****************************************
2652*01826a49SYabin Cui *  Version
2653*01826a49SYabin Cui ******************************************/
2654*01826a49SYabin Cui 
2655*01826a49SYabin Cui /*-****************************************
2656*01826a49SYabin Cui *  ZSTD Error Management
2657*01826a49SYabin Cui ******************************************/
2658*01826a49SYabin Cui /*! ZSTDv06_isError() :
2659*01826a49SYabin Cui *   tells if a return value is an error code */
ZSTDv06_isError(size_t code)2660*01826a49SYabin Cui unsigned ZSTDv06_isError(size_t code) { return ERR_isError(code); }
2661*01826a49SYabin Cui 
2662*01826a49SYabin Cui /*! ZSTDv06_getErrorName() :
2663*01826a49SYabin Cui *   provides error code string from function result (useful for debugging) */
ZSTDv06_getErrorName(size_t code)2664*01826a49SYabin Cui const char* ZSTDv06_getErrorName(size_t code) { return ERR_getErrorName(code); }
2665*01826a49SYabin Cui 
2666*01826a49SYabin Cui 
2667*01826a49SYabin Cui /* **************************************************************
2668*01826a49SYabin Cui *  ZBUFF Error Management
2669*01826a49SYabin Cui ****************************************************************/
ZBUFFv06_isError(size_t errorCode)2670*01826a49SYabin Cui unsigned ZBUFFv06_isError(size_t errorCode) { return ERR_isError(errorCode); }
2671*01826a49SYabin Cui 
ZBUFFv06_getErrorName(size_t errorCode)2672*01826a49SYabin Cui const char* ZBUFFv06_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
2673*01826a49SYabin Cui /*
2674*01826a49SYabin Cui     zstd - standard compression library
2675*01826a49SYabin Cui     Copyright (C) 2014-2016, Yann Collet.
2676*01826a49SYabin Cui 
2677*01826a49SYabin Cui     BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
2678*01826a49SYabin Cui 
2679*01826a49SYabin Cui     Redistribution and use in source and binary forms, with or without
2680*01826a49SYabin Cui     modification, are permitted provided that the following conditions are
2681*01826a49SYabin Cui     met:
2682*01826a49SYabin Cui     * Redistributions of source code must retain the above copyright
2683*01826a49SYabin Cui     notice, this list of conditions and the following disclaimer.
2684*01826a49SYabin Cui     * Redistributions in binary form must reproduce the above
2685*01826a49SYabin Cui     copyright notice, this list of conditions and the following disclaimer
2686*01826a49SYabin Cui     in the documentation and/or other materials provided with the
2687*01826a49SYabin Cui     distribution.
2688*01826a49SYabin Cui     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2689*01826a49SYabin Cui     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2690*01826a49SYabin Cui     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2691*01826a49SYabin Cui     A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2692*01826a49SYabin Cui     OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2693*01826a49SYabin Cui     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2694*01826a49SYabin Cui     LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2695*01826a49SYabin Cui     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2696*01826a49SYabin Cui     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2697*01826a49SYabin Cui     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2698*01826a49SYabin Cui     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2699*01826a49SYabin Cui 
2700*01826a49SYabin Cui     You can contact the author at :
2701*01826a49SYabin Cui     - zstd homepage : https://facebook.github.io/zstd
2702*01826a49SYabin Cui */
2703*01826a49SYabin Cui 
2704*01826a49SYabin Cui /* ***************************************************************
2705*01826a49SYabin Cui *  Tuning parameters
2706*01826a49SYabin Cui *****************************************************************/
2707*01826a49SYabin Cui /*!
2708*01826a49SYabin Cui  * HEAPMODE :
2709*01826a49SYabin Cui  * Select how default decompression function ZSTDv06_decompress() will allocate memory,
2710*01826a49SYabin Cui  * in memory stack (0), or in memory heap (1, requires malloc())
2711*01826a49SYabin Cui  */
2712*01826a49SYabin Cui #ifndef ZSTDv06_HEAPMODE
2713*01826a49SYabin Cui #  define ZSTDv06_HEAPMODE 1
2714*01826a49SYabin Cui #endif
2715*01826a49SYabin Cui 
2716*01826a49SYabin Cui 
2717*01826a49SYabin Cui 
2718*01826a49SYabin Cui /*-*******************************************************
2719*01826a49SYabin Cui *  Compiler specifics
2720*01826a49SYabin Cui *********************************************************/
2721*01826a49SYabin Cui #ifdef _MSC_VER    /* Visual Studio */
2722*01826a49SYabin Cui #  include <intrin.h>                    /* For Visual 2005 */
2723*01826a49SYabin Cui #  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */
2724*01826a49SYabin Cui #  pragma warning(disable : 4324)        /* disable: C4324: padded structure */
2725*01826a49SYabin Cui #endif
2726*01826a49SYabin Cui 
2727*01826a49SYabin Cui 
2728*01826a49SYabin Cui /*-*************************************
2729*01826a49SYabin Cui *  Macros
2730*01826a49SYabin Cui ***************************************/
2731*01826a49SYabin Cui #define ZSTDv06_isError ERR_isError   /* for inlining */
2732*01826a49SYabin Cui #define FSEv06_isError  ERR_isError
2733*01826a49SYabin Cui #define HUFv06_isError  ERR_isError
2734*01826a49SYabin Cui 
2735*01826a49SYabin Cui 
2736*01826a49SYabin Cui /*_*******************************************************
2737*01826a49SYabin Cui *  Memory operations
2738*01826a49SYabin Cui **********************************************************/
ZSTDv06_copy4(void * dst,const void * src)2739*01826a49SYabin Cui static void ZSTDv06_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
2740*01826a49SYabin Cui 
2741*01826a49SYabin Cui 
2742*01826a49SYabin Cui /*-*************************************************************
2743*01826a49SYabin Cui *   Context management
2744*01826a49SYabin Cui ***************************************************************/
2745*01826a49SYabin Cui typedef enum { ZSTDds_getFrameHeaderSize, ZSTDds_decodeFrameHeader,
2746*01826a49SYabin Cui                ZSTDds_decodeBlockHeader, ZSTDds_decompressBlock } ZSTDv06_dStage;
2747*01826a49SYabin Cui 
2748*01826a49SYabin Cui struct ZSTDv06_DCtx_s
2749*01826a49SYabin Cui {
2750*01826a49SYabin Cui     FSEv06_DTable LLTable[FSEv06_DTABLE_SIZE_U32(LLFSELog)];
2751*01826a49SYabin Cui     FSEv06_DTable OffTable[FSEv06_DTABLE_SIZE_U32(OffFSELog)];
2752*01826a49SYabin Cui     FSEv06_DTable MLTable[FSEv06_DTABLE_SIZE_U32(MLFSELog)];
2753*01826a49SYabin Cui     unsigned   hufTableX4[HUFv06_DTABLE_SIZE(ZSTD_HUFFDTABLE_CAPACITY_LOG)];
2754*01826a49SYabin Cui     const void* previousDstEnd;
2755*01826a49SYabin Cui     const void* base;
2756*01826a49SYabin Cui     const void* vBase;
2757*01826a49SYabin Cui     const void* dictEnd;
2758*01826a49SYabin Cui     size_t expected;
2759*01826a49SYabin Cui     size_t headerSize;
2760*01826a49SYabin Cui     ZSTDv06_frameParams fParams;
2761*01826a49SYabin Cui     blockType_t bType;   /* used in ZSTDv06_decompressContinue(), to transfer blockType between header decoding and block decoding stages */
2762*01826a49SYabin Cui     ZSTDv06_dStage stage;
2763*01826a49SYabin Cui     U32 flagRepeatTable;
2764*01826a49SYabin Cui     const BYTE* litPtr;
2765*01826a49SYabin Cui     size_t litSize;
2766*01826a49SYabin Cui     BYTE litBuffer[ZSTDv06_BLOCKSIZE_MAX + WILDCOPY_OVERLENGTH];
2767*01826a49SYabin Cui     BYTE headerBuffer[ZSTDv06_FRAMEHEADERSIZE_MAX];
2768*01826a49SYabin Cui };  /* typedef'd to ZSTDv06_DCtx within "zstd_static.h" */
2769*01826a49SYabin Cui 
2770*01826a49SYabin Cui size_t ZSTDv06_sizeofDCtx (void); /* Hidden declaration */
ZSTDv06_sizeofDCtx(void)2771*01826a49SYabin Cui size_t ZSTDv06_sizeofDCtx (void) { return sizeof(ZSTDv06_DCtx); }
2772*01826a49SYabin Cui 
ZSTDv06_decompressBegin(ZSTDv06_DCtx * dctx)2773*01826a49SYabin Cui size_t ZSTDv06_decompressBegin(ZSTDv06_DCtx* dctx)
2774*01826a49SYabin Cui {
2775*01826a49SYabin Cui     dctx->expected = ZSTDv06_frameHeaderSize_min;
2776*01826a49SYabin Cui     dctx->stage = ZSTDds_getFrameHeaderSize;
2777*01826a49SYabin Cui     dctx->previousDstEnd = NULL;
2778*01826a49SYabin Cui     dctx->base = NULL;
2779*01826a49SYabin Cui     dctx->vBase = NULL;
2780*01826a49SYabin Cui     dctx->dictEnd = NULL;
2781*01826a49SYabin Cui     dctx->hufTableX4[0] = ZSTD_HUFFDTABLE_CAPACITY_LOG;
2782*01826a49SYabin Cui     dctx->flagRepeatTable = 0;
2783*01826a49SYabin Cui     return 0;
2784*01826a49SYabin Cui }
2785*01826a49SYabin Cui 
ZSTDv06_createDCtx(void)2786*01826a49SYabin Cui ZSTDv06_DCtx* ZSTDv06_createDCtx(void)
2787*01826a49SYabin Cui {
2788*01826a49SYabin Cui     ZSTDv06_DCtx* dctx = (ZSTDv06_DCtx*)malloc(sizeof(ZSTDv06_DCtx));
2789*01826a49SYabin Cui     if (dctx==NULL) return NULL;
2790*01826a49SYabin Cui     ZSTDv06_decompressBegin(dctx);
2791*01826a49SYabin Cui     return dctx;
2792*01826a49SYabin Cui }
2793*01826a49SYabin Cui 
ZSTDv06_freeDCtx(ZSTDv06_DCtx * dctx)2794*01826a49SYabin Cui size_t ZSTDv06_freeDCtx(ZSTDv06_DCtx* dctx)
2795*01826a49SYabin Cui {
2796*01826a49SYabin Cui     free(dctx);
2797*01826a49SYabin Cui     return 0;   /* reserved as a potential error code in the future */
2798*01826a49SYabin Cui }
2799*01826a49SYabin Cui 
ZSTDv06_copyDCtx(ZSTDv06_DCtx * dstDCtx,const ZSTDv06_DCtx * srcDCtx)2800*01826a49SYabin Cui void ZSTDv06_copyDCtx(ZSTDv06_DCtx* dstDCtx, const ZSTDv06_DCtx* srcDCtx)
2801*01826a49SYabin Cui {
2802*01826a49SYabin Cui     memcpy(dstDCtx, srcDCtx,
2803*01826a49SYabin Cui            sizeof(ZSTDv06_DCtx) - (ZSTDv06_BLOCKSIZE_MAX+WILDCOPY_OVERLENGTH + ZSTDv06_frameHeaderSize_max));  /* no need to copy workspace */
2804*01826a49SYabin Cui }
2805*01826a49SYabin Cui 
2806*01826a49SYabin Cui 
2807*01826a49SYabin Cui /*-*************************************************************
2808*01826a49SYabin Cui *   Decompression section
2809*01826a49SYabin Cui ***************************************************************/
2810*01826a49SYabin Cui 
2811*01826a49SYabin Cui /* Frame format description
2812*01826a49SYabin Cui    Frame Header -  [ Block Header - Block ] - Frame End
2813*01826a49SYabin Cui    1) Frame Header
2814*01826a49SYabin Cui       - 4 bytes - Magic Number : ZSTDv06_MAGICNUMBER (defined within zstd_static.h)
2815*01826a49SYabin Cui       - 1 byte  - Frame Descriptor
2816*01826a49SYabin Cui    2) Block Header
2817*01826a49SYabin Cui       - 3 bytes, starting with a 2-bits descriptor
2818*01826a49SYabin Cui                  Uncompressed, Compressed, Frame End, unused
2819*01826a49SYabin Cui    3) Block
2820*01826a49SYabin Cui       See Block Format Description
2821*01826a49SYabin Cui    4) Frame End
2822*01826a49SYabin Cui       - 3 bytes, compatible with Block Header
2823*01826a49SYabin Cui */
2824*01826a49SYabin Cui 
2825*01826a49SYabin Cui 
2826*01826a49SYabin Cui /* Frame descriptor
2827*01826a49SYabin Cui 
2828*01826a49SYabin Cui    1 byte, using :
2829*01826a49SYabin Cui    bit 0-3 : windowLog - ZSTDv06_WINDOWLOG_ABSOLUTEMIN   (see zstd_internal.h)
2830*01826a49SYabin Cui    bit 4   : minmatch 4(0) or 3(1)
2831*01826a49SYabin Cui    bit 5   : reserved (must be zero)
2832*01826a49SYabin Cui    bit 6-7 : Frame content size : unknown, 1 byte, 2 bytes, 8 bytes
2833*01826a49SYabin Cui 
2834*01826a49SYabin Cui    Optional : content size (0, 1, 2 or 8 bytes)
2835*01826a49SYabin Cui    0 : unknown
2836*01826a49SYabin Cui    1 : 0-255 bytes
2837*01826a49SYabin Cui    2 : 256 - 65535+256
2838*01826a49SYabin Cui    8 : up to 16 exa
2839*01826a49SYabin Cui */
2840*01826a49SYabin Cui 
2841*01826a49SYabin Cui 
2842*01826a49SYabin Cui /* Compressed Block, format description
2843*01826a49SYabin Cui 
2844*01826a49SYabin Cui    Block = Literal Section - Sequences Section
2845*01826a49SYabin Cui    Prerequisite : size of (compressed) block, maximum size of regenerated data
2846*01826a49SYabin Cui 
2847*01826a49SYabin Cui    1) Literal Section
2848*01826a49SYabin Cui 
2849*01826a49SYabin Cui    1.1) Header : 1-5 bytes
2850*01826a49SYabin Cui         flags: 2 bits
2851*01826a49SYabin Cui             00 compressed by Huff0
2852*01826a49SYabin Cui             01 unused
2853*01826a49SYabin Cui             10 is Raw (uncompressed)
2854*01826a49SYabin Cui             11 is Rle
2855*01826a49SYabin Cui             Note : using 01 => Huff0 with precomputed table ?
2856*01826a49SYabin Cui             Note : delta map ? => compressed ?
2857*01826a49SYabin Cui 
2858*01826a49SYabin Cui    1.1.1) Huff0-compressed literal block : 3-5 bytes
2859*01826a49SYabin Cui             srcSize < 1 KB => 3 bytes (2-2-10-10) => single stream
2860*01826a49SYabin Cui             srcSize < 1 KB => 3 bytes (2-2-10-10)
2861*01826a49SYabin Cui             srcSize < 16KB => 4 bytes (2-2-14-14)
2862*01826a49SYabin Cui             else           => 5 bytes (2-2-18-18)
2863*01826a49SYabin Cui             big endian convention
2864*01826a49SYabin Cui 
2865*01826a49SYabin Cui    1.1.2) Raw (uncompressed) literal block header : 1-3 bytes
2866*01826a49SYabin Cui         size :  5 bits: (IS_RAW<<6) + (0<<4) + size
2867*01826a49SYabin Cui                12 bits: (IS_RAW<<6) + (2<<4) + (size>>8)
2868*01826a49SYabin Cui                         size&255
2869*01826a49SYabin Cui                20 bits: (IS_RAW<<6) + (3<<4) + (size>>16)
2870*01826a49SYabin Cui                         size>>8&255
2871*01826a49SYabin Cui                         size&255
2872*01826a49SYabin Cui 
2873*01826a49SYabin Cui    1.1.3) Rle (repeated single byte) literal block header : 1-3 bytes
2874*01826a49SYabin Cui         size :  5 bits: (IS_RLE<<6) + (0<<4) + size
2875*01826a49SYabin Cui                12 bits: (IS_RLE<<6) + (2<<4) + (size>>8)
2876*01826a49SYabin Cui                         size&255
2877*01826a49SYabin Cui                20 bits: (IS_RLE<<6) + (3<<4) + (size>>16)
2878*01826a49SYabin Cui                         size>>8&255
2879*01826a49SYabin Cui                         size&255
2880*01826a49SYabin Cui 
2881*01826a49SYabin Cui    1.1.4) Huff0-compressed literal block, using precomputed CTables : 3-5 bytes
2882*01826a49SYabin Cui             srcSize < 1 KB => 3 bytes (2-2-10-10) => single stream
2883*01826a49SYabin Cui             srcSize < 1 KB => 3 bytes (2-2-10-10)
2884*01826a49SYabin Cui             srcSize < 16KB => 4 bytes (2-2-14-14)
2885*01826a49SYabin Cui             else           => 5 bytes (2-2-18-18)
2886*01826a49SYabin Cui             big endian convention
2887*01826a49SYabin Cui 
2888*01826a49SYabin Cui         1- CTable available (stored into workspace ?)
2889*01826a49SYabin Cui         2- Small input (fast heuristic ? Full comparison ? depend on clevel ?)
2890*01826a49SYabin Cui 
2891*01826a49SYabin Cui 
2892*01826a49SYabin Cui    1.2) Literal block content
2893*01826a49SYabin Cui 
2894*01826a49SYabin Cui    1.2.1) Huff0 block, using sizes from header
2895*01826a49SYabin Cui         See Huff0 format
2896*01826a49SYabin Cui 
2897*01826a49SYabin Cui    1.2.2) Huff0 block, using prepared table
2898*01826a49SYabin Cui 
2899*01826a49SYabin Cui    1.2.3) Raw content
2900*01826a49SYabin Cui 
2901*01826a49SYabin Cui    1.2.4) single byte
2902*01826a49SYabin Cui 
2903*01826a49SYabin Cui 
2904*01826a49SYabin Cui    2) Sequences section
2905*01826a49SYabin Cui       TO DO
2906*01826a49SYabin Cui */
2907*01826a49SYabin Cui 
2908*01826a49SYabin Cui /** ZSTDv06_frameHeaderSize() :
2909*01826a49SYabin Cui *   srcSize must be >= ZSTDv06_frameHeaderSize_min.
2910*01826a49SYabin Cui *   @return : size of the Frame Header */
ZSTDv06_frameHeaderSize(const void * src,size_t srcSize)2911*01826a49SYabin Cui static size_t ZSTDv06_frameHeaderSize(const void* src, size_t srcSize)
2912*01826a49SYabin Cui {
2913*01826a49SYabin Cui     if (srcSize < ZSTDv06_frameHeaderSize_min) return ERROR(srcSize_wrong);
2914*01826a49SYabin Cui     { U32 const fcsId = (((const BYTE*)src)[4]) >> 6;
2915*01826a49SYabin Cui       return ZSTDv06_frameHeaderSize_min + ZSTDv06_fcs_fieldSize[fcsId]; }
2916*01826a49SYabin Cui }
2917*01826a49SYabin Cui 
2918*01826a49SYabin Cui 
2919*01826a49SYabin Cui /** ZSTDv06_getFrameParams() :
2920*01826a49SYabin Cui *   decode Frame Header, or provide expected `srcSize`.
2921*01826a49SYabin Cui *   @return : 0, `fparamsPtr` is correctly filled,
2922*01826a49SYabin Cui *            >0, `srcSize` is too small, result is expected `srcSize`,
2923*01826a49SYabin Cui *             or an error code, which can be tested using ZSTDv06_isError() */
ZSTDv06_getFrameParams(ZSTDv06_frameParams * fparamsPtr,const void * src,size_t srcSize)2924*01826a49SYabin Cui size_t ZSTDv06_getFrameParams(ZSTDv06_frameParams* fparamsPtr, const void* src, size_t srcSize)
2925*01826a49SYabin Cui {
2926*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
2927*01826a49SYabin Cui 
2928*01826a49SYabin Cui     if (srcSize < ZSTDv06_frameHeaderSize_min) return ZSTDv06_frameHeaderSize_min;
2929*01826a49SYabin Cui     if (MEM_readLE32(src) != ZSTDv06_MAGICNUMBER) return ERROR(prefix_unknown);
2930*01826a49SYabin Cui 
2931*01826a49SYabin Cui     /* ensure there is enough `srcSize` to fully read/decode frame header */
2932*01826a49SYabin Cui     { size_t const fhsize = ZSTDv06_frameHeaderSize(src, srcSize);
2933*01826a49SYabin Cui       if (srcSize < fhsize) return fhsize; }
2934*01826a49SYabin Cui 
2935*01826a49SYabin Cui     memset(fparamsPtr, 0, sizeof(*fparamsPtr));
2936*01826a49SYabin Cui     {   BYTE const frameDesc = ip[4];
2937*01826a49SYabin Cui         fparamsPtr->windowLog = (frameDesc & 0xF) + ZSTDv06_WINDOWLOG_ABSOLUTEMIN;
2938*01826a49SYabin Cui         if ((frameDesc & 0x20) != 0) return ERROR(frameParameter_unsupported);   /* reserved 1 bit */
2939*01826a49SYabin Cui         switch(frameDesc >> 6)  /* fcsId */
2940*01826a49SYabin Cui         {
2941*01826a49SYabin Cui             default:   /* impossible */
2942*01826a49SYabin Cui             case 0 : fparamsPtr->frameContentSize = 0; break;
2943*01826a49SYabin Cui             case 1 : fparamsPtr->frameContentSize = ip[5]; break;
2944*01826a49SYabin Cui             case 2 : fparamsPtr->frameContentSize = MEM_readLE16(ip+5)+256; break;
2945*01826a49SYabin Cui             case 3 : fparamsPtr->frameContentSize = MEM_readLE64(ip+5); break;
2946*01826a49SYabin Cui     }   }
2947*01826a49SYabin Cui     return 0;
2948*01826a49SYabin Cui }
2949*01826a49SYabin Cui 
2950*01826a49SYabin Cui 
2951*01826a49SYabin Cui /** ZSTDv06_decodeFrameHeader() :
2952*01826a49SYabin Cui *   `srcSize` must be the size provided by ZSTDv06_frameHeaderSize().
2953*01826a49SYabin Cui *   @return : 0 if success, or an error code, which can be tested using ZSTDv06_isError() */
ZSTDv06_decodeFrameHeader(ZSTDv06_DCtx * zc,const void * src,size_t srcSize)2954*01826a49SYabin Cui static size_t ZSTDv06_decodeFrameHeader(ZSTDv06_DCtx* zc, const void* src, size_t srcSize)
2955*01826a49SYabin Cui {
2956*01826a49SYabin Cui     size_t const result = ZSTDv06_getFrameParams(&(zc->fParams), src, srcSize);
2957*01826a49SYabin Cui     if ((MEM_32bits()) && (zc->fParams.windowLog > 25)) return ERROR(frameParameter_unsupported);
2958*01826a49SYabin Cui     return result;
2959*01826a49SYabin Cui }
2960*01826a49SYabin Cui 
2961*01826a49SYabin Cui 
2962*01826a49SYabin Cui typedef struct
2963*01826a49SYabin Cui {
2964*01826a49SYabin Cui     blockType_t blockType;
2965*01826a49SYabin Cui     U32 origSize;
2966*01826a49SYabin Cui } blockProperties_t;
2967*01826a49SYabin Cui 
2968*01826a49SYabin Cui /*! ZSTDv06_getcBlockSize() :
2969*01826a49SYabin Cui *   Provides the size of compressed block from block header `src` */
ZSTDv06_getcBlockSize(const void * src,size_t srcSize,blockProperties_t * bpPtr)2970*01826a49SYabin Cui static size_t ZSTDv06_getcBlockSize(const void* src, size_t srcSize, blockProperties_t* bpPtr)
2971*01826a49SYabin Cui {
2972*01826a49SYabin Cui     const BYTE* const in = (const BYTE*)src;
2973*01826a49SYabin Cui     U32 cSize;
2974*01826a49SYabin Cui 
2975*01826a49SYabin Cui     if (srcSize < ZSTDv06_blockHeaderSize) return ERROR(srcSize_wrong);
2976*01826a49SYabin Cui 
2977*01826a49SYabin Cui     bpPtr->blockType = (blockType_t)((*in) >> 6);
2978*01826a49SYabin Cui     cSize = in[2] + (in[1]<<8) + ((in[0] & 7)<<16);
2979*01826a49SYabin Cui     bpPtr->origSize = (bpPtr->blockType == bt_rle) ? cSize : 0;
2980*01826a49SYabin Cui 
2981*01826a49SYabin Cui     if (bpPtr->blockType == bt_end) return 0;
2982*01826a49SYabin Cui     if (bpPtr->blockType == bt_rle) return 1;
2983*01826a49SYabin Cui     return cSize;
2984*01826a49SYabin Cui }
2985*01826a49SYabin Cui 
2986*01826a49SYabin Cui 
ZSTDv06_copyRawBlock(void * dst,size_t dstCapacity,const void * src,size_t srcSize)2987*01826a49SYabin Cui static size_t ZSTDv06_copyRawBlock(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
2988*01826a49SYabin Cui {
2989*01826a49SYabin Cui     if (dst==NULL) return ERROR(dstSize_tooSmall);
2990*01826a49SYabin Cui     if (srcSize > dstCapacity) return ERROR(dstSize_tooSmall);
2991*01826a49SYabin Cui     memcpy(dst, src, srcSize);
2992*01826a49SYabin Cui     return srcSize;
2993*01826a49SYabin Cui }
2994*01826a49SYabin Cui 
2995*01826a49SYabin Cui 
2996*01826a49SYabin Cui /*! ZSTDv06_decodeLiteralsBlock() :
2997*01826a49SYabin Cui     @return : nb of bytes read from src (< srcSize ) */
ZSTDv06_decodeLiteralsBlock(ZSTDv06_DCtx * dctx,const void * src,size_t srcSize)2998*01826a49SYabin Cui static size_t ZSTDv06_decodeLiteralsBlock(ZSTDv06_DCtx* dctx,
2999*01826a49SYabin Cui                           const void* src, size_t srcSize)   /* note : srcSize < BLOCKSIZE */
3000*01826a49SYabin Cui {
3001*01826a49SYabin Cui     const BYTE* const istart = (const BYTE*) src;
3002*01826a49SYabin Cui 
3003*01826a49SYabin Cui     /* any compressed block with literals segment must be at least this size */
3004*01826a49SYabin Cui     if (srcSize < MIN_CBLOCK_SIZE) return ERROR(corruption_detected);
3005*01826a49SYabin Cui 
3006*01826a49SYabin Cui     switch(istart[0]>> 6)
3007*01826a49SYabin Cui     {
3008*01826a49SYabin Cui     case IS_HUF:
3009*01826a49SYabin Cui         {   size_t litSize, litCSize, singleStream=0;
3010*01826a49SYabin Cui             U32 lhSize = ((istart[0]) >> 4) & 3;
3011*01826a49SYabin Cui             if (srcSize < 5) return ERROR(corruption_detected);   /* srcSize >= MIN_CBLOCK_SIZE == 3; here we need up to 5 for lhSize, + cSize (+nbSeq) */
3012*01826a49SYabin Cui             switch(lhSize)
3013*01826a49SYabin Cui             {
3014*01826a49SYabin Cui             case 0: case 1: default:   /* note : default is impossible, since lhSize into [0..3] */
3015*01826a49SYabin Cui                 /* 2 - 2 - 10 - 10 */
3016*01826a49SYabin Cui                 lhSize=3;
3017*01826a49SYabin Cui                 singleStream = istart[0] & 16;
3018*01826a49SYabin Cui                 litSize  = ((istart[0] & 15) << 6) + (istart[1] >> 2);
3019*01826a49SYabin Cui                 litCSize = ((istart[1] &  3) << 8) + istart[2];
3020*01826a49SYabin Cui                 break;
3021*01826a49SYabin Cui             case 2:
3022*01826a49SYabin Cui                 /* 2 - 2 - 14 - 14 */
3023*01826a49SYabin Cui                 lhSize=4;
3024*01826a49SYabin Cui                 litSize  = ((istart[0] & 15) << 10) + (istart[1] << 2) + (istart[2] >> 6);
3025*01826a49SYabin Cui                 litCSize = ((istart[2] & 63) <<  8) + istart[3];
3026*01826a49SYabin Cui                 break;
3027*01826a49SYabin Cui             case 3:
3028*01826a49SYabin Cui                 /* 2 - 2 - 18 - 18 */
3029*01826a49SYabin Cui                 lhSize=5;
3030*01826a49SYabin Cui                 litSize  = ((istart[0] & 15) << 14) + (istart[1] << 6) + (istart[2] >> 2);
3031*01826a49SYabin Cui                 litCSize = ((istart[2] &  3) << 16) + (istart[3] << 8) + istart[4];
3032*01826a49SYabin Cui                 break;
3033*01826a49SYabin Cui             }
3034*01826a49SYabin Cui             if (litSize > ZSTDv06_BLOCKSIZE_MAX) return ERROR(corruption_detected);
3035*01826a49SYabin Cui             if (litCSize + lhSize > srcSize) return ERROR(corruption_detected);
3036*01826a49SYabin Cui 
3037*01826a49SYabin Cui             if (HUFv06_isError(singleStream ?
3038*01826a49SYabin Cui                             HUFv06_decompress1X2(dctx->litBuffer, litSize, istart+lhSize, litCSize) :
3039*01826a49SYabin Cui                             HUFv06_decompress   (dctx->litBuffer, litSize, istart+lhSize, litCSize) ))
3040*01826a49SYabin Cui                 return ERROR(corruption_detected);
3041*01826a49SYabin Cui 
3042*01826a49SYabin Cui             dctx->litPtr = dctx->litBuffer;
3043*01826a49SYabin Cui             dctx->litSize = litSize;
3044*01826a49SYabin Cui             memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
3045*01826a49SYabin Cui             return litCSize + lhSize;
3046*01826a49SYabin Cui         }
3047*01826a49SYabin Cui     case IS_PCH:
3048*01826a49SYabin Cui         {   size_t litSize, litCSize;
3049*01826a49SYabin Cui             U32 lhSize = ((istart[0]) >> 4) & 3;
3050*01826a49SYabin Cui             if (lhSize != 1)  /* only case supported for now : small litSize, single stream */
3051*01826a49SYabin Cui                 return ERROR(corruption_detected);
3052*01826a49SYabin Cui             if (!dctx->flagRepeatTable)
3053*01826a49SYabin Cui                 return ERROR(dictionary_corrupted);
3054*01826a49SYabin Cui 
3055*01826a49SYabin Cui             /* 2 - 2 - 10 - 10 */
3056*01826a49SYabin Cui             lhSize=3;
3057*01826a49SYabin Cui             litSize  = ((istart[0] & 15) << 6) + (istart[1] >> 2);
3058*01826a49SYabin Cui             litCSize = ((istart[1] &  3) << 8) + istart[2];
3059*01826a49SYabin Cui             if (litCSize + lhSize > srcSize) return ERROR(corruption_detected);
3060*01826a49SYabin Cui 
3061*01826a49SYabin Cui             {   size_t const errorCode = HUFv06_decompress1X4_usingDTable(dctx->litBuffer, litSize, istart+lhSize, litCSize, dctx->hufTableX4);
3062*01826a49SYabin Cui                 if (HUFv06_isError(errorCode)) return ERROR(corruption_detected);
3063*01826a49SYabin Cui             }
3064*01826a49SYabin Cui             dctx->litPtr = dctx->litBuffer;
3065*01826a49SYabin Cui             dctx->litSize = litSize;
3066*01826a49SYabin Cui             memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
3067*01826a49SYabin Cui             return litCSize + lhSize;
3068*01826a49SYabin Cui         }
3069*01826a49SYabin Cui     case IS_RAW:
3070*01826a49SYabin Cui         {   size_t litSize;
3071*01826a49SYabin Cui             U32 lhSize = ((istart[0]) >> 4) & 3;
3072*01826a49SYabin Cui             switch(lhSize)
3073*01826a49SYabin Cui             {
3074*01826a49SYabin Cui             case 0: case 1: default:   /* note : default is impossible, since lhSize into [0..3] */
3075*01826a49SYabin Cui                 lhSize=1;
3076*01826a49SYabin Cui                 litSize = istart[0] & 31;
3077*01826a49SYabin Cui                 break;
3078*01826a49SYabin Cui             case 2:
3079*01826a49SYabin Cui                 litSize = ((istart[0] & 15) << 8) + istart[1];
3080*01826a49SYabin Cui                 break;
3081*01826a49SYabin Cui             case 3:
3082*01826a49SYabin Cui                 litSize = ((istart[0] & 15) << 16) + (istart[1] << 8) + istart[2];
3083*01826a49SYabin Cui                 break;
3084*01826a49SYabin Cui             }
3085*01826a49SYabin Cui 
3086*01826a49SYabin Cui             if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) {  /* risk reading beyond src buffer with wildcopy */
3087*01826a49SYabin Cui                 if (litSize+lhSize > srcSize) return ERROR(corruption_detected);
3088*01826a49SYabin Cui                 memcpy(dctx->litBuffer, istart+lhSize, litSize);
3089*01826a49SYabin Cui                 dctx->litPtr = dctx->litBuffer;
3090*01826a49SYabin Cui                 dctx->litSize = litSize;
3091*01826a49SYabin Cui                 memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
3092*01826a49SYabin Cui                 return lhSize+litSize;
3093*01826a49SYabin Cui             }
3094*01826a49SYabin Cui             /* direct reference into compressed stream */
3095*01826a49SYabin Cui             dctx->litPtr = istart+lhSize;
3096*01826a49SYabin Cui             dctx->litSize = litSize;
3097*01826a49SYabin Cui             return lhSize+litSize;
3098*01826a49SYabin Cui         }
3099*01826a49SYabin Cui     case IS_RLE:
3100*01826a49SYabin Cui         {   size_t litSize;
3101*01826a49SYabin Cui             U32 lhSize = ((istart[0]) >> 4) & 3;
3102*01826a49SYabin Cui             switch(lhSize)
3103*01826a49SYabin Cui             {
3104*01826a49SYabin Cui             case 0: case 1: default:   /* note : default is impossible, since lhSize into [0..3] */
3105*01826a49SYabin Cui                 lhSize = 1;
3106*01826a49SYabin Cui                 litSize = istart[0] & 31;
3107*01826a49SYabin Cui                 break;
3108*01826a49SYabin Cui             case 2:
3109*01826a49SYabin Cui                 litSize = ((istart[0] & 15) << 8) + istart[1];
3110*01826a49SYabin Cui                 break;
3111*01826a49SYabin Cui             case 3:
3112*01826a49SYabin Cui                 litSize = ((istart[0] & 15) << 16) + (istart[1] << 8) + istart[2];
3113*01826a49SYabin Cui                 if (srcSize<4) return ERROR(corruption_detected);   /* srcSize >= MIN_CBLOCK_SIZE == 3; here we need lhSize+1 = 4 */
3114*01826a49SYabin Cui                 break;
3115*01826a49SYabin Cui             }
3116*01826a49SYabin Cui             if (litSize > ZSTDv06_BLOCKSIZE_MAX) return ERROR(corruption_detected);
3117*01826a49SYabin Cui             memset(dctx->litBuffer, istart[lhSize], litSize + WILDCOPY_OVERLENGTH);
3118*01826a49SYabin Cui             dctx->litPtr = dctx->litBuffer;
3119*01826a49SYabin Cui             dctx->litSize = litSize;
3120*01826a49SYabin Cui             return lhSize+1;
3121*01826a49SYabin Cui         }
3122*01826a49SYabin Cui     default:
3123*01826a49SYabin Cui         return ERROR(corruption_detected);   /* impossible */
3124*01826a49SYabin Cui     }
3125*01826a49SYabin Cui }
3126*01826a49SYabin Cui 
3127*01826a49SYabin Cui 
3128*01826a49SYabin Cui /*! ZSTDv06_buildSeqTable() :
3129*01826a49SYabin Cui     @return : nb bytes read from src,
3130*01826a49SYabin Cui               or an error code if it fails, testable with ZSTDv06_isError()
3131*01826a49SYabin Cui */
ZSTDv06_buildSeqTable(FSEv06_DTable * DTable,U32 type,U32 max,U32 maxLog,const void * src,size_t srcSize,const S16 * defaultNorm,U32 defaultLog,U32 flagRepeatTable)3132*01826a49SYabin Cui static size_t ZSTDv06_buildSeqTable(FSEv06_DTable* DTable, U32 type, U32 max, U32 maxLog,
3133*01826a49SYabin Cui                                  const void* src, size_t srcSize,
3134*01826a49SYabin Cui                                  const S16* defaultNorm, U32 defaultLog, U32 flagRepeatTable)
3135*01826a49SYabin Cui {
3136*01826a49SYabin Cui     switch(type)
3137*01826a49SYabin Cui     {
3138*01826a49SYabin Cui     case FSEv06_ENCODING_RLE :
3139*01826a49SYabin Cui         if (!srcSize) return ERROR(srcSize_wrong);
3140*01826a49SYabin Cui         if ( (*(const BYTE*)src) > max) return ERROR(corruption_detected);
3141*01826a49SYabin Cui         FSEv06_buildDTable_rle(DTable, *(const BYTE*)src);   /* if *src > max, data is corrupted */
3142*01826a49SYabin Cui         return 1;
3143*01826a49SYabin Cui     case FSEv06_ENCODING_RAW :
3144*01826a49SYabin Cui         FSEv06_buildDTable(DTable, defaultNorm, max, defaultLog);
3145*01826a49SYabin Cui         return 0;
3146*01826a49SYabin Cui     case FSEv06_ENCODING_STATIC:
3147*01826a49SYabin Cui         if (!flagRepeatTable) return ERROR(corruption_detected);
3148*01826a49SYabin Cui         return 0;
3149*01826a49SYabin Cui     default :   /* impossible */
3150*01826a49SYabin Cui     case FSEv06_ENCODING_DYNAMIC :
3151*01826a49SYabin Cui         {   U32 tableLog;
3152*01826a49SYabin Cui             S16 norm[MaxSeq+1];
3153*01826a49SYabin Cui             size_t const headerSize = FSEv06_readNCount(norm, &max, &tableLog, src, srcSize);
3154*01826a49SYabin Cui             if (FSEv06_isError(headerSize)) return ERROR(corruption_detected);
3155*01826a49SYabin Cui             if (tableLog > maxLog) return ERROR(corruption_detected);
3156*01826a49SYabin Cui             FSEv06_buildDTable(DTable, norm, max, tableLog);
3157*01826a49SYabin Cui             return headerSize;
3158*01826a49SYabin Cui     }   }
3159*01826a49SYabin Cui }
3160*01826a49SYabin Cui 
3161*01826a49SYabin Cui 
ZSTDv06_decodeSeqHeaders(int * nbSeqPtr,FSEv06_DTable * DTableLL,FSEv06_DTable * DTableML,FSEv06_DTable * DTableOffb,U32 flagRepeatTable,const void * src,size_t srcSize)3162*01826a49SYabin Cui static size_t ZSTDv06_decodeSeqHeaders(int* nbSeqPtr,
3163*01826a49SYabin Cui                              FSEv06_DTable* DTableLL, FSEv06_DTable* DTableML, FSEv06_DTable* DTableOffb, U32 flagRepeatTable,
3164*01826a49SYabin Cui                              const void* src, size_t srcSize)
3165*01826a49SYabin Cui {
3166*01826a49SYabin Cui     const BYTE* const istart = (const BYTE*)src;
3167*01826a49SYabin Cui     const BYTE* const iend = istart + srcSize;
3168*01826a49SYabin Cui     const BYTE* ip = istart;
3169*01826a49SYabin Cui 
3170*01826a49SYabin Cui     /* check */
3171*01826a49SYabin Cui     if (srcSize < MIN_SEQUENCES_SIZE) return ERROR(srcSize_wrong);
3172*01826a49SYabin Cui 
3173*01826a49SYabin Cui     /* SeqHead */
3174*01826a49SYabin Cui     {   int nbSeq = *ip++;
3175*01826a49SYabin Cui         if (!nbSeq) { *nbSeqPtr=0; return 1; }
3176*01826a49SYabin Cui         if (nbSeq > 0x7F) {
3177*01826a49SYabin Cui             if (nbSeq == 0xFF) {
3178*01826a49SYabin Cui                 if (ip+2 > iend) return ERROR(srcSize_wrong);
3179*01826a49SYabin Cui                 nbSeq = MEM_readLE16(ip) + LONGNBSEQ, ip+=2;
3180*01826a49SYabin Cui             } else {
3181*01826a49SYabin Cui                 if (ip >= iend) return ERROR(srcSize_wrong);
3182*01826a49SYabin Cui                 nbSeq = ((nbSeq-0x80)<<8) + *ip++;
3183*01826a49SYabin Cui             }
3184*01826a49SYabin Cui         }
3185*01826a49SYabin Cui         *nbSeqPtr = nbSeq;
3186*01826a49SYabin Cui     }
3187*01826a49SYabin Cui 
3188*01826a49SYabin Cui     /* FSE table descriptors */
3189*01826a49SYabin Cui     if (ip + 4 > iend) return ERROR(srcSize_wrong); /* min : header byte + all 3 are "raw", hence no header, but at least xxLog bits per type */
3190*01826a49SYabin Cui     {   U32 const LLtype  = *ip >> 6;
3191*01826a49SYabin Cui         U32 const Offtype = (*ip >> 4) & 3;
3192*01826a49SYabin Cui         U32 const MLtype  = (*ip >> 2) & 3;
3193*01826a49SYabin Cui         ip++;
3194*01826a49SYabin Cui 
3195*01826a49SYabin Cui         /* Build DTables */
3196*01826a49SYabin Cui         {   size_t const bhSize = ZSTDv06_buildSeqTable(DTableLL, LLtype, MaxLL, LLFSELog, ip, iend-ip, LL_defaultNorm, LL_defaultNormLog, flagRepeatTable);
3197*01826a49SYabin Cui             if (ZSTDv06_isError(bhSize)) return ERROR(corruption_detected);
3198*01826a49SYabin Cui             ip += bhSize;
3199*01826a49SYabin Cui         }
3200*01826a49SYabin Cui         {   size_t const bhSize = ZSTDv06_buildSeqTable(DTableOffb, Offtype, MaxOff, OffFSELog, ip, iend-ip, OF_defaultNorm, OF_defaultNormLog, flagRepeatTable);
3201*01826a49SYabin Cui             if (ZSTDv06_isError(bhSize)) return ERROR(corruption_detected);
3202*01826a49SYabin Cui             ip += bhSize;
3203*01826a49SYabin Cui         }
3204*01826a49SYabin Cui         {   size_t const bhSize = ZSTDv06_buildSeqTable(DTableML, MLtype, MaxML, MLFSELog, ip, iend-ip, ML_defaultNorm, ML_defaultNormLog, flagRepeatTable);
3205*01826a49SYabin Cui             if (ZSTDv06_isError(bhSize)) return ERROR(corruption_detected);
3206*01826a49SYabin Cui             ip += bhSize;
3207*01826a49SYabin Cui     }   }
3208*01826a49SYabin Cui 
3209*01826a49SYabin Cui     return ip-istart;
3210*01826a49SYabin Cui }
3211*01826a49SYabin Cui 
3212*01826a49SYabin Cui 
3213*01826a49SYabin Cui typedef struct {
3214*01826a49SYabin Cui     size_t litLength;
3215*01826a49SYabin Cui     size_t matchLength;
3216*01826a49SYabin Cui     size_t offset;
3217*01826a49SYabin Cui } seq_t;
3218*01826a49SYabin Cui 
3219*01826a49SYabin Cui typedef struct {
3220*01826a49SYabin Cui     BITv06_DStream_t DStream;
3221*01826a49SYabin Cui     FSEv06_DState_t stateLL;
3222*01826a49SYabin Cui     FSEv06_DState_t stateOffb;
3223*01826a49SYabin Cui     FSEv06_DState_t stateML;
3224*01826a49SYabin Cui     size_t prevOffset[ZSTDv06_REP_INIT];
3225*01826a49SYabin Cui } seqState_t;
3226*01826a49SYabin Cui 
3227*01826a49SYabin Cui 
3228*01826a49SYabin Cui 
ZSTDv06_decodeSequence(seq_t * seq,seqState_t * seqState)3229*01826a49SYabin Cui static void ZSTDv06_decodeSequence(seq_t* seq, seqState_t* seqState)
3230*01826a49SYabin Cui {
3231*01826a49SYabin Cui     /* Literal length */
3232*01826a49SYabin Cui     U32 const llCode = FSEv06_peekSymbol(&(seqState->stateLL));
3233*01826a49SYabin Cui     U32 const mlCode = FSEv06_peekSymbol(&(seqState->stateML));
3234*01826a49SYabin Cui     U32 const ofCode = FSEv06_peekSymbol(&(seqState->stateOffb));   /* <= maxOff, by table construction */
3235*01826a49SYabin Cui 
3236*01826a49SYabin Cui     U32 const llBits = LL_bits[llCode];
3237*01826a49SYabin Cui     U32 const mlBits = ML_bits[mlCode];
3238*01826a49SYabin Cui     U32 const ofBits = ofCode;
3239*01826a49SYabin Cui     U32 const totalBits = llBits+mlBits+ofBits;
3240*01826a49SYabin Cui 
3241*01826a49SYabin Cui     static const U32 LL_base[MaxLL+1] = {
3242*01826a49SYabin Cui                              0,  1,  2,  3,  4,  5,  6,  7,  8,  9,   10,    11,    12,    13,    14,     15,
3243*01826a49SYabin Cui                             16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000,
3244*01826a49SYabin Cui                             0x2000, 0x4000, 0x8000, 0x10000 };
3245*01826a49SYabin Cui 
3246*01826a49SYabin Cui     static const U32 ML_base[MaxML+1] = {
3247*01826a49SYabin Cui                              0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10,   11,    12,    13,    14,    15,
3248*01826a49SYabin Cui                             16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,   27,    28,    29,    30,    31,
3249*01826a49SYabin Cui                             32, 34, 36, 38, 40, 44, 48, 56, 64, 80, 96, 0x80, 0x100, 0x200, 0x400, 0x800,
3250*01826a49SYabin Cui                             0x1000, 0x2000, 0x4000, 0x8000, 0x10000 };
3251*01826a49SYabin Cui 
3252*01826a49SYabin Cui     static const U32 OF_base[MaxOff+1] = {
3253*01826a49SYabin Cui                  0,        1,       3,       7,     0xF,     0x1F,     0x3F,     0x7F,
3254*01826a49SYabin Cui                  0xFF,   0x1FF,   0x3FF,   0x7FF,   0xFFF,   0x1FFF,   0x3FFF,   0x7FFF,
3255*01826a49SYabin Cui                  0xFFFF, 0x1FFFF, 0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF,
3256*01826a49SYabin Cui                  0xFFFFFF, 0x1FFFFFF, 0x3FFFFFF, /*fake*/ 1, 1 };
3257*01826a49SYabin Cui 
3258*01826a49SYabin Cui     /* sequence */
3259*01826a49SYabin Cui     {   size_t offset;
3260*01826a49SYabin Cui         if (!ofCode)
3261*01826a49SYabin Cui             offset = 0;
3262*01826a49SYabin Cui         else {
3263*01826a49SYabin Cui             offset = OF_base[ofCode] + BITv06_readBits(&(seqState->DStream), ofBits);   /* <=  26 bits */
3264*01826a49SYabin Cui             if (MEM_32bits()) BITv06_reloadDStream(&(seqState->DStream));
3265*01826a49SYabin Cui         }
3266*01826a49SYabin Cui 
3267*01826a49SYabin Cui         if (offset < ZSTDv06_REP_NUM) {
3268*01826a49SYabin Cui             if (llCode == 0 && offset <= 1) offset = 1-offset;
3269*01826a49SYabin Cui 
3270*01826a49SYabin Cui             if (offset != 0) {
3271*01826a49SYabin Cui                 size_t temp = seqState->prevOffset[offset];
3272*01826a49SYabin Cui                 if (offset != 1) {
3273*01826a49SYabin Cui                     seqState->prevOffset[2] = seqState->prevOffset[1];
3274*01826a49SYabin Cui                 }
3275*01826a49SYabin Cui                 seqState->prevOffset[1] = seqState->prevOffset[0];
3276*01826a49SYabin Cui                 seqState->prevOffset[0] = offset = temp;
3277*01826a49SYabin Cui 
3278*01826a49SYabin Cui             } else {
3279*01826a49SYabin Cui                 offset = seqState->prevOffset[0];
3280*01826a49SYabin Cui             }
3281*01826a49SYabin Cui         } else {
3282*01826a49SYabin Cui             offset -= ZSTDv06_REP_MOVE;
3283*01826a49SYabin Cui             seqState->prevOffset[2] = seqState->prevOffset[1];
3284*01826a49SYabin Cui             seqState->prevOffset[1] = seqState->prevOffset[0];
3285*01826a49SYabin Cui             seqState->prevOffset[0] = offset;
3286*01826a49SYabin Cui         }
3287*01826a49SYabin Cui         seq->offset = offset;
3288*01826a49SYabin Cui     }
3289*01826a49SYabin Cui 
3290*01826a49SYabin Cui     seq->matchLength = ML_base[mlCode] + MINMATCH + ((mlCode>31) ? BITv06_readBits(&(seqState->DStream), mlBits) : 0);   /* <=  16 bits */
3291*01826a49SYabin Cui     if (MEM_32bits() && (mlBits+llBits>24)) BITv06_reloadDStream(&(seqState->DStream));
3292*01826a49SYabin Cui 
3293*01826a49SYabin Cui     seq->litLength = LL_base[llCode] + ((llCode>15) ? BITv06_readBits(&(seqState->DStream), llBits) : 0);   /* <=  16 bits */
3294*01826a49SYabin Cui     if (MEM_32bits() ||
3295*01826a49SYabin Cui        (totalBits > 64 - 7 - (LLFSELog+MLFSELog+OffFSELog)) ) BITv06_reloadDStream(&(seqState->DStream));
3296*01826a49SYabin Cui 
3297*01826a49SYabin Cui     /* ANS state update */
3298*01826a49SYabin Cui     FSEv06_updateState(&(seqState->stateLL), &(seqState->DStream));   /* <=  9 bits */
3299*01826a49SYabin Cui     FSEv06_updateState(&(seqState->stateML), &(seqState->DStream));   /* <=  9 bits */
3300*01826a49SYabin Cui     if (MEM_32bits()) BITv06_reloadDStream(&(seqState->DStream));     /* <= 18 bits */
3301*01826a49SYabin Cui     FSEv06_updateState(&(seqState->stateOffb), &(seqState->DStream)); /* <=  8 bits */
3302*01826a49SYabin Cui }
3303*01826a49SYabin Cui 
3304*01826a49SYabin Cui 
ZSTDv06_execSequence(BYTE * op,BYTE * const oend,seq_t sequence,const BYTE ** litPtr,const BYTE * const litLimit,const BYTE * const base,const BYTE * const vBase,const BYTE * const dictEnd)3305*01826a49SYabin Cui static size_t ZSTDv06_execSequence(BYTE* op,
3306*01826a49SYabin Cui                                 BYTE* const oend, seq_t sequence,
3307*01826a49SYabin Cui                                 const BYTE** litPtr, const BYTE* const litLimit,
3308*01826a49SYabin Cui                                 const BYTE* const base, const BYTE* const vBase, const BYTE* const dictEnd)
3309*01826a49SYabin Cui {
3310*01826a49SYabin Cui     BYTE* const oLitEnd = op + sequence.litLength;
3311*01826a49SYabin Cui     size_t const sequenceLength = sequence.litLength + sequence.matchLength;
3312*01826a49SYabin Cui     BYTE* const oMatchEnd = op + sequenceLength;   /* risk : address space overflow (32-bits) */
3313*01826a49SYabin Cui     BYTE* const oend_8 = oend-8;
3314*01826a49SYabin Cui     const BYTE* const iLitEnd = *litPtr + sequence.litLength;
3315*01826a49SYabin Cui     const BYTE* match = oLitEnd - sequence.offset;
3316*01826a49SYabin Cui 
3317*01826a49SYabin Cui     /* checks */
3318*01826a49SYabin Cui     size_t const seqLength = sequence.litLength + sequence.matchLength;
3319*01826a49SYabin Cui 
3320*01826a49SYabin Cui     if (seqLength > (size_t)(oend - op)) return ERROR(dstSize_tooSmall);
3321*01826a49SYabin Cui     if (sequence.litLength > (size_t)(litLimit - *litPtr)) return ERROR(corruption_detected);
3322*01826a49SYabin Cui     /* Now we know there are no overflow in literal nor match lengths, can use pointer checks */
3323*01826a49SYabin Cui     if (oLitEnd > oend_8) return ERROR(dstSize_tooSmall);
3324*01826a49SYabin Cui 
3325*01826a49SYabin Cui     if (oMatchEnd > oend) return ERROR(dstSize_tooSmall);   /* overwrite beyond dst buffer */
3326*01826a49SYabin Cui     if (iLitEnd > litLimit) return ERROR(corruption_detected);   /* overRead beyond lit buffer */
3327*01826a49SYabin Cui 
3328*01826a49SYabin Cui     /* copy Literals */
3329*01826a49SYabin Cui     ZSTDv06_wildcopy(op, *litPtr, (ptrdiff_t)sequence.litLength);   /* note : oLitEnd <= oend-8 : no risk of overwrite beyond oend */
3330*01826a49SYabin Cui     op = oLitEnd;
3331*01826a49SYabin Cui     *litPtr = iLitEnd;   /* update for next sequence */
3332*01826a49SYabin Cui 
3333*01826a49SYabin Cui     /* copy Match */
3334*01826a49SYabin Cui     if (sequence.offset > (size_t)(oLitEnd - base)) {
3335*01826a49SYabin Cui         /* offset beyond prefix */
3336*01826a49SYabin Cui         if (sequence.offset > (size_t)(oLitEnd - vBase)) return ERROR(corruption_detected);
3337*01826a49SYabin Cui         match = dictEnd - (base-match);
3338*01826a49SYabin Cui         if (match + sequence.matchLength <= dictEnd) {
3339*01826a49SYabin Cui             memmove(oLitEnd, match, sequence.matchLength);
3340*01826a49SYabin Cui             return sequenceLength;
3341*01826a49SYabin Cui         }
3342*01826a49SYabin Cui         /* span extDict & currentPrefixSegment */
3343*01826a49SYabin Cui         {   size_t const length1 = dictEnd - match;
3344*01826a49SYabin Cui             memmove(oLitEnd, match, length1);
3345*01826a49SYabin Cui             op = oLitEnd + length1;
3346*01826a49SYabin Cui             sequence.matchLength -= length1;
3347*01826a49SYabin Cui             match = base;
3348*01826a49SYabin Cui             if (op > oend_8 || sequence.matchLength < MINMATCH) {
3349*01826a49SYabin Cui               while (op < oMatchEnd) *op++ = *match++;
3350*01826a49SYabin Cui               return sequenceLength;
3351*01826a49SYabin Cui             }
3352*01826a49SYabin Cui     }   }
3353*01826a49SYabin Cui     /* Requirement: op <= oend_8 */
3354*01826a49SYabin Cui 
3355*01826a49SYabin Cui     /* match within prefix */
3356*01826a49SYabin Cui     if (sequence.offset < 8) {
3357*01826a49SYabin Cui         /* close range match, overlap */
3358*01826a49SYabin Cui         static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 };   /* added */
3359*01826a49SYabin Cui         static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 };   /* subtracted */
3360*01826a49SYabin Cui         int const sub2 = dec64table[sequence.offset];
3361*01826a49SYabin Cui         op[0] = match[0];
3362*01826a49SYabin Cui         op[1] = match[1];
3363*01826a49SYabin Cui         op[2] = match[2];
3364*01826a49SYabin Cui         op[3] = match[3];
3365*01826a49SYabin Cui         match += dec32table[sequence.offset];
3366*01826a49SYabin Cui         ZSTDv06_copy4(op+4, match);
3367*01826a49SYabin Cui         match -= sub2;
3368*01826a49SYabin Cui     } else {
3369*01826a49SYabin Cui         ZSTDv06_copy8(op, match);
3370*01826a49SYabin Cui     }
3371*01826a49SYabin Cui     op += 8; match += 8;
3372*01826a49SYabin Cui 
3373*01826a49SYabin Cui     if (oMatchEnd > oend-(16-MINMATCH)) {
3374*01826a49SYabin Cui         if (op < oend_8) {
3375*01826a49SYabin Cui             ZSTDv06_wildcopy(op, match, oend_8 - op);
3376*01826a49SYabin Cui             match += oend_8 - op;
3377*01826a49SYabin Cui             op = oend_8;
3378*01826a49SYabin Cui         }
3379*01826a49SYabin Cui         while (op < oMatchEnd) *op++ = *match++;
3380*01826a49SYabin Cui     } else {
3381*01826a49SYabin Cui         ZSTDv06_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8);   /* works even if matchLength < 8 */
3382*01826a49SYabin Cui     }
3383*01826a49SYabin Cui     return sequenceLength;
3384*01826a49SYabin Cui }
3385*01826a49SYabin Cui 
3386*01826a49SYabin Cui 
ZSTDv06_decompressSequences(ZSTDv06_DCtx * dctx,void * dst,size_t maxDstSize,const void * seqStart,size_t seqSize)3387*01826a49SYabin Cui static size_t ZSTDv06_decompressSequences(
3388*01826a49SYabin Cui                                ZSTDv06_DCtx* dctx,
3389*01826a49SYabin Cui                                void* dst, size_t maxDstSize,
3390*01826a49SYabin Cui                          const void* seqStart, size_t seqSize)
3391*01826a49SYabin Cui {
3392*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)seqStart;
3393*01826a49SYabin Cui     const BYTE* const iend = ip + seqSize;
3394*01826a49SYabin Cui     BYTE* const ostart = (BYTE*)dst;
3395*01826a49SYabin Cui     BYTE* const oend = ostart + maxDstSize;
3396*01826a49SYabin Cui     BYTE* op = ostart;
3397*01826a49SYabin Cui     const BYTE* litPtr = dctx->litPtr;
3398*01826a49SYabin Cui     const BYTE* const litEnd = litPtr + dctx->litSize;
3399*01826a49SYabin Cui     FSEv06_DTable* DTableLL = dctx->LLTable;
3400*01826a49SYabin Cui     FSEv06_DTable* DTableML = dctx->MLTable;
3401*01826a49SYabin Cui     FSEv06_DTable* DTableOffb = dctx->OffTable;
3402*01826a49SYabin Cui     const BYTE* const base = (const BYTE*) (dctx->base);
3403*01826a49SYabin Cui     const BYTE* const vBase = (const BYTE*) (dctx->vBase);
3404*01826a49SYabin Cui     const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
3405*01826a49SYabin Cui     int nbSeq;
3406*01826a49SYabin Cui 
3407*01826a49SYabin Cui     /* Build Decoding Tables */
3408*01826a49SYabin Cui     {   size_t const seqHSize = ZSTDv06_decodeSeqHeaders(&nbSeq, DTableLL, DTableML, DTableOffb, dctx->flagRepeatTable, ip, seqSize);
3409*01826a49SYabin Cui         if (ZSTDv06_isError(seqHSize)) return seqHSize;
3410*01826a49SYabin Cui         ip += seqHSize;
3411*01826a49SYabin Cui         dctx->flagRepeatTable = 0;
3412*01826a49SYabin Cui     }
3413*01826a49SYabin Cui 
3414*01826a49SYabin Cui     /* Regen sequences */
3415*01826a49SYabin Cui     if (nbSeq) {
3416*01826a49SYabin Cui         seq_t sequence;
3417*01826a49SYabin Cui         seqState_t seqState;
3418*01826a49SYabin Cui 
3419*01826a49SYabin Cui         memset(&sequence, 0, sizeof(sequence));
3420*01826a49SYabin Cui         sequence.offset = REPCODE_STARTVALUE;
3421*01826a49SYabin Cui         { U32 i; for (i=0; i<ZSTDv06_REP_INIT; i++) seqState.prevOffset[i] = REPCODE_STARTVALUE; }
3422*01826a49SYabin Cui         { size_t const errorCode = BITv06_initDStream(&(seqState.DStream), ip, iend-ip);
3423*01826a49SYabin Cui           if (ERR_isError(errorCode)) return ERROR(corruption_detected); }
3424*01826a49SYabin Cui         FSEv06_initDState(&(seqState.stateLL), &(seqState.DStream), DTableLL);
3425*01826a49SYabin Cui         FSEv06_initDState(&(seqState.stateOffb), &(seqState.DStream), DTableOffb);
3426*01826a49SYabin Cui         FSEv06_initDState(&(seqState.stateML), &(seqState.DStream), DTableML);
3427*01826a49SYabin Cui 
3428*01826a49SYabin Cui         for ( ; (BITv06_reloadDStream(&(seqState.DStream)) <= BITv06_DStream_completed) && nbSeq ; ) {
3429*01826a49SYabin Cui             nbSeq--;
3430*01826a49SYabin Cui             ZSTDv06_decodeSequence(&sequence, &seqState);
3431*01826a49SYabin Cui 
3432*01826a49SYabin Cui #if 0  /* debug */
3433*01826a49SYabin Cui             static BYTE* start = NULL;
3434*01826a49SYabin Cui             if (start==NULL) start = op;
3435*01826a49SYabin Cui             size_t pos = (size_t)(op-start);
3436*01826a49SYabin Cui             if ((pos >= 5810037) && (pos < 5810400))
3437*01826a49SYabin Cui                 printf("Dpos %6u :%5u literals & match %3u bytes at distance %6u \n",
3438*01826a49SYabin Cui                        pos, (U32)sequence.litLength, (U32)sequence.matchLength, (U32)sequence.offset);
3439*01826a49SYabin Cui #endif
3440*01826a49SYabin Cui 
3441*01826a49SYabin Cui             {   size_t const oneSeqSize = ZSTDv06_execSequence(op, oend, sequence, &litPtr, litEnd, base, vBase, dictEnd);
3442*01826a49SYabin Cui                 if (ZSTDv06_isError(oneSeqSize)) return oneSeqSize;
3443*01826a49SYabin Cui                 op += oneSeqSize;
3444*01826a49SYabin Cui         }   }
3445*01826a49SYabin Cui 
3446*01826a49SYabin Cui         /* check if reached exact end */
3447*01826a49SYabin Cui         if (nbSeq) return ERROR(corruption_detected);
3448*01826a49SYabin Cui     }
3449*01826a49SYabin Cui 
3450*01826a49SYabin Cui     /* last literal segment */
3451*01826a49SYabin Cui     {   size_t const lastLLSize = litEnd - litPtr;
3452*01826a49SYabin Cui         if (litPtr > litEnd) return ERROR(corruption_detected);   /* too many literals already used */
3453*01826a49SYabin Cui         if (op+lastLLSize > oend) return ERROR(dstSize_tooSmall);
3454*01826a49SYabin Cui         if (lastLLSize > 0) {
3455*01826a49SYabin Cui             memcpy(op, litPtr, lastLLSize);
3456*01826a49SYabin Cui             op += lastLLSize;
3457*01826a49SYabin Cui         }
3458*01826a49SYabin Cui     }
3459*01826a49SYabin Cui 
3460*01826a49SYabin Cui     return op-ostart;
3461*01826a49SYabin Cui }
3462*01826a49SYabin Cui 
3463*01826a49SYabin Cui 
ZSTDv06_checkContinuity(ZSTDv06_DCtx * dctx,const void * dst)3464*01826a49SYabin Cui static void ZSTDv06_checkContinuity(ZSTDv06_DCtx* dctx, const void* dst)
3465*01826a49SYabin Cui {
3466*01826a49SYabin Cui     if (dst != dctx->previousDstEnd) {   /* not contiguous */
3467*01826a49SYabin Cui         dctx->dictEnd = dctx->previousDstEnd;
3468*01826a49SYabin Cui         dctx->vBase = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->base));
3469*01826a49SYabin Cui         dctx->base = dst;
3470*01826a49SYabin Cui         dctx->previousDstEnd = dst;
3471*01826a49SYabin Cui     }
3472*01826a49SYabin Cui }
3473*01826a49SYabin Cui 
3474*01826a49SYabin Cui 
ZSTDv06_decompressBlock_internal(ZSTDv06_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)3475*01826a49SYabin Cui static size_t ZSTDv06_decompressBlock_internal(ZSTDv06_DCtx* dctx,
3476*01826a49SYabin Cui                             void* dst, size_t dstCapacity,
3477*01826a49SYabin Cui                       const void* src, size_t srcSize)
3478*01826a49SYabin Cui {   /* blockType == blockCompressed */
3479*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
3480*01826a49SYabin Cui 
3481*01826a49SYabin Cui     if (srcSize >= ZSTDv06_BLOCKSIZE_MAX) return ERROR(srcSize_wrong);
3482*01826a49SYabin Cui 
3483*01826a49SYabin Cui     /* Decode literals sub-block */
3484*01826a49SYabin Cui     {   size_t const litCSize = ZSTDv06_decodeLiteralsBlock(dctx, src, srcSize);
3485*01826a49SYabin Cui         if (ZSTDv06_isError(litCSize)) return litCSize;
3486*01826a49SYabin Cui         ip += litCSize;
3487*01826a49SYabin Cui         srcSize -= litCSize;
3488*01826a49SYabin Cui     }
3489*01826a49SYabin Cui     return ZSTDv06_decompressSequences(dctx, dst, dstCapacity, ip, srcSize);
3490*01826a49SYabin Cui }
3491*01826a49SYabin Cui 
3492*01826a49SYabin Cui 
ZSTDv06_decompressBlock(ZSTDv06_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)3493*01826a49SYabin Cui size_t ZSTDv06_decompressBlock(ZSTDv06_DCtx* dctx,
3494*01826a49SYabin Cui                             void* dst, size_t dstCapacity,
3495*01826a49SYabin Cui                       const void* src, size_t srcSize)
3496*01826a49SYabin Cui {
3497*01826a49SYabin Cui     ZSTDv06_checkContinuity(dctx, dst);
3498*01826a49SYabin Cui     return ZSTDv06_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize);
3499*01826a49SYabin Cui }
3500*01826a49SYabin Cui 
3501*01826a49SYabin Cui 
3502*01826a49SYabin Cui /*! ZSTDv06_decompressFrame() :
3503*01826a49SYabin Cui *   `dctx` must be properly initialized */
ZSTDv06_decompressFrame(ZSTDv06_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)3504*01826a49SYabin Cui static size_t ZSTDv06_decompressFrame(ZSTDv06_DCtx* dctx,
3505*01826a49SYabin Cui                                  void* dst, size_t dstCapacity,
3506*01826a49SYabin Cui                                  const void* src, size_t srcSize)
3507*01826a49SYabin Cui {
3508*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
3509*01826a49SYabin Cui     const BYTE* const iend = ip + srcSize;
3510*01826a49SYabin Cui     BYTE* const ostart = (BYTE*)dst;
3511*01826a49SYabin Cui     BYTE* op = ostart;
3512*01826a49SYabin Cui     BYTE* const oend = ostart + dstCapacity;
3513*01826a49SYabin Cui     size_t remainingSize = srcSize;
3514*01826a49SYabin Cui     blockProperties_t blockProperties = { bt_compressed, 0 };
3515*01826a49SYabin Cui 
3516*01826a49SYabin Cui     /* check */
3517*01826a49SYabin Cui     if (srcSize < ZSTDv06_frameHeaderSize_min+ZSTDv06_blockHeaderSize) return ERROR(srcSize_wrong);
3518*01826a49SYabin Cui 
3519*01826a49SYabin Cui     /* Frame Header */
3520*01826a49SYabin Cui     {   size_t const frameHeaderSize = ZSTDv06_frameHeaderSize(src, ZSTDv06_frameHeaderSize_min);
3521*01826a49SYabin Cui         if (ZSTDv06_isError(frameHeaderSize)) return frameHeaderSize;
3522*01826a49SYabin Cui         if (srcSize < frameHeaderSize+ZSTDv06_blockHeaderSize) return ERROR(srcSize_wrong);
3523*01826a49SYabin Cui         if (ZSTDv06_decodeFrameHeader(dctx, src, frameHeaderSize)) return ERROR(corruption_detected);
3524*01826a49SYabin Cui         ip += frameHeaderSize; remainingSize -= frameHeaderSize;
3525*01826a49SYabin Cui     }
3526*01826a49SYabin Cui 
3527*01826a49SYabin Cui     /* Loop on each block */
3528*01826a49SYabin Cui     while (1) {
3529*01826a49SYabin Cui         size_t decodedSize=0;
3530*01826a49SYabin Cui         size_t const cBlockSize = ZSTDv06_getcBlockSize(ip, iend-ip, &blockProperties);
3531*01826a49SYabin Cui         if (ZSTDv06_isError(cBlockSize)) return cBlockSize;
3532*01826a49SYabin Cui 
3533*01826a49SYabin Cui         ip += ZSTDv06_blockHeaderSize;
3534*01826a49SYabin Cui         remainingSize -= ZSTDv06_blockHeaderSize;
3535*01826a49SYabin Cui         if (cBlockSize > remainingSize) return ERROR(srcSize_wrong);
3536*01826a49SYabin Cui 
3537*01826a49SYabin Cui         switch(blockProperties.blockType)
3538*01826a49SYabin Cui         {
3539*01826a49SYabin Cui         case bt_compressed:
3540*01826a49SYabin Cui             decodedSize = ZSTDv06_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize);
3541*01826a49SYabin Cui             break;
3542*01826a49SYabin Cui         case bt_raw :
3543*01826a49SYabin Cui             decodedSize = ZSTDv06_copyRawBlock(op, oend-op, ip, cBlockSize);
3544*01826a49SYabin Cui             break;
3545*01826a49SYabin Cui         case bt_rle :
3546*01826a49SYabin Cui             return ERROR(GENERIC);   /* not yet supported */
3547*01826a49SYabin Cui             break;
3548*01826a49SYabin Cui         case bt_end :
3549*01826a49SYabin Cui             /* end of frame */
3550*01826a49SYabin Cui             if (remainingSize) return ERROR(srcSize_wrong);
3551*01826a49SYabin Cui             break;
3552*01826a49SYabin Cui         default:
3553*01826a49SYabin Cui             return ERROR(GENERIC);   /* impossible */
3554*01826a49SYabin Cui         }
3555*01826a49SYabin Cui         if (cBlockSize == 0) break;   /* bt_end */
3556*01826a49SYabin Cui 
3557*01826a49SYabin Cui         if (ZSTDv06_isError(decodedSize)) return decodedSize;
3558*01826a49SYabin Cui         op += decodedSize;
3559*01826a49SYabin Cui         ip += cBlockSize;
3560*01826a49SYabin Cui         remainingSize -= cBlockSize;
3561*01826a49SYabin Cui     }
3562*01826a49SYabin Cui 
3563*01826a49SYabin Cui     return op-ostart;
3564*01826a49SYabin Cui }
3565*01826a49SYabin Cui 
3566*01826a49SYabin Cui 
ZSTDv06_decompress_usingPreparedDCtx(ZSTDv06_DCtx * dctx,const ZSTDv06_DCtx * refDCtx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)3567*01826a49SYabin Cui size_t ZSTDv06_decompress_usingPreparedDCtx(ZSTDv06_DCtx* dctx, const ZSTDv06_DCtx* refDCtx,
3568*01826a49SYabin Cui                                          void* dst, size_t dstCapacity,
3569*01826a49SYabin Cui                                    const void* src, size_t srcSize)
3570*01826a49SYabin Cui {
3571*01826a49SYabin Cui     ZSTDv06_copyDCtx(dctx, refDCtx);
3572*01826a49SYabin Cui     ZSTDv06_checkContinuity(dctx, dst);
3573*01826a49SYabin Cui     return ZSTDv06_decompressFrame(dctx, dst, dstCapacity, src, srcSize);
3574*01826a49SYabin Cui }
3575*01826a49SYabin Cui 
3576*01826a49SYabin Cui 
ZSTDv06_decompress_usingDict(ZSTDv06_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const void * dict,size_t dictSize)3577*01826a49SYabin Cui size_t ZSTDv06_decompress_usingDict(ZSTDv06_DCtx* dctx,
3578*01826a49SYabin Cui                                  void* dst, size_t dstCapacity,
3579*01826a49SYabin Cui                                  const void* src, size_t srcSize,
3580*01826a49SYabin Cui                                  const void* dict, size_t dictSize)
3581*01826a49SYabin Cui {
3582*01826a49SYabin Cui     ZSTDv06_decompressBegin_usingDict(dctx, dict, dictSize);
3583*01826a49SYabin Cui     ZSTDv06_checkContinuity(dctx, dst);
3584*01826a49SYabin Cui     return ZSTDv06_decompressFrame(dctx, dst, dstCapacity, src, srcSize);
3585*01826a49SYabin Cui }
3586*01826a49SYabin Cui 
3587*01826a49SYabin Cui 
ZSTDv06_decompressDCtx(ZSTDv06_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)3588*01826a49SYabin Cui size_t ZSTDv06_decompressDCtx(ZSTDv06_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
3589*01826a49SYabin Cui {
3590*01826a49SYabin Cui     return ZSTDv06_decompress_usingDict(dctx, dst, dstCapacity, src, srcSize, NULL, 0);
3591*01826a49SYabin Cui }
3592*01826a49SYabin Cui 
3593*01826a49SYabin Cui 
ZSTDv06_decompress(void * dst,size_t dstCapacity,const void * src,size_t srcSize)3594*01826a49SYabin Cui size_t ZSTDv06_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
3595*01826a49SYabin Cui {
3596*01826a49SYabin Cui #if defined(ZSTDv06_HEAPMODE) && (ZSTDv06_HEAPMODE==1)
3597*01826a49SYabin Cui     size_t regenSize;
3598*01826a49SYabin Cui     ZSTDv06_DCtx* dctx = ZSTDv06_createDCtx();
3599*01826a49SYabin Cui     if (dctx==NULL) return ERROR(memory_allocation);
3600*01826a49SYabin Cui     regenSize = ZSTDv06_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);
3601*01826a49SYabin Cui     ZSTDv06_freeDCtx(dctx);
3602*01826a49SYabin Cui     return regenSize;
3603*01826a49SYabin Cui #else   /* stack mode */
3604*01826a49SYabin Cui     ZSTDv06_DCtx dctx;
3605*01826a49SYabin Cui     return ZSTDv06_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize);
3606*01826a49SYabin Cui #endif
3607*01826a49SYabin Cui }
3608*01826a49SYabin Cui 
3609*01826a49SYabin Cui /* ZSTD_errorFrameSizeInfoLegacy() :
3610*01826a49SYabin Cui    assumes `cSize` and `dBound` are _not_ NULL */
ZSTD_errorFrameSizeInfoLegacy(size_t * cSize,unsigned long long * dBound,size_t ret)3611*01826a49SYabin Cui static void ZSTD_errorFrameSizeInfoLegacy(size_t* cSize, unsigned long long* dBound, size_t ret)
3612*01826a49SYabin Cui {
3613*01826a49SYabin Cui     *cSize = ret;
3614*01826a49SYabin Cui     *dBound = ZSTD_CONTENTSIZE_ERROR;
3615*01826a49SYabin Cui }
3616*01826a49SYabin Cui 
ZSTDv06_findFrameSizeInfoLegacy(const void * src,size_t srcSize,size_t * cSize,unsigned long long * dBound)3617*01826a49SYabin Cui void ZSTDv06_findFrameSizeInfoLegacy(const void *src, size_t srcSize, size_t* cSize, unsigned long long* dBound)
3618*01826a49SYabin Cui {
3619*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
3620*01826a49SYabin Cui     size_t remainingSize = srcSize;
3621*01826a49SYabin Cui     size_t nbBlocks = 0;
3622*01826a49SYabin Cui     blockProperties_t blockProperties = { bt_compressed, 0 };
3623*01826a49SYabin Cui 
3624*01826a49SYabin Cui     /* Frame Header */
3625*01826a49SYabin Cui     {   size_t const frameHeaderSize = ZSTDv06_frameHeaderSize(src, srcSize);
3626*01826a49SYabin Cui         if (ZSTDv06_isError(frameHeaderSize)) {
3627*01826a49SYabin Cui             ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, frameHeaderSize);
3628*01826a49SYabin Cui             return;
3629*01826a49SYabin Cui         }
3630*01826a49SYabin Cui         if (MEM_readLE32(src) != ZSTDv06_MAGICNUMBER) {
3631*01826a49SYabin Cui             ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(prefix_unknown));
3632*01826a49SYabin Cui             return;
3633*01826a49SYabin Cui         }
3634*01826a49SYabin Cui         if (srcSize < frameHeaderSize+ZSTDv06_blockHeaderSize) {
3635*01826a49SYabin Cui             ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
3636*01826a49SYabin Cui             return;
3637*01826a49SYabin Cui         }
3638*01826a49SYabin Cui         ip += frameHeaderSize; remainingSize -= frameHeaderSize;
3639*01826a49SYabin Cui     }
3640*01826a49SYabin Cui 
3641*01826a49SYabin Cui     /* Loop on each block */
3642*01826a49SYabin Cui     while (1) {
3643*01826a49SYabin Cui         size_t const cBlockSize = ZSTDv06_getcBlockSize(ip, remainingSize, &blockProperties);
3644*01826a49SYabin Cui         if (ZSTDv06_isError(cBlockSize)) {
3645*01826a49SYabin Cui             ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, cBlockSize);
3646*01826a49SYabin Cui             return;
3647*01826a49SYabin Cui         }
3648*01826a49SYabin Cui 
3649*01826a49SYabin Cui         ip += ZSTDv06_blockHeaderSize;
3650*01826a49SYabin Cui         remainingSize -= ZSTDv06_blockHeaderSize;
3651*01826a49SYabin Cui         if (cBlockSize > remainingSize) {
3652*01826a49SYabin Cui             ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
3653*01826a49SYabin Cui             return;
3654*01826a49SYabin Cui         }
3655*01826a49SYabin Cui 
3656*01826a49SYabin Cui         if (cBlockSize == 0) break;   /* bt_end */
3657*01826a49SYabin Cui 
3658*01826a49SYabin Cui         ip += cBlockSize;
3659*01826a49SYabin Cui         remainingSize -= cBlockSize;
3660*01826a49SYabin Cui         nbBlocks++;
3661*01826a49SYabin Cui     }
3662*01826a49SYabin Cui 
3663*01826a49SYabin Cui     *cSize = ip - (const BYTE*)src;
3664*01826a49SYabin Cui     *dBound = nbBlocks * ZSTDv06_BLOCKSIZE_MAX;
3665*01826a49SYabin Cui }
3666*01826a49SYabin Cui 
3667*01826a49SYabin Cui /*_******************************
3668*01826a49SYabin Cui *  Streaming Decompression API
3669*01826a49SYabin Cui ********************************/
ZSTDv06_nextSrcSizeToDecompress(ZSTDv06_DCtx * dctx)3670*01826a49SYabin Cui size_t ZSTDv06_nextSrcSizeToDecompress(ZSTDv06_DCtx* dctx)
3671*01826a49SYabin Cui {
3672*01826a49SYabin Cui     return dctx->expected;
3673*01826a49SYabin Cui }
3674*01826a49SYabin Cui 
ZSTDv06_decompressContinue(ZSTDv06_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)3675*01826a49SYabin Cui size_t ZSTDv06_decompressContinue(ZSTDv06_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
3676*01826a49SYabin Cui {
3677*01826a49SYabin Cui     /* Sanity check */
3678*01826a49SYabin Cui     if (srcSize != dctx->expected) return ERROR(srcSize_wrong);
3679*01826a49SYabin Cui     if (dstCapacity) ZSTDv06_checkContinuity(dctx, dst);
3680*01826a49SYabin Cui 
3681*01826a49SYabin Cui     /* Decompress : frame header; part 1 */
3682*01826a49SYabin Cui     switch (dctx->stage)
3683*01826a49SYabin Cui     {
3684*01826a49SYabin Cui     case ZSTDds_getFrameHeaderSize :
3685*01826a49SYabin Cui         if (srcSize != ZSTDv06_frameHeaderSize_min) return ERROR(srcSize_wrong);   /* impossible */
3686*01826a49SYabin Cui         dctx->headerSize = ZSTDv06_frameHeaderSize(src, ZSTDv06_frameHeaderSize_min);
3687*01826a49SYabin Cui         if (ZSTDv06_isError(dctx->headerSize)) return dctx->headerSize;
3688*01826a49SYabin Cui         memcpy(dctx->headerBuffer, src, ZSTDv06_frameHeaderSize_min);
3689*01826a49SYabin Cui         if (dctx->headerSize > ZSTDv06_frameHeaderSize_min) {
3690*01826a49SYabin Cui             dctx->expected = dctx->headerSize - ZSTDv06_frameHeaderSize_min;
3691*01826a49SYabin Cui             dctx->stage = ZSTDds_decodeFrameHeader;
3692*01826a49SYabin Cui             return 0;
3693*01826a49SYabin Cui         }
3694*01826a49SYabin Cui         dctx->expected = 0;   /* not necessary to copy more */
3695*01826a49SYabin Cui 	/* fall-through */
3696*01826a49SYabin Cui     case ZSTDds_decodeFrameHeader:
3697*01826a49SYabin Cui         {   size_t result;
3698*01826a49SYabin Cui             memcpy(dctx->headerBuffer + ZSTDv06_frameHeaderSize_min, src, dctx->expected);
3699*01826a49SYabin Cui             result = ZSTDv06_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize);
3700*01826a49SYabin Cui             if (ZSTDv06_isError(result)) return result;
3701*01826a49SYabin Cui             dctx->expected = ZSTDv06_blockHeaderSize;
3702*01826a49SYabin Cui             dctx->stage = ZSTDds_decodeBlockHeader;
3703*01826a49SYabin Cui             return 0;
3704*01826a49SYabin Cui         }
3705*01826a49SYabin Cui     case ZSTDds_decodeBlockHeader:
3706*01826a49SYabin Cui         {   blockProperties_t bp;
3707*01826a49SYabin Cui             size_t const cBlockSize = ZSTDv06_getcBlockSize(src, ZSTDv06_blockHeaderSize, &bp);
3708*01826a49SYabin Cui             if (ZSTDv06_isError(cBlockSize)) return cBlockSize;
3709*01826a49SYabin Cui             if (bp.blockType == bt_end) {
3710*01826a49SYabin Cui                 dctx->expected = 0;
3711*01826a49SYabin Cui                 dctx->stage = ZSTDds_getFrameHeaderSize;
3712*01826a49SYabin Cui             } else {
3713*01826a49SYabin Cui                 dctx->expected = cBlockSize;
3714*01826a49SYabin Cui                 dctx->bType = bp.blockType;
3715*01826a49SYabin Cui                 dctx->stage = ZSTDds_decompressBlock;
3716*01826a49SYabin Cui             }
3717*01826a49SYabin Cui             return 0;
3718*01826a49SYabin Cui         }
3719*01826a49SYabin Cui     case ZSTDds_decompressBlock:
3720*01826a49SYabin Cui         {   size_t rSize;
3721*01826a49SYabin Cui             switch(dctx->bType)
3722*01826a49SYabin Cui             {
3723*01826a49SYabin Cui             case bt_compressed:
3724*01826a49SYabin Cui                 rSize = ZSTDv06_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize);
3725*01826a49SYabin Cui                 break;
3726*01826a49SYabin Cui             case bt_raw :
3727*01826a49SYabin Cui                 rSize = ZSTDv06_copyRawBlock(dst, dstCapacity, src, srcSize);
3728*01826a49SYabin Cui                 break;
3729*01826a49SYabin Cui             case bt_rle :
3730*01826a49SYabin Cui                 return ERROR(GENERIC);   /* not yet handled */
3731*01826a49SYabin Cui                 break;
3732*01826a49SYabin Cui             case bt_end :   /* should never happen (filtered at phase 1) */
3733*01826a49SYabin Cui                 rSize = 0;
3734*01826a49SYabin Cui                 break;
3735*01826a49SYabin Cui             default:
3736*01826a49SYabin Cui                 return ERROR(GENERIC);   /* impossible */
3737*01826a49SYabin Cui             }
3738*01826a49SYabin Cui             dctx->stage = ZSTDds_decodeBlockHeader;
3739*01826a49SYabin Cui             dctx->expected = ZSTDv06_blockHeaderSize;
3740*01826a49SYabin Cui             if (ZSTDv06_isError(rSize)) return rSize;
3741*01826a49SYabin Cui             dctx->previousDstEnd = (char*)dst + rSize;
3742*01826a49SYabin Cui             return rSize;
3743*01826a49SYabin Cui         }
3744*01826a49SYabin Cui     default:
3745*01826a49SYabin Cui         return ERROR(GENERIC);   /* impossible */
3746*01826a49SYabin Cui     }
3747*01826a49SYabin Cui }
3748*01826a49SYabin Cui 
3749*01826a49SYabin Cui 
ZSTDv06_refDictContent(ZSTDv06_DCtx * dctx,const void * dict,size_t dictSize)3750*01826a49SYabin Cui static void ZSTDv06_refDictContent(ZSTDv06_DCtx* dctx, const void* dict, size_t dictSize)
3751*01826a49SYabin Cui {
3752*01826a49SYabin Cui     dctx->dictEnd = dctx->previousDstEnd;
3753*01826a49SYabin Cui     dctx->vBase = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->base));
3754*01826a49SYabin Cui     dctx->base = dict;
3755*01826a49SYabin Cui     dctx->previousDstEnd = (const char*)dict + dictSize;
3756*01826a49SYabin Cui }
3757*01826a49SYabin Cui 
ZSTDv06_loadEntropy(ZSTDv06_DCtx * dctx,const void * dict,size_t dictSize)3758*01826a49SYabin Cui static size_t ZSTDv06_loadEntropy(ZSTDv06_DCtx* dctx, const void* dict, size_t dictSize)
3759*01826a49SYabin Cui {
3760*01826a49SYabin Cui     size_t hSize, offcodeHeaderSize, matchlengthHeaderSize, litlengthHeaderSize;
3761*01826a49SYabin Cui 
3762*01826a49SYabin Cui     hSize = HUFv06_readDTableX4(dctx->hufTableX4, dict, dictSize);
3763*01826a49SYabin Cui     if (HUFv06_isError(hSize)) return ERROR(dictionary_corrupted);
3764*01826a49SYabin Cui     dict = (const char*)dict + hSize;
3765*01826a49SYabin Cui     dictSize -= hSize;
3766*01826a49SYabin Cui 
3767*01826a49SYabin Cui     {   short offcodeNCount[MaxOff+1];
3768*01826a49SYabin Cui         U32 offcodeMaxValue=MaxOff, offcodeLog;
3769*01826a49SYabin Cui         offcodeHeaderSize = FSEv06_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dict, dictSize);
3770*01826a49SYabin Cui         if (FSEv06_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
3771*01826a49SYabin Cui         if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted);
3772*01826a49SYabin Cui         { size_t const errorCode = FSEv06_buildDTable(dctx->OffTable, offcodeNCount, offcodeMaxValue, offcodeLog);
3773*01826a49SYabin Cui           if (FSEv06_isError(errorCode)) return ERROR(dictionary_corrupted); }
3774*01826a49SYabin Cui         dict = (const char*)dict + offcodeHeaderSize;
3775*01826a49SYabin Cui         dictSize -= offcodeHeaderSize;
3776*01826a49SYabin Cui     }
3777*01826a49SYabin Cui 
3778*01826a49SYabin Cui     {   short matchlengthNCount[MaxML+1];
3779*01826a49SYabin Cui         unsigned matchlengthMaxValue = MaxML, matchlengthLog;
3780*01826a49SYabin Cui         matchlengthHeaderSize = FSEv06_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dict, dictSize);
3781*01826a49SYabin Cui         if (FSEv06_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
3782*01826a49SYabin Cui         if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted);
3783*01826a49SYabin Cui         { size_t const errorCode = FSEv06_buildDTable(dctx->MLTable, matchlengthNCount, matchlengthMaxValue, matchlengthLog);
3784*01826a49SYabin Cui           if (FSEv06_isError(errorCode)) return ERROR(dictionary_corrupted); }
3785*01826a49SYabin Cui         dict = (const char*)dict + matchlengthHeaderSize;
3786*01826a49SYabin Cui         dictSize -= matchlengthHeaderSize;
3787*01826a49SYabin Cui     }
3788*01826a49SYabin Cui 
3789*01826a49SYabin Cui     {   short litlengthNCount[MaxLL+1];
3790*01826a49SYabin Cui         unsigned litlengthMaxValue = MaxLL, litlengthLog;
3791*01826a49SYabin Cui         litlengthHeaderSize = FSEv06_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dict, dictSize);
3792*01826a49SYabin Cui         if (FSEv06_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
3793*01826a49SYabin Cui         if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted);
3794*01826a49SYabin Cui         { size_t const errorCode = FSEv06_buildDTable(dctx->LLTable, litlengthNCount, litlengthMaxValue, litlengthLog);
3795*01826a49SYabin Cui           if (FSEv06_isError(errorCode)) return ERROR(dictionary_corrupted); }
3796*01826a49SYabin Cui     }
3797*01826a49SYabin Cui 
3798*01826a49SYabin Cui     dctx->flagRepeatTable = 1;
3799*01826a49SYabin Cui     return hSize + offcodeHeaderSize + matchlengthHeaderSize + litlengthHeaderSize;
3800*01826a49SYabin Cui }
3801*01826a49SYabin Cui 
ZSTDv06_decompress_insertDictionary(ZSTDv06_DCtx * dctx,const void * dict,size_t dictSize)3802*01826a49SYabin Cui static size_t ZSTDv06_decompress_insertDictionary(ZSTDv06_DCtx* dctx, const void* dict, size_t dictSize)
3803*01826a49SYabin Cui {
3804*01826a49SYabin Cui     size_t eSize;
3805*01826a49SYabin Cui     U32 const magic = MEM_readLE32(dict);
3806*01826a49SYabin Cui     if (magic != ZSTDv06_DICT_MAGIC) {
3807*01826a49SYabin Cui         /* pure content mode */
3808*01826a49SYabin Cui         ZSTDv06_refDictContent(dctx, dict, dictSize);
3809*01826a49SYabin Cui         return 0;
3810*01826a49SYabin Cui     }
3811*01826a49SYabin Cui     /* load entropy tables */
3812*01826a49SYabin Cui     dict = (const char*)dict + 4;
3813*01826a49SYabin Cui     dictSize -= 4;
3814*01826a49SYabin Cui     eSize = ZSTDv06_loadEntropy(dctx, dict, dictSize);
3815*01826a49SYabin Cui     if (ZSTDv06_isError(eSize)) return ERROR(dictionary_corrupted);
3816*01826a49SYabin Cui 
3817*01826a49SYabin Cui     /* reference dictionary content */
3818*01826a49SYabin Cui     dict = (const char*)dict + eSize;
3819*01826a49SYabin Cui     dictSize -= eSize;
3820*01826a49SYabin Cui     ZSTDv06_refDictContent(dctx, dict, dictSize);
3821*01826a49SYabin Cui 
3822*01826a49SYabin Cui     return 0;
3823*01826a49SYabin Cui }
3824*01826a49SYabin Cui 
3825*01826a49SYabin Cui 
ZSTDv06_decompressBegin_usingDict(ZSTDv06_DCtx * dctx,const void * dict,size_t dictSize)3826*01826a49SYabin Cui size_t ZSTDv06_decompressBegin_usingDict(ZSTDv06_DCtx* dctx, const void* dict, size_t dictSize)
3827*01826a49SYabin Cui {
3828*01826a49SYabin Cui     { size_t const errorCode = ZSTDv06_decompressBegin(dctx);
3829*01826a49SYabin Cui       if (ZSTDv06_isError(errorCode)) return errorCode; }
3830*01826a49SYabin Cui 
3831*01826a49SYabin Cui     if (dict && dictSize) {
3832*01826a49SYabin Cui         size_t const errorCode = ZSTDv06_decompress_insertDictionary(dctx, dict, dictSize);
3833*01826a49SYabin Cui         if (ZSTDv06_isError(errorCode)) return ERROR(dictionary_corrupted);
3834*01826a49SYabin Cui     }
3835*01826a49SYabin Cui 
3836*01826a49SYabin Cui     return 0;
3837*01826a49SYabin Cui }
3838*01826a49SYabin Cui 
3839*01826a49SYabin Cui /*
3840*01826a49SYabin Cui     Buffered version of Zstd compression library
3841*01826a49SYabin Cui     Copyright (C) 2015-2016, Yann Collet.
3842*01826a49SYabin Cui 
3843*01826a49SYabin Cui     BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
3844*01826a49SYabin Cui 
3845*01826a49SYabin Cui     Redistribution and use in source and binary forms, with or without
3846*01826a49SYabin Cui     modification, are permitted provided that the following conditions are
3847*01826a49SYabin Cui     met:
3848*01826a49SYabin Cui     * Redistributions of source code must retain the above copyright
3849*01826a49SYabin Cui     notice, this list of conditions and the following disclaimer.
3850*01826a49SYabin Cui     * Redistributions in binary form must reproduce the above
3851*01826a49SYabin Cui     copyright notice, this list of conditions and the following disclaimer
3852*01826a49SYabin Cui     in the documentation and/or other materials provided with the
3853*01826a49SYabin Cui     distribution.
3854*01826a49SYabin Cui     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
3855*01826a49SYabin Cui     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
3856*01826a49SYabin Cui     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
3857*01826a49SYabin Cui     A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3858*01826a49SYabin Cui     OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3859*01826a49SYabin Cui     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3860*01826a49SYabin Cui     LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3861*01826a49SYabin Cui     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3862*01826a49SYabin Cui     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3863*01826a49SYabin Cui     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3864*01826a49SYabin Cui     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3865*01826a49SYabin Cui 
3866*01826a49SYabin Cui     You can contact the author at :
3867*01826a49SYabin Cui     - zstd homepage : https://facebook.github.io/zstd/
3868*01826a49SYabin Cui */
3869*01826a49SYabin Cui 
3870*01826a49SYabin Cui 
3871*01826a49SYabin Cui /*-***************************************************************************
3872*01826a49SYabin Cui *  Streaming decompression howto
3873*01826a49SYabin Cui *
3874*01826a49SYabin Cui *  A ZBUFFv06_DCtx object is required to track streaming operations.
3875*01826a49SYabin Cui *  Use ZBUFFv06_createDCtx() and ZBUFFv06_freeDCtx() to create/release resources.
3876*01826a49SYabin Cui *  Use ZBUFFv06_decompressInit() to start a new decompression operation,
3877*01826a49SYabin Cui *   or ZBUFFv06_decompressInitDictionary() if decompression requires a dictionary.
3878*01826a49SYabin Cui *  Note that ZBUFFv06_DCtx objects can be re-init multiple times.
3879*01826a49SYabin Cui *
3880*01826a49SYabin Cui *  Use ZBUFFv06_decompressContinue() repetitively to consume your input.
3881*01826a49SYabin Cui *  *srcSizePtr and *dstCapacityPtr can be any size.
3882*01826a49SYabin Cui *  The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr.
3883*01826a49SYabin Cui *  Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again.
3884*01826a49SYabin Cui *  The content of @dst will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters, or change @dst.
3885*01826a49SYabin Cui *  @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency),
3886*01826a49SYabin Cui *            or 0 when a frame is completely decoded,
3887*01826a49SYabin Cui *            or an error code, which can be tested using ZBUFFv06_isError().
3888*01826a49SYabin Cui *
3889*01826a49SYabin Cui *  Hint : recommended buffer sizes (not compulsory) : ZBUFFv06_recommendedDInSize() and ZBUFFv06_recommendedDOutSize()
3890*01826a49SYabin Cui *  output : ZBUFFv06_recommendedDOutSize==128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded.
3891*01826a49SYabin Cui *  input  : ZBUFFv06_recommendedDInSize == 128KB + 3;
3892*01826a49SYabin Cui *           just follow indications from ZBUFFv06_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 .
3893*01826a49SYabin Cui * *******************************************************************************/
3894*01826a49SYabin Cui 
3895*01826a49SYabin Cui typedef enum { ZBUFFds_init, ZBUFFds_loadHeader,
3896*01826a49SYabin Cui                ZBUFFds_read, ZBUFFds_load, ZBUFFds_flush } ZBUFFv06_dStage;
3897*01826a49SYabin Cui 
3898*01826a49SYabin Cui /* *** Resource management *** */
3899*01826a49SYabin Cui struct ZBUFFv06_DCtx_s {
3900*01826a49SYabin Cui     ZSTDv06_DCtx* zd;
3901*01826a49SYabin Cui     ZSTDv06_frameParams fParams;
3902*01826a49SYabin Cui     ZBUFFv06_dStage stage;
3903*01826a49SYabin Cui     char*  inBuff;
3904*01826a49SYabin Cui     size_t inBuffSize;
3905*01826a49SYabin Cui     size_t inPos;
3906*01826a49SYabin Cui     char*  outBuff;
3907*01826a49SYabin Cui     size_t outBuffSize;
3908*01826a49SYabin Cui     size_t outStart;
3909*01826a49SYabin Cui     size_t outEnd;
3910*01826a49SYabin Cui     size_t blockSize;
3911*01826a49SYabin Cui     BYTE headerBuffer[ZSTDv06_FRAMEHEADERSIZE_MAX];
3912*01826a49SYabin Cui     size_t lhSize;
3913*01826a49SYabin Cui };   /* typedef'd to ZBUFFv06_DCtx within "zstd_buffered.h" */
3914*01826a49SYabin Cui 
3915*01826a49SYabin Cui 
ZBUFFv06_createDCtx(void)3916*01826a49SYabin Cui ZBUFFv06_DCtx* ZBUFFv06_createDCtx(void)
3917*01826a49SYabin Cui {
3918*01826a49SYabin Cui     ZBUFFv06_DCtx* zbd = (ZBUFFv06_DCtx*)malloc(sizeof(ZBUFFv06_DCtx));
3919*01826a49SYabin Cui     if (zbd==NULL) return NULL;
3920*01826a49SYabin Cui     memset(zbd, 0, sizeof(*zbd));
3921*01826a49SYabin Cui     zbd->zd = ZSTDv06_createDCtx();
3922*01826a49SYabin Cui     zbd->stage = ZBUFFds_init;
3923*01826a49SYabin Cui     return zbd;
3924*01826a49SYabin Cui }
3925*01826a49SYabin Cui 
ZBUFFv06_freeDCtx(ZBUFFv06_DCtx * zbd)3926*01826a49SYabin Cui size_t ZBUFFv06_freeDCtx(ZBUFFv06_DCtx* zbd)
3927*01826a49SYabin Cui {
3928*01826a49SYabin Cui     if (zbd==NULL) return 0;   /* support free on null */
3929*01826a49SYabin Cui     ZSTDv06_freeDCtx(zbd->zd);
3930*01826a49SYabin Cui     free(zbd->inBuff);
3931*01826a49SYabin Cui     free(zbd->outBuff);
3932*01826a49SYabin Cui     free(zbd);
3933*01826a49SYabin Cui     return 0;
3934*01826a49SYabin Cui }
3935*01826a49SYabin Cui 
3936*01826a49SYabin Cui 
3937*01826a49SYabin Cui /* *** Initialization *** */
3938*01826a49SYabin Cui 
ZBUFFv06_decompressInitDictionary(ZBUFFv06_DCtx * zbd,const void * dict,size_t dictSize)3939*01826a49SYabin Cui size_t ZBUFFv06_decompressInitDictionary(ZBUFFv06_DCtx* zbd, const void* dict, size_t dictSize)
3940*01826a49SYabin Cui {
3941*01826a49SYabin Cui     zbd->stage = ZBUFFds_loadHeader;
3942*01826a49SYabin Cui     zbd->lhSize = zbd->inPos = zbd->outStart = zbd->outEnd = 0;
3943*01826a49SYabin Cui     return ZSTDv06_decompressBegin_usingDict(zbd->zd, dict, dictSize);
3944*01826a49SYabin Cui }
3945*01826a49SYabin Cui 
ZBUFFv06_decompressInit(ZBUFFv06_DCtx * zbd)3946*01826a49SYabin Cui size_t ZBUFFv06_decompressInit(ZBUFFv06_DCtx* zbd)
3947*01826a49SYabin Cui {
3948*01826a49SYabin Cui     return ZBUFFv06_decompressInitDictionary(zbd, NULL, 0);
3949*01826a49SYabin Cui }
3950*01826a49SYabin Cui 
3951*01826a49SYabin Cui 
3952*01826a49SYabin Cui 
ZBUFFv06_limitCopy(void * dst,size_t dstCapacity,const void * src,size_t srcSize)3953*01826a49SYabin Cui MEM_STATIC size_t ZBUFFv06_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
3954*01826a49SYabin Cui {
3955*01826a49SYabin Cui     size_t length = MIN(dstCapacity, srcSize);
3956*01826a49SYabin Cui     if (length > 0) {
3957*01826a49SYabin Cui         memcpy(dst, src, length);
3958*01826a49SYabin Cui     }
3959*01826a49SYabin Cui     return length;
3960*01826a49SYabin Cui }
3961*01826a49SYabin Cui 
3962*01826a49SYabin Cui 
3963*01826a49SYabin Cui /* *** Decompression *** */
3964*01826a49SYabin Cui 
ZBUFFv06_decompressContinue(ZBUFFv06_DCtx * zbd,void * dst,size_t * dstCapacityPtr,const void * src,size_t * srcSizePtr)3965*01826a49SYabin Cui size_t ZBUFFv06_decompressContinue(ZBUFFv06_DCtx* zbd,
3966*01826a49SYabin Cui                                 void* dst, size_t* dstCapacityPtr,
3967*01826a49SYabin Cui                           const void* src, size_t* srcSizePtr)
3968*01826a49SYabin Cui {
3969*01826a49SYabin Cui     const char* const istart = (const char*)src;
3970*01826a49SYabin Cui     const char* const iend = istart + *srcSizePtr;
3971*01826a49SYabin Cui     const char* ip = istart;
3972*01826a49SYabin Cui     char* const ostart = (char*)dst;
3973*01826a49SYabin Cui     char* const oend = ostart + *dstCapacityPtr;
3974*01826a49SYabin Cui     char* op = ostart;
3975*01826a49SYabin Cui     U32 notDone = 1;
3976*01826a49SYabin Cui 
3977*01826a49SYabin Cui     while (notDone) {
3978*01826a49SYabin Cui         switch(zbd->stage)
3979*01826a49SYabin Cui         {
3980*01826a49SYabin Cui         case ZBUFFds_init :
3981*01826a49SYabin Cui             return ERROR(init_missing);
3982*01826a49SYabin Cui 
3983*01826a49SYabin Cui         case ZBUFFds_loadHeader :
3984*01826a49SYabin Cui             {   size_t const hSize = ZSTDv06_getFrameParams(&(zbd->fParams), zbd->headerBuffer, zbd->lhSize);
3985*01826a49SYabin Cui                 if (hSize != 0) {
3986*01826a49SYabin Cui                     size_t const toLoad = hSize - zbd->lhSize;   /* if hSize!=0, hSize > zbd->lhSize */
3987*01826a49SYabin Cui                     if (ZSTDv06_isError(hSize)) return hSize;
3988*01826a49SYabin Cui                     if (toLoad > (size_t)(iend-ip)) {   /* not enough input to load full header */
3989*01826a49SYabin Cui                         if (ip != NULL)
3990*01826a49SYabin Cui                             memcpy(zbd->headerBuffer + zbd->lhSize, ip, iend-ip);
3991*01826a49SYabin Cui                         zbd->lhSize += iend-ip;
3992*01826a49SYabin Cui                         *dstCapacityPtr = 0;
3993*01826a49SYabin Cui                         return (hSize - zbd->lhSize) + ZSTDv06_blockHeaderSize;   /* remaining header bytes + next block header */
3994*01826a49SYabin Cui                     }
3995*01826a49SYabin Cui                     memcpy(zbd->headerBuffer + zbd->lhSize, ip, toLoad); zbd->lhSize = hSize; ip += toLoad;
3996*01826a49SYabin Cui                     break;
3997*01826a49SYabin Cui             }   }
3998*01826a49SYabin Cui 
3999*01826a49SYabin Cui             /* Consume header */
4000*01826a49SYabin Cui             {   size_t const h1Size = ZSTDv06_nextSrcSizeToDecompress(zbd->zd);  /* == ZSTDv06_frameHeaderSize_min */
4001*01826a49SYabin Cui                 size_t const h1Result = ZSTDv06_decompressContinue(zbd->zd, NULL, 0, zbd->headerBuffer, h1Size);
4002*01826a49SYabin Cui                 if (ZSTDv06_isError(h1Result)) return h1Result;
4003*01826a49SYabin Cui                 if (h1Size < zbd->lhSize) {   /* long header */
4004*01826a49SYabin Cui                     size_t const h2Size = ZSTDv06_nextSrcSizeToDecompress(zbd->zd);
4005*01826a49SYabin Cui                     size_t const h2Result = ZSTDv06_decompressContinue(zbd->zd, NULL, 0, zbd->headerBuffer+h1Size, h2Size);
4006*01826a49SYabin Cui                     if (ZSTDv06_isError(h2Result)) return h2Result;
4007*01826a49SYabin Cui             }   }
4008*01826a49SYabin Cui 
4009*01826a49SYabin Cui             /* Frame header instruct buffer sizes */
4010*01826a49SYabin Cui             {   size_t const blockSize = MIN(1 << zbd->fParams.windowLog, ZSTDv06_BLOCKSIZE_MAX);
4011*01826a49SYabin Cui                 zbd->blockSize = blockSize;
4012*01826a49SYabin Cui                 if (zbd->inBuffSize < blockSize) {
4013*01826a49SYabin Cui                     free(zbd->inBuff);
4014*01826a49SYabin Cui                     zbd->inBuffSize = blockSize;
4015*01826a49SYabin Cui                     zbd->inBuff = (char*)malloc(blockSize);
4016*01826a49SYabin Cui                     if (zbd->inBuff == NULL) return ERROR(memory_allocation);
4017*01826a49SYabin Cui                 }
4018*01826a49SYabin Cui                 {   size_t const neededOutSize = ((size_t)1 << zbd->fParams.windowLog) + blockSize + WILDCOPY_OVERLENGTH * 2;
4019*01826a49SYabin Cui                     if (zbd->outBuffSize < neededOutSize) {
4020*01826a49SYabin Cui                         free(zbd->outBuff);
4021*01826a49SYabin Cui                         zbd->outBuffSize = neededOutSize;
4022*01826a49SYabin Cui                         zbd->outBuff = (char*)malloc(neededOutSize);
4023*01826a49SYabin Cui                         if (zbd->outBuff == NULL) return ERROR(memory_allocation);
4024*01826a49SYabin Cui             }   }   }
4025*01826a49SYabin Cui             zbd->stage = ZBUFFds_read;
4026*01826a49SYabin Cui 	    /* fall-through */
4027*01826a49SYabin Cui         case ZBUFFds_read:
4028*01826a49SYabin Cui             {   size_t const neededInSize = ZSTDv06_nextSrcSizeToDecompress(zbd->zd);
4029*01826a49SYabin Cui                 if (neededInSize==0) {  /* end of frame */
4030*01826a49SYabin Cui                     zbd->stage = ZBUFFds_init;
4031*01826a49SYabin Cui                     notDone = 0;
4032*01826a49SYabin Cui                     break;
4033*01826a49SYabin Cui                 }
4034*01826a49SYabin Cui                 if ((size_t)(iend-ip) >= neededInSize) {  /* decode directly from src */
4035*01826a49SYabin Cui                     size_t const decodedSize = ZSTDv06_decompressContinue(zbd->zd,
4036*01826a49SYabin Cui                         zbd->outBuff + zbd->outStart, zbd->outBuffSize - zbd->outStart,
4037*01826a49SYabin Cui                         ip, neededInSize);
4038*01826a49SYabin Cui                     if (ZSTDv06_isError(decodedSize)) return decodedSize;
4039*01826a49SYabin Cui                     ip += neededInSize;
4040*01826a49SYabin Cui                     if (!decodedSize) break;   /* this was just a header */
4041*01826a49SYabin Cui                     zbd->outEnd = zbd->outStart +  decodedSize;
4042*01826a49SYabin Cui                     zbd->stage = ZBUFFds_flush;
4043*01826a49SYabin Cui                     break;
4044*01826a49SYabin Cui                 }
4045*01826a49SYabin Cui                 if (ip==iend) { notDone = 0; break; }   /* no more input */
4046*01826a49SYabin Cui                 zbd->stage = ZBUFFds_load;
4047*01826a49SYabin Cui             }
4048*01826a49SYabin Cui 	    /* fall-through */
4049*01826a49SYabin Cui         case ZBUFFds_load:
4050*01826a49SYabin Cui             {   size_t const neededInSize = ZSTDv06_nextSrcSizeToDecompress(zbd->zd);
4051*01826a49SYabin Cui                 size_t const toLoad = neededInSize - zbd->inPos;   /* should always be <= remaining space within inBuff */
4052*01826a49SYabin Cui                 size_t loadedSize;
4053*01826a49SYabin Cui                 if (toLoad > zbd->inBuffSize - zbd->inPos) return ERROR(corruption_detected);   /* should never happen */
4054*01826a49SYabin Cui                 loadedSize = ZBUFFv06_limitCopy(zbd->inBuff + zbd->inPos, toLoad, ip, iend-ip);
4055*01826a49SYabin Cui                 ip += loadedSize;
4056*01826a49SYabin Cui                 zbd->inPos += loadedSize;
4057*01826a49SYabin Cui                 if (loadedSize < toLoad) { notDone = 0; break; }   /* not enough input, wait for more */
4058*01826a49SYabin Cui 
4059*01826a49SYabin Cui                 /* decode loaded input */
4060*01826a49SYabin Cui                 {   size_t const decodedSize = ZSTDv06_decompressContinue(zbd->zd,
4061*01826a49SYabin Cui                         zbd->outBuff + zbd->outStart, zbd->outBuffSize - zbd->outStart,
4062*01826a49SYabin Cui                         zbd->inBuff, neededInSize);
4063*01826a49SYabin Cui                     if (ZSTDv06_isError(decodedSize)) return decodedSize;
4064*01826a49SYabin Cui                     zbd->inPos = 0;   /* input is consumed */
4065*01826a49SYabin Cui                     if (!decodedSize) { zbd->stage = ZBUFFds_read; break; }   /* this was just a header */
4066*01826a49SYabin Cui                     zbd->outEnd = zbd->outStart +  decodedSize;
4067*01826a49SYabin Cui                     zbd->stage = ZBUFFds_flush;
4068*01826a49SYabin Cui                     /* break; */ /* ZBUFFds_flush follows */
4069*01826a49SYabin Cui                 }
4070*01826a49SYabin Cui 	    }
4071*01826a49SYabin Cui 	    /* fall-through */
4072*01826a49SYabin Cui         case ZBUFFds_flush:
4073*01826a49SYabin Cui             {   size_t const toFlushSize = zbd->outEnd - zbd->outStart;
4074*01826a49SYabin Cui                 size_t const flushedSize = ZBUFFv06_limitCopy(op, oend-op, zbd->outBuff + zbd->outStart, toFlushSize);
4075*01826a49SYabin Cui                 op += flushedSize;
4076*01826a49SYabin Cui                 zbd->outStart += flushedSize;
4077*01826a49SYabin Cui                 if (flushedSize == toFlushSize) {
4078*01826a49SYabin Cui                     zbd->stage = ZBUFFds_read;
4079*01826a49SYabin Cui                     if (zbd->outStart + zbd->blockSize > zbd->outBuffSize)
4080*01826a49SYabin Cui                         zbd->outStart = zbd->outEnd = 0;
4081*01826a49SYabin Cui                     break;
4082*01826a49SYabin Cui                 }
4083*01826a49SYabin Cui                 /* cannot flush everything */
4084*01826a49SYabin Cui                 notDone = 0;
4085*01826a49SYabin Cui                 break;
4086*01826a49SYabin Cui             }
4087*01826a49SYabin Cui         default: return ERROR(GENERIC);   /* impossible */
4088*01826a49SYabin Cui     }   }
4089*01826a49SYabin Cui 
4090*01826a49SYabin Cui     /* result */
4091*01826a49SYabin Cui     *srcSizePtr = ip-istart;
4092*01826a49SYabin Cui     *dstCapacityPtr = op-ostart;
4093*01826a49SYabin Cui     {   size_t nextSrcSizeHint = ZSTDv06_nextSrcSizeToDecompress(zbd->zd);
4094*01826a49SYabin Cui         if (nextSrcSizeHint > ZSTDv06_blockHeaderSize) nextSrcSizeHint+= ZSTDv06_blockHeaderSize;   /* get following block header too */
4095*01826a49SYabin Cui         nextSrcSizeHint -= zbd->inPos;   /* already loaded*/
4096*01826a49SYabin Cui         return nextSrcSizeHint;
4097*01826a49SYabin Cui     }
4098*01826a49SYabin Cui }
4099*01826a49SYabin Cui 
4100*01826a49SYabin Cui 
4101*01826a49SYabin Cui 
4102*01826a49SYabin Cui /* *************************************
4103*01826a49SYabin Cui *  Tool functions
4104*01826a49SYabin Cui ***************************************/
ZBUFFv06_recommendedDInSize(void)4105*01826a49SYabin Cui size_t ZBUFFv06_recommendedDInSize(void)  { return ZSTDv06_BLOCKSIZE_MAX + ZSTDv06_blockHeaderSize /* block header size*/ ; }
ZBUFFv06_recommendedDOutSize(void)4106*01826a49SYabin Cui size_t ZBUFFv06_recommendedDOutSize(void) { return ZSTDv06_BLOCKSIZE_MAX; }
4107