xref: /aosp_15_r20/external/zstd/lib/legacy/zstd_v02.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 #include <stddef.h>    /* size_t, ptrdiff_t */
13*01826a49SYabin Cui #include "zstd_v02.h"
14*01826a49SYabin Cui #include "../common/compiler.h"
15*01826a49SYabin Cui #include "../common/error_private.h"
16*01826a49SYabin Cui 
17*01826a49SYabin Cui 
18*01826a49SYabin Cui /******************************************
19*01826a49SYabin Cui *  Compiler-specific
20*01826a49SYabin Cui ******************************************/
21*01826a49SYabin Cui #if defined(_MSC_VER)   /* Visual Studio */
22*01826a49SYabin Cui #   include <stdlib.h>  /* _byteswap_ulong */
23*01826a49SYabin Cui #   include <intrin.h>  /* _byteswap_* */
24*01826a49SYabin Cui #endif
25*01826a49SYabin Cui 
26*01826a49SYabin Cui 
27*01826a49SYabin Cui /* ******************************************************************
28*01826a49SYabin Cui    mem.h
29*01826a49SYabin Cui    low-level memory access routines
30*01826a49SYabin Cui    Copyright (C) 2013-2015, Yann Collet.
31*01826a49SYabin Cui 
32*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
33*01826a49SYabin Cui 
34*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
35*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
36*01826a49SYabin Cui    met:
37*01826a49SYabin Cui 
38*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
39*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
40*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
41*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
42*01826a49SYabin Cui    in the documentation and/or other materials provided with the
43*01826a49SYabin Cui    distribution.
44*01826a49SYabin Cui 
45*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
46*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
47*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
48*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
49*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
50*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
51*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
52*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
53*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
54*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
55*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
56*01826a49SYabin Cui 
57*01826a49SYabin Cui     You can contact the author at :
58*01826a49SYabin Cui     - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
59*01826a49SYabin Cui     - Public forum : https://groups.google.com/forum/#!forum/lz4c
60*01826a49SYabin Cui ****************************************************************** */
61*01826a49SYabin Cui #ifndef MEM_H_MODULE
62*01826a49SYabin Cui #define MEM_H_MODULE
63*01826a49SYabin Cui 
64*01826a49SYabin Cui #if defined (__cplusplus)
65*01826a49SYabin Cui extern "C" {
66*01826a49SYabin Cui #endif
67*01826a49SYabin Cui 
68*01826a49SYabin Cui /******************************************
69*01826a49SYabin Cui *  Includes
70*01826a49SYabin Cui ******************************************/
71*01826a49SYabin Cui #include <stddef.h>    /* size_t, ptrdiff_t */
72*01826a49SYabin Cui #include <string.h>    /* memcpy */
73*01826a49SYabin Cui 
74*01826a49SYabin Cui 
75*01826a49SYabin Cui /****************************************************************
76*01826a49SYabin Cui *  Basic Types
77*01826a49SYabin Cui *****************************************************************/
78*01826a49SYabin Cui #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
79*01826a49SYabin Cui # if defined(_AIX)
80*01826a49SYabin Cui #  include <inttypes.h>
81*01826a49SYabin Cui # else
82*01826a49SYabin Cui #  include <stdint.h> /* intptr_t */
83*01826a49SYabin Cui # endif
84*01826a49SYabin Cui   typedef  uint8_t BYTE;
85*01826a49SYabin Cui   typedef uint16_t U16;
86*01826a49SYabin Cui   typedef  int16_t S16;
87*01826a49SYabin Cui   typedef uint32_t U32;
88*01826a49SYabin Cui   typedef  int32_t S32;
89*01826a49SYabin Cui   typedef uint64_t U64;
90*01826a49SYabin Cui   typedef  int64_t S64;
91*01826a49SYabin Cui #else
92*01826a49SYabin Cui   typedef unsigned char       BYTE;
93*01826a49SYabin Cui   typedef unsigned short      U16;
94*01826a49SYabin Cui   typedef   signed short      S16;
95*01826a49SYabin Cui   typedef unsigned int        U32;
96*01826a49SYabin Cui   typedef   signed int        S32;
97*01826a49SYabin Cui   typedef unsigned long long  U64;
98*01826a49SYabin Cui   typedef   signed long long  S64;
99*01826a49SYabin Cui #endif
100*01826a49SYabin Cui 
101*01826a49SYabin Cui 
102*01826a49SYabin Cui /****************************************************************
103*01826a49SYabin Cui *  Memory I/O
104*01826a49SYabin Cui *****************************************************************/
105*01826a49SYabin Cui 
MEM_32bits(void)106*01826a49SYabin Cui MEM_STATIC unsigned MEM_32bits(void) { return sizeof(void*)==4; }
MEM_64bits(void)107*01826a49SYabin Cui MEM_STATIC unsigned MEM_64bits(void) { return sizeof(void*)==8; }
108*01826a49SYabin Cui 
MEM_isLittleEndian(void)109*01826a49SYabin Cui MEM_STATIC unsigned MEM_isLittleEndian(void)
110*01826a49SYabin Cui {
111*01826a49SYabin Cui     const union { U32 u; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental  */
112*01826a49SYabin Cui     return one.c[0];
113*01826a49SYabin Cui }
114*01826a49SYabin Cui 
MEM_read16(const void * memPtr)115*01826a49SYabin Cui MEM_STATIC U16 MEM_read16(const void* memPtr)
116*01826a49SYabin Cui {
117*01826a49SYabin Cui     U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
118*01826a49SYabin Cui }
119*01826a49SYabin Cui 
MEM_read32(const void * memPtr)120*01826a49SYabin Cui MEM_STATIC U32 MEM_read32(const void* memPtr)
121*01826a49SYabin Cui {
122*01826a49SYabin Cui     U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
123*01826a49SYabin Cui }
124*01826a49SYabin Cui 
MEM_read64(const void * memPtr)125*01826a49SYabin Cui MEM_STATIC U64 MEM_read64(const void* memPtr)
126*01826a49SYabin Cui {
127*01826a49SYabin Cui     U64 val; memcpy(&val, memPtr, sizeof(val)); return val;
128*01826a49SYabin Cui }
129*01826a49SYabin Cui 
MEM_write16(void * memPtr,U16 value)130*01826a49SYabin Cui MEM_STATIC void MEM_write16(void* memPtr, U16 value)
131*01826a49SYabin Cui {
132*01826a49SYabin Cui     memcpy(memPtr, &value, sizeof(value));
133*01826a49SYabin Cui }
134*01826a49SYabin Cui 
MEM_readLE16(const void * memPtr)135*01826a49SYabin Cui MEM_STATIC U16 MEM_readLE16(const void* memPtr)
136*01826a49SYabin Cui {
137*01826a49SYabin Cui     if (MEM_isLittleEndian())
138*01826a49SYabin Cui         return MEM_read16(memPtr);
139*01826a49SYabin Cui     else
140*01826a49SYabin Cui     {
141*01826a49SYabin Cui         const BYTE* p = (const BYTE*)memPtr;
142*01826a49SYabin Cui         return (U16)(p[0] + (p[1]<<8));
143*01826a49SYabin Cui     }
144*01826a49SYabin Cui }
145*01826a49SYabin Cui 
MEM_writeLE16(void * memPtr,U16 val)146*01826a49SYabin Cui MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val)
147*01826a49SYabin Cui {
148*01826a49SYabin Cui     if (MEM_isLittleEndian())
149*01826a49SYabin Cui     {
150*01826a49SYabin Cui         MEM_write16(memPtr, val);
151*01826a49SYabin Cui     }
152*01826a49SYabin Cui     else
153*01826a49SYabin Cui     {
154*01826a49SYabin Cui         BYTE* p = (BYTE*)memPtr;
155*01826a49SYabin Cui         p[0] = (BYTE)val;
156*01826a49SYabin Cui         p[1] = (BYTE)(val>>8);
157*01826a49SYabin Cui     }
158*01826a49SYabin Cui }
159*01826a49SYabin Cui 
MEM_readLE24(const void * memPtr)160*01826a49SYabin Cui MEM_STATIC U32 MEM_readLE24(const void* memPtr)
161*01826a49SYabin Cui {
162*01826a49SYabin Cui     return MEM_readLE16(memPtr) + (((const BYTE*)memPtr)[2] << 16);
163*01826a49SYabin Cui }
164*01826a49SYabin Cui 
MEM_readLE32(const void * memPtr)165*01826a49SYabin Cui MEM_STATIC U32 MEM_readLE32(const void* memPtr)
166*01826a49SYabin Cui {
167*01826a49SYabin Cui     if (MEM_isLittleEndian())
168*01826a49SYabin Cui         return MEM_read32(memPtr);
169*01826a49SYabin Cui     else
170*01826a49SYabin Cui     {
171*01826a49SYabin Cui         const BYTE* p = (const BYTE*)memPtr;
172*01826a49SYabin Cui         return (U32)((U32)p[0] + ((U32)p[1]<<8) + ((U32)p[2]<<16) + ((U32)p[3]<<24));
173*01826a49SYabin Cui     }
174*01826a49SYabin Cui }
175*01826a49SYabin Cui 
176*01826a49SYabin Cui 
MEM_readLE64(const void * memPtr)177*01826a49SYabin Cui MEM_STATIC U64 MEM_readLE64(const void* memPtr)
178*01826a49SYabin Cui {
179*01826a49SYabin Cui     if (MEM_isLittleEndian())
180*01826a49SYabin Cui         return MEM_read64(memPtr);
181*01826a49SYabin Cui     else
182*01826a49SYabin Cui     {
183*01826a49SYabin Cui         const BYTE* p = (const BYTE*)memPtr;
184*01826a49SYabin Cui         return (U64)((U64)p[0] + ((U64)p[1]<<8) + ((U64)p[2]<<16) + ((U64)p[3]<<24)
185*01826a49SYabin Cui                      + ((U64)p[4]<<32) + ((U64)p[5]<<40) + ((U64)p[6]<<48) + ((U64)p[7]<<56));
186*01826a49SYabin Cui     }
187*01826a49SYabin Cui }
188*01826a49SYabin Cui 
189*01826a49SYabin Cui 
MEM_readLEST(const void * memPtr)190*01826a49SYabin Cui MEM_STATIC size_t MEM_readLEST(const void* memPtr)
191*01826a49SYabin Cui {
192*01826a49SYabin Cui     if (MEM_32bits())
193*01826a49SYabin Cui         return (size_t)MEM_readLE32(memPtr);
194*01826a49SYabin Cui     else
195*01826a49SYabin Cui         return (size_t)MEM_readLE64(memPtr);
196*01826a49SYabin Cui }
197*01826a49SYabin Cui 
198*01826a49SYabin Cui #if defined (__cplusplus)
199*01826a49SYabin Cui }
200*01826a49SYabin Cui #endif
201*01826a49SYabin Cui 
202*01826a49SYabin Cui #endif /* MEM_H_MODULE */
203*01826a49SYabin Cui 
204*01826a49SYabin Cui 
205*01826a49SYabin Cui /* ******************************************************************
206*01826a49SYabin Cui    bitstream
207*01826a49SYabin Cui    Part of NewGen Entropy library
208*01826a49SYabin Cui    header file (to include)
209*01826a49SYabin Cui    Copyright (C) 2013-2015, Yann Collet.
210*01826a49SYabin Cui 
211*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
212*01826a49SYabin Cui 
213*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
214*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
215*01826a49SYabin Cui    met:
216*01826a49SYabin Cui 
217*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
218*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
219*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
220*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
221*01826a49SYabin Cui    in the documentation and/or other materials provided with the
222*01826a49SYabin Cui    distribution.
223*01826a49SYabin Cui 
224*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
225*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
226*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
227*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
228*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
229*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
230*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
231*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
232*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
233*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
234*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
235*01826a49SYabin Cui 
236*01826a49SYabin Cui    You can contact the author at :
237*01826a49SYabin Cui    - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
238*01826a49SYabin Cui    - Public forum : https://groups.google.com/forum/#!forum/lz4c
239*01826a49SYabin Cui ****************************************************************** */
240*01826a49SYabin Cui #ifndef BITSTREAM_H_MODULE
241*01826a49SYabin Cui #define BITSTREAM_H_MODULE
242*01826a49SYabin Cui 
243*01826a49SYabin Cui #if defined (__cplusplus)
244*01826a49SYabin Cui extern "C" {
245*01826a49SYabin Cui #endif
246*01826a49SYabin Cui 
247*01826a49SYabin Cui 
248*01826a49SYabin Cui /*
249*01826a49SYabin Cui *  This API consists of small unitary functions, which highly benefit from being inlined.
250*01826a49SYabin Cui *  Since link-time-optimization is not available for all compilers,
251*01826a49SYabin Cui *  these functions are defined into a .h to be included.
252*01826a49SYabin Cui */
253*01826a49SYabin Cui 
254*01826a49SYabin Cui 
255*01826a49SYabin Cui /**********************************************
256*01826a49SYabin Cui *  bitStream decompression API (read backward)
257*01826a49SYabin Cui **********************************************/
258*01826a49SYabin Cui typedef struct
259*01826a49SYabin Cui {
260*01826a49SYabin Cui     size_t   bitContainer;
261*01826a49SYabin Cui     unsigned bitsConsumed;
262*01826a49SYabin Cui     const char* ptr;
263*01826a49SYabin Cui     const char* start;
264*01826a49SYabin Cui } BIT_DStream_t;
265*01826a49SYabin Cui 
266*01826a49SYabin Cui typedef enum { BIT_DStream_unfinished = 0,
267*01826a49SYabin Cui                BIT_DStream_endOfBuffer = 1,
268*01826a49SYabin Cui                BIT_DStream_completed = 2,
269*01826a49SYabin Cui                BIT_DStream_overflow = 3 } BIT_DStream_status;  /* result of BIT_reloadDStream() */
270*01826a49SYabin Cui                /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */
271*01826a49SYabin Cui 
272*01826a49SYabin Cui MEM_STATIC size_t   BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
273*01826a49SYabin Cui MEM_STATIC size_t   BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits);
274*01826a49SYabin Cui MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD);
275*01826a49SYabin Cui MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD);
276*01826a49SYabin Cui 
277*01826a49SYabin Cui 
278*01826a49SYabin Cui /******************************************
279*01826a49SYabin Cui *  unsafe API
280*01826a49SYabin Cui ******************************************/
281*01826a49SYabin Cui MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits);
282*01826a49SYabin Cui /* faster, but works only if nbBits >= 1 */
283*01826a49SYabin Cui 
284*01826a49SYabin Cui 
285*01826a49SYabin Cui 
286*01826a49SYabin Cui /****************************************************************
287*01826a49SYabin Cui *  Helper functions
288*01826a49SYabin Cui ****************************************************************/
BIT_highbit32(U32 val)289*01826a49SYabin Cui MEM_STATIC unsigned BIT_highbit32 (U32 val)
290*01826a49SYabin Cui {
291*01826a49SYabin Cui #   if defined(_MSC_VER)   /* Visual */
292*01826a49SYabin Cui     unsigned long r;
293*01826a49SYabin Cui     return _BitScanReverse(&r, val) ? (unsigned)r : 0;
294*01826a49SYabin Cui #   elif defined(__GNUC__) && (__GNUC__ >= 3)   /* Use GCC Intrinsic */
295*01826a49SYabin Cui     return __builtin_clz (val) ^ 31;
296*01826a49SYabin Cui #   else   /* Software version */
297*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 };
298*01826a49SYabin Cui     U32 v = val;
299*01826a49SYabin Cui     unsigned r;
300*01826a49SYabin Cui     v |= v >> 1;
301*01826a49SYabin Cui     v |= v >> 2;
302*01826a49SYabin Cui     v |= v >> 4;
303*01826a49SYabin Cui     v |= v >> 8;
304*01826a49SYabin Cui     v |= v >> 16;
305*01826a49SYabin Cui     r = DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
306*01826a49SYabin Cui     return r;
307*01826a49SYabin Cui #   endif
308*01826a49SYabin Cui }
309*01826a49SYabin Cui 
310*01826a49SYabin Cui 
311*01826a49SYabin Cui 
312*01826a49SYabin Cui /**********************************************************
313*01826a49SYabin Cui * bitStream decoding
314*01826a49SYabin Cui **********************************************************/
315*01826a49SYabin Cui 
316*01826a49SYabin Cui /*!BIT_initDStream
317*01826a49SYabin Cui *  Initialize a BIT_DStream_t.
318*01826a49SYabin Cui *  @bitD : a pointer to an already allocated BIT_DStream_t structure
319*01826a49SYabin Cui *  @srcBuffer must point at the beginning of a bitStream
320*01826a49SYabin Cui *  @srcSize must be the exact size of the bitStream
321*01826a49SYabin Cui *  @result : size of stream (== srcSize) or an errorCode if a problem is detected
322*01826a49SYabin Cui */
BIT_initDStream(BIT_DStream_t * bitD,const void * srcBuffer,size_t srcSize)323*01826a49SYabin Cui MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
324*01826a49SYabin Cui {
325*01826a49SYabin Cui     if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }
326*01826a49SYabin Cui 
327*01826a49SYabin Cui     if (srcSize >=  sizeof(size_t))   /* normal case */
328*01826a49SYabin Cui     {
329*01826a49SYabin Cui         U32 contain32;
330*01826a49SYabin Cui         bitD->start = (const char*)srcBuffer;
331*01826a49SYabin Cui         bitD->ptr   = (const char*)srcBuffer + srcSize - sizeof(size_t);
332*01826a49SYabin Cui         bitD->bitContainer = MEM_readLEST(bitD->ptr);
333*01826a49SYabin Cui         contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
334*01826a49SYabin Cui         if (contain32 == 0) return ERROR(GENERIC);   /* endMark not present */
335*01826a49SYabin Cui         bitD->bitsConsumed = 8 - BIT_highbit32(contain32);
336*01826a49SYabin Cui     }
337*01826a49SYabin Cui     else
338*01826a49SYabin Cui     {
339*01826a49SYabin Cui         U32 contain32;
340*01826a49SYabin Cui         bitD->start = (const char*)srcBuffer;
341*01826a49SYabin Cui         bitD->ptr   = bitD->start;
342*01826a49SYabin Cui         bitD->bitContainer = *(const BYTE*)(bitD->start);
343*01826a49SYabin Cui         switch(srcSize)
344*01826a49SYabin Cui         {
345*01826a49SYabin Cui             case 7: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[6]) << (sizeof(size_t)*8 - 16);
346*01826a49SYabin Cui                     /* fallthrough */
347*01826a49SYabin Cui             case 6: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[5]) << (sizeof(size_t)*8 - 24);
348*01826a49SYabin Cui                     /* fallthrough */
349*01826a49SYabin Cui             case 5: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[4]) << (sizeof(size_t)*8 - 32);
350*01826a49SYabin Cui                     /* fallthrough */
351*01826a49SYabin Cui             case 4: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[3]) << 24;
352*01826a49SYabin Cui                     /* fallthrough */
353*01826a49SYabin Cui             case 3: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[2]) << 16;
354*01826a49SYabin Cui                     /* fallthrough */
355*01826a49SYabin Cui             case 2: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[1]) <<  8;
356*01826a49SYabin Cui                     /* fallthrough */
357*01826a49SYabin Cui             default:;
358*01826a49SYabin Cui         }
359*01826a49SYabin Cui         contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
360*01826a49SYabin Cui         if (contain32 == 0) return ERROR(GENERIC);   /* endMark not present */
361*01826a49SYabin Cui         bitD->bitsConsumed = 8 - BIT_highbit32(contain32);
362*01826a49SYabin Cui         bitD->bitsConsumed += (U32)(sizeof(size_t) - srcSize)*8;
363*01826a49SYabin Cui     }
364*01826a49SYabin Cui 
365*01826a49SYabin Cui     return srcSize;
366*01826a49SYabin Cui }
367*01826a49SYabin Cui 
BIT_lookBits(BIT_DStream_t * bitD,U32 nbBits)368*01826a49SYabin Cui MEM_STATIC size_t BIT_lookBits(BIT_DStream_t* bitD, U32 nbBits)
369*01826a49SYabin Cui {
370*01826a49SYabin Cui     const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
371*01826a49SYabin Cui     return ((bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> 1) >> ((bitMask-nbBits) & bitMask);
372*01826a49SYabin Cui }
373*01826a49SYabin Cui 
374*01826a49SYabin Cui /*! BIT_lookBitsFast :
375*01826a49SYabin Cui *   unsafe version; only works if nbBits >= 1 */
BIT_lookBitsFast(BIT_DStream_t * bitD,U32 nbBits)376*01826a49SYabin Cui MEM_STATIC size_t BIT_lookBitsFast(BIT_DStream_t* bitD, U32 nbBits)
377*01826a49SYabin Cui {
378*01826a49SYabin Cui     const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
379*01826a49SYabin Cui     return (bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> (((bitMask+1)-nbBits) & bitMask);
380*01826a49SYabin Cui }
381*01826a49SYabin Cui 
BIT_skipBits(BIT_DStream_t * bitD,U32 nbBits)382*01826a49SYabin Cui MEM_STATIC void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits)
383*01826a49SYabin Cui {
384*01826a49SYabin Cui     bitD->bitsConsumed += nbBits;
385*01826a49SYabin Cui }
386*01826a49SYabin Cui 
BIT_readBits(BIT_DStream_t * bitD,U32 nbBits)387*01826a49SYabin Cui MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, U32 nbBits)
388*01826a49SYabin Cui {
389*01826a49SYabin Cui     size_t value = BIT_lookBits(bitD, nbBits);
390*01826a49SYabin Cui     BIT_skipBits(bitD, nbBits);
391*01826a49SYabin Cui     return value;
392*01826a49SYabin Cui }
393*01826a49SYabin Cui 
394*01826a49SYabin Cui /*!BIT_readBitsFast :
395*01826a49SYabin Cui *  unsafe version; only works if nbBits >= 1 */
BIT_readBitsFast(BIT_DStream_t * bitD,U32 nbBits)396*01826a49SYabin Cui MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, U32 nbBits)
397*01826a49SYabin Cui {
398*01826a49SYabin Cui     size_t value = BIT_lookBitsFast(bitD, nbBits);
399*01826a49SYabin Cui     BIT_skipBits(bitD, nbBits);
400*01826a49SYabin Cui     return value;
401*01826a49SYabin Cui }
402*01826a49SYabin Cui 
BIT_reloadDStream(BIT_DStream_t * bitD)403*01826a49SYabin Cui MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD)
404*01826a49SYabin Cui {
405*01826a49SYabin Cui     if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8))  /* should never happen */
406*01826a49SYabin Cui         return BIT_DStream_overflow;
407*01826a49SYabin Cui 
408*01826a49SYabin Cui     if (bitD->ptr >= bitD->start + sizeof(bitD->bitContainer))
409*01826a49SYabin Cui     {
410*01826a49SYabin Cui         bitD->ptr -= bitD->bitsConsumed >> 3;
411*01826a49SYabin Cui         bitD->bitsConsumed &= 7;
412*01826a49SYabin Cui         bitD->bitContainer = MEM_readLEST(bitD->ptr);
413*01826a49SYabin Cui         return BIT_DStream_unfinished;
414*01826a49SYabin Cui     }
415*01826a49SYabin Cui     if (bitD->ptr == bitD->start)
416*01826a49SYabin Cui     {
417*01826a49SYabin Cui         if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer;
418*01826a49SYabin Cui         return BIT_DStream_completed;
419*01826a49SYabin Cui     }
420*01826a49SYabin Cui     {
421*01826a49SYabin Cui         U32 nbBytes = bitD->bitsConsumed >> 3;
422*01826a49SYabin Cui         BIT_DStream_status result = BIT_DStream_unfinished;
423*01826a49SYabin Cui         if (bitD->ptr - nbBytes < bitD->start)
424*01826a49SYabin Cui         {
425*01826a49SYabin Cui             nbBytes = (U32)(bitD->ptr - bitD->start);  /* ptr > start */
426*01826a49SYabin Cui             result = BIT_DStream_endOfBuffer;
427*01826a49SYabin Cui         }
428*01826a49SYabin Cui         bitD->ptr -= nbBytes;
429*01826a49SYabin Cui         bitD->bitsConsumed -= nbBytes*8;
430*01826a49SYabin Cui         bitD->bitContainer = MEM_readLEST(bitD->ptr);   /* reminder : srcSize > sizeof(bitD) */
431*01826a49SYabin Cui         return result;
432*01826a49SYabin Cui     }
433*01826a49SYabin Cui }
434*01826a49SYabin Cui 
435*01826a49SYabin Cui /*! BIT_endOfDStream
436*01826a49SYabin Cui *   @return Tells if DStream has reached its exact end
437*01826a49SYabin Cui */
BIT_endOfDStream(const BIT_DStream_t * DStream)438*01826a49SYabin Cui MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream)
439*01826a49SYabin Cui {
440*01826a49SYabin Cui     return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
441*01826a49SYabin Cui }
442*01826a49SYabin Cui 
443*01826a49SYabin Cui #if defined (__cplusplus)
444*01826a49SYabin Cui }
445*01826a49SYabin Cui #endif
446*01826a49SYabin Cui 
447*01826a49SYabin Cui #endif /* BITSTREAM_H_MODULE */
448*01826a49SYabin Cui /* ******************************************************************
449*01826a49SYabin Cui    Error codes and messages
450*01826a49SYabin Cui    Copyright (C) 2013-2015, Yann Collet
451*01826a49SYabin Cui 
452*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
453*01826a49SYabin Cui 
454*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
455*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
456*01826a49SYabin Cui    met:
457*01826a49SYabin Cui 
458*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
459*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
460*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
461*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
462*01826a49SYabin Cui    in the documentation and/or other materials provided with the
463*01826a49SYabin Cui    distribution.
464*01826a49SYabin Cui 
465*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
466*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
467*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
468*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
469*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
470*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
471*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
472*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
473*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
474*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
475*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
476*01826a49SYabin Cui 
477*01826a49SYabin Cui    You can contact the author at :
478*01826a49SYabin Cui    - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
479*01826a49SYabin Cui    - Public forum : https://groups.google.com/forum/#!forum/lz4c
480*01826a49SYabin Cui ****************************************************************** */
481*01826a49SYabin Cui #ifndef ERROR_H_MODULE
482*01826a49SYabin Cui #define ERROR_H_MODULE
483*01826a49SYabin Cui 
484*01826a49SYabin Cui #if defined (__cplusplus)
485*01826a49SYabin Cui extern "C" {
486*01826a49SYabin Cui #endif
487*01826a49SYabin Cui 
488*01826a49SYabin Cui 
489*01826a49SYabin Cui /******************************************
490*01826a49SYabin Cui *  Compiler-specific
491*01826a49SYabin Cui ******************************************/
492*01826a49SYabin Cui #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
493*01826a49SYabin Cui #  define ERR_STATIC static inline
494*01826a49SYabin Cui #elif defined(_MSC_VER)
495*01826a49SYabin Cui #  define ERR_STATIC static __inline
496*01826a49SYabin Cui #elif defined(__GNUC__)
497*01826a49SYabin Cui #  define ERR_STATIC static __attribute__((unused))
498*01826a49SYabin Cui #else
499*01826a49SYabin Cui #  define ERR_STATIC static  /* this version may generate warnings for unused static functions; disable the relevant warning */
500*01826a49SYabin Cui #endif
501*01826a49SYabin Cui 
502*01826a49SYabin Cui 
503*01826a49SYabin Cui /******************************************
504*01826a49SYabin Cui *  Error Management
505*01826a49SYabin Cui ******************************************/
506*01826a49SYabin Cui #define PREFIX(name) ZSTD_error_##name
507*01826a49SYabin Cui 
508*01826a49SYabin Cui #define ERROR(name) (size_t)-PREFIX(name)
509*01826a49SYabin Cui 
510*01826a49SYabin Cui #define ERROR_LIST(ITEM) \
511*01826a49SYabin Cui         ITEM(PREFIX(No_Error)) ITEM(PREFIX(GENERIC)) \
512*01826a49SYabin Cui         ITEM(PREFIX(dstSize_tooSmall)) ITEM(PREFIX(srcSize_wrong)) \
513*01826a49SYabin Cui         ITEM(PREFIX(prefix_unknown)) ITEM(PREFIX(corruption_detected)) \
514*01826a49SYabin Cui         ITEM(PREFIX(tableLog_tooLarge)) ITEM(PREFIX(maxSymbolValue_tooLarge)) ITEM(PREFIX(maxSymbolValue_tooSmall)) \
515*01826a49SYabin Cui         ITEM(PREFIX(maxCode))
516*01826a49SYabin Cui 
517*01826a49SYabin Cui #define ERROR_GENERATE_ENUM(ENUM) ENUM,
518*01826a49SYabin Cui typedef enum { ERROR_LIST(ERROR_GENERATE_ENUM) } ERR_codes;  /* enum is exposed, to detect & handle specific errors; compare function result to -enum value */
519*01826a49SYabin Cui 
520*01826a49SYabin Cui #define ERROR_CONVERTTOSTRING(STRING) #STRING,
521*01826a49SYabin Cui #define ERROR_GENERATE_STRING(EXPR) ERROR_CONVERTTOSTRING(EXPR)
522*01826a49SYabin Cui static const char* ERR_strings[] = { ERROR_LIST(ERROR_GENERATE_STRING) };
523*01826a49SYabin Cui 
ERR_isError(size_t code)524*01826a49SYabin Cui ERR_STATIC unsigned ERR_isError(size_t code) { return (code > ERROR(maxCode)); }
525*01826a49SYabin Cui 
ERR_getErrorName(size_t code)526*01826a49SYabin Cui ERR_STATIC const char* ERR_getErrorName(size_t code)
527*01826a49SYabin Cui {
528*01826a49SYabin Cui     static const char* codeError = "Unspecified error code";
529*01826a49SYabin Cui     if (ERR_isError(code)) return ERR_strings[-(int)(code)];
530*01826a49SYabin Cui     return codeError;
531*01826a49SYabin Cui }
532*01826a49SYabin Cui 
533*01826a49SYabin Cui 
534*01826a49SYabin Cui #if defined (__cplusplus)
535*01826a49SYabin Cui }
536*01826a49SYabin Cui #endif
537*01826a49SYabin Cui 
538*01826a49SYabin Cui #endif /* ERROR_H_MODULE */
539*01826a49SYabin Cui /*
540*01826a49SYabin Cui Constructor and Destructor of type FSE_CTable
541*01826a49SYabin Cui     Note that its size depends on 'tableLog' and 'maxSymbolValue' */
542*01826a49SYabin Cui typedef unsigned FSE_CTable;   /* don't allocate that. It's just a way to be more restrictive than void* */
543*01826a49SYabin Cui typedef unsigned FSE_DTable;   /* don't allocate that. It's just a way to be more restrictive than void* */
544*01826a49SYabin Cui 
545*01826a49SYabin Cui 
546*01826a49SYabin Cui /* ******************************************************************
547*01826a49SYabin Cui    FSE : Finite State Entropy coder
548*01826a49SYabin Cui    header file for static linking (only)
549*01826a49SYabin Cui    Copyright (C) 2013-2015, Yann Collet
550*01826a49SYabin Cui 
551*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
552*01826a49SYabin Cui 
553*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
554*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
555*01826a49SYabin Cui    met:
556*01826a49SYabin Cui 
557*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
558*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
559*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
560*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
561*01826a49SYabin Cui    in the documentation and/or other materials provided with the
562*01826a49SYabin Cui    distribution.
563*01826a49SYabin Cui 
564*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
565*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
566*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
567*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
568*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
569*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
570*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
571*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
572*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
573*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
574*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
575*01826a49SYabin Cui 
576*01826a49SYabin Cui    You can contact the author at :
577*01826a49SYabin Cui    - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
578*01826a49SYabin Cui    - Public forum : https://groups.google.com/forum/#!forum/lz4c
579*01826a49SYabin Cui ****************************************************************** */
580*01826a49SYabin Cui #if defined (__cplusplus)
581*01826a49SYabin Cui extern "C" {
582*01826a49SYabin Cui #endif
583*01826a49SYabin Cui 
584*01826a49SYabin Cui 
585*01826a49SYabin Cui /******************************************
586*01826a49SYabin Cui *  Static allocation
587*01826a49SYabin Cui ******************************************/
588*01826a49SYabin Cui /* FSE buffer bounds */
589*01826a49SYabin Cui #define FSE_NCOUNTBOUND 512
590*01826a49SYabin Cui #define FSE_BLOCKBOUND(size) (size + (size>>7))
591*01826a49SYabin Cui #define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size))   /* Macro version, useful for static allocation */
592*01826a49SYabin Cui 
593*01826a49SYabin Cui /* You can statically allocate FSE CTable/DTable as a table of unsigned using below macro */
594*01826a49SYabin Cui #define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue)   (1 + (1<<(maxTableLog-1)) + ((maxSymbolValue+1)*2))
595*01826a49SYabin Cui #define FSE_DTABLE_SIZE_U32(maxTableLog)                   (1 + (1<<maxTableLog))
596*01826a49SYabin Cui 
597*01826a49SYabin Cui 
598*01826a49SYabin Cui /******************************************
599*01826a49SYabin Cui *  FSE advanced API
600*01826a49SYabin Cui ******************************************/
601*01826a49SYabin Cui static size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits);
602*01826a49SYabin Cui /* build a fake FSE_DTable, designed to read an uncompressed bitstream where each symbol uses nbBits */
603*01826a49SYabin Cui 
604*01826a49SYabin Cui static size_t FSE_buildDTable_rle (FSE_DTable* dt, unsigned char symbolValue);
605*01826a49SYabin Cui /* build a fake FSE_DTable, designed to always generate the same symbolValue */
606*01826a49SYabin Cui 
607*01826a49SYabin Cui 
608*01826a49SYabin Cui /******************************************
609*01826a49SYabin Cui *  FSE symbol decompression API
610*01826a49SYabin Cui ******************************************/
611*01826a49SYabin Cui typedef struct
612*01826a49SYabin Cui {
613*01826a49SYabin Cui     size_t      state;
614*01826a49SYabin Cui     const void* table;   /* precise table may vary, depending on U16 */
615*01826a49SYabin Cui } FSE_DState_t;
616*01826a49SYabin Cui 
617*01826a49SYabin Cui 
618*01826a49SYabin Cui static void     FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt);
619*01826a49SYabin Cui 
620*01826a49SYabin Cui static unsigned char FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
621*01826a49SYabin Cui 
622*01826a49SYabin Cui static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr);
623*01826a49SYabin Cui 
624*01826a49SYabin Cui 
625*01826a49SYabin Cui /******************************************
626*01826a49SYabin Cui *  FSE unsafe API
627*01826a49SYabin Cui ******************************************/
628*01826a49SYabin Cui static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
629*01826a49SYabin Cui /* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */
630*01826a49SYabin Cui 
631*01826a49SYabin Cui 
632*01826a49SYabin Cui /******************************************
633*01826a49SYabin Cui *  Implementation of inline functions
634*01826a49SYabin Cui ******************************************/
635*01826a49SYabin Cui 
636*01826a49SYabin Cui /* decompression */
637*01826a49SYabin Cui 
638*01826a49SYabin Cui typedef struct {
639*01826a49SYabin Cui     U16 tableLog;
640*01826a49SYabin Cui     U16 fastMode;
641*01826a49SYabin Cui } FSE_DTableHeader;   /* sizeof U32 */
642*01826a49SYabin Cui 
643*01826a49SYabin Cui typedef struct
644*01826a49SYabin Cui {
645*01826a49SYabin Cui     unsigned short newState;
646*01826a49SYabin Cui     unsigned char  symbol;
647*01826a49SYabin Cui     unsigned char  nbBits;
648*01826a49SYabin Cui } FSE_decode_t;   /* size == U32 */
649*01826a49SYabin Cui 
FSE_initDState(FSE_DState_t * DStatePtr,BIT_DStream_t * bitD,const FSE_DTable * dt)650*01826a49SYabin Cui MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt)
651*01826a49SYabin Cui {
652*01826a49SYabin Cui     FSE_DTableHeader DTableH;
653*01826a49SYabin Cui     memcpy(&DTableH, dt, sizeof(DTableH));
654*01826a49SYabin Cui     DStatePtr->state = BIT_readBits(bitD, DTableH.tableLog);
655*01826a49SYabin Cui     BIT_reloadDStream(bitD);
656*01826a49SYabin Cui     DStatePtr->table = dt + 1;
657*01826a49SYabin Cui }
658*01826a49SYabin Cui 
FSE_decodeSymbol(FSE_DState_t * DStatePtr,BIT_DStream_t * bitD)659*01826a49SYabin Cui MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
660*01826a49SYabin Cui {
661*01826a49SYabin Cui     const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
662*01826a49SYabin Cui     const U32  nbBits = DInfo.nbBits;
663*01826a49SYabin Cui     BYTE symbol = DInfo.symbol;
664*01826a49SYabin Cui     size_t lowBits = BIT_readBits(bitD, nbBits);
665*01826a49SYabin Cui 
666*01826a49SYabin Cui     DStatePtr->state = DInfo.newState + lowBits;
667*01826a49SYabin Cui     return symbol;
668*01826a49SYabin Cui }
669*01826a49SYabin Cui 
FSE_decodeSymbolFast(FSE_DState_t * DStatePtr,BIT_DStream_t * bitD)670*01826a49SYabin Cui MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
671*01826a49SYabin Cui {
672*01826a49SYabin Cui     const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
673*01826a49SYabin Cui     const U32 nbBits = DInfo.nbBits;
674*01826a49SYabin Cui     BYTE symbol = DInfo.symbol;
675*01826a49SYabin Cui     size_t lowBits = BIT_readBitsFast(bitD, nbBits);
676*01826a49SYabin Cui 
677*01826a49SYabin Cui     DStatePtr->state = DInfo.newState + lowBits;
678*01826a49SYabin Cui     return symbol;
679*01826a49SYabin Cui }
680*01826a49SYabin Cui 
FSE_endOfDState(const FSE_DState_t * DStatePtr)681*01826a49SYabin Cui MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
682*01826a49SYabin Cui {
683*01826a49SYabin Cui     return DStatePtr->state == 0;
684*01826a49SYabin Cui }
685*01826a49SYabin Cui 
686*01826a49SYabin Cui 
687*01826a49SYabin Cui #if defined (__cplusplus)
688*01826a49SYabin Cui }
689*01826a49SYabin Cui #endif
690*01826a49SYabin Cui /* ******************************************************************
691*01826a49SYabin Cui    Huff0 : Huffman coder, part of New Generation Entropy library
692*01826a49SYabin Cui    header file for static linking (only)
693*01826a49SYabin Cui    Copyright (C) 2013-2015, Yann Collet
694*01826a49SYabin Cui 
695*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
696*01826a49SYabin Cui 
697*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
698*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
699*01826a49SYabin Cui    met:
700*01826a49SYabin Cui 
701*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
702*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
703*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
704*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
705*01826a49SYabin Cui    in the documentation and/or other materials provided with the
706*01826a49SYabin Cui    distribution.
707*01826a49SYabin Cui 
708*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
709*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
710*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
711*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
712*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
713*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
714*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
715*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
716*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
717*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
718*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
719*01826a49SYabin Cui 
720*01826a49SYabin Cui    You can contact the author at :
721*01826a49SYabin Cui    - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
722*01826a49SYabin Cui    - Public forum : https://groups.google.com/forum/#!forum/lz4c
723*01826a49SYabin Cui ****************************************************************** */
724*01826a49SYabin Cui 
725*01826a49SYabin Cui #if defined (__cplusplus)
726*01826a49SYabin Cui extern "C" {
727*01826a49SYabin Cui #endif
728*01826a49SYabin Cui 
729*01826a49SYabin Cui /******************************************
730*01826a49SYabin Cui *  Static allocation macros
731*01826a49SYabin Cui ******************************************/
732*01826a49SYabin Cui /* Huff0 buffer bounds */
733*01826a49SYabin Cui #define HUF_CTABLEBOUND 129
734*01826a49SYabin Cui #define HUF_BLOCKBOUND(size) (size + (size>>8) + 8)   /* only true if incompressible pre-filtered with fast heuristic */
735*01826a49SYabin Cui #define HUF_COMPRESSBOUND(size) (HUF_CTABLEBOUND + HUF_BLOCKBOUND(size))   /* Macro version, useful for static allocation */
736*01826a49SYabin Cui 
737*01826a49SYabin Cui /* static allocation of Huff0's DTable */
738*01826a49SYabin Cui #define HUF_DTABLE_SIZE(maxTableLog)   (1 + (1<<maxTableLog))  /* nb Cells; use unsigned short for X2, unsigned int for X4 */
739*01826a49SYabin Cui #define HUF_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \
740*01826a49SYabin Cui         unsigned short DTable[HUF_DTABLE_SIZE(maxTableLog)] = { maxTableLog }
741*01826a49SYabin Cui #define HUF_CREATE_STATIC_DTABLEX4(DTable, maxTableLog) \
742*01826a49SYabin Cui         unsigned int DTable[HUF_DTABLE_SIZE(maxTableLog)] = { maxTableLog }
743*01826a49SYabin Cui #define HUF_CREATE_STATIC_DTABLEX6(DTable, maxTableLog) \
744*01826a49SYabin Cui         unsigned int DTable[HUF_DTABLE_SIZE(maxTableLog) * 3 / 2] = { maxTableLog }
745*01826a49SYabin Cui 
746*01826a49SYabin Cui 
747*01826a49SYabin Cui /******************************************
748*01826a49SYabin Cui *  Advanced functions
749*01826a49SYabin Cui ******************************************/
750*01826a49SYabin Cui static size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /* single-symbol decoder */
751*01826a49SYabin Cui static size_t HUF_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /* double-symbols decoder */
752*01826a49SYabin Cui static size_t HUF_decompress4X6 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /* quad-symbols decoder */
753*01826a49SYabin Cui 
754*01826a49SYabin Cui 
755*01826a49SYabin Cui #if defined (__cplusplus)
756*01826a49SYabin Cui }
757*01826a49SYabin Cui #endif
758*01826a49SYabin Cui 
759*01826a49SYabin Cui /*
760*01826a49SYabin Cui     zstd - standard compression library
761*01826a49SYabin Cui     Header File
762*01826a49SYabin Cui     Copyright (C) 2014-2015, Yann Collet.
763*01826a49SYabin Cui 
764*01826a49SYabin Cui     BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
765*01826a49SYabin Cui 
766*01826a49SYabin Cui     Redistribution and use in source and binary forms, with or without
767*01826a49SYabin Cui     modification, are permitted provided that the following conditions are
768*01826a49SYabin Cui     met:
769*01826a49SYabin Cui     * Redistributions of source code must retain the above copyright
770*01826a49SYabin Cui     notice, this list of conditions and the following disclaimer.
771*01826a49SYabin Cui     * Redistributions in binary form must reproduce the above
772*01826a49SYabin Cui     copyright notice, this list of conditions and the following disclaimer
773*01826a49SYabin Cui     in the documentation and/or other materials provided with the
774*01826a49SYabin Cui     distribution.
775*01826a49SYabin Cui     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
776*01826a49SYabin Cui     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
777*01826a49SYabin Cui     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
778*01826a49SYabin Cui     A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
779*01826a49SYabin Cui     OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
780*01826a49SYabin Cui     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
781*01826a49SYabin Cui     LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
782*01826a49SYabin Cui     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
783*01826a49SYabin Cui     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
784*01826a49SYabin Cui     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
785*01826a49SYabin Cui     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
786*01826a49SYabin Cui 
787*01826a49SYabin Cui     You can contact the author at :
788*01826a49SYabin Cui     - zstd source repository : https://github.com/Cyan4973/zstd
789*01826a49SYabin Cui     - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
790*01826a49SYabin Cui */
791*01826a49SYabin Cui 
792*01826a49SYabin Cui #if defined (__cplusplus)
793*01826a49SYabin Cui extern "C" {
794*01826a49SYabin Cui #endif
795*01826a49SYabin Cui 
796*01826a49SYabin Cui /* *************************************
797*01826a49SYabin Cui *  Includes
798*01826a49SYabin Cui ***************************************/
799*01826a49SYabin Cui #include <stddef.h>   /* size_t */
800*01826a49SYabin Cui 
801*01826a49SYabin Cui 
802*01826a49SYabin Cui /* *************************************
803*01826a49SYabin Cui *  Version
804*01826a49SYabin Cui ***************************************/
805*01826a49SYabin Cui #define ZSTD_VERSION_MAJOR    0    /* for breaking interface changes  */
806*01826a49SYabin Cui #define ZSTD_VERSION_MINOR    2    /* for new (non-breaking) interface capabilities */
807*01826a49SYabin Cui #define ZSTD_VERSION_RELEASE  2    /* for tweaks, bug-fixes, or development */
808*01826a49SYabin Cui #define ZSTD_VERSION_NUMBER  (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
809*01826a49SYabin Cui 
810*01826a49SYabin Cui 
811*01826a49SYabin Cui /* *************************************
812*01826a49SYabin Cui *  Advanced functions
813*01826a49SYabin Cui ***************************************/
814*01826a49SYabin Cui typedef struct ZSTD_CCtx_s ZSTD_CCtx;   /* incomplete type */
815*01826a49SYabin Cui 
816*01826a49SYabin Cui #if defined (__cplusplus)
817*01826a49SYabin Cui }
818*01826a49SYabin Cui #endif
819*01826a49SYabin Cui /*
820*01826a49SYabin Cui     zstd - standard compression library
821*01826a49SYabin Cui     Header File for static linking only
822*01826a49SYabin Cui     Copyright (C) 2014-2015, Yann Collet.
823*01826a49SYabin Cui 
824*01826a49SYabin Cui     BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
825*01826a49SYabin Cui 
826*01826a49SYabin Cui     Redistribution and use in source and binary forms, with or without
827*01826a49SYabin Cui     modification, are permitted provided that the following conditions are
828*01826a49SYabin Cui     met:
829*01826a49SYabin Cui     * Redistributions of source code must retain the above copyright
830*01826a49SYabin Cui     notice, this list of conditions and the following disclaimer.
831*01826a49SYabin Cui     * Redistributions in binary form must reproduce the above
832*01826a49SYabin Cui     copyright notice, this list of conditions and the following disclaimer
833*01826a49SYabin Cui     in the documentation and/or other materials provided with the
834*01826a49SYabin Cui     distribution.
835*01826a49SYabin Cui     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
836*01826a49SYabin Cui     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
837*01826a49SYabin Cui     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
838*01826a49SYabin Cui     A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
839*01826a49SYabin Cui     OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
840*01826a49SYabin Cui     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
841*01826a49SYabin Cui     LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
842*01826a49SYabin Cui     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
843*01826a49SYabin Cui     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
844*01826a49SYabin Cui     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
845*01826a49SYabin Cui     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
846*01826a49SYabin Cui 
847*01826a49SYabin Cui     You can contact the author at :
848*01826a49SYabin Cui     - zstd source repository : https://github.com/Cyan4973/zstd
849*01826a49SYabin Cui     - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
850*01826a49SYabin Cui */
851*01826a49SYabin Cui 
852*01826a49SYabin Cui /* The objects defined into this file should be considered experimental.
853*01826a49SYabin Cui  * They are not labelled stable, as their prototype may change in the future.
854*01826a49SYabin Cui  * You can use them for tests, provide feedback, or if you can endure risk of future changes.
855*01826a49SYabin Cui  */
856*01826a49SYabin Cui 
857*01826a49SYabin Cui #if defined (__cplusplus)
858*01826a49SYabin Cui extern "C" {
859*01826a49SYabin Cui #endif
860*01826a49SYabin Cui 
861*01826a49SYabin Cui /* *************************************
862*01826a49SYabin Cui *  Streaming functions
863*01826a49SYabin Cui ***************************************/
864*01826a49SYabin Cui 
865*01826a49SYabin Cui typedef struct ZSTDv02_Dctx_s ZSTD_DCtx;
866*01826a49SYabin Cui 
867*01826a49SYabin Cui /*
868*01826a49SYabin Cui   Use above functions alternatively.
869*01826a49SYabin Cui   ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue().
870*01826a49SYabin Cui   ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block.
871*01826a49SYabin Cui   Result is the number of bytes regenerated within 'dst'.
872*01826a49SYabin Cui   It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header.
873*01826a49SYabin Cui */
874*01826a49SYabin Cui 
875*01826a49SYabin Cui /* *************************************
876*01826a49SYabin Cui *  Prefix - version detection
877*01826a49SYabin Cui ***************************************/
878*01826a49SYabin Cui #define ZSTD_magicNumber 0xFD2FB522   /* v0.2 (current)*/
879*01826a49SYabin Cui 
880*01826a49SYabin Cui 
881*01826a49SYabin Cui #if defined (__cplusplus)
882*01826a49SYabin Cui }
883*01826a49SYabin Cui #endif
884*01826a49SYabin Cui /* ******************************************************************
885*01826a49SYabin Cui    FSE : Finite State Entropy coder
886*01826a49SYabin Cui    Copyright (C) 2013-2015, Yann Collet.
887*01826a49SYabin Cui 
888*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
889*01826a49SYabin Cui 
890*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
891*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
892*01826a49SYabin Cui    met:
893*01826a49SYabin Cui 
894*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
895*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
896*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
897*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
898*01826a49SYabin Cui    in the documentation and/or other materials provided with the
899*01826a49SYabin Cui    distribution.
900*01826a49SYabin Cui 
901*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
902*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
903*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
904*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
905*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
906*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
907*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
908*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
909*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
910*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
911*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
912*01826a49SYabin Cui 
913*01826a49SYabin Cui     You can contact the author at :
914*01826a49SYabin Cui     - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
915*01826a49SYabin Cui     - Public forum : https://groups.google.com/forum/#!forum/lz4c
916*01826a49SYabin Cui ****************************************************************** */
917*01826a49SYabin Cui 
918*01826a49SYabin Cui #ifndef FSE_COMMONDEFS_ONLY
919*01826a49SYabin Cui 
920*01826a49SYabin Cui /****************************************************************
921*01826a49SYabin Cui *  Tuning parameters
922*01826a49SYabin Cui ****************************************************************/
923*01826a49SYabin Cui /* MEMORY_USAGE :
924*01826a49SYabin Cui *  Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
925*01826a49SYabin Cui *  Increasing memory usage improves compression ratio
926*01826a49SYabin Cui *  Reduced memory usage can improve speed, due to cache effect
927*01826a49SYabin Cui *  Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
928*01826a49SYabin Cui #define FSE_MAX_MEMORY_USAGE 14
929*01826a49SYabin Cui #define FSE_DEFAULT_MEMORY_USAGE 13
930*01826a49SYabin Cui 
931*01826a49SYabin Cui /* FSE_MAX_SYMBOL_VALUE :
932*01826a49SYabin Cui *  Maximum symbol value authorized.
933*01826a49SYabin Cui *  Required for proper stack allocation */
934*01826a49SYabin Cui #define FSE_MAX_SYMBOL_VALUE 255
935*01826a49SYabin Cui 
936*01826a49SYabin Cui 
937*01826a49SYabin Cui /****************************************************************
938*01826a49SYabin Cui *  template functions type & suffix
939*01826a49SYabin Cui ****************************************************************/
940*01826a49SYabin Cui #define FSE_FUNCTION_TYPE BYTE
941*01826a49SYabin Cui #define FSE_FUNCTION_EXTENSION
942*01826a49SYabin Cui 
943*01826a49SYabin Cui 
944*01826a49SYabin Cui /****************************************************************
945*01826a49SYabin Cui *  Byte symbol type
946*01826a49SYabin Cui ****************************************************************/
947*01826a49SYabin Cui #endif   /* !FSE_COMMONDEFS_ONLY */
948*01826a49SYabin Cui 
949*01826a49SYabin Cui 
950*01826a49SYabin Cui /****************************************************************
951*01826a49SYabin Cui *  Compiler specifics
952*01826a49SYabin Cui ****************************************************************/
953*01826a49SYabin Cui #ifdef _MSC_VER    /* Visual Studio */
954*01826a49SYabin Cui #  define FORCE_INLINE static __forceinline
955*01826a49SYabin Cui #  include <intrin.h>                    /* For Visual 2005 */
956*01826a49SYabin Cui #  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */
957*01826a49SYabin Cui #  pragma warning(disable : 4214)        /* disable: C4214: non-int bitfields */
958*01826a49SYabin Cui #else
959*01826a49SYabin Cui #  if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
960*01826a49SYabin Cui #    ifdef __GNUC__
961*01826a49SYabin Cui #      define FORCE_INLINE static inline __attribute__((always_inline))
962*01826a49SYabin Cui #    else
963*01826a49SYabin Cui #      define FORCE_INLINE static inline
964*01826a49SYabin Cui #    endif
965*01826a49SYabin Cui #  else
966*01826a49SYabin Cui #    define FORCE_INLINE static
967*01826a49SYabin Cui #  endif /* __STDC_VERSION__ */
968*01826a49SYabin Cui #endif
969*01826a49SYabin Cui 
970*01826a49SYabin Cui 
971*01826a49SYabin Cui /****************************************************************
972*01826a49SYabin Cui *  Includes
973*01826a49SYabin Cui ****************************************************************/
974*01826a49SYabin Cui #include <stdlib.h>     /* malloc, free, qsort */
975*01826a49SYabin Cui #include <string.h>     /* memcpy, memset */
976*01826a49SYabin Cui #include <stdio.h>      /* printf (debug) */
977*01826a49SYabin Cui 
978*01826a49SYabin Cui /****************************************************************
979*01826a49SYabin Cui *  Constants
980*01826a49SYabin Cui *****************************************************************/
981*01826a49SYabin Cui #define FSE_MAX_TABLELOG  (FSE_MAX_MEMORY_USAGE-2)
982*01826a49SYabin Cui #define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)
983*01826a49SYabin Cui #define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)
984*01826a49SYabin Cui #define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)
985*01826a49SYabin Cui #define FSE_MIN_TABLELOG 5
986*01826a49SYabin Cui 
987*01826a49SYabin Cui #define FSE_TABLELOG_ABSOLUTE_MAX 15
988*01826a49SYabin Cui #if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
989*01826a49SYabin Cui #error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
990*01826a49SYabin Cui #endif
991*01826a49SYabin Cui 
992*01826a49SYabin Cui 
993*01826a49SYabin Cui /****************************************************************
994*01826a49SYabin Cui *  Error Management
995*01826a49SYabin Cui ****************************************************************/
996*01826a49SYabin Cui #define FSE_STATIC_ASSERT(c) { enum { FSE_static_assert = 1/(int)(!!(c)) }; }   /* use only *after* variable declarations */
997*01826a49SYabin Cui 
998*01826a49SYabin Cui 
999*01826a49SYabin Cui /****************************************************************
1000*01826a49SYabin Cui *  Complex types
1001*01826a49SYabin Cui ****************************************************************/
1002*01826a49SYabin Cui typedef U32 DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)];
1003*01826a49SYabin Cui 
1004*01826a49SYabin Cui 
1005*01826a49SYabin Cui /****************************************************************
1006*01826a49SYabin Cui *  Templates
1007*01826a49SYabin Cui ****************************************************************/
1008*01826a49SYabin Cui /*
1009*01826a49SYabin Cui   designed to be included
1010*01826a49SYabin Cui   for type-specific functions (template emulation in C)
1011*01826a49SYabin Cui   Objective is to write these functions only once, for improved maintenance
1012*01826a49SYabin Cui */
1013*01826a49SYabin Cui 
1014*01826a49SYabin Cui /* safety checks */
1015*01826a49SYabin Cui #ifndef FSE_FUNCTION_EXTENSION
1016*01826a49SYabin Cui #  error "FSE_FUNCTION_EXTENSION must be defined"
1017*01826a49SYabin Cui #endif
1018*01826a49SYabin Cui #ifndef FSE_FUNCTION_TYPE
1019*01826a49SYabin Cui #  error "FSE_FUNCTION_TYPE must be defined"
1020*01826a49SYabin Cui #endif
1021*01826a49SYabin Cui 
1022*01826a49SYabin Cui /* Function names */
1023*01826a49SYabin Cui #define FSE_CAT(X,Y) X##Y
1024*01826a49SYabin Cui #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
1025*01826a49SYabin Cui #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
1026*01826a49SYabin Cui 
1027*01826a49SYabin Cui 
1028*01826a49SYabin Cui /* Function templates */
1029*01826a49SYabin Cui 
1030*01826a49SYabin Cui #define FSE_DECODE_TYPE FSE_decode_t
1031*01826a49SYabin Cui 
FSE_tableStep(U32 tableSize)1032*01826a49SYabin Cui static U32 FSE_tableStep(U32 tableSize) { return (tableSize>>1) + (tableSize>>3) + 3; }
1033*01826a49SYabin Cui 
FSE_buildDTable(FSE_DTable * dt,const short * normalizedCounter,unsigned maxSymbolValue,unsigned tableLog)1034*01826a49SYabin Cui static size_t FSE_buildDTable
1035*01826a49SYabin Cui (FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
1036*01826a49SYabin Cui {
1037*01826a49SYabin Cui     void* ptr = dt+1;
1038*01826a49SYabin Cui     FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*)ptr;
1039*01826a49SYabin Cui     FSE_DTableHeader DTableH;
1040*01826a49SYabin Cui     const U32 tableSize = 1 << tableLog;
1041*01826a49SYabin Cui     const U32 tableMask = tableSize-1;
1042*01826a49SYabin Cui     const U32 step = FSE_tableStep(tableSize);
1043*01826a49SYabin Cui     U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1];
1044*01826a49SYabin Cui     U32 position = 0;
1045*01826a49SYabin Cui     U32 highThreshold = tableSize-1;
1046*01826a49SYabin Cui     const S16 largeLimit= (S16)(1 << (tableLog-1));
1047*01826a49SYabin Cui     U32 noLarge = 1;
1048*01826a49SYabin Cui     U32 s;
1049*01826a49SYabin Cui 
1050*01826a49SYabin Cui     /* Sanity Checks */
1051*01826a49SYabin Cui     if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
1052*01826a49SYabin Cui     if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
1053*01826a49SYabin Cui 
1054*01826a49SYabin Cui     /* Init, lay down lowprob symbols */
1055*01826a49SYabin Cui     DTableH.tableLog = (U16)tableLog;
1056*01826a49SYabin Cui     for (s=0; s<=maxSymbolValue; s++)
1057*01826a49SYabin Cui     {
1058*01826a49SYabin Cui         if (normalizedCounter[s]==-1)
1059*01826a49SYabin Cui         {
1060*01826a49SYabin Cui             tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
1061*01826a49SYabin Cui             symbolNext[s] = 1;
1062*01826a49SYabin Cui         }
1063*01826a49SYabin Cui         else
1064*01826a49SYabin Cui         {
1065*01826a49SYabin Cui             if (normalizedCounter[s] >= largeLimit) noLarge=0;
1066*01826a49SYabin Cui             symbolNext[s] = normalizedCounter[s];
1067*01826a49SYabin Cui         }
1068*01826a49SYabin Cui     }
1069*01826a49SYabin Cui 
1070*01826a49SYabin Cui     /* Spread symbols */
1071*01826a49SYabin Cui     for (s=0; s<=maxSymbolValue; s++)
1072*01826a49SYabin Cui     {
1073*01826a49SYabin Cui         int i;
1074*01826a49SYabin Cui         for (i=0; i<normalizedCounter[s]; i++)
1075*01826a49SYabin Cui         {
1076*01826a49SYabin Cui             tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
1077*01826a49SYabin Cui             position = (position + step) & tableMask;
1078*01826a49SYabin Cui             while (position > highThreshold) position = (position + step) & tableMask;   /* lowprob area */
1079*01826a49SYabin Cui         }
1080*01826a49SYabin Cui     }
1081*01826a49SYabin Cui 
1082*01826a49SYabin Cui     if (position!=0) return ERROR(GENERIC);   /* position must reach all cells once, otherwise normalizedCounter is incorrect */
1083*01826a49SYabin Cui 
1084*01826a49SYabin Cui     /* Build Decoding table */
1085*01826a49SYabin Cui     {
1086*01826a49SYabin Cui         U32 i;
1087*01826a49SYabin Cui         for (i=0; i<tableSize; i++)
1088*01826a49SYabin Cui         {
1089*01826a49SYabin Cui             FSE_FUNCTION_TYPE symbol = (FSE_FUNCTION_TYPE)(tableDecode[i].symbol);
1090*01826a49SYabin Cui             U16 nextState = symbolNext[symbol]++;
1091*01826a49SYabin Cui             tableDecode[i].nbBits = (BYTE) (tableLog - BIT_highbit32 ((U32)nextState) );
1092*01826a49SYabin Cui             tableDecode[i].newState = (U16) ( (nextState << tableDecode[i].nbBits) - tableSize);
1093*01826a49SYabin Cui         }
1094*01826a49SYabin Cui     }
1095*01826a49SYabin Cui 
1096*01826a49SYabin Cui     DTableH.fastMode = (U16)noLarge;
1097*01826a49SYabin Cui     memcpy(dt, &DTableH, sizeof(DTableH));   /* memcpy(), to avoid strict aliasing warnings */
1098*01826a49SYabin Cui     return 0;
1099*01826a49SYabin Cui }
1100*01826a49SYabin Cui 
1101*01826a49SYabin Cui 
1102*01826a49SYabin Cui #ifndef FSE_COMMONDEFS_ONLY
1103*01826a49SYabin Cui /******************************************
1104*01826a49SYabin Cui *  FSE helper functions
1105*01826a49SYabin Cui ******************************************/
FSE_isError(size_t code)1106*01826a49SYabin Cui static unsigned FSE_isError(size_t code) { return ERR_isError(code); }
1107*01826a49SYabin Cui 
1108*01826a49SYabin Cui 
1109*01826a49SYabin Cui /****************************************************************
1110*01826a49SYabin Cui *  FSE NCount encoding-decoding
1111*01826a49SYabin Cui ****************************************************************/
FSE_abs(short a)1112*01826a49SYabin Cui static short FSE_abs(short a)
1113*01826a49SYabin Cui {
1114*01826a49SYabin Cui     return (short)(a<0 ? -a : a);
1115*01826a49SYabin Cui }
1116*01826a49SYabin Cui 
FSE_readNCount(short * normalizedCounter,unsigned * maxSVPtr,unsigned * tableLogPtr,const void * headerBuffer,size_t hbSize)1117*01826a49SYabin Cui static size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
1118*01826a49SYabin Cui                  const void* headerBuffer, size_t hbSize)
1119*01826a49SYabin Cui {
1120*01826a49SYabin Cui     const BYTE* const istart = (const BYTE*) headerBuffer;
1121*01826a49SYabin Cui     const BYTE* const iend = istart + hbSize;
1122*01826a49SYabin Cui     const BYTE* ip = istart;
1123*01826a49SYabin Cui     int nbBits;
1124*01826a49SYabin Cui     int remaining;
1125*01826a49SYabin Cui     int threshold;
1126*01826a49SYabin Cui     U32 bitStream;
1127*01826a49SYabin Cui     int bitCount;
1128*01826a49SYabin Cui     unsigned charnum = 0;
1129*01826a49SYabin Cui     int previous0 = 0;
1130*01826a49SYabin Cui 
1131*01826a49SYabin Cui     if (hbSize < 4) return ERROR(srcSize_wrong);
1132*01826a49SYabin Cui     bitStream = MEM_readLE32(ip);
1133*01826a49SYabin Cui     nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG;   /* extract tableLog */
1134*01826a49SYabin Cui     if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
1135*01826a49SYabin Cui     bitStream >>= 4;
1136*01826a49SYabin Cui     bitCount = 4;
1137*01826a49SYabin Cui     *tableLogPtr = nbBits;
1138*01826a49SYabin Cui     remaining = (1<<nbBits)+1;
1139*01826a49SYabin Cui     threshold = 1<<nbBits;
1140*01826a49SYabin Cui     nbBits++;
1141*01826a49SYabin Cui 
1142*01826a49SYabin Cui     while ((remaining>1) && (charnum<=*maxSVPtr))
1143*01826a49SYabin Cui     {
1144*01826a49SYabin Cui         if (previous0)
1145*01826a49SYabin Cui         {
1146*01826a49SYabin Cui             unsigned n0 = charnum;
1147*01826a49SYabin Cui             while ((bitStream & 0xFFFF) == 0xFFFF)
1148*01826a49SYabin Cui             {
1149*01826a49SYabin Cui                 n0+=24;
1150*01826a49SYabin Cui                 if (ip < iend-5)
1151*01826a49SYabin Cui                 {
1152*01826a49SYabin Cui                     ip+=2;
1153*01826a49SYabin Cui                     bitStream = MEM_readLE32(ip) >> bitCount;
1154*01826a49SYabin Cui                 }
1155*01826a49SYabin Cui                 else
1156*01826a49SYabin Cui                 {
1157*01826a49SYabin Cui                     bitStream >>= 16;
1158*01826a49SYabin Cui                     bitCount+=16;
1159*01826a49SYabin Cui                 }
1160*01826a49SYabin Cui             }
1161*01826a49SYabin Cui             while ((bitStream & 3) == 3)
1162*01826a49SYabin Cui             {
1163*01826a49SYabin Cui                 n0+=3;
1164*01826a49SYabin Cui                 bitStream>>=2;
1165*01826a49SYabin Cui                 bitCount+=2;
1166*01826a49SYabin Cui             }
1167*01826a49SYabin Cui             n0 += bitStream & 3;
1168*01826a49SYabin Cui             bitCount += 2;
1169*01826a49SYabin Cui             if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
1170*01826a49SYabin Cui             while (charnum < n0) normalizedCounter[charnum++] = 0;
1171*01826a49SYabin Cui             if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
1172*01826a49SYabin Cui             {
1173*01826a49SYabin Cui                 ip += bitCount>>3;
1174*01826a49SYabin Cui                 bitCount &= 7;
1175*01826a49SYabin Cui                 bitStream = MEM_readLE32(ip) >> bitCount;
1176*01826a49SYabin Cui             }
1177*01826a49SYabin Cui             else
1178*01826a49SYabin Cui                 bitStream >>= 2;
1179*01826a49SYabin Cui         }
1180*01826a49SYabin Cui         {
1181*01826a49SYabin Cui             const short max = (short)((2*threshold-1)-remaining);
1182*01826a49SYabin Cui             short count;
1183*01826a49SYabin Cui 
1184*01826a49SYabin Cui             if ((bitStream & (threshold-1)) < (U32)max)
1185*01826a49SYabin Cui             {
1186*01826a49SYabin Cui                 count = (short)(bitStream & (threshold-1));
1187*01826a49SYabin Cui                 bitCount   += nbBits-1;
1188*01826a49SYabin Cui             }
1189*01826a49SYabin Cui             else
1190*01826a49SYabin Cui             {
1191*01826a49SYabin Cui                 count = (short)(bitStream & (2*threshold-1));
1192*01826a49SYabin Cui                 if (count >= threshold) count -= max;
1193*01826a49SYabin Cui                 bitCount   += nbBits;
1194*01826a49SYabin Cui             }
1195*01826a49SYabin Cui 
1196*01826a49SYabin Cui             count--;   /* extra accuracy */
1197*01826a49SYabin Cui             remaining -= FSE_abs(count);
1198*01826a49SYabin Cui             normalizedCounter[charnum++] = count;
1199*01826a49SYabin Cui             previous0 = !count;
1200*01826a49SYabin Cui             while (remaining < threshold)
1201*01826a49SYabin Cui             {
1202*01826a49SYabin Cui                 nbBits--;
1203*01826a49SYabin Cui                 threshold >>= 1;
1204*01826a49SYabin Cui             }
1205*01826a49SYabin Cui 
1206*01826a49SYabin Cui             {
1207*01826a49SYabin Cui                 if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
1208*01826a49SYabin Cui                 {
1209*01826a49SYabin Cui                     ip += bitCount>>3;
1210*01826a49SYabin Cui                     bitCount &= 7;
1211*01826a49SYabin Cui                 }
1212*01826a49SYabin Cui                 else
1213*01826a49SYabin Cui                 {
1214*01826a49SYabin Cui                     bitCount -= (int)(8 * (iend - 4 - ip));
1215*01826a49SYabin Cui                     ip = iend - 4;
1216*01826a49SYabin Cui                 }
1217*01826a49SYabin Cui                 bitStream = MEM_readLE32(ip) >> (bitCount & 31);
1218*01826a49SYabin Cui             }
1219*01826a49SYabin Cui         }
1220*01826a49SYabin Cui     }
1221*01826a49SYabin Cui     if (remaining != 1) return ERROR(GENERIC);
1222*01826a49SYabin Cui     *maxSVPtr = charnum-1;
1223*01826a49SYabin Cui 
1224*01826a49SYabin Cui     ip += (bitCount+7)>>3;
1225*01826a49SYabin Cui     if ((size_t)(ip-istart) > hbSize) return ERROR(srcSize_wrong);
1226*01826a49SYabin Cui     return ip-istart;
1227*01826a49SYabin Cui }
1228*01826a49SYabin Cui 
1229*01826a49SYabin Cui 
1230*01826a49SYabin Cui /*********************************************************
1231*01826a49SYabin Cui *  Decompression (Byte symbols)
1232*01826a49SYabin Cui *********************************************************/
FSE_buildDTable_rle(FSE_DTable * dt,BYTE symbolValue)1233*01826a49SYabin Cui static size_t FSE_buildDTable_rle (FSE_DTable* dt, BYTE symbolValue)
1234*01826a49SYabin Cui {
1235*01826a49SYabin Cui     void* ptr = dt;
1236*01826a49SYabin Cui     FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
1237*01826a49SYabin Cui     FSE_decode_t* const cell = (FSE_decode_t*)(ptr) + 1;   /* because dt is unsigned */
1238*01826a49SYabin Cui 
1239*01826a49SYabin Cui     DTableH->tableLog = 0;
1240*01826a49SYabin Cui     DTableH->fastMode = 0;
1241*01826a49SYabin Cui 
1242*01826a49SYabin Cui     cell->newState = 0;
1243*01826a49SYabin Cui     cell->symbol = symbolValue;
1244*01826a49SYabin Cui     cell->nbBits = 0;
1245*01826a49SYabin Cui 
1246*01826a49SYabin Cui     return 0;
1247*01826a49SYabin Cui }
1248*01826a49SYabin Cui 
1249*01826a49SYabin Cui 
FSE_buildDTable_raw(FSE_DTable * dt,unsigned nbBits)1250*01826a49SYabin Cui static size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits)
1251*01826a49SYabin Cui {
1252*01826a49SYabin Cui     void* ptr = dt;
1253*01826a49SYabin Cui     FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
1254*01826a49SYabin Cui     FSE_decode_t* const dinfo = (FSE_decode_t*)(ptr) + 1;   /* because dt is unsigned */
1255*01826a49SYabin Cui     const unsigned tableSize = 1 << nbBits;
1256*01826a49SYabin Cui     const unsigned tableMask = tableSize - 1;
1257*01826a49SYabin Cui     const unsigned maxSymbolValue = tableMask;
1258*01826a49SYabin Cui     unsigned s;
1259*01826a49SYabin Cui 
1260*01826a49SYabin Cui     /* Sanity checks */
1261*01826a49SYabin Cui     if (nbBits < 1) return ERROR(GENERIC);         /* min size */
1262*01826a49SYabin Cui 
1263*01826a49SYabin Cui     /* Build Decoding Table */
1264*01826a49SYabin Cui     DTableH->tableLog = (U16)nbBits;
1265*01826a49SYabin Cui     DTableH->fastMode = 1;
1266*01826a49SYabin Cui     for (s=0; s<=maxSymbolValue; s++)
1267*01826a49SYabin Cui     {
1268*01826a49SYabin Cui         dinfo[s].newState = 0;
1269*01826a49SYabin Cui         dinfo[s].symbol = (BYTE)s;
1270*01826a49SYabin Cui         dinfo[s].nbBits = (BYTE)nbBits;
1271*01826a49SYabin Cui     }
1272*01826a49SYabin Cui 
1273*01826a49SYabin Cui     return 0;
1274*01826a49SYabin Cui }
1275*01826a49SYabin Cui 
FSE_decompress_usingDTable_generic(void * dst,size_t maxDstSize,const void * cSrc,size_t cSrcSize,const FSE_DTable * dt,const unsigned fast)1276*01826a49SYabin Cui FORCE_INLINE size_t FSE_decompress_usingDTable_generic(
1277*01826a49SYabin Cui           void* dst, size_t maxDstSize,
1278*01826a49SYabin Cui     const void* cSrc, size_t cSrcSize,
1279*01826a49SYabin Cui     const FSE_DTable* dt, const unsigned fast)
1280*01826a49SYabin Cui {
1281*01826a49SYabin Cui     BYTE* const ostart = (BYTE*) dst;
1282*01826a49SYabin Cui     BYTE* op = ostart;
1283*01826a49SYabin Cui     BYTE* const omax = op + maxDstSize;
1284*01826a49SYabin Cui     BYTE* const olimit = omax-3;
1285*01826a49SYabin Cui 
1286*01826a49SYabin Cui     BIT_DStream_t bitD;
1287*01826a49SYabin Cui     FSE_DState_t state1;
1288*01826a49SYabin Cui     FSE_DState_t state2;
1289*01826a49SYabin Cui     size_t errorCode;
1290*01826a49SYabin Cui 
1291*01826a49SYabin Cui     /* Init */
1292*01826a49SYabin Cui     errorCode = BIT_initDStream(&bitD, cSrc, cSrcSize);   /* replaced last arg by maxCompressed Size */
1293*01826a49SYabin Cui     if (FSE_isError(errorCode)) return errorCode;
1294*01826a49SYabin Cui 
1295*01826a49SYabin Cui     FSE_initDState(&state1, &bitD, dt);
1296*01826a49SYabin Cui     FSE_initDState(&state2, &bitD, dt);
1297*01826a49SYabin Cui 
1298*01826a49SYabin Cui #define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)
1299*01826a49SYabin Cui 
1300*01826a49SYabin Cui     /* 4 symbols per loop */
1301*01826a49SYabin Cui     for ( ; (BIT_reloadDStream(&bitD)==BIT_DStream_unfinished) && (op<olimit) ; op+=4)
1302*01826a49SYabin Cui     {
1303*01826a49SYabin Cui         op[0] = FSE_GETSYMBOL(&state1);
1304*01826a49SYabin Cui 
1305*01826a49SYabin Cui         if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
1306*01826a49SYabin Cui             BIT_reloadDStream(&bitD);
1307*01826a49SYabin Cui 
1308*01826a49SYabin Cui         op[1] = FSE_GETSYMBOL(&state2);
1309*01826a49SYabin Cui 
1310*01826a49SYabin Cui         if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
1311*01826a49SYabin Cui             { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } }
1312*01826a49SYabin Cui 
1313*01826a49SYabin Cui         op[2] = FSE_GETSYMBOL(&state1);
1314*01826a49SYabin Cui 
1315*01826a49SYabin Cui         if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
1316*01826a49SYabin Cui             BIT_reloadDStream(&bitD);
1317*01826a49SYabin Cui 
1318*01826a49SYabin Cui         op[3] = FSE_GETSYMBOL(&state2);
1319*01826a49SYabin Cui     }
1320*01826a49SYabin Cui 
1321*01826a49SYabin Cui     /* tail */
1322*01826a49SYabin Cui     /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */
1323*01826a49SYabin Cui     while (1)
1324*01826a49SYabin Cui     {
1325*01826a49SYabin Cui         if ( (BIT_reloadDStream(&bitD)>BIT_DStream_completed) || (op==omax) || (BIT_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state1))) )
1326*01826a49SYabin Cui             break;
1327*01826a49SYabin Cui 
1328*01826a49SYabin Cui         *op++ = FSE_GETSYMBOL(&state1);
1329*01826a49SYabin Cui 
1330*01826a49SYabin Cui         if ( (BIT_reloadDStream(&bitD)>BIT_DStream_completed) || (op==omax) || (BIT_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state2))) )
1331*01826a49SYabin Cui             break;
1332*01826a49SYabin Cui 
1333*01826a49SYabin Cui         *op++ = FSE_GETSYMBOL(&state2);
1334*01826a49SYabin Cui     }
1335*01826a49SYabin Cui 
1336*01826a49SYabin Cui     /* end ? */
1337*01826a49SYabin Cui     if (BIT_endOfDStream(&bitD) && FSE_endOfDState(&state1) && FSE_endOfDState(&state2))
1338*01826a49SYabin Cui         return op-ostart;
1339*01826a49SYabin Cui 
1340*01826a49SYabin Cui     if (op==omax) return ERROR(dstSize_tooSmall);   /* dst buffer is full, but cSrc unfinished */
1341*01826a49SYabin Cui 
1342*01826a49SYabin Cui     return ERROR(corruption_detected);
1343*01826a49SYabin Cui }
1344*01826a49SYabin Cui 
1345*01826a49SYabin Cui 
FSE_decompress_usingDTable(void * dst,size_t originalSize,const void * cSrc,size_t cSrcSize,const FSE_DTable * dt)1346*01826a49SYabin Cui static size_t FSE_decompress_usingDTable(void* dst, size_t originalSize,
1347*01826a49SYabin Cui                             const void* cSrc, size_t cSrcSize,
1348*01826a49SYabin Cui                             const FSE_DTable* dt)
1349*01826a49SYabin Cui {
1350*01826a49SYabin Cui     FSE_DTableHeader DTableH;
1351*01826a49SYabin Cui     memcpy(&DTableH, dt, sizeof(DTableH));
1352*01826a49SYabin Cui 
1353*01826a49SYabin Cui     /* select fast mode (static) */
1354*01826a49SYabin Cui     if (DTableH.fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
1355*01826a49SYabin Cui     return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
1356*01826a49SYabin Cui }
1357*01826a49SYabin Cui 
1358*01826a49SYabin Cui 
FSE_decompress(void * dst,size_t maxDstSize,const void * cSrc,size_t cSrcSize)1359*01826a49SYabin Cui static size_t FSE_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
1360*01826a49SYabin Cui {
1361*01826a49SYabin Cui     const BYTE* const istart = (const BYTE*)cSrc;
1362*01826a49SYabin Cui     const BYTE* ip = istart;
1363*01826a49SYabin Cui     short counting[FSE_MAX_SYMBOL_VALUE+1];
1364*01826a49SYabin Cui     DTable_max_t dt;   /* Static analyzer seems unable to understand this table will be properly initialized later */
1365*01826a49SYabin Cui     unsigned tableLog;
1366*01826a49SYabin Cui     unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
1367*01826a49SYabin Cui     size_t errorCode;
1368*01826a49SYabin Cui 
1369*01826a49SYabin Cui     if (cSrcSize<2) return ERROR(srcSize_wrong);   /* too small input size */
1370*01826a49SYabin Cui 
1371*01826a49SYabin Cui     /* normal FSE decoding mode */
1372*01826a49SYabin Cui     errorCode = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
1373*01826a49SYabin Cui     if (FSE_isError(errorCode)) return errorCode;
1374*01826a49SYabin Cui     if (errorCode >= cSrcSize) return ERROR(srcSize_wrong);   /* too small input size */
1375*01826a49SYabin Cui     ip += errorCode;
1376*01826a49SYabin Cui     cSrcSize -= errorCode;
1377*01826a49SYabin Cui 
1378*01826a49SYabin Cui     errorCode = FSE_buildDTable (dt, counting, maxSymbolValue, tableLog);
1379*01826a49SYabin Cui     if (FSE_isError(errorCode)) return errorCode;
1380*01826a49SYabin Cui 
1381*01826a49SYabin Cui     /* always return, even if it is an error code */
1382*01826a49SYabin Cui     return FSE_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt);
1383*01826a49SYabin Cui }
1384*01826a49SYabin Cui 
1385*01826a49SYabin Cui 
1386*01826a49SYabin Cui 
1387*01826a49SYabin Cui #endif   /* FSE_COMMONDEFS_ONLY */
1388*01826a49SYabin Cui /* ******************************************************************
1389*01826a49SYabin Cui    Huff0 : Huffman coder, part of New Generation Entropy library
1390*01826a49SYabin Cui    Copyright (C) 2013-2015, Yann Collet.
1391*01826a49SYabin Cui 
1392*01826a49SYabin Cui    BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
1393*01826a49SYabin Cui 
1394*01826a49SYabin Cui    Redistribution and use in source and binary forms, with or without
1395*01826a49SYabin Cui    modification, are permitted provided that the following conditions are
1396*01826a49SYabin Cui    met:
1397*01826a49SYabin Cui 
1398*01826a49SYabin Cui        * Redistributions of source code must retain the above copyright
1399*01826a49SYabin Cui    notice, this list of conditions and the following disclaimer.
1400*01826a49SYabin Cui        * Redistributions in binary form must reproduce the above
1401*01826a49SYabin Cui    copyright notice, this list of conditions and the following disclaimer
1402*01826a49SYabin Cui    in the documentation and/or other materials provided with the
1403*01826a49SYabin Cui    distribution.
1404*01826a49SYabin Cui 
1405*01826a49SYabin Cui    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1406*01826a49SYabin Cui    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1407*01826a49SYabin Cui    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1408*01826a49SYabin Cui    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1409*01826a49SYabin Cui    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1410*01826a49SYabin Cui    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1411*01826a49SYabin Cui    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1412*01826a49SYabin Cui    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1413*01826a49SYabin Cui    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1414*01826a49SYabin Cui    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1415*01826a49SYabin Cui    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1416*01826a49SYabin Cui 
1417*01826a49SYabin Cui     You can contact the author at :
1418*01826a49SYabin Cui     - FSE+Huff0 source repository : https://github.com/Cyan4973/FiniteStateEntropy
1419*01826a49SYabin Cui     - Public forum : https://groups.google.com/forum/#!forum/lz4c
1420*01826a49SYabin Cui ****************************************************************** */
1421*01826a49SYabin Cui 
1422*01826a49SYabin Cui /****************************************************************
1423*01826a49SYabin Cui *  Compiler specifics
1424*01826a49SYabin Cui ****************************************************************/
1425*01826a49SYabin Cui #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
1426*01826a49SYabin Cui /* inline is defined */
1427*01826a49SYabin Cui #elif defined(_MSC_VER)
1428*01826a49SYabin Cui #  define inline __inline
1429*01826a49SYabin Cui #else
1430*01826a49SYabin Cui #  define inline /* disable inline */
1431*01826a49SYabin Cui #endif
1432*01826a49SYabin Cui 
1433*01826a49SYabin Cui 
1434*01826a49SYabin Cui #ifdef _MSC_VER    /* Visual Studio */
1435*01826a49SYabin Cui #  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */
1436*01826a49SYabin Cui #endif
1437*01826a49SYabin Cui 
1438*01826a49SYabin Cui 
1439*01826a49SYabin Cui /****************************************************************
1440*01826a49SYabin Cui *  Includes
1441*01826a49SYabin Cui ****************************************************************/
1442*01826a49SYabin Cui #include <stdlib.h>     /* malloc, free, qsort */
1443*01826a49SYabin Cui #include <string.h>     /* memcpy, memset */
1444*01826a49SYabin Cui #include <stdio.h>      /* printf (debug) */
1445*01826a49SYabin Cui 
1446*01826a49SYabin Cui /****************************************************************
1447*01826a49SYabin Cui *  Error Management
1448*01826a49SYabin Cui ****************************************************************/
1449*01826a49SYabin Cui #define HUF_STATIC_ASSERT(c) { enum { HUF_static_assert = 1/(int)(!!(c)) }; }   /* use only *after* variable declarations */
1450*01826a49SYabin Cui 
1451*01826a49SYabin Cui 
1452*01826a49SYabin Cui /******************************************
1453*01826a49SYabin Cui *  Helper functions
1454*01826a49SYabin Cui ******************************************/
HUF_isError(size_t code)1455*01826a49SYabin Cui static unsigned HUF_isError(size_t code) { return ERR_isError(code); }
1456*01826a49SYabin Cui 
1457*01826a49SYabin Cui #define HUF_ABSOLUTEMAX_TABLELOG  16   /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */
1458*01826a49SYabin Cui #define HUF_MAX_TABLELOG  12           /* max configured tableLog (for static allocation); can be modified up to HUF_ABSOLUTEMAX_TABLELOG */
1459*01826a49SYabin Cui #define HUF_DEFAULT_TABLELOG  HUF_MAX_TABLELOG   /* tableLog by default, when not specified */
1460*01826a49SYabin Cui #define HUF_MAX_SYMBOL_VALUE 255
1461*01826a49SYabin Cui #if (HUF_MAX_TABLELOG > HUF_ABSOLUTEMAX_TABLELOG)
1462*01826a49SYabin Cui #  error "HUF_MAX_TABLELOG is too large !"
1463*01826a49SYabin Cui #endif
1464*01826a49SYabin Cui 
1465*01826a49SYabin Cui 
1466*01826a49SYabin Cui 
1467*01826a49SYabin Cui /*********************************************************
1468*01826a49SYabin Cui *  Huff0 : Huffman block decompression
1469*01826a49SYabin Cui *********************************************************/
1470*01826a49SYabin Cui typedef struct { BYTE byte; BYTE nbBits; } HUF_DEltX2;   /* single-symbol decoding */
1471*01826a49SYabin Cui 
1472*01826a49SYabin Cui typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUF_DEltX4;  /* double-symbols decoding */
1473*01826a49SYabin Cui 
1474*01826a49SYabin Cui typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t;
1475*01826a49SYabin Cui 
1476*01826a49SYabin Cui /*! HUF_readStats
1477*01826a49SYabin Cui     Read compact Huffman tree, saved by HUF_writeCTable
1478*01826a49SYabin Cui     @huffWeight : destination buffer
1479*01826a49SYabin Cui     @return : size read from `src`
1480*01826a49SYabin Cui */
HUF_readStats(BYTE * huffWeight,size_t hwSize,U32 * rankStats,U32 * nbSymbolsPtr,U32 * tableLogPtr,const void * src,size_t srcSize)1481*01826a49SYabin Cui static size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
1482*01826a49SYabin Cui                             U32* nbSymbolsPtr, U32* tableLogPtr,
1483*01826a49SYabin Cui                             const void* src, size_t srcSize)
1484*01826a49SYabin Cui {
1485*01826a49SYabin Cui     U32 weightTotal;
1486*01826a49SYabin Cui     U32 tableLog;
1487*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) src;
1488*01826a49SYabin Cui     size_t iSize;
1489*01826a49SYabin Cui     size_t oSize;
1490*01826a49SYabin Cui     U32 n;
1491*01826a49SYabin Cui 
1492*01826a49SYabin Cui     if (!srcSize) return ERROR(srcSize_wrong);
1493*01826a49SYabin Cui     iSize = ip[0];
1494*01826a49SYabin Cui     //memset(huffWeight, 0, hwSize);   /* is not necessary, even though some analyzer complain ... */
1495*01826a49SYabin Cui 
1496*01826a49SYabin Cui     if (iSize >= 128)  /* special header */
1497*01826a49SYabin Cui     {
1498*01826a49SYabin Cui         if (iSize >= (242))   /* RLE */
1499*01826a49SYabin Cui         {
1500*01826a49SYabin Cui             static int l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 };
1501*01826a49SYabin Cui             oSize = l[iSize-242];
1502*01826a49SYabin Cui             memset(huffWeight, 1, hwSize);
1503*01826a49SYabin Cui             iSize = 0;
1504*01826a49SYabin Cui         }
1505*01826a49SYabin Cui         else   /* Incompressible */
1506*01826a49SYabin Cui         {
1507*01826a49SYabin Cui             oSize = iSize - 127;
1508*01826a49SYabin Cui             iSize = ((oSize+1)/2);
1509*01826a49SYabin Cui             if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
1510*01826a49SYabin Cui             if (oSize >= hwSize) return ERROR(corruption_detected);
1511*01826a49SYabin Cui             ip += 1;
1512*01826a49SYabin Cui             for (n=0; n<oSize; n+=2)
1513*01826a49SYabin Cui             {
1514*01826a49SYabin Cui                 huffWeight[n]   = ip[n/2] >> 4;
1515*01826a49SYabin Cui                 huffWeight[n+1] = ip[n/2] & 15;
1516*01826a49SYabin Cui             }
1517*01826a49SYabin Cui         }
1518*01826a49SYabin Cui     }
1519*01826a49SYabin Cui     else  /* header compressed with FSE (normal case) */
1520*01826a49SYabin Cui     {
1521*01826a49SYabin Cui         if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
1522*01826a49SYabin Cui         oSize = FSE_decompress(huffWeight, hwSize-1, ip+1, iSize);   /* max (hwSize-1) values decoded, as last one is implied */
1523*01826a49SYabin Cui         if (FSE_isError(oSize)) return oSize;
1524*01826a49SYabin Cui     }
1525*01826a49SYabin Cui 
1526*01826a49SYabin Cui     /* collect weight stats */
1527*01826a49SYabin Cui     memset(rankStats, 0, (HUF_ABSOLUTEMAX_TABLELOG + 1) * sizeof(U32));
1528*01826a49SYabin Cui     weightTotal = 0;
1529*01826a49SYabin Cui     for (n=0; n<oSize; n++)
1530*01826a49SYabin Cui     {
1531*01826a49SYabin Cui         if (huffWeight[n] >= HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
1532*01826a49SYabin Cui         rankStats[huffWeight[n]]++;
1533*01826a49SYabin Cui         weightTotal += (1 << huffWeight[n]) >> 1;
1534*01826a49SYabin Cui     }
1535*01826a49SYabin Cui     if (weightTotal == 0) return ERROR(corruption_detected);
1536*01826a49SYabin Cui 
1537*01826a49SYabin Cui     /* get last non-null symbol weight (implied, total must be 2^n) */
1538*01826a49SYabin Cui     tableLog = BIT_highbit32(weightTotal) + 1;
1539*01826a49SYabin Cui     if (tableLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
1540*01826a49SYabin Cui     {
1541*01826a49SYabin Cui         U32 total = 1 << tableLog;
1542*01826a49SYabin Cui         U32 rest = total - weightTotal;
1543*01826a49SYabin Cui         U32 verif = 1 << BIT_highbit32(rest);
1544*01826a49SYabin Cui         U32 lastWeight = BIT_highbit32(rest) + 1;
1545*01826a49SYabin Cui         if (verif != rest) return ERROR(corruption_detected);    /* last value must be a clean power of 2 */
1546*01826a49SYabin Cui         huffWeight[oSize] = (BYTE)lastWeight;
1547*01826a49SYabin Cui         rankStats[lastWeight]++;
1548*01826a49SYabin Cui     }
1549*01826a49SYabin Cui 
1550*01826a49SYabin Cui     /* check tree construction validity */
1551*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 */
1552*01826a49SYabin Cui 
1553*01826a49SYabin Cui     /* results */
1554*01826a49SYabin Cui     *nbSymbolsPtr = (U32)(oSize+1);
1555*01826a49SYabin Cui     *tableLogPtr = tableLog;
1556*01826a49SYabin Cui     return iSize+1;
1557*01826a49SYabin Cui }
1558*01826a49SYabin Cui 
1559*01826a49SYabin Cui 
1560*01826a49SYabin Cui /**************************/
1561*01826a49SYabin Cui /* single-symbol decoding */
1562*01826a49SYabin Cui /**************************/
1563*01826a49SYabin Cui 
HUF_readDTableX2(U16 * DTable,const void * src,size_t srcSize)1564*01826a49SYabin Cui static size_t HUF_readDTableX2 (U16* DTable, const void* src, size_t srcSize)
1565*01826a49SYabin Cui {
1566*01826a49SYabin Cui     BYTE huffWeight[HUF_MAX_SYMBOL_VALUE + 1];
1567*01826a49SYabin Cui     U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1];   /* large enough for values from 0 to 16 */
1568*01826a49SYabin Cui     U32 tableLog = 0;
1569*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) src;
1570*01826a49SYabin Cui     size_t iSize = ip[0];
1571*01826a49SYabin Cui     U32 nbSymbols = 0;
1572*01826a49SYabin Cui     U32 n;
1573*01826a49SYabin Cui     U32 nextRankStart;
1574*01826a49SYabin Cui     void* ptr = DTable+1;
1575*01826a49SYabin Cui     HUF_DEltX2* const dt = (HUF_DEltX2*)ptr;
1576*01826a49SYabin Cui 
1577*01826a49SYabin Cui     HUF_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(U16));   /* if compilation fails here, assertion is false */
1578*01826a49SYabin Cui     //memset(huffWeight, 0, sizeof(huffWeight));   /* is not necessary, even though some analyzer complain ... */
1579*01826a49SYabin Cui 
1580*01826a49SYabin Cui     iSize = HUF_readStats(huffWeight, HUF_MAX_SYMBOL_VALUE + 1, rankVal, &nbSymbols, &tableLog, src, srcSize);
1581*01826a49SYabin Cui     if (HUF_isError(iSize)) return iSize;
1582*01826a49SYabin Cui 
1583*01826a49SYabin Cui     /* check result */
1584*01826a49SYabin Cui     if (tableLog > DTable[0]) return ERROR(tableLog_tooLarge);   /* DTable is too small */
1585*01826a49SYabin Cui     DTable[0] = (U16)tableLog;   /* maybe should separate sizeof DTable, as allocated, from used size of DTable, in case of DTable re-use */
1586*01826a49SYabin Cui 
1587*01826a49SYabin Cui     /* Prepare ranks */
1588*01826a49SYabin Cui     nextRankStart = 0;
1589*01826a49SYabin Cui     for (n=1; n<=tableLog; n++)
1590*01826a49SYabin Cui     {
1591*01826a49SYabin Cui         U32 current = nextRankStart;
1592*01826a49SYabin Cui         nextRankStart += (rankVal[n] << (n-1));
1593*01826a49SYabin Cui         rankVal[n] = current;
1594*01826a49SYabin Cui     }
1595*01826a49SYabin Cui 
1596*01826a49SYabin Cui     /* fill DTable */
1597*01826a49SYabin Cui     for (n=0; n<nbSymbols; n++)
1598*01826a49SYabin Cui     {
1599*01826a49SYabin Cui         const U32 w = huffWeight[n];
1600*01826a49SYabin Cui         const U32 length = (1 << w) >> 1;
1601*01826a49SYabin Cui         U32 i;
1602*01826a49SYabin Cui         HUF_DEltX2 D;
1603*01826a49SYabin Cui         D.byte = (BYTE)n; D.nbBits = (BYTE)(tableLog + 1 - w);
1604*01826a49SYabin Cui         for (i = rankVal[w]; i < rankVal[w] + length; i++)
1605*01826a49SYabin Cui             dt[i] = D;
1606*01826a49SYabin Cui         rankVal[w] += length;
1607*01826a49SYabin Cui     }
1608*01826a49SYabin Cui 
1609*01826a49SYabin Cui     return iSize;
1610*01826a49SYabin Cui }
1611*01826a49SYabin Cui 
HUF_decodeSymbolX2(BIT_DStream_t * Dstream,const HUF_DEltX2 * dt,const U32 dtLog)1612*01826a49SYabin Cui static BYTE HUF_decodeSymbolX2(BIT_DStream_t* Dstream, const HUF_DEltX2* dt, const U32 dtLog)
1613*01826a49SYabin Cui {
1614*01826a49SYabin Cui         const size_t val = BIT_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
1615*01826a49SYabin Cui         const BYTE c = dt[val].byte;
1616*01826a49SYabin Cui         BIT_skipBits(Dstream, dt[val].nbBits);
1617*01826a49SYabin Cui         return c;
1618*01826a49SYabin Cui }
1619*01826a49SYabin Cui 
1620*01826a49SYabin Cui #define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
1621*01826a49SYabin Cui     *ptr++ = HUF_decodeSymbolX2(DStreamPtr, dt, dtLog)
1622*01826a49SYabin Cui 
1623*01826a49SYabin Cui #define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
1624*01826a49SYabin Cui     if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \
1625*01826a49SYabin Cui         HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
1626*01826a49SYabin Cui 
1627*01826a49SYabin Cui #define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
1628*01826a49SYabin Cui     if (MEM_64bits()) \
1629*01826a49SYabin Cui         HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
1630*01826a49SYabin Cui 
HUF_decodeStreamX2(BYTE * p,BIT_DStream_t * const bitDPtr,BYTE * const pEnd,const HUF_DEltX2 * const dt,const U32 dtLog)1631*01826a49SYabin Cui static inline size_t HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX2* const dt, const U32 dtLog)
1632*01826a49SYabin Cui {
1633*01826a49SYabin Cui     BYTE* const pStart = p;
1634*01826a49SYabin Cui 
1635*01826a49SYabin Cui     /* up to 4 symbols at a time */
1636*01826a49SYabin Cui     while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-4))
1637*01826a49SYabin Cui     {
1638*01826a49SYabin Cui         HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
1639*01826a49SYabin Cui         HUF_DECODE_SYMBOLX2_1(p, bitDPtr);
1640*01826a49SYabin Cui         HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
1641*01826a49SYabin Cui         HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
1642*01826a49SYabin Cui     }
1643*01826a49SYabin Cui 
1644*01826a49SYabin Cui     /* closer to the end */
1645*01826a49SYabin Cui     while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p < pEnd))
1646*01826a49SYabin Cui         HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
1647*01826a49SYabin Cui 
1648*01826a49SYabin Cui     /* no more data to retrieve from bitstream, hence no need to reload */
1649*01826a49SYabin Cui     while (p < pEnd)
1650*01826a49SYabin Cui         HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
1651*01826a49SYabin Cui 
1652*01826a49SYabin Cui     return pEnd-pStart;
1653*01826a49SYabin Cui }
1654*01826a49SYabin Cui 
1655*01826a49SYabin Cui 
HUF_decompress4X2_usingDTable(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize,const U16 * DTable)1656*01826a49SYabin Cui static size_t HUF_decompress4X2_usingDTable(
1657*01826a49SYabin Cui           void* dst,  size_t dstSize,
1658*01826a49SYabin Cui     const void* cSrc, size_t cSrcSize,
1659*01826a49SYabin Cui     const U16* DTable)
1660*01826a49SYabin Cui {
1661*01826a49SYabin Cui     if (cSrcSize < 10) return ERROR(corruption_detected);   /* strict minimum : jump table + 1 byte per stream */
1662*01826a49SYabin Cui 
1663*01826a49SYabin Cui     {
1664*01826a49SYabin Cui         const BYTE* const istart = (const BYTE*) cSrc;
1665*01826a49SYabin Cui         BYTE* const ostart = (BYTE*) dst;
1666*01826a49SYabin Cui         BYTE* const oend = ostart + dstSize;
1667*01826a49SYabin Cui 
1668*01826a49SYabin Cui         const void* ptr = DTable;
1669*01826a49SYabin Cui         const HUF_DEltX2* const dt = ((const HUF_DEltX2*)ptr) +1;
1670*01826a49SYabin Cui         const U32 dtLog = DTable[0];
1671*01826a49SYabin Cui         size_t errorCode;
1672*01826a49SYabin Cui 
1673*01826a49SYabin Cui         /* Init */
1674*01826a49SYabin Cui         BIT_DStream_t bitD1;
1675*01826a49SYabin Cui         BIT_DStream_t bitD2;
1676*01826a49SYabin Cui         BIT_DStream_t bitD3;
1677*01826a49SYabin Cui         BIT_DStream_t bitD4;
1678*01826a49SYabin Cui         const size_t length1 = MEM_readLE16(istart);
1679*01826a49SYabin Cui         const size_t length2 = MEM_readLE16(istart+2);
1680*01826a49SYabin Cui         const size_t length3 = MEM_readLE16(istart+4);
1681*01826a49SYabin Cui         size_t length4;
1682*01826a49SYabin Cui         const BYTE* const istart1 = istart + 6;  /* jumpTable */
1683*01826a49SYabin Cui         const BYTE* const istart2 = istart1 + length1;
1684*01826a49SYabin Cui         const BYTE* const istart3 = istart2 + length2;
1685*01826a49SYabin Cui         const BYTE* const istart4 = istart3 + length3;
1686*01826a49SYabin Cui         const size_t segmentSize = (dstSize+3) / 4;
1687*01826a49SYabin Cui         BYTE* const opStart2 = ostart + segmentSize;
1688*01826a49SYabin Cui         BYTE* const opStart3 = opStart2 + segmentSize;
1689*01826a49SYabin Cui         BYTE* const opStart4 = opStart3 + segmentSize;
1690*01826a49SYabin Cui         BYTE* op1 = ostart;
1691*01826a49SYabin Cui         BYTE* op2 = opStart2;
1692*01826a49SYabin Cui         BYTE* op3 = opStart3;
1693*01826a49SYabin Cui         BYTE* op4 = opStart4;
1694*01826a49SYabin Cui         U32 endSignal;
1695*01826a49SYabin Cui 
1696*01826a49SYabin Cui         length4 = cSrcSize - (length1 + length2 + length3 + 6);
1697*01826a49SYabin Cui         if (length4 > cSrcSize) return ERROR(corruption_detected);   /* overflow */
1698*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD1, istart1, length1);
1699*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
1700*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD2, istart2, length2);
1701*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
1702*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD3, istart3, length3);
1703*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
1704*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD4, istart4, length4);
1705*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
1706*01826a49SYabin Cui 
1707*01826a49SYabin Cui         /* 16-32 symbols per loop (4-8 symbols per stream) */
1708*01826a49SYabin Cui         endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
1709*01826a49SYabin Cui         for ( ; (endSignal==BIT_DStream_unfinished) && (op4<(oend-7)) ; )
1710*01826a49SYabin Cui         {
1711*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
1712*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
1713*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
1714*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
1715*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
1716*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
1717*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
1718*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
1719*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
1720*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
1721*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
1722*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
1723*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
1724*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
1725*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
1726*01826a49SYabin Cui             HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
1727*01826a49SYabin Cui 
1728*01826a49SYabin Cui             endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
1729*01826a49SYabin Cui         }
1730*01826a49SYabin Cui 
1731*01826a49SYabin Cui         /* check corruption */
1732*01826a49SYabin Cui         if (op1 > opStart2) return ERROR(corruption_detected);
1733*01826a49SYabin Cui         if (op2 > opStart3) return ERROR(corruption_detected);
1734*01826a49SYabin Cui         if (op3 > opStart4) return ERROR(corruption_detected);
1735*01826a49SYabin Cui         /* note : op4 supposed already verified within main loop */
1736*01826a49SYabin Cui 
1737*01826a49SYabin Cui         /* finish bitStreams one by one */
1738*01826a49SYabin Cui         HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
1739*01826a49SYabin Cui         HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
1740*01826a49SYabin Cui         HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
1741*01826a49SYabin Cui         HUF_decodeStreamX2(op4, &bitD4, oend,     dt, dtLog);
1742*01826a49SYabin Cui 
1743*01826a49SYabin Cui         /* check */
1744*01826a49SYabin Cui         endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
1745*01826a49SYabin Cui         if (!endSignal) return ERROR(corruption_detected);
1746*01826a49SYabin Cui 
1747*01826a49SYabin Cui         /* decoded size */
1748*01826a49SYabin Cui         return dstSize;
1749*01826a49SYabin Cui     }
1750*01826a49SYabin Cui }
1751*01826a49SYabin Cui 
1752*01826a49SYabin Cui 
HUF_decompress4X2(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize)1753*01826a49SYabin Cui static size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
1754*01826a49SYabin Cui {
1755*01826a49SYabin Cui     HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_MAX_TABLELOG);
1756*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) cSrc;
1757*01826a49SYabin Cui     size_t errorCode;
1758*01826a49SYabin Cui 
1759*01826a49SYabin Cui     errorCode = HUF_readDTableX2 (DTable, cSrc, cSrcSize);
1760*01826a49SYabin Cui     if (HUF_isError(errorCode)) return errorCode;
1761*01826a49SYabin Cui     if (errorCode >= cSrcSize) return ERROR(srcSize_wrong);
1762*01826a49SYabin Cui     ip += errorCode;
1763*01826a49SYabin Cui     cSrcSize -= errorCode;
1764*01826a49SYabin Cui 
1765*01826a49SYabin Cui     return HUF_decompress4X2_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
1766*01826a49SYabin Cui }
1767*01826a49SYabin Cui 
1768*01826a49SYabin Cui 
1769*01826a49SYabin Cui /***************************/
1770*01826a49SYabin Cui /* double-symbols decoding */
1771*01826a49SYabin Cui /***************************/
1772*01826a49SYabin Cui 
HUF_fillDTableX4Level2(HUF_DEltX4 * DTable,U32 sizeLog,const U32 consumed,const U32 * rankValOrigin,const int minWeight,const sortedSymbol_t * sortedSymbols,const U32 sortedListSize,U32 nbBitsBaseline,U16 baseSeq)1773*01826a49SYabin Cui static void HUF_fillDTableX4Level2(HUF_DEltX4* DTable, U32 sizeLog, const U32 consumed,
1774*01826a49SYabin Cui                            const U32* rankValOrigin, const int minWeight,
1775*01826a49SYabin Cui                            const sortedSymbol_t* sortedSymbols, const U32 sortedListSize,
1776*01826a49SYabin Cui                            U32 nbBitsBaseline, U16 baseSeq)
1777*01826a49SYabin Cui {
1778*01826a49SYabin Cui     HUF_DEltX4 DElt;
1779*01826a49SYabin Cui     U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1];
1780*01826a49SYabin Cui     U32 s;
1781*01826a49SYabin Cui 
1782*01826a49SYabin Cui     /* get pre-calculated rankVal */
1783*01826a49SYabin Cui     memcpy(rankVal, rankValOrigin, sizeof(rankVal));
1784*01826a49SYabin Cui 
1785*01826a49SYabin Cui     /* fill skipped values */
1786*01826a49SYabin Cui     if (minWeight>1)
1787*01826a49SYabin Cui     {
1788*01826a49SYabin Cui         U32 i, skipSize = rankVal[minWeight];
1789*01826a49SYabin Cui         MEM_writeLE16(&(DElt.sequence), baseSeq);
1790*01826a49SYabin Cui         DElt.nbBits   = (BYTE)(consumed);
1791*01826a49SYabin Cui         DElt.length   = 1;
1792*01826a49SYabin Cui         for (i = 0; i < skipSize; i++)
1793*01826a49SYabin Cui             DTable[i] = DElt;
1794*01826a49SYabin Cui     }
1795*01826a49SYabin Cui 
1796*01826a49SYabin Cui     /* fill DTable */
1797*01826a49SYabin Cui     for (s=0; s<sortedListSize; s++)   /* note : sortedSymbols already skipped */
1798*01826a49SYabin Cui     {
1799*01826a49SYabin Cui         const U32 symbol = sortedSymbols[s].symbol;
1800*01826a49SYabin Cui         const U32 weight = sortedSymbols[s].weight;
1801*01826a49SYabin Cui         const U32 nbBits = nbBitsBaseline - weight;
1802*01826a49SYabin Cui         const U32 length = 1 << (sizeLog-nbBits);
1803*01826a49SYabin Cui         const U32 start = rankVal[weight];
1804*01826a49SYabin Cui         U32 i = start;
1805*01826a49SYabin Cui         const U32 end = start + length;
1806*01826a49SYabin Cui 
1807*01826a49SYabin Cui         MEM_writeLE16(&(DElt.sequence), (U16)(baseSeq + (symbol << 8)));
1808*01826a49SYabin Cui         DElt.nbBits = (BYTE)(nbBits + consumed);
1809*01826a49SYabin Cui         DElt.length = 2;
1810*01826a49SYabin Cui         do { DTable[i++] = DElt; } while (i<end);   /* since length >= 1 */
1811*01826a49SYabin Cui 
1812*01826a49SYabin Cui         rankVal[weight] += length;
1813*01826a49SYabin Cui     }
1814*01826a49SYabin Cui }
1815*01826a49SYabin Cui 
1816*01826a49SYabin Cui typedef U32 rankVal_t[HUF_ABSOLUTEMAX_TABLELOG][HUF_ABSOLUTEMAX_TABLELOG + 1];
1817*01826a49SYabin Cui 
HUF_fillDTableX4(HUF_DEltX4 * DTable,const U32 targetLog,const sortedSymbol_t * sortedList,const U32 sortedListSize,const U32 * rankStart,rankVal_t rankValOrigin,const U32 maxWeight,const U32 nbBitsBaseline)1818*01826a49SYabin Cui static void HUF_fillDTableX4(HUF_DEltX4* DTable, const U32 targetLog,
1819*01826a49SYabin Cui                            const sortedSymbol_t* sortedList, const U32 sortedListSize,
1820*01826a49SYabin Cui                            const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight,
1821*01826a49SYabin Cui                            const U32 nbBitsBaseline)
1822*01826a49SYabin Cui {
1823*01826a49SYabin Cui     U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1];
1824*01826a49SYabin Cui     const int scaleLog = nbBitsBaseline - targetLog;   /* note : targetLog >= srcLog, hence scaleLog <= 1 */
1825*01826a49SYabin Cui     const U32 minBits  = nbBitsBaseline - maxWeight;
1826*01826a49SYabin Cui     U32 s;
1827*01826a49SYabin Cui 
1828*01826a49SYabin Cui     memcpy(rankVal, rankValOrigin, sizeof(rankVal));
1829*01826a49SYabin Cui 
1830*01826a49SYabin Cui     /* fill DTable */
1831*01826a49SYabin Cui     for (s=0; s<sortedListSize; s++)
1832*01826a49SYabin Cui     {
1833*01826a49SYabin Cui         const U16 symbol = sortedList[s].symbol;
1834*01826a49SYabin Cui         const U32 weight = sortedList[s].weight;
1835*01826a49SYabin Cui         const U32 nbBits = nbBitsBaseline - weight;
1836*01826a49SYabin Cui         const U32 start = rankVal[weight];
1837*01826a49SYabin Cui         const U32 length = 1 << (targetLog-nbBits);
1838*01826a49SYabin Cui 
1839*01826a49SYabin Cui         if (targetLog-nbBits >= minBits)   /* enough room for a second symbol */
1840*01826a49SYabin Cui         {
1841*01826a49SYabin Cui             U32 sortedRank;
1842*01826a49SYabin Cui             int minWeight = nbBits + scaleLog;
1843*01826a49SYabin Cui             if (minWeight < 1) minWeight = 1;
1844*01826a49SYabin Cui             sortedRank = rankStart[minWeight];
1845*01826a49SYabin Cui             HUF_fillDTableX4Level2(DTable+start, targetLog-nbBits, nbBits,
1846*01826a49SYabin Cui                            rankValOrigin[nbBits], minWeight,
1847*01826a49SYabin Cui                            sortedList+sortedRank, sortedListSize-sortedRank,
1848*01826a49SYabin Cui                            nbBitsBaseline, symbol);
1849*01826a49SYabin Cui         }
1850*01826a49SYabin Cui         else
1851*01826a49SYabin Cui         {
1852*01826a49SYabin Cui             U32 i;
1853*01826a49SYabin Cui             const U32 end = start + length;
1854*01826a49SYabin Cui             HUF_DEltX4 DElt;
1855*01826a49SYabin Cui 
1856*01826a49SYabin Cui             MEM_writeLE16(&(DElt.sequence), symbol);
1857*01826a49SYabin Cui             DElt.nbBits   = (BYTE)(nbBits);
1858*01826a49SYabin Cui             DElt.length   = 1;
1859*01826a49SYabin Cui             for (i = start; i < end; i++)
1860*01826a49SYabin Cui                 DTable[i] = DElt;
1861*01826a49SYabin Cui         }
1862*01826a49SYabin Cui         rankVal[weight] += length;
1863*01826a49SYabin Cui     }
1864*01826a49SYabin Cui }
1865*01826a49SYabin Cui 
HUF_readDTableX4(U32 * DTable,const void * src,size_t srcSize)1866*01826a49SYabin Cui static size_t HUF_readDTableX4 (U32* DTable, const void* src, size_t srcSize)
1867*01826a49SYabin Cui {
1868*01826a49SYabin Cui     BYTE weightList[HUF_MAX_SYMBOL_VALUE + 1];
1869*01826a49SYabin Cui     sortedSymbol_t sortedSymbol[HUF_MAX_SYMBOL_VALUE + 1];
1870*01826a49SYabin Cui     U32 rankStats[HUF_ABSOLUTEMAX_TABLELOG + 1] = { 0 };
1871*01826a49SYabin Cui     U32 rankStart0[HUF_ABSOLUTEMAX_TABLELOG + 2] = { 0 };
1872*01826a49SYabin Cui     U32* const rankStart = rankStart0+1;
1873*01826a49SYabin Cui     rankVal_t rankVal;
1874*01826a49SYabin Cui     U32 tableLog, maxW, sizeOfSort, nbSymbols;
1875*01826a49SYabin Cui     const U32 memLog = DTable[0];
1876*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) src;
1877*01826a49SYabin Cui     size_t iSize = ip[0];
1878*01826a49SYabin Cui     void* ptr = DTable;
1879*01826a49SYabin Cui     HUF_DEltX4* const dt = ((HUF_DEltX4*)ptr) + 1;
1880*01826a49SYabin Cui 
1881*01826a49SYabin Cui     HUF_STATIC_ASSERT(sizeof(HUF_DEltX4) == sizeof(U32));   /* if compilation fails here, assertion is false */
1882*01826a49SYabin Cui     if (memLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(tableLog_tooLarge);
1883*01826a49SYabin Cui     //memset(weightList, 0, sizeof(weightList));   /* is not necessary, even though some analyzer complain ... */
1884*01826a49SYabin Cui 
1885*01826a49SYabin Cui     iSize = HUF_readStats(weightList, HUF_MAX_SYMBOL_VALUE + 1, rankStats, &nbSymbols, &tableLog, src, srcSize);
1886*01826a49SYabin Cui     if (HUF_isError(iSize)) return iSize;
1887*01826a49SYabin Cui 
1888*01826a49SYabin Cui     /* check result */
1889*01826a49SYabin Cui     if (tableLog > memLog) return ERROR(tableLog_tooLarge);   /* DTable can't fit code depth */
1890*01826a49SYabin Cui 
1891*01826a49SYabin Cui     /* find maxWeight */
1892*01826a49SYabin Cui     for (maxW = tableLog; rankStats[maxW]==0; maxW--)
1893*01826a49SYabin Cui         {if (!maxW) return ERROR(GENERIC); }  /* necessarily finds a solution before maxW==0 */
1894*01826a49SYabin Cui 
1895*01826a49SYabin Cui     /* Get start index of each weight */
1896*01826a49SYabin Cui     {
1897*01826a49SYabin Cui         U32 w, nextRankStart = 0;
1898*01826a49SYabin Cui         for (w=1; w<=maxW; w++)
1899*01826a49SYabin Cui         {
1900*01826a49SYabin Cui             U32 current = nextRankStart;
1901*01826a49SYabin Cui             nextRankStart += rankStats[w];
1902*01826a49SYabin Cui             rankStart[w] = current;
1903*01826a49SYabin Cui         }
1904*01826a49SYabin Cui         rankStart[0] = nextRankStart;   /* put all 0w symbols at the end of sorted list*/
1905*01826a49SYabin Cui         sizeOfSort = nextRankStart;
1906*01826a49SYabin Cui     }
1907*01826a49SYabin Cui 
1908*01826a49SYabin Cui     /* sort symbols by weight */
1909*01826a49SYabin Cui     {
1910*01826a49SYabin Cui         U32 s;
1911*01826a49SYabin Cui         for (s=0; s<nbSymbols; s++)
1912*01826a49SYabin Cui         {
1913*01826a49SYabin Cui             U32 w = weightList[s];
1914*01826a49SYabin Cui             U32 r = rankStart[w]++;
1915*01826a49SYabin Cui             sortedSymbol[r].symbol = (BYTE)s;
1916*01826a49SYabin Cui             sortedSymbol[r].weight = (BYTE)w;
1917*01826a49SYabin Cui         }
1918*01826a49SYabin Cui         rankStart[0] = 0;   /* forget 0w symbols; this is beginning of weight(1) */
1919*01826a49SYabin Cui     }
1920*01826a49SYabin Cui 
1921*01826a49SYabin Cui     /* Build rankVal */
1922*01826a49SYabin Cui     {
1923*01826a49SYabin Cui         const U32 minBits = tableLog+1 - maxW;
1924*01826a49SYabin Cui         U32 nextRankVal = 0;
1925*01826a49SYabin Cui         U32 w, consumed;
1926*01826a49SYabin Cui         const int rescale = (memLog-tableLog) - 1;   /* tableLog <= memLog */
1927*01826a49SYabin Cui         U32* rankVal0 = rankVal[0];
1928*01826a49SYabin Cui         for (w=1; w<=maxW; w++)
1929*01826a49SYabin Cui         {
1930*01826a49SYabin Cui             U32 current = nextRankVal;
1931*01826a49SYabin Cui             nextRankVal += rankStats[w] << (w+rescale);
1932*01826a49SYabin Cui             rankVal0[w] = current;
1933*01826a49SYabin Cui         }
1934*01826a49SYabin Cui         for (consumed = minBits; consumed <= memLog - minBits; consumed++)
1935*01826a49SYabin Cui         {
1936*01826a49SYabin Cui             U32* rankValPtr = rankVal[consumed];
1937*01826a49SYabin Cui             for (w = 1; w <= maxW; w++)
1938*01826a49SYabin Cui             {
1939*01826a49SYabin Cui                 rankValPtr[w] = rankVal0[w] >> consumed;
1940*01826a49SYabin Cui             }
1941*01826a49SYabin Cui         }
1942*01826a49SYabin Cui     }
1943*01826a49SYabin Cui 
1944*01826a49SYabin Cui     HUF_fillDTableX4(dt, memLog,
1945*01826a49SYabin Cui                    sortedSymbol, sizeOfSort,
1946*01826a49SYabin Cui                    rankStart0, rankVal, maxW,
1947*01826a49SYabin Cui                    tableLog+1);
1948*01826a49SYabin Cui 
1949*01826a49SYabin Cui     return iSize;
1950*01826a49SYabin Cui }
1951*01826a49SYabin Cui 
1952*01826a49SYabin Cui 
HUF_decodeSymbolX4(void * op,BIT_DStream_t * DStream,const HUF_DEltX4 * dt,const U32 dtLog)1953*01826a49SYabin Cui static U32 HUF_decodeSymbolX4(void* op, BIT_DStream_t* DStream, const HUF_DEltX4* dt, const U32 dtLog)
1954*01826a49SYabin Cui {
1955*01826a49SYabin Cui     const size_t val = BIT_lookBitsFast(DStream, dtLog);   /* note : dtLog >= 1 */
1956*01826a49SYabin Cui     memcpy(op, dt+val, 2);
1957*01826a49SYabin Cui     BIT_skipBits(DStream, dt[val].nbBits);
1958*01826a49SYabin Cui     return dt[val].length;
1959*01826a49SYabin Cui }
1960*01826a49SYabin Cui 
HUF_decodeLastSymbolX4(void * op,BIT_DStream_t * DStream,const HUF_DEltX4 * dt,const U32 dtLog)1961*01826a49SYabin Cui static U32 HUF_decodeLastSymbolX4(void* op, BIT_DStream_t* DStream, const HUF_DEltX4* dt, const U32 dtLog)
1962*01826a49SYabin Cui {
1963*01826a49SYabin Cui     const size_t val = BIT_lookBitsFast(DStream, dtLog);   /* note : dtLog >= 1 */
1964*01826a49SYabin Cui     memcpy(op, dt+val, 1);
1965*01826a49SYabin Cui     if (dt[val].length==1) BIT_skipBits(DStream, dt[val].nbBits);
1966*01826a49SYabin Cui     else
1967*01826a49SYabin Cui     {
1968*01826a49SYabin Cui         if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8))
1969*01826a49SYabin Cui         {
1970*01826a49SYabin Cui             BIT_skipBits(DStream, dt[val].nbBits);
1971*01826a49SYabin Cui             if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
1972*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 */
1973*01826a49SYabin Cui         }
1974*01826a49SYabin Cui     }
1975*01826a49SYabin Cui     return 1;
1976*01826a49SYabin Cui }
1977*01826a49SYabin Cui 
1978*01826a49SYabin Cui 
1979*01826a49SYabin Cui #define HUF_DECODE_SYMBOLX4_0(ptr, DStreamPtr) \
1980*01826a49SYabin Cui     ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
1981*01826a49SYabin Cui 
1982*01826a49SYabin Cui #define HUF_DECODE_SYMBOLX4_1(ptr, DStreamPtr) \
1983*01826a49SYabin Cui     if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \
1984*01826a49SYabin Cui         ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
1985*01826a49SYabin Cui 
1986*01826a49SYabin Cui #define HUF_DECODE_SYMBOLX4_2(ptr, DStreamPtr) \
1987*01826a49SYabin Cui     if (MEM_64bits()) \
1988*01826a49SYabin Cui         ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
1989*01826a49SYabin Cui 
HUF_decodeStreamX4(BYTE * p,BIT_DStream_t * bitDPtr,BYTE * const pEnd,const HUF_DEltX4 * const dt,const U32 dtLog)1990*01826a49SYabin Cui static inline size_t HUF_decodeStreamX4(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd, const HUF_DEltX4* const dt, const U32 dtLog)
1991*01826a49SYabin Cui {
1992*01826a49SYabin Cui     BYTE* const pStart = p;
1993*01826a49SYabin Cui 
1994*01826a49SYabin Cui     /* up to 8 symbols at a time */
1995*01826a49SYabin Cui     while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p < pEnd-7))
1996*01826a49SYabin Cui     {
1997*01826a49SYabin Cui         HUF_DECODE_SYMBOLX4_2(p, bitDPtr);
1998*01826a49SYabin Cui         HUF_DECODE_SYMBOLX4_1(p, bitDPtr);
1999*01826a49SYabin Cui         HUF_DECODE_SYMBOLX4_2(p, bitDPtr);
2000*01826a49SYabin Cui         HUF_DECODE_SYMBOLX4_0(p, bitDPtr);
2001*01826a49SYabin Cui     }
2002*01826a49SYabin Cui 
2003*01826a49SYabin Cui     /* closer to the end */
2004*01826a49SYabin Cui     while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-2))
2005*01826a49SYabin Cui         HUF_DECODE_SYMBOLX4_0(p, bitDPtr);
2006*01826a49SYabin Cui 
2007*01826a49SYabin Cui     while (p <= pEnd-2)
2008*01826a49SYabin Cui         HUF_DECODE_SYMBOLX4_0(p, bitDPtr);   /* no need to reload : reached the end of DStream */
2009*01826a49SYabin Cui 
2010*01826a49SYabin Cui     if (p < pEnd)
2011*01826a49SYabin Cui         p += HUF_decodeLastSymbolX4(p, bitDPtr, dt, dtLog);
2012*01826a49SYabin Cui 
2013*01826a49SYabin Cui     return p-pStart;
2014*01826a49SYabin Cui }
2015*01826a49SYabin Cui 
2016*01826a49SYabin Cui 
2017*01826a49SYabin Cui 
HUF_decompress4X4_usingDTable(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize,const U32 * DTable)2018*01826a49SYabin Cui static size_t HUF_decompress4X4_usingDTable(
2019*01826a49SYabin Cui           void* dst,  size_t dstSize,
2020*01826a49SYabin Cui     const void* cSrc, size_t cSrcSize,
2021*01826a49SYabin Cui     const U32* DTable)
2022*01826a49SYabin Cui {
2023*01826a49SYabin Cui     if (cSrcSize < 10) return ERROR(corruption_detected);   /* strict minimum : jump table + 1 byte per stream */
2024*01826a49SYabin Cui 
2025*01826a49SYabin Cui     {
2026*01826a49SYabin Cui         const BYTE* const istart = (const BYTE*) cSrc;
2027*01826a49SYabin Cui         BYTE* const ostart = (BYTE*) dst;
2028*01826a49SYabin Cui         BYTE* const oend = ostart + dstSize;
2029*01826a49SYabin Cui 
2030*01826a49SYabin Cui         const void* ptr = DTable;
2031*01826a49SYabin Cui         const HUF_DEltX4* const dt = ((const HUF_DEltX4*)ptr) +1;
2032*01826a49SYabin Cui         const U32 dtLog = DTable[0];
2033*01826a49SYabin Cui         size_t errorCode;
2034*01826a49SYabin Cui 
2035*01826a49SYabin Cui         /* Init */
2036*01826a49SYabin Cui         BIT_DStream_t bitD1;
2037*01826a49SYabin Cui         BIT_DStream_t bitD2;
2038*01826a49SYabin Cui         BIT_DStream_t bitD3;
2039*01826a49SYabin Cui         BIT_DStream_t bitD4;
2040*01826a49SYabin Cui         const size_t length1 = MEM_readLE16(istart);
2041*01826a49SYabin Cui         const size_t length2 = MEM_readLE16(istart+2);
2042*01826a49SYabin Cui         const size_t length3 = MEM_readLE16(istart+4);
2043*01826a49SYabin Cui         size_t length4;
2044*01826a49SYabin Cui         const BYTE* const istart1 = istart + 6;  /* jumpTable */
2045*01826a49SYabin Cui         const BYTE* const istart2 = istart1 + length1;
2046*01826a49SYabin Cui         const BYTE* const istart3 = istart2 + length2;
2047*01826a49SYabin Cui         const BYTE* const istart4 = istart3 + length3;
2048*01826a49SYabin Cui         const size_t segmentSize = (dstSize+3) / 4;
2049*01826a49SYabin Cui         BYTE* const opStart2 = ostart + segmentSize;
2050*01826a49SYabin Cui         BYTE* const opStart3 = opStart2 + segmentSize;
2051*01826a49SYabin Cui         BYTE* const opStart4 = opStart3 + segmentSize;
2052*01826a49SYabin Cui         BYTE* op1 = ostart;
2053*01826a49SYabin Cui         BYTE* op2 = opStart2;
2054*01826a49SYabin Cui         BYTE* op3 = opStart3;
2055*01826a49SYabin Cui         BYTE* op4 = opStart4;
2056*01826a49SYabin Cui         U32 endSignal;
2057*01826a49SYabin Cui 
2058*01826a49SYabin Cui         length4 = cSrcSize - (length1 + length2 + length3 + 6);
2059*01826a49SYabin Cui         if (length4 > cSrcSize) return ERROR(corruption_detected);   /* overflow */
2060*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD1, istart1, length1);
2061*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
2062*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD2, istart2, length2);
2063*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
2064*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD3, istart3, length3);
2065*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
2066*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD4, istart4, length4);
2067*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
2068*01826a49SYabin Cui 
2069*01826a49SYabin Cui         /* 16-32 symbols per loop (4-8 symbols per stream) */
2070*01826a49SYabin Cui         endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
2071*01826a49SYabin Cui         for ( ; (endSignal==BIT_DStream_unfinished) && (op4<(oend-7)) ; )
2072*01826a49SYabin Cui         {
2073*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_2(op1, &bitD1);
2074*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_2(op2, &bitD2);
2075*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_2(op3, &bitD3);
2076*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_2(op4, &bitD4);
2077*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_1(op1, &bitD1);
2078*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_1(op2, &bitD2);
2079*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_1(op3, &bitD3);
2080*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_1(op4, &bitD4);
2081*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_2(op1, &bitD1);
2082*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_2(op2, &bitD2);
2083*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_2(op3, &bitD3);
2084*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_2(op4, &bitD4);
2085*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_0(op1, &bitD1);
2086*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_0(op2, &bitD2);
2087*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_0(op3, &bitD3);
2088*01826a49SYabin Cui             HUF_DECODE_SYMBOLX4_0(op4, &bitD4);
2089*01826a49SYabin Cui 
2090*01826a49SYabin Cui             endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
2091*01826a49SYabin Cui         }
2092*01826a49SYabin Cui 
2093*01826a49SYabin Cui         /* check corruption */
2094*01826a49SYabin Cui         if (op1 > opStart2) return ERROR(corruption_detected);
2095*01826a49SYabin Cui         if (op2 > opStart3) return ERROR(corruption_detected);
2096*01826a49SYabin Cui         if (op3 > opStart4) return ERROR(corruption_detected);
2097*01826a49SYabin Cui         /* note : op4 supposed already verified within main loop */
2098*01826a49SYabin Cui 
2099*01826a49SYabin Cui         /* finish bitStreams one by one */
2100*01826a49SYabin Cui         HUF_decodeStreamX4(op1, &bitD1, opStart2, dt, dtLog);
2101*01826a49SYabin Cui         HUF_decodeStreamX4(op2, &bitD2, opStart3, dt, dtLog);
2102*01826a49SYabin Cui         HUF_decodeStreamX4(op3, &bitD3, opStart4, dt, dtLog);
2103*01826a49SYabin Cui         HUF_decodeStreamX4(op4, &bitD4, oend,     dt, dtLog);
2104*01826a49SYabin Cui 
2105*01826a49SYabin Cui         /* check */
2106*01826a49SYabin Cui         endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
2107*01826a49SYabin Cui         if (!endSignal) return ERROR(corruption_detected);
2108*01826a49SYabin Cui 
2109*01826a49SYabin Cui         /* decoded size */
2110*01826a49SYabin Cui         return dstSize;
2111*01826a49SYabin Cui     }
2112*01826a49SYabin Cui }
2113*01826a49SYabin Cui 
2114*01826a49SYabin Cui 
HUF_decompress4X4(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize)2115*01826a49SYabin Cui static size_t HUF_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
2116*01826a49SYabin Cui {
2117*01826a49SYabin Cui     HUF_CREATE_STATIC_DTABLEX4(DTable, HUF_MAX_TABLELOG);
2118*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) cSrc;
2119*01826a49SYabin Cui 
2120*01826a49SYabin Cui     size_t hSize = HUF_readDTableX4 (DTable, cSrc, cSrcSize);
2121*01826a49SYabin Cui     if (HUF_isError(hSize)) return hSize;
2122*01826a49SYabin Cui     if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
2123*01826a49SYabin Cui     ip += hSize;
2124*01826a49SYabin Cui     cSrcSize -= hSize;
2125*01826a49SYabin Cui 
2126*01826a49SYabin Cui     return HUF_decompress4X4_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
2127*01826a49SYabin Cui }
2128*01826a49SYabin Cui 
2129*01826a49SYabin Cui 
2130*01826a49SYabin Cui /**********************************/
2131*01826a49SYabin Cui /* quad-symbol decoding           */
2132*01826a49SYabin Cui /**********************************/
2133*01826a49SYabin Cui typedef struct { BYTE nbBits; BYTE nbBytes; } HUF_DDescX6;
2134*01826a49SYabin Cui typedef union { BYTE byte[4]; U32 sequence; } HUF_DSeqX6;
2135*01826a49SYabin Cui 
2136*01826a49SYabin Cui /* recursive, up to level 3; may benefit from <template>-like strategy to nest each level inline */
HUF_fillDTableX6LevelN(HUF_DDescX6 * DDescription,HUF_DSeqX6 * DSequence,int sizeLog,const rankVal_t rankValOrigin,const U32 consumed,const int minWeight,const U32 maxWeight,const sortedSymbol_t * sortedSymbols,const U32 sortedListSize,const U32 * rankStart,const U32 nbBitsBaseline,HUF_DSeqX6 baseSeq,HUF_DDescX6 DDesc)2137*01826a49SYabin Cui static void HUF_fillDTableX6LevelN(HUF_DDescX6* DDescription, HUF_DSeqX6* DSequence, int sizeLog,
2138*01826a49SYabin Cui                            const rankVal_t rankValOrigin, const U32 consumed, const int minWeight, const U32 maxWeight,
2139*01826a49SYabin Cui                            const sortedSymbol_t* sortedSymbols, const U32 sortedListSize, const U32* rankStart,
2140*01826a49SYabin Cui                            const U32 nbBitsBaseline, HUF_DSeqX6 baseSeq, HUF_DDescX6 DDesc)
2141*01826a49SYabin Cui {
2142*01826a49SYabin Cui     const int scaleLog = nbBitsBaseline - sizeLog;   /* note : targetLog >= (nbBitsBaseline-1), hence scaleLog <= 1 */
2143*01826a49SYabin Cui     const int minBits  = nbBitsBaseline - maxWeight;
2144*01826a49SYabin Cui     const U32 level = DDesc.nbBytes;
2145*01826a49SYabin Cui     U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1];
2146*01826a49SYabin Cui     U32 symbolStartPos, s;
2147*01826a49SYabin Cui 
2148*01826a49SYabin Cui     /* local rankVal, will be modified */
2149*01826a49SYabin Cui     memcpy(rankVal, rankValOrigin[consumed], sizeof(rankVal));
2150*01826a49SYabin Cui 
2151*01826a49SYabin Cui     /* fill skipped values */
2152*01826a49SYabin Cui     if (minWeight>1)
2153*01826a49SYabin Cui     {
2154*01826a49SYabin Cui         U32 i;
2155*01826a49SYabin Cui         const U32 skipSize = rankVal[minWeight];
2156*01826a49SYabin Cui         for (i = 0; i < skipSize; i++)
2157*01826a49SYabin Cui         {
2158*01826a49SYabin Cui             DSequence[i] = baseSeq;
2159*01826a49SYabin Cui             DDescription[i] = DDesc;
2160*01826a49SYabin Cui         }
2161*01826a49SYabin Cui     }
2162*01826a49SYabin Cui 
2163*01826a49SYabin Cui     /* fill DTable */
2164*01826a49SYabin Cui     DDesc.nbBytes++;
2165*01826a49SYabin Cui     symbolStartPos = rankStart[minWeight];
2166*01826a49SYabin Cui     for (s=symbolStartPos; s<sortedListSize; s++)
2167*01826a49SYabin Cui     {
2168*01826a49SYabin Cui         const BYTE symbol = sortedSymbols[s].symbol;
2169*01826a49SYabin Cui         const U32  weight = sortedSymbols[s].weight;   /* >= 1 (sorted) */
2170*01826a49SYabin Cui         const int  nbBits = nbBitsBaseline - weight;   /* >= 1 (by construction) */
2171*01826a49SYabin Cui         const int  totalBits = consumed+nbBits;
2172*01826a49SYabin Cui         const U32  start  = rankVal[weight];
2173*01826a49SYabin Cui         const U32  length = 1 << (sizeLog-nbBits);
2174*01826a49SYabin Cui         baseSeq.byte[level] = symbol;
2175*01826a49SYabin Cui         DDesc.nbBits = (BYTE)totalBits;
2176*01826a49SYabin Cui 
2177*01826a49SYabin Cui         if ((level<3) && (sizeLog-totalBits >= minBits))   /* enough room for another symbol */
2178*01826a49SYabin Cui         {
2179*01826a49SYabin Cui             int nextMinWeight = totalBits + scaleLog;
2180*01826a49SYabin Cui             if (nextMinWeight < 1) nextMinWeight = 1;
2181*01826a49SYabin Cui             HUF_fillDTableX6LevelN(DDescription+start, DSequence+start, sizeLog-nbBits,
2182*01826a49SYabin Cui                            rankValOrigin, totalBits, nextMinWeight, maxWeight,
2183*01826a49SYabin Cui                            sortedSymbols, sortedListSize, rankStart,
2184*01826a49SYabin Cui                            nbBitsBaseline, baseSeq, DDesc);   /* recursive (max : level 3) */
2185*01826a49SYabin Cui         }
2186*01826a49SYabin Cui         else
2187*01826a49SYabin Cui         {
2188*01826a49SYabin Cui             U32 i;
2189*01826a49SYabin Cui             const U32 end = start + length;
2190*01826a49SYabin Cui             for (i = start; i < end; i++)
2191*01826a49SYabin Cui             {
2192*01826a49SYabin Cui                 DDescription[i] = DDesc;
2193*01826a49SYabin Cui                 DSequence[i] = baseSeq;
2194*01826a49SYabin Cui             }
2195*01826a49SYabin Cui         }
2196*01826a49SYabin Cui         rankVal[weight] += length;
2197*01826a49SYabin Cui     }
2198*01826a49SYabin Cui }
2199*01826a49SYabin Cui 
2200*01826a49SYabin Cui 
2201*01826a49SYabin Cui /* note : same preparation as X4 */
HUF_readDTableX6(U32 * DTable,const void * src,size_t srcSize)2202*01826a49SYabin Cui static size_t HUF_readDTableX6 (U32* DTable, const void* src, size_t srcSize)
2203*01826a49SYabin Cui {
2204*01826a49SYabin Cui     BYTE weightList[HUF_MAX_SYMBOL_VALUE + 1];
2205*01826a49SYabin Cui     sortedSymbol_t sortedSymbol[HUF_MAX_SYMBOL_VALUE + 1];
2206*01826a49SYabin Cui     U32 rankStats[HUF_ABSOLUTEMAX_TABLELOG + 1] = { 0 };
2207*01826a49SYabin Cui     U32 rankStart0[HUF_ABSOLUTEMAX_TABLELOG + 2] = { 0 };
2208*01826a49SYabin Cui     U32* const rankStart = rankStart0+1;
2209*01826a49SYabin Cui     U32 tableLog, maxW, sizeOfSort, nbSymbols;
2210*01826a49SYabin Cui     rankVal_t rankVal;
2211*01826a49SYabin Cui     const U32 memLog = DTable[0];
2212*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) src;
2213*01826a49SYabin Cui     size_t iSize = ip[0];
2214*01826a49SYabin Cui 
2215*01826a49SYabin Cui     if (memLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(tableLog_tooLarge);
2216*01826a49SYabin Cui     //memset(weightList, 0, sizeof(weightList));   /* is not necessary, even though some analyzer complain ... */
2217*01826a49SYabin Cui 
2218*01826a49SYabin Cui     iSize = HUF_readStats(weightList, HUF_MAX_SYMBOL_VALUE + 1, rankStats, &nbSymbols, &tableLog, src, srcSize);
2219*01826a49SYabin Cui     if (HUF_isError(iSize)) return iSize;
2220*01826a49SYabin Cui 
2221*01826a49SYabin Cui     /* check result */
2222*01826a49SYabin Cui     if (tableLog > memLog) return ERROR(tableLog_tooLarge);   /* DTable is too small */
2223*01826a49SYabin Cui 
2224*01826a49SYabin Cui     /* find maxWeight */
2225*01826a49SYabin Cui     for (maxW = tableLog; rankStats[maxW]==0; maxW--)
2226*01826a49SYabin Cui         { if (!maxW) return ERROR(GENERIC); }  /* necessarily finds a solution before maxW==0 */
2227*01826a49SYabin Cui 
2228*01826a49SYabin Cui 
2229*01826a49SYabin Cui     /* Get start index of each weight */
2230*01826a49SYabin Cui     {
2231*01826a49SYabin Cui         U32 w, nextRankStart = 0;
2232*01826a49SYabin Cui         for (w=1; w<=maxW; w++)
2233*01826a49SYabin Cui         {
2234*01826a49SYabin Cui             U32 current = nextRankStart;
2235*01826a49SYabin Cui             nextRankStart += rankStats[w];
2236*01826a49SYabin Cui             rankStart[w] = current;
2237*01826a49SYabin Cui         }
2238*01826a49SYabin Cui         rankStart[0] = nextRankStart;   /* put all 0w symbols at the end of sorted list*/
2239*01826a49SYabin Cui         sizeOfSort = nextRankStart;
2240*01826a49SYabin Cui     }
2241*01826a49SYabin Cui 
2242*01826a49SYabin Cui     /* sort symbols by weight */
2243*01826a49SYabin Cui     {
2244*01826a49SYabin Cui         U32 s;
2245*01826a49SYabin Cui         for (s=0; s<nbSymbols; s++)
2246*01826a49SYabin Cui         {
2247*01826a49SYabin Cui             U32 w = weightList[s];
2248*01826a49SYabin Cui             U32 r = rankStart[w]++;
2249*01826a49SYabin Cui             sortedSymbol[r].symbol = (BYTE)s;
2250*01826a49SYabin Cui             sortedSymbol[r].weight = (BYTE)w;
2251*01826a49SYabin Cui         }
2252*01826a49SYabin Cui         rankStart[0] = 0;   /* forget 0w symbols; this is beginning of weight(1) */
2253*01826a49SYabin Cui     }
2254*01826a49SYabin Cui 
2255*01826a49SYabin Cui     /* Build rankVal */
2256*01826a49SYabin Cui     {
2257*01826a49SYabin Cui         const U32 minBits = tableLog+1 - maxW;
2258*01826a49SYabin Cui         U32 nextRankVal = 0;
2259*01826a49SYabin Cui         U32 w, consumed;
2260*01826a49SYabin Cui         const int rescale = (memLog-tableLog) - 1;   /* tableLog <= memLog */
2261*01826a49SYabin Cui         U32* rankVal0 = rankVal[0];
2262*01826a49SYabin Cui         for (w=1; w<=maxW; w++)
2263*01826a49SYabin Cui         {
2264*01826a49SYabin Cui             U32 current = nextRankVal;
2265*01826a49SYabin Cui             nextRankVal += rankStats[w] << (w+rescale);
2266*01826a49SYabin Cui             rankVal0[w] = current;
2267*01826a49SYabin Cui         }
2268*01826a49SYabin Cui         for (consumed = minBits; consumed <= memLog - minBits; consumed++)
2269*01826a49SYabin Cui         {
2270*01826a49SYabin Cui             U32* rankValPtr = rankVal[consumed];
2271*01826a49SYabin Cui             for (w = 1; w <= maxW; w++)
2272*01826a49SYabin Cui             {
2273*01826a49SYabin Cui                 rankValPtr[w] = rankVal0[w] >> consumed;
2274*01826a49SYabin Cui             }
2275*01826a49SYabin Cui         }
2276*01826a49SYabin Cui     }
2277*01826a49SYabin Cui 
2278*01826a49SYabin Cui 
2279*01826a49SYabin Cui     /* fill tables */
2280*01826a49SYabin Cui     {
2281*01826a49SYabin Cui         void* ptr = DTable+1;
2282*01826a49SYabin Cui         HUF_DDescX6* DDescription = (HUF_DDescX6*)(ptr);
2283*01826a49SYabin Cui         void* dSeqStart = DTable + 1 + ((size_t)1<<(memLog-1));
2284*01826a49SYabin Cui         HUF_DSeqX6* DSequence = (HUF_DSeqX6*)(dSeqStart);
2285*01826a49SYabin Cui         HUF_DSeqX6 DSeq;
2286*01826a49SYabin Cui         HUF_DDescX6 DDesc;
2287*01826a49SYabin Cui         DSeq.sequence = 0;
2288*01826a49SYabin Cui         DDesc.nbBits = 0;
2289*01826a49SYabin Cui         DDesc.nbBytes = 0;
2290*01826a49SYabin Cui         HUF_fillDTableX6LevelN(DDescription, DSequence, memLog,
2291*01826a49SYabin Cui                        (const U32 (*)[HUF_ABSOLUTEMAX_TABLELOG + 1])rankVal, 0, 1, maxW,
2292*01826a49SYabin Cui                        sortedSymbol, sizeOfSort, rankStart0,
2293*01826a49SYabin Cui                        tableLog+1, DSeq, DDesc);
2294*01826a49SYabin Cui     }
2295*01826a49SYabin Cui 
2296*01826a49SYabin Cui     return iSize;
2297*01826a49SYabin Cui }
2298*01826a49SYabin Cui 
2299*01826a49SYabin Cui 
HUF_decodeSymbolX6(void * op,BIT_DStream_t * DStream,const HUF_DDescX6 * dd,const HUF_DSeqX6 * ds,const U32 dtLog)2300*01826a49SYabin Cui static U32 HUF_decodeSymbolX6(void* op, BIT_DStream_t* DStream, const HUF_DDescX6* dd, const HUF_DSeqX6* ds, const U32 dtLog)
2301*01826a49SYabin Cui {
2302*01826a49SYabin Cui     const size_t val = BIT_lookBitsFast(DStream, dtLog);   /* note : dtLog >= 1 */
2303*01826a49SYabin Cui     memcpy(op, ds+val, sizeof(HUF_DSeqX6));
2304*01826a49SYabin Cui     BIT_skipBits(DStream, dd[val].nbBits);
2305*01826a49SYabin Cui     return dd[val].nbBytes;
2306*01826a49SYabin Cui }
2307*01826a49SYabin Cui 
HUF_decodeLastSymbolsX6(void * op,const U32 maxL,BIT_DStream_t * DStream,const HUF_DDescX6 * dd,const HUF_DSeqX6 * ds,const U32 dtLog)2308*01826a49SYabin Cui static U32 HUF_decodeLastSymbolsX6(void* op, const U32 maxL, BIT_DStream_t* DStream,
2309*01826a49SYabin Cui                                   const HUF_DDescX6* dd, const HUF_DSeqX6* ds, const U32 dtLog)
2310*01826a49SYabin Cui {
2311*01826a49SYabin Cui     const size_t val = BIT_lookBitsFast(DStream, dtLog);   /* note : dtLog >= 1 */
2312*01826a49SYabin Cui     U32 length = dd[val].nbBytes;
2313*01826a49SYabin Cui     if (length <= maxL)
2314*01826a49SYabin Cui     {
2315*01826a49SYabin Cui         memcpy(op, ds+val, length);
2316*01826a49SYabin Cui         BIT_skipBits(DStream, dd[val].nbBits);
2317*01826a49SYabin Cui         return length;
2318*01826a49SYabin Cui     }
2319*01826a49SYabin Cui     memcpy(op, ds+val, maxL);
2320*01826a49SYabin Cui     if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8))
2321*01826a49SYabin Cui     {
2322*01826a49SYabin Cui         BIT_skipBits(DStream, dd[val].nbBits);
2323*01826a49SYabin Cui         if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
2324*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 */
2325*01826a49SYabin Cui     }
2326*01826a49SYabin Cui     return maxL;
2327*01826a49SYabin Cui }
2328*01826a49SYabin Cui 
2329*01826a49SYabin Cui 
2330*01826a49SYabin Cui #define HUF_DECODE_SYMBOLX6_0(ptr, DStreamPtr) \
2331*01826a49SYabin Cui     ptr += HUF_decodeSymbolX6(ptr, DStreamPtr, dd, ds, dtLog)
2332*01826a49SYabin Cui 
2333*01826a49SYabin Cui #define HUF_DECODE_SYMBOLX6_1(ptr, DStreamPtr) \
2334*01826a49SYabin Cui     if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \
2335*01826a49SYabin Cui         HUF_DECODE_SYMBOLX6_0(ptr, DStreamPtr)
2336*01826a49SYabin Cui 
2337*01826a49SYabin Cui #define HUF_DECODE_SYMBOLX6_2(ptr, DStreamPtr) \
2338*01826a49SYabin Cui     if (MEM_64bits()) \
2339*01826a49SYabin Cui         HUF_DECODE_SYMBOLX6_0(ptr, DStreamPtr)
2340*01826a49SYabin Cui 
HUF_decodeStreamX6(BYTE * p,BIT_DStream_t * bitDPtr,BYTE * const pEnd,const U32 * DTable,const U32 dtLog)2341*01826a49SYabin Cui static inline size_t HUF_decodeStreamX6(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd, const U32* DTable, const U32 dtLog)
2342*01826a49SYabin Cui {
2343*01826a49SYabin Cui     const void* ddPtr = DTable+1;
2344*01826a49SYabin Cui     const HUF_DDescX6* dd = (const HUF_DDescX6*)(ddPtr);
2345*01826a49SYabin Cui     const void* dsPtr = DTable + 1 + ((size_t)1<<(dtLog-1));
2346*01826a49SYabin Cui     const HUF_DSeqX6* ds = (const HUF_DSeqX6*)(dsPtr);
2347*01826a49SYabin Cui     BYTE* const pStart = p;
2348*01826a49SYabin Cui 
2349*01826a49SYabin Cui     /* up to 16 symbols at a time */
2350*01826a49SYabin Cui     while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-16))
2351*01826a49SYabin Cui     {
2352*01826a49SYabin Cui         HUF_DECODE_SYMBOLX6_2(p, bitDPtr);
2353*01826a49SYabin Cui         HUF_DECODE_SYMBOLX6_1(p, bitDPtr);
2354*01826a49SYabin Cui         HUF_DECODE_SYMBOLX6_2(p, bitDPtr);
2355*01826a49SYabin Cui         HUF_DECODE_SYMBOLX6_0(p, bitDPtr);
2356*01826a49SYabin Cui     }
2357*01826a49SYabin Cui 
2358*01826a49SYabin Cui     /* closer to the end, up to 4 symbols at a time */
2359*01826a49SYabin Cui     while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-4))
2360*01826a49SYabin Cui         HUF_DECODE_SYMBOLX6_0(p, bitDPtr);
2361*01826a49SYabin Cui 
2362*01826a49SYabin Cui     while (p <= pEnd-4)
2363*01826a49SYabin Cui         HUF_DECODE_SYMBOLX6_0(p, bitDPtr);   /* no need to reload : reached the end of DStream */
2364*01826a49SYabin Cui 
2365*01826a49SYabin Cui     while (p < pEnd)
2366*01826a49SYabin Cui         p += HUF_decodeLastSymbolsX6(p, (U32)(pEnd-p), bitDPtr, dd, ds, dtLog);
2367*01826a49SYabin Cui 
2368*01826a49SYabin Cui     return p-pStart;
2369*01826a49SYabin Cui }
2370*01826a49SYabin Cui 
2371*01826a49SYabin Cui 
2372*01826a49SYabin Cui 
HUF_decompress4X6_usingDTable(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize,const U32 * DTable)2373*01826a49SYabin Cui static size_t HUF_decompress4X6_usingDTable(
2374*01826a49SYabin Cui           void* dst,  size_t dstSize,
2375*01826a49SYabin Cui     const void* cSrc, size_t cSrcSize,
2376*01826a49SYabin Cui     const U32* DTable)
2377*01826a49SYabin Cui {
2378*01826a49SYabin Cui     if (cSrcSize < 10) return ERROR(corruption_detected);   /* strict minimum : jump table + 1 byte per stream */
2379*01826a49SYabin Cui 
2380*01826a49SYabin Cui     {
2381*01826a49SYabin Cui         const BYTE* const istart = (const BYTE*) cSrc;
2382*01826a49SYabin Cui         BYTE* const ostart = (BYTE*) dst;
2383*01826a49SYabin Cui         BYTE* const oend = ostart + dstSize;
2384*01826a49SYabin Cui 
2385*01826a49SYabin Cui         const U32 dtLog = DTable[0];
2386*01826a49SYabin Cui         const void* ddPtr = DTable+1;
2387*01826a49SYabin Cui         const HUF_DDescX6* dd = (const HUF_DDescX6*)(ddPtr);
2388*01826a49SYabin Cui         const void* dsPtr = DTable + 1 + ((size_t)1<<(dtLog-1));
2389*01826a49SYabin Cui         const HUF_DSeqX6* ds = (const HUF_DSeqX6*)(dsPtr);
2390*01826a49SYabin Cui         size_t errorCode;
2391*01826a49SYabin Cui 
2392*01826a49SYabin Cui         /* Init */
2393*01826a49SYabin Cui         BIT_DStream_t bitD1;
2394*01826a49SYabin Cui         BIT_DStream_t bitD2;
2395*01826a49SYabin Cui         BIT_DStream_t bitD3;
2396*01826a49SYabin Cui         BIT_DStream_t bitD4;
2397*01826a49SYabin Cui         const size_t length1 = MEM_readLE16(istart);
2398*01826a49SYabin Cui         const size_t length2 = MEM_readLE16(istart+2);
2399*01826a49SYabin Cui         const size_t length3 = MEM_readLE16(istart+4);
2400*01826a49SYabin Cui         size_t length4;
2401*01826a49SYabin Cui         const BYTE* const istart1 = istart + 6;  /* jumpTable */
2402*01826a49SYabin Cui         const BYTE* const istart2 = istart1 + length1;
2403*01826a49SYabin Cui         const BYTE* const istart3 = istart2 + length2;
2404*01826a49SYabin Cui         const BYTE* const istart4 = istart3 + length3;
2405*01826a49SYabin Cui         const size_t segmentSize = (dstSize+3) / 4;
2406*01826a49SYabin Cui         BYTE* const opStart2 = ostart + segmentSize;
2407*01826a49SYabin Cui         BYTE* const opStart3 = opStart2 + segmentSize;
2408*01826a49SYabin Cui         BYTE* const opStart4 = opStart3 + segmentSize;
2409*01826a49SYabin Cui         BYTE* op1 = ostart;
2410*01826a49SYabin Cui         BYTE* op2 = opStart2;
2411*01826a49SYabin Cui         BYTE* op3 = opStart3;
2412*01826a49SYabin Cui         BYTE* op4 = opStart4;
2413*01826a49SYabin Cui         U32 endSignal;
2414*01826a49SYabin Cui 
2415*01826a49SYabin Cui         length4 = cSrcSize - (length1 + length2 + length3 + 6);
2416*01826a49SYabin Cui         if (length4 > cSrcSize) return ERROR(corruption_detected);   /* overflow */
2417*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD1, istart1, length1);
2418*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
2419*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD2, istart2, length2);
2420*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
2421*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD3, istart3, length3);
2422*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
2423*01826a49SYabin Cui         errorCode = BIT_initDStream(&bitD4, istart4, length4);
2424*01826a49SYabin Cui         if (HUF_isError(errorCode)) return errorCode;
2425*01826a49SYabin Cui 
2426*01826a49SYabin Cui         /* 16-64 symbols per loop (4-16 symbols per stream) */
2427*01826a49SYabin Cui         endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
2428*01826a49SYabin Cui         for ( ; (op3 <= opStart4) && (endSignal==BIT_DStream_unfinished) && (op4<=(oend-16)) ; )
2429*01826a49SYabin Cui         {
2430*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_2(op1, &bitD1);
2431*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_2(op2, &bitD2);
2432*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_2(op3, &bitD3);
2433*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_2(op4, &bitD4);
2434*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_1(op1, &bitD1);
2435*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_1(op2, &bitD2);
2436*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_1(op3, &bitD3);
2437*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_1(op4, &bitD4);
2438*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_2(op1, &bitD1);
2439*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_2(op2, &bitD2);
2440*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_2(op3, &bitD3);
2441*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_2(op4, &bitD4);
2442*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_0(op1, &bitD1);
2443*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_0(op2, &bitD2);
2444*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_0(op3, &bitD3);
2445*01826a49SYabin Cui             HUF_DECODE_SYMBOLX6_0(op4, &bitD4);
2446*01826a49SYabin Cui 
2447*01826a49SYabin Cui             endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
2448*01826a49SYabin Cui         }
2449*01826a49SYabin Cui 
2450*01826a49SYabin Cui         /* check corruption */
2451*01826a49SYabin Cui         if (op1 > opStart2) return ERROR(corruption_detected);
2452*01826a49SYabin Cui         if (op2 > opStart3) return ERROR(corruption_detected);
2453*01826a49SYabin Cui         if (op3 > opStart4) return ERROR(corruption_detected);
2454*01826a49SYabin Cui         /* note : op4 supposed already verified within main loop */
2455*01826a49SYabin Cui 
2456*01826a49SYabin Cui         /* finish bitStreams one by one */
2457*01826a49SYabin Cui         HUF_decodeStreamX6(op1, &bitD1, opStart2, DTable, dtLog);
2458*01826a49SYabin Cui         HUF_decodeStreamX6(op2, &bitD2, opStart3, DTable, dtLog);
2459*01826a49SYabin Cui         HUF_decodeStreamX6(op3, &bitD3, opStart4, DTable, dtLog);
2460*01826a49SYabin Cui         HUF_decodeStreamX6(op4, &bitD4, oend,     DTable, dtLog);
2461*01826a49SYabin Cui 
2462*01826a49SYabin Cui         /* check */
2463*01826a49SYabin Cui         endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
2464*01826a49SYabin Cui         if (!endSignal) return ERROR(corruption_detected);
2465*01826a49SYabin Cui 
2466*01826a49SYabin Cui         /* decoded size */
2467*01826a49SYabin Cui         return dstSize;
2468*01826a49SYabin Cui     }
2469*01826a49SYabin Cui }
2470*01826a49SYabin Cui 
2471*01826a49SYabin Cui 
HUF_decompress4X6(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize)2472*01826a49SYabin Cui static size_t HUF_decompress4X6 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
2473*01826a49SYabin Cui {
2474*01826a49SYabin Cui     HUF_CREATE_STATIC_DTABLEX6(DTable, HUF_MAX_TABLELOG);
2475*01826a49SYabin Cui     const BYTE* ip = (const BYTE*) cSrc;
2476*01826a49SYabin Cui 
2477*01826a49SYabin Cui     size_t hSize = HUF_readDTableX6 (DTable, cSrc, cSrcSize);
2478*01826a49SYabin Cui     if (HUF_isError(hSize)) return hSize;
2479*01826a49SYabin Cui     if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
2480*01826a49SYabin Cui     ip += hSize;
2481*01826a49SYabin Cui     cSrcSize -= hSize;
2482*01826a49SYabin Cui 
2483*01826a49SYabin Cui     return HUF_decompress4X6_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
2484*01826a49SYabin Cui }
2485*01826a49SYabin Cui 
2486*01826a49SYabin Cui 
2487*01826a49SYabin Cui /**********************************/
2488*01826a49SYabin Cui /* Generic decompression selector */
2489*01826a49SYabin Cui /**********************************/
2490*01826a49SYabin Cui 
2491*01826a49SYabin Cui typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t;
2492*01826a49SYabin Cui static const algo_time_t algoTime[16 /* Quantization */][3 /* single, double, quad */] =
2493*01826a49SYabin Cui {
2494*01826a49SYabin Cui     /* single, double, quad */
2495*01826a49SYabin Cui     {{0,0}, {1,1}, {2,2}},  /* Q==0 : impossible */
2496*01826a49SYabin Cui     {{0,0}, {1,1}, {2,2}},  /* Q==1 : impossible */
2497*01826a49SYabin Cui     {{  38,130}, {1313, 74}, {2151, 38}},   /* Q == 2 : 12-18% */
2498*01826a49SYabin Cui     {{ 448,128}, {1353, 74}, {2238, 41}},   /* Q == 3 : 18-25% */
2499*01826a49SYabin Cui     {{ 556,128}, {1353, 74}, {2238, 47}},   /* Q == 4 : 25-32% */
2500*01826a49SYabin Cui     {{ 714,128}, {1418, 74}, {2436, 53}},   /* Q == 5 : 32-38% */
2501*01826a49SYabin Cui     {{ 883,128}, {1437, 74}, {2464, 61}},   /* Q == 6 : 38-44% */
2502*01826a49SYabin Cui     {{ 897,128}, {1515, 75}, {2622, 68}},   /* Q == 7 : 44-50% */
2503*01826a49SYabin Cui     {{ 926,128}, {1613, 75}, {2730, 75}},   /* Q == 8 : 50-56% */
2504*01826a49SYabin Cui     {{ 947,128}, {1729, 77}, {3359, 77}},   /* Q == 9 : 56-62% */
2505*01826a49SYabin Cui     {{1107,128}, {2083, 81}, {4006, 84}},   /* Q ==10 : 62-69% */
2506*01826a49SYabin Cui     {{1177,128}, {2379, 87}, {4785, 88}},   /* Q ==11 : 69-75% */
2507*01826a49SYabin Cui     {{1242,128}, {2415, 93}, {5155, 84}},   /* Q ==12 : 75-81% */
2508*01826a49SYabin Cui     {{1349,128}, {2644,106}, {5260,106}},   /* Q ==13 : 81-87% */
2509*01826a49SYabin Cui     {{1455,128}, {2422,124}, {4174,124}},   /* Q ==14 : 87-93% */
2510*01826a49SYabin Cui     {{ 722,128}, {1891,145}, {1936,146}},   /* Q ==15 : 93-99% */
2511*01826a49SYabin Cui };
2512*01826a49SYabin Cui 
2513*01826a49SYabin Cui typedef size_t (*decompressionAlgo)(void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
2514*01826a49SYabin Cui 
HUF_decompress(void * dst,size_t dstSize,const void * cSrc,size_t cSrcSize)2515*01826a49SYabin Cui static size_t HUF_decompress (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
2516*01826a49SYabin Cui {
2517*01826a49SYabin Cui     static const decompressionAlgo decompress[3] = { HUF_decompress4X2, HUF_decompress4X4, HUF_decompress4X6 };
2518*01826a49SYabin Cui     /* estimate decompression time */
2519*01826a49SYabin Cui     U32 Q;
2520*01826a49SYabin Cui     const U32 D256 = (U32)(dstSize >> 8);
2521*01826a49SYabin Cui     U32 Dtime[3];
2522*01826a49SYabin Cui     U32 algoNb = 0;
2523*01826a49SYabin Cui     int n;
2524*01826a49SYabin Cui 
2525*01826a49SYabin Cui     /* validation checks */
2526*01826a49SYabin Cui     if (dstSize == 0) return ERROR(dstSize_tooSmall);
2527*01826a49SYabin Cui     if (cSrcSize > dstSize) return ERROR(corruption_detected);   /* invalid */
2528*01826a49SYabin Cui     if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; }   /* not compressed */
2529*01826a49SYabin Cui     if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; }   /* RLE */
2530*01826a49SYabin Cui 
2531*01826a49SYabin Cui     /* decoder timing evaluation */
2532*01826a49SYabin Cui     Q = (U32)(cSrcSize * 16 / dstSize);   /* Q < 16 since dstSize > cSrcSize */
2533*01826a49SYabin Cui     for (n=0; n<3; n++)
2534*01826a49SYabin Cui         Dtime[n] = algoTime[Q][n].tableTime + (algoTime[Q][n].decode256Time * D256);
2535*01826a49SYabin Cui 
2536*01826a49SYabin Cui     Dtime[1] += Dtime[1] >> 4; Dtime[2] += Dtime[2] >> 3; /* advantage to algorithms using less memory, for cache eviction */
2537*01826a49SYabin Cui 
2538*01826a49SYabin Cui     if (Dtime[1] < Dtime[0]) algoNb = 1;
2539*01826a49SYabin Cui     if (Dtime[2] < Dtime[algoNb]) algoNb = 2;
2540*01826a49SYabin Cui 
2541*01826a49SYabin Cui     return decompress[algoNb](dst, dstSize, cSrc, cSrcSize);
2542*01826a49SYabin Cui 
2543*01826a49SYabin Cui     //return HUF_decompress4X2(dst, dstSize, cSrc, cSrcSize);   /* multi-streams single-symbol decoding */
2544*01826a49SYabin Cui     //return HUF_decompress4X4(dst, dstSize, cSrc, cSrcSize);   /* multi-streams double-symbols decoding */
2545*01826a49SYabin Cui     //return HUF_decompress4X6(dst, dstSize, cSrc, cSrcSize);   /* multi-streams quad-symbols decoding */
2546*01826a49SYabin Cui }
2547*01826a49SYabin Cui /*
2548*01826a49SYabin Cui     zstd - standard compression library
2549*01826a49SYabin Cui     Copyright (C) 2014-2015, Yann Collet.
2550*01826a49SYabin Cui 
2551*01826a49SYabin Cui     BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
2552*01826a49SYabin Cui 
2553*01826a49SYabin Cui     Redistribution and use in source and binary forms, with or without
2554*01826a49SYabin Cui     modification, are permitted provided that the following conditions are
2555*01826a49SYabin Cui     met:
2556*01826a49SYabin Cui     * Redistributions of source code must retain the above copyright
2557*01826a49SYabin Cui     notice, this list of conditions and the following disclaimer.
2558*01826a49SYabin Cui     * Redistributions in binary form must reproduce the above
2559*01826a49SYabin Cui     copyright notice, this list of conditions and the following disclaimer
2560*01826a49SYabin Cui     in the documentation and/or other materials provided with the
2561*01826a49SYabin Cui     distribution.
2562*01826a49SYabin Cui     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2563*01826a49SYabin Cui     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2564*01826a49SYabin Cui     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2565*01826a49SYabin Cui     A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2566*01826a49SYabin Cui     OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2567*01826a49SYabin Cui     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2568*01826a49SYabin Cui     LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2569*01826a49SYabin Cui     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2570*01826a49SYabin Cui     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2571*01826a49SYabin Cui     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2572*01826a49SYabin Cui     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2573*01826a49SYabin Cui 
2574*01826a49SYabin Cui     You can contact the author at :
2575*01826a49SYabin Cui     - zstd source repository : https://github.com/Cyan4973/zstd
2576*01826a49SYabin Cui     - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
2577*01826a49SYabin Cui */
2578*01826a49SYabin Cui 
2579*01826a49SYabin Cui /* ***************************************************************
2580*01826a49SYabin Cui *  Tuning parameters
2581*01826a49SYabin Cui *****************************************************************/
2582*01826a49SYabin Cui /*!
2583*01826a49SYabin Cui *  MEMORY_USAGE :
2584*01826a49SYabin Cui *  Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
2585*01826a49SYabin Cui *  Increasing memory usage improves compression ratio
2586*01826a49SYabin Cui *  Reduced memory usage can improve speed, due to cache effect
2587*01826a49SYabin Cui */
2588*01826a49SYabin Cui #define ZSTD_MEMORY_USAGE 17
2589*01826a49SYabin Cui 
2590*01826a49SYabin Cui /*!
2591*01826a49SYabin Cui  * HEAPMODE :
2592*01826a49SYabin Cui  * Select how default compression functions will allocate memory for their hash table,
2593*01826a49SYabin Cui  * in memory stack (0, fastest), or in memory heap (1, requires malloc())
2594*01826a49SYabin Cui  * Note that compression context is fairly large, as a consequence heap memory is recommended.
2595*01826a49SYabin Cui  */
2596*01826a49SYabin Cui #ifndef ZSTD_HEAPMODE
2597*01826a49SYabin Cui #  define ZSTD_HEAPMODE 1
2598*01826a49SYabin Cui #endif /* ZSTD_HEAPMODE */
2599*01826a49SYabin Cui 
2600*01826a49SYabin Cui /*!
2601*01826a49SYabin Cui *  LEGACY_SUPPORT :
2602*01826a49SYabin Cui *  decompressor can decode older formats (starting from Zstd 0.1+)
2603*01826a49SYabin Cui */
2604*01826a49SYabin Cui #ifndef ZSTD_LEGACY_SUPPORT
2605*01826a49SYabin Cui #  define ZSTD_LEGACY_SUPPORT 1
2606*01826a49SYabin Cui #endif
2607*01826a49SYabin Cui 
2608*01826a49SYabin Cui 
2609*01826a49SYabin Cui /* *******************************************************
2610*01826a49SYabin Cui *  Includes
2611*01826a49SYabin Cui *********************************************************/
2612*01826a49SYabin Cui #include <stdlib.h>      /* calloc */
2613*01826a49SYabin Cui #include <string.h>      /* memcpy, memmove */
2614*01826a49SYabin Cui #include <stdio.h>       /* debug : printf */
2615*01826a49SYabin Cui 
2616*01826a49SYabin Cui 
2617*01826a49SYabin Cui /* *******************************************************
2618*01826a49SYabin Cui *  Compiler specifics
2619*01826a49SYabin Cui *********************************************************/
2620*01826a49SYabin Cui #ifdef __AVX2__
2621*01826a49SYabin Cui #  include <immintrin.h>   /* AVX2 intrinsics */
2622*01826a49SYabin Cui #endif
2623*01826a49SYabin Cui 
2624*01826a49SYabin Cui #ifdef _MSC_VER    /* Visual Studio */
2625*01826a49SYabin Cui #  include <intrin.h>                    /* For Visual 2005 */
2626*01826a49SYabin Cui #  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */
2627*01826a49SYabin Cui #  pragma warning(disable : 4324)        /* disable: C4324: padded structure */
2628*01826a49SYabin Cui #endif
2629*01826a49SYabin Cui 
2630*01826a49SYabin Cui 
2631*01826a49SYabin Cui /* *******************************************************
2632*01826a49SYabin Cui *  Constants
2633*01826a49SYabin Cui *********************************************************/
2634*01826a49SYabin Cui #define HASH_LOG (ZSTD_MEMORY_USAGE - 2)
2635*01826a49SYabin Cui #define HASH_TABLESIZE (1 << HASH_LOG)
2636*01826a49SYabin Cui #define HASH_MASK (HASH_TABLESIZE - 1)
2637*01826a49SYabin Cui 
2638*01826a49SYabin Cui #define KNUTH 2654435761
2639*01826a49SYabin Cui 
2640*01826a49SYabin Cui #define BIT7 128
2641*01826a49SYabin Cui #define BIT6  64
2642*01826a49SYabin Cui #define BIT5  32
2643*01826a49SYabin Cui #define BIT4  16
2644*01826a49SYabin Cui #define BIT1   2
2645*01826a49SYabin Cui #define BIT0   1
2646*01826a49SYabin Cui 
2647*01826a49SYabin Cui #define KB *(1 <<10)
2648*01826a49SYabin Cui #define MB *(1 <<20)
2649*01826a49SYabin Cui #define GB *(1U<<30)
2650*01826a49SYabin Cui 
2651*01826a49SYabin Cui #define BLOCKSIZE (128 KB)                 /* define, for static allocation */
2652*01826a49SYabin Cui #define MIN_SEQUENCES_SIZE (2 /*seqNb*/ + 2 /*dumps*/ + 3 /*seqTables*/ + 1 /*bitStream*/)
2653*01826a49SYabin Cui #define MIN_CBLOCK_SIZE (3 /*litCSize*/ + MIN_SEQUENCES_SIZE)
2654*01826a49SYabin Cui #define IS_RAW BIT0
2655*01826a49SYabin Cui #define IS_RLE BIT1
2656*01826a49SYabin Cui 
2657*01826a49SYabin Cui #define WORKPLACESIZE (BLOCKSIZE*3)
2658*01826a49SYabin Cui #define MINMATCH 4
2659*01826a49SYabin Cui #define MLbits   7
2660*01826a49SYabin Cui #define LLbits   6
2661*01826a49SYabin Cui #define Offbits  5
2662*01826a49SYabin Cui #define MaxML  ((1<<MLbits )-1)
2663*01826a49SYabin Cui #define MaxLL  ((1<<LLbits )-1)
2664*01826a49SYabin Cui #define MaxOff   31
2665*01826a49SYabin Cui #define LitFSELog  11
2666*01826a49SYabin Cui #define MLFSELog   10
2667*01826a49SYabin Cui #define LLFSELog   10
2668*01826a49SYabin Cui #define OffFSELog   9
2669*01826a49SYabin Cui #define MAX(a,b) ((a)<(b)?(b):(a))
2670*01826a49SYabin Cui #define MaxSeq MAX(MaxLL, MaxML)
2671*01826a49SYabin Cui 
2672*01826a49SYabin Cui #define LITERAL_NOENTROPY 63
2673*01826a49SYabin Cui #define COMMAND_NOENTROPY 7   /* to remove */
2674*01826a49SYabin Cui 
2675*01826a49SYabin Cui #define ZSTD_CONTENTSIZE_ERROR   (0ULL - 2)
2676*01826a49SYabin Cui 
2677*01826a49SYabin Cui static const size_t ZSTD_blockHeaderSize = 3;
2678*01826a49SYabin Cui static const size_t ZSTD_frameHeaderSize = 4;
2679*01826a49SYabin Cui 
2680*01826a49SYabin Cui 
2681*01826a49SYabin Cui /* *******************************************************
2682*01826a49SYabin Cui *  Memory operations
2683*01826a49SYabin Cui **********************************************************/
ZSTD_copy4(void * dst,const void * src)2684*01826a49SYabin Cui static void   ZSTD_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
2685*01826a49SYabin Cui 
ZSTD_copy8(void * dst,const void * src)2686*01826a49SYabin Cui static void   ZSTD_copy8(void* dst, const void* src) { memcpy(dst, src, 8); }
2687*01826a49SYabin Cui 
2688*01826a49SYabin Cui #define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
2689*01826a49SYabin Cui 
2690*01826a49SYabin Cui /*! ZSTD_wildcopy : custom version of memcpy(), can copy up to 7-8 bytes too many */
ZSTD_wildcopy(void * dst,const void * src,ptrdiff_t length)2691*01826a49SYabin Cui static void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length)
2692*01826a49SYabin Cui {
2693*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
2694*01826a49SYabin Cui     BYTE* op = (BYTE*)dst;
2695*01826a49SYabin Cui     BYTE* const oend = op + length;
2696*01826a49SYabin Cui     do COPY8(op, ip) while (op < oend);
2697*01826a49SYabin Cui }
2698*01826a49SYabin Cui 
2699*01826a49SYabin Cui 
2700*01826a49SYabin Cui /* **************************************
2701*01826a49SYabin Cui *  Local structures
2702*01826a49SYabin Cui ****************************************/
2703*01826a49SYabin Cui typedef enum { bt_compressed, bt_raw, bt_rle, bt_end } blockType_t;
2704*01826a49SYabin Cui 
2705*01826a49SYabin Cui typedef struct
2706*01826a49SYabin Cui {
2707*01826a49SYabin Cui     blockType_t blockType;
2708*01826a49SYabin Cui     U32 origSize;
2709*01826a49SYabin Cui } blockProperties_t;
2710*01826a49SYabin Cui 
2711*01826a49SYabin Cui typedef struct {
2712*01826a49SYabin Cui     void* buffer;
2713*01826a49SYabin Cui     U32*  offsetStart;
2714*01826a49SYabin Cui     U32*  offset;
2715*01826a49SYabin Cui     BYTE* offCodeStart;
2716*01826a49SYabin Cui     BYTE* offCode;
2717*01826a49SYabin Cui     BYTE* litStart;
2718*01826a49SYabin Cui     BYTE* lit;
2719*01826a49SYabin Cui     BYTE* litLengthStart;
2720*01826a49SYabin Cui     BYTE* litLength;
2721*01826a49SYabin Cui     BYTE* matchLengthStart;
2722*01826a49SYabin Cui     BYTE* matchLength;
2723*01826a49SYabin Cui     BYTE* dumpsStart;
2724*01826a49SYabin Cui     BYTE* dumps;
2725*01826a49SYabin Cui } seqStore_t;
2726*01826a49SYabin Cui 
2727*01826a49SYabin Cui 
2728*01826a49SYabin Cui /* *************************************
2729*01826a49SYabin Cui *  Error Management
2730*01826a49SYabin Cui ***************************************/
2731*01826a49SYabin Cui /*! ZSTD_isError
2732*01826a49SYabin Cui *   tells if a return value is an error code */
ZSTD_isError(size_t code)2733*01826a49SYabin Cui static unsigned ZSTD_isError(size_t code) { return ERR_isError(code); }
2734*01826a49SYabin Cui 
2735*01826a49SYabin Cui 
2736*01826a49SYabin Cui 
2737*01826a49SYabin Cui /* *************************************************************
2738*01826a49SYabin Cui *   Decompression section
2739*01826a49SYabin Cui ***************************************************************/
2740*01826a49SYabin Cui struct ZSTDv02_Dctx_s
2741*01826a49SYabin Cui {
2742*01826a49SYabin Cui     U32 LLTable[FSE_DTABLE_SIZE_U32(LLFSELog)];
2743*01826a49SYabin Cui     U32 OffTable[FSE_DTABLE_SIZE_U32(OffFSELog)];
2744*01826a49SYabin Cui     U32 MLTable[FSE_DTABLE_SIZE_U32(MLFSELog)];
2745*01826a49SYabin Cui     void* previousDstEnd;
2746*01826a49SYabin Cui     void* base;
2747*01826a49SYabin Cui     size_t expected;
2748*01826a49SYabin Cui     blockType_t bType;
2749*01826a49SYabin Cui     U32 phase;
2750*01826a49SYabin Cui     const BYTE* litPtr;
2751*01826a49SYabin Cui     size_t litSize;
2752*01826a49SYabin Cui     BYTE litBuffer[BLOCKSIZE + 8 /* margin for wildcopy */];
2753*01826a49SYabin Cui };   /* typedef'd to ZSTD_Dctx within "zstd_static.h" */
2754*01826a49SYabin Cui 
2755*01826a49SYabin Cui 
ZSTD_getcBlockSize(const void * src,size_t srcSize,blockProperties_t * bpPtr)2756*01826a49SYabin Cui static size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, blockProperties_t* bpPtr)
2757*01826a49SYabin Cui {
2758*01826a49SYabin Cui     const BYTE* const in = (const BYTE* const)src;
2759*01826a49SYabin Cui     BYTE headerFlags;
2760*01826a49SYabin Cui     U32 cSize;
2761*01826a49SYabin Cui 
2762*01826a49SYabin Cui     if (srcSize < 3) return ERROR(srcSize_wrong);
2763*01826a49SYabin Cui 
2764*01826a49SYabin Cui     headerFlags = *in;
2765*01826a49SYabin Cui     cSize = in[2] + (in[1]<<8) + ((in[0] & 7)<<16);
2766*01826a49SYabin Cui 
2767*01826a49SYabin Cui     bpPtr->blockType = (blockType_t)(headerFlags >> 6);
2768*01826a49SYabin Cui     bpPtr->origSize = (bpPtr->blockType == bt_rle) ? cSize : 0;
2769*01826a49SYabin Cui 
2770*01826a49SYabin Cui     if (bpPtr->blockType == bt_end) return 0;
2771*01826a49SYabin Cui     if (bpPtr->blockType == bt_rle) return 1;
2772*01826a49SYabin Cui     return cSize;
2773*01826a49SYabin Cui }
2774*01826a49SYabin Cui 
ZSTD_copyUncompressedBlock(void * dst,size_t maxDstSize,const void * src,size_t srcSize)2775*01826a49SYabin Cui static size_t ZSTD_copyUncompressedBlock(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
2776*01826a49SYabin Cui {
2777*01826a49SYabin Cui     if (srcSize > maxDstSize) return ERROR(dstSize_tooSmall);
2778*01826a49SYabin Cui     if (srcSize > 0) {
2779*01826a49SYabin Cui         memcpy(dst, src, srcSize);
2780*01826a49SYabin Cui     }
2781*01826a49SYabin Cui     return srcSize;
2782*01826a49SYabin Cui }
2783*01826a49SYabin Cui 
2784*01826a49SYabin Cui 
2785*01826a49SYabin Cui /** ZSTD_decompressLiterals
2786*01826a49SYabin Cui     @return : nb of bytes read from src, or an error code*/
ZSTD_decompressLiterals(void * dst,size_t * maxDstSizePtr,const void * src,size_t srcSize)2787*01826a49SYabin Cui static size_t ZSTD_decompressLiterals(void* dst, size_t* maxDstSizePtr,
2788*01826a49SYabin Cui                                 const void* src, size_t srcSize)
2789*01826a49SYabin Cui {
2790*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
2791*01826a49SYabin Cui 
2792*01826a49SYabin Cui     const size_t litSize = (MEM_readLE32(src) & 0x1FFFFF) >> 2;   /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
2793*01826a49SYabin Cui     const size_t litCSize = (MEM_readLE32(ip+2) & 0xFFFFFF) >> 5;   /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
2794*01826a49SYabin Cui 
2795*01826a49SYabin Cui     if (litSize > *maxDstSizePtr) return ERROR(corruption_detected);
2796*01826a49SYabin Cui     if (litCSize + 5 > srcSize) return ERROR(corruption_detected);
2797*01826a49SYabin Cui 
2798*01826a49SYabin Cui     if (HUF_isError(HUF_decompress(dst, litSize, ip+5, litCSize))) return ERROR(corruption_detected);
2799*01826a49SYabin Cui 
2800*01826a49SYabin Cui     *maxDstSizePtr = litSize;
2801*01826a49SYabin Cui     return litCSize + 5;
2802*01826a49SYabin Cui }
2803*01826a49SYabin Cui 
2804*01826a49SYabin Cui 
2805*01826a49SYabin Cui /** ZSTD_decodeLiteralsBlock
2806*01826a49SYabin Cui     @return : nb of bytes read from src (< srcSize )*/
ZSTD_decodeLiteralsBlock(void * ctx,const void * src,size_t srcSize)2807*01826a49SYabin Cui static size_t ZSTD_decodeLiteralsBlock(void* ctx,
2808*01826a49SYabin Cui                           const void* src, size_t srcSize)
2809*01826a49SYabin Cui {
2810*01826a49SYabin Cui     ZSTD_DCtx* dctx = (ZSTD_DCtx*)ctx;
2811*01826a49SYabin Cui     const BYTE* const istart = (const BYTE* const)src;
2812*01826a49SYabin Cui 
2813*01826a49SYabin Cui     /* any compressed block with literals segment must be at least this size */
2814*01826a49SYabin Cui     if (srcSize < MIN_CBLOCK_SIZE) return ERROR(corruption_detected);
2815*01826a49SYabin Cui 
2816*01826a49SYabin Cui     switch(*istart & 3)
2817*01826a49SYabin Cui     {
2818*01826a49SYabin Cui     default:
2819*01826a49SYabin Cui     case 0:
2820*01826a49SYabin Cui         {
2821*01826a49SYabin Cui             size_t litSize = BLOCKSIZE;
2822*01826a49SYabin Cui             const size_t readSize = ZSTD_decompressLiterals(dctx->litBuffer, &litSize, src, srcSize);
2823*01826a49SYabin Cui             dctx->litPtr = dctx->litBuffer;
2824*01826a49SYabin Cui             dctx->litSize = litSize;
2825*01826a49SYabin Cui             memset(dctx->litBuffer + dctx->litSize, 0, 8);
2826*01826a49SYabin Cui             return readSize;   /* works if it's an error too */
2827*01826a49SYabin Cui         }
2828*01826a49SYabin Cui     case IS_RAW:
2829*01826a49SYabin Cui         {
2830*01826a49SYabin Cui             const size_t litSize = (MEM_readLE32(istart) & 0xFFFFFF) >> 2;   /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
2831*01826a49SYabin Cui             if (litSize > srcSize-11)   /* risk of reading too far with wildcopy */
2832*01826a49SYabin Cui             {
2833*01826a49SYabin Cui                 if (litSize > BLOCKSIZE) return ERROR(corruption_detected);
2834*01826a49SYabin Cui                 if (litSize > srcSize-3) return ERROR(corruption_detected);
2835*01826a49SYabin Cui                 memcpy(dctx->litBuffer, istart, litSize);
2836*01826a49SYabin Cui                 dctx->litPtr = dctx->litBuffer;
2837*01826a49SYabin Cui                 dctx->litSize = litSize;
2838*01826a49SYabin Cui                 memset(dctx->litBuffer + dctx->litSize, 0, 8);
2839*01826a49SYabin Cui                 return litSize+3;
2840*01826a49SYabin Cui             }
2841*01826a49SYabin Cui             /* direct reference into compressed stream */
2842*01826a49SYabin Cui             dctx->litPtr = istart+3;
2843*01826a49SYabin Cui             dctx->litSize = litSize;
2844*01826a49SYabin Cui             return litSize+3;
2845*01826a49SYabin Cui         }
2846*01826a49SYabin Cui     case IS_RLE:
2847*01826a49SYabin Cui         {
2848*01826a49SYabin Cui             const size_t litSize = (MEM_readLE32(istart) & 0xFFFFFF) >> 2;   /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
2849*01826a49SYabin Cui             if (litSize > BLOCKSIZE) return ERROR(corruption_detected);
2850*01826a49SYabin Cui             memset(dctx->litBuffer, istart[3], litSize + 8);
2851*01826a49SYabin Cui             dctx->litPtr = dctx->litBuffer;
2852*01826a49SYabin Cui             dctx->litSize = litSize;
2853*01826a49SYabin Cui             return 4;
2854*01826a49SYabin Cui         }
2855*01826a49SYabin Cui     }
2856*01826a49SYabin Cui }
2857*01826a49SYabin Cui 
2858*01826a49SYabin Cui 
ZSTD_decodeSeqHeaders(int * nbSeq,const BYTE ** dumpsPtr,size_t * dumpsLengthPtr,FSE_DTable * DTableLL,FSE_DTable * DTableML,FSE_DTable * DTableOffb,const void * src,size_t srcSize)2859*01826a49SYabin Cui static size_t ZSTD_decodeSeqHeaders(int* nbSeq, const BYTE** dumpsPtr, size_t* dumpsLengthPtr,
2860*01826a49SYabin Cui                          FSE_DTable* DTableLL, FSE_DTable* DTableML, FSE_DTable* DTableOffb,
2861*01826a49SYabin Cui                          const void* src, size_t srcSize)
2862*01826a49SYabin Cui {
2863*01826a49SYabin Cui     const BYTE* const istart = (const BYTE* const)src;
2864*01826a49SYabin Cui     const BYTE* ip = istart;
2865*01826a49SYabin Cui     const BYTE* const iend = istart + srcSize;
2866*01826a49SYabin Cui     U32 LLtype, Offtype, MLtype;
2867*01826a49SYabin Cui     U32 LLlog, Offlog, MLlog;
2868*01826a49SYabin Cui     size_t dumpsLength;
2869*01826a49SYabin Cui 
2870*01826a49SYabin Cui     /* check */
2871*01826a49SYabin Cui     if (srcSize < 5) return ERROR(srcSize_wrong);
2872*01826a49SYabin Cui 
2873*01826a49SYabin Cui     /* SeqHead */
2874*01826a49SYabin Cui     *nbSeq = MEM_readLE16(ip); ip+=2;
2875*01826a49SYabin Cui     LLtype  = *ip >> 6;
2876*01826a49SYabin Cui     Offtype = (*ip >> 4) & 3;
2877*01826a49SYabin Cui     MLtype  = (*ip >> 2) & 3;
2878*01826a49SYabin Cui     if (*ip & 2)
2879*01826a49SYabin Cui     {
2880*01826a49SYabin Cui         dumpsLength  = ip[2];
2881*01826a49SYabin Cui         dumpsLength += ip[1] << 8;
2882*01826a49SYabin Cui         ip += 3;
2883*01826a49SYabin Cui     }
2884*01826a49SYabin Cui     else
2885*01826a49SYabin Cui     {
2886*01826a49SYabin Cui         dumpsLength  = ip[1];
2887*01826a49SYabin Cui         dumpsLength += (ip[0] & 1) << 8;
2888*01826a49SYabin Cui         ip += 2;
2889*01826a49SYabin Cui     }
2890*01826a49SYabin Cui     *dumpsPtr = ip;
2891*01826a49SYabin Cui     ip += dumpsLength;
2892*01826a49SYabin Cui     *dumpsLengthPtr = dumpsLength;
2893*01826a49SYabin Cui 
2894*01826a49SYabin Cui     /* check */
2895*01826a49SYabin Cui     if (ip > iend-3) return ERROR(srcSize_wrong); /* min : all 3 are "raw", hence no header, but at least xxLog bits per type */
2896*01826a49SYabin Cui 
2897*01826a49SYabin Cui     /* sequences */
2898*01826a49SYabin Cui     {
2899*01826a49SYabin Cui         S16 norm[MaxML+1];    /* assumption : MaxML >= MaxLL and MaxOff */
2900*01826a49SYabin Cui         size_t headerSize;
2901*01826a49SYabin Cui 
2902*01826a49SYabin Cui         /* Build DTables */
2903*01826a49SYabin Cui         switch(LLtype)
2904*01826a49SYabin Cui         {
2905*01826a49SYabin Cui         case bt_rle :
2906*01826a49SYabin Cui             LLlog = 0;
2907*01826a49SYabin Cui             FSE_buildDTable_rle(DTableLL, *ip++); break;
2908*01826a49SYabin Cui         case bt_raw :
2909*01826a49SYabin Cui             LLlog = LLbits;
2910*01826a49SYabin Cui             FSE_buildDTable_raw(DTableLL, LLbits); break;
2911*01826a49SYabin Cui         default :
2912*01826a49SYabin Cui             {   U32 max = MaxLL;
2913*01826a49SYabin Cui                 headerSize = FSE_readNCount(norm, &max, &LLlog, ip, iend-ip);
2914*01826a49SYabin Cui                 if (FSE_isError(headerSize)) return ERROR(GENERIC);
2915*01826a49SYabin Cui                 if (LLlog > LLFSELog) return ERROR(corruption_detected);
2916*01826a49SYabin Cui                 ip += headerSize;
2917*01826a49SYabin Cui                 FSE_buildDTable(DTableLL, norm, max, LLlog);
2918*01826a49SYabin Cui         }   }
2919*01826a49SYabin Cui 
2920*01826a49SYabin Cui         switch(Offtype)
2921*01826a49SYabin Cui         {
2922*01826a49SYabin Cui         case bt_rle :
2923*01826a49SYabin Cui             Offlog = 0;
2924*01826a49SYabin Cui             if (ip > iend-2) return ERROR(srcSize_wrong);   /* min : "raw", hence no header, but at least xxLog bits */
2925*01826a49SYabin Cui             FSE_buildDTable_rle(DTableOffb, *ip++ & MaxOff); /* if *ip > MaxOff, data is corrupted */
2926*01826a49SYabin Cui             break;
2927*01826a49SYabin Cui         case bt_raw :
2928*01826a49SYabin Cui             Offlog = Offbits;
2929*01826a49SYabin Cui             FSE_buildDTable_raw(DTableOffb, Offbits); break;
2930*01826a49SYabin Cui         default :
2931*01826a49SYabin Cui             {   U32 max = MaxOff;
2932*01826a49SYabin Cui                 headerSize = FSE_readNCount(norm, &max, &Offlog, ip, iend-ip);
2933*01826a49SYabin Cui                 if (FSE_isError(headerSize)) return ERROR(GENERIC);
2934*01826a49SYabin Cui                 if (Offlog > OffFSELog) return ERROR(corruption_detected);
2935*01826a49SYabin Cui                 ip += headerSize;
2936*01826a49SYabin Cui                 FSE_buildDTable(DTableOffb, norm, max, Offlog);
2937*01826a49SYabin Cui         }   }
2938*01826a49SYabin Cui 
2939*01826a49SYabin Cui         switch(MLtype)
2940*01826a49SYabin Cui         {
2941*01826a49SYabin Cui         case bt_rle :
2942*01826a49SYabin Cui             MLlog = 0;
2943*01826a49SYabin Cui             if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
2944*01826a49SYabin Cui             FSE_buildDTable_rle(DTableML, *ip++); break;
2945*01826a49SYabin Cui         case bt_raw :
2946*01826a49SYabin Cui             MLlog = MLbits;
2947*01826a49SYabin Cui             FSE_buildDTable_raw(DTableML, MLbits); break;
2948*01826a49SYabin Cui         default :
2949*01826a49SYabin Cui             {   U32 max = MaxML;
2950*01826a49SYabin Cui                 headerSize = FSE_readNCount(norm, &max, &MLlog, ip, iend-ip);
2951*01826a49SYabin Cui                 if (FSE_isError(headerSize)) return ERROR(GENERIC);
2952*01826a49SYabin Cui                 if (MLlog > MLFSELog) return ERROR(corruption_detected);
2953*01826a49SYabin Cui                 ip += headerSize;
2954*01826a49SYabin Cui                 FSE_buildDTable(DTableML, norm, max, MLlog);
2955*01826a49SYabin Cui     }   }   }
2956*01826a49SYabin Cui 
2957*01826a49SYabin Cui     return ip-istart;
2958*01826a49SYabin Cui }
2959*01826a49SYabin Cui 
2960*01826a49SYabin Cui 
2961*01826a49SYabin Cui typedef struct {
2962*01826a49SYabin Cui     size_t litLength;
2963*01826a49SYabin Cui     size_t offset;
2964*01826a49SYabin Cui     size_t matchLength;
2965*01826a49SYabin Cui } seq_t;
2966*01826a49SYabin Cui 
2967*01826a49SYabin Cui typedef struct {
2968*01826a49SYabin Cui     BIT_DStream_t DStream;
2969*01826a49SYabin Cui     FSE_DState_t stateLL;
2970*01826a49SYabin Cui     FSE_DState_t stateOffb;
2971*01826a49SYabin Cui     FSE_DState_t stateML;
2972*01826a49SYabin Cui     size_t prevOffset;
2973*01826a49SYabin Cui     const BYTE* dumps;
2974*01826a49SYabin Cui     const BYTE* dumpsEnd;
2975*01826a49SYabin Cui } seqState_t;
2976*01826a49SYabin Cui 
2977*01826a49SYabin Cui 
ZSTD_decodeSequence(seq_t * seq,seqState_t * seqState)2978*01826a49SYabin Cui static void ZSTD_decodeSequence(seq_t* seq, seqState_t* seqState)
2979*01826a49SYabin Cui {
2980*01826a49SYabin Cui     size_t litLength;
2981*01826a49SYabin Cui     size_t prevOffset;
2982*01826a49SYabin Cui     size_t offset;
2983*01826a49SYabin Cui     size_t matchLength;
2984*01826a49SYabin Cui     const BYTE* dumps = seqState->dumps;
2985*01826a49SYabin Cui     const BYTE* const de = seqState->dumpsEnd;
2986*01826a49SYabin Cui 
2987*01826a49SYabin Cui     /* Literal length */
2988*01826a49SYabin Cui     litLength = FSE_decodeSymbol(&(seqState->stateLL), &(seqState->DStream));
2989*01826a49SYabin Cui     prevOffset = litLength ? seq->offset : seqState->prevOffset;
2990*01826a49SYabin Cui     seqState->prevOffset = seq->offset;
2991*01826a49SYabin Cui     if (litLength == MaxLL)
2992*01826a49SYabin Cui     {
2993*01826a49SYabin Cui         const U32 add = dumps<de ? *dumps++ : 0;
2994*01826a49SYabin Cui         if (add < 255) litLength += add;
2995*01826a49SYabin Cui         else if (dumps + 3 <= de)
2996*01826a49SYabin Cui         {
2997*01826a49SYabin Cui             litLength = MEM_readLE24(dumps);
2998*01826a49SYabin Cui             dumps += 3;
2999*01826a49SYabin Cui         }
3000*01826a49SYabin Cui         if (dumps >= de) dumps = de-1;   /* late correction, to avoid read overflow (data is now corrupted anyway) */
3001*01826a49SYabin Cui     }
3002*01826a49SYabin Cui 
3003*01826a49SYabin Cui     /* Offset */
3004*01826a49SYabin Cui     {
3005*01826a49SYabin Cui         static const size_t offsetPrefix[MaxOff+1] = {  /* note : size_t faster than U32 */
3006*01826a49SYabin Cui                 1 /*fake*/, 1, 2, 4, 8, 16, 32, 64, 128, 256,
3007*01826a49SYabin Cui                 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144,
3008*01826a49SYabin Cui                 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, /*fake*/ 1, 1, 1, 1, 1 };
3009*01826a49SYabin Cui         U32 offsetCode, nbBits;
3010*01826a49SYabin Cui         offsetCode = FSE_decodeSymbol(&(seqState->stateOffb), &(seqState->DStream));   /* <= maxOff, by table construction */
3011*01826a49SYabin Cui         if (MEM_32bits()) BIT_reloadDStream(&(seqState->DStream));
3012*01826a49SYabin Cui         nbBits = offsetCode - 1;
3013*01826a49SYabin Cui         if (offsetCode==0) nbBits = 0;   /* cmove */
3014*01826a49SYabin Cui         offset = offsetPrefix[offsetCode] + BIT_readBits(&(seqState->DStream), nbBits);
3015*01826a49SYabin Cui         if (MEM_32bits()) BIT_reloadDStream(&(seqState->DStream));
3016*01826a49SYabin Cui         if (offsetCode==0) offset = prevOffset;   /* cmove */
3017*01826a49SYabin Cui     }
3018*01826a49SYabin Cui 
3019*01826a49SYabin Cui     /* MatchLength */
3020*01826a49SYabin Cui     matchLength = FSE_decodeSymbol(&(seqState->stateML), &(seqState->DStream));
3021*01826a49SYabin Cui     if (matchLength == MaxML)
3022*01826a49SYabin Cui     {
3023*01826a49SYabin Cui         const U32 add = dumps<de ? *dumps++ : 0;
3024*01826a49SYabin Cui         if (add < 255) matchLength += add;
3025*01826a49SYabin Cui         else if (dumps + 3 <= de)
3026*01826a49SYabin Cui         {
3027*01826a49SYabin Cui             matchLength = MEM_readLE24(dumps);
3028*01826a49SYabin Cui             dumps += 3;
3029*01826a49SYabin Cui         }
3030*01826a49SYabin Cui         if (dumps >= de) dumps = de-1;   /* late correction, to avoid read overflow (data is now corrupted anyway) */
3031*01826a49SYabin Cui     }
3032*01826a49SYabin Cui     matchLength += MINMATCH;
3033*01826a49SYabin Cui 
3034*01826a49SYabin Cui     /* save result */
3035*01826a49SYabin Cui     seq->litLength = litLength;
3036*01826a49SYabin Cui     seq->offset = offset;
3037*01826a49SYabin Cui     seq->matchLength = matchLength;
3038*01826a49SYabin Cui     seqState->dumps = dumps;
3039*01826a49SYabin Cui }
3040*01826a49SYabin Cui 
3041*01826a49SYabin Cui 
ZSTD_execSequence(BYTE * op,seq_t sequence,const BYTE ** litPtr,const BYTE * const litLimit,BYTE * const base,BYTE * const oend)3042*01826a49SYabin Cui static size_t ZSTD_execSequence(BYTE* op,
3043*01826a49SYabin Cui                                 seq_t sequence,
3044*01826a49SYabin Cui                                 const BYTE** litPtr, const BYTE* const litLimit,
3045*01826a49SYabin Cui                                 BYTE* const base, BYTE* const oend)
3046*01826a49SYabin Cui {
3047*01826a49SYabin Cui     static const int dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4};   /* added */
3048*01826a49SYabin Cui     static const int dec64table[] = {8, 8, 8, 7, 8, 9,10,11};   /* subtracted */
3049*01826a49SYabin Cui     const BYTE* const ostart = op;
3050*01826a49SYabin Cui     BYTE* const oLitEnd = op + sequence.litLength;
3051*01826a49SYabin Cui     BYTE* const oMatchEnd = op + sequence.litLength + sequence.matchLength;   /* risk : address space overflow (32-bits) */
3052*01826a49SYabin Cui     BYTE* const oend_8 = oend-8;
3053*01826a49SYabin Cui     const BYTE* const litEnd = *litPtr + sequence.litLength;
3054*01826a49SYabin Cui 
3055*01826a49SYabin Cui     /* checks */
3056*01826a49SYabin Cui     size_t const seqLength = sequence.litLength + sequence.matchLength;
3057*01826a49SYabin Cui 
3058*01826a49SYabin Cui     if (seqLength > (size_t)(oend - op)) return ERROR(dstSize_tooSmall);
3059*01826a49SYabin Cui     if (sequence.litLength > (size_t)(litLimit - *litPtr)) return ERROR(corruption_detected);
3060*01826a49SYabin Cui     /* Now we know there are no overflow in literal nor match lengths, can use the pointer check */
3061*01826a49SYabin Cui     if (oLitEnd > oend_8) return ERROR(dstSize_tooSmall);
3062*01826a49SYabin Cui     if (sequence.offset > (U32)(oLitEnd - base)) return ERROR(corruption_detected);
3063*01826a49SYabin Cui 
3064*01826a49SYabin Cui     if (oMatchEnd > oend) return ERROR(dstSize_tooSmall);   /* overwrite beyond dst buffer */
3065*01826a49SYabin Cui     if (litEnd > litLimit) return ERROR(corruption_detected);   /* overRead beyond lit buffer */
3066*01826a49SYabin Cui 
3067*01826a49SYabin Cui     /* copy Literals */
3068*01826a49SYabin Cui     ZSTD_wildcopy(op, *litPtr, (ptrdiff_t)sequence.litLength);   /* note : oLitEnd <= oend-8 : no risk of overwrite beyond oend */
3069*01826a49SYabin Cui     op = oLitEnd;
3070*01826a49SYabin Cui     *litPtr = litEnd;   /* update for next sequence */
3071*01826a49SYabin Cui 
3072*01826a49SYabin Cui     /* copy Match */
3073*01826a49SYabin Cui     {
3074*01826a49SYabin Cui         const BYTE* match = op - sequence.offset;
3075*01826a49SYabin Cui 
3076*01826a49SYabin Cui         /* check */
3077*01826a49SYabin Cui         if (sequence.offset > (size_t)op) return ERROR(corruption_detected);   /* address space overflow test (this test seems kept by clang optimizer) */
3078*01826a49SYabin Cui         //if (match > op) return ERROR(corruption_detected);   /* address space overflow test (is clang optimizer removing this test ?) */
3079*01826a49SYabin Cui         if (match < base) return ERROR(corruption_detected);
3080*01826a49SYabin Cui 
3081*01826a49SYabin Cui         /* close range match, overlap */
3082*01826a49SYabin Cui         if (sequence.offset < 8)
3083*01826a49SYabin Cui         {
3084*01826a49SYabin Cui             const int dec64 = dec64table[sequence.offset];
3085*01826a49SYabin Cui             op[0] = match[0];
3086*01826a49SYabin Cui             op[1] = match[1];
3087*01826a49SYabin Cui             op[2] = match[2];
3088*01826a49SYabin Cui             op[3] = match[3];
3089*01826a49SYabin Cui             match += dec32table[sequence.offset];
3090*01826a49SYabin Cui             ZSTD_copy4(op+4, match);
3091*01826a49SYabin Cui             match -= dec64;
3092*01826a49SYabin Cui         }
3093*01826a49SYabin Cui         else
3094*01826a49SYabin Cui         {
3095*01826a49SYabin Cui             ZSTD_copy8(op, match);
3096*01826a49SYabin Cui         }
3097*01826a49SYabin Cui         op += 8; match += 8;
3098*01826a49SYabin Cui 
3099*01826a49SYabin Cui         if (oMatchEnd > oend-(16-MINMATCH))
3100*01826a49SYabin Cui         {
3101*01826a49SYabin Cui             if (op < oend_8)
3102*01826a49SYabin Cui             {
3103*01826a49SYabin Cui                 ZSTD_wildcopy(op, match, oend_8 - op);
3104*01826a49SYabin Cui                 match += oend_8 - op;
3105*01826a49SYabin Cui                 op = oend_8;
3106*01826a49SYabin Cui             }
3107*01826a49SYabin Cui             while (op < oMatchEnd) *op++ = *match++;
3108*01826a49SYabin Cui         }
3109*01826a49SYabin Cui         else
3110*01826a49SYabin Cui         {
3111*01826a49SYabin Cui             ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8);   /* works even if matchLength < 8 */
3112*01826a49SYabin Cui         }
3113*01826a49SYabin Cui     }
3114*01826a49SYabin Cui 
3115*01826a49SYabin Cui     return oMatchEnd - ostart;
3116*01826a49SYabin Cui }
3117*01826a49SYabin Cui 
ZSTD_decompressSequences(void * ctx,void * dst,size_t maxDstSize,const void * seqStart,size_t seqSize)3118*01826a49SYabin Cui static size_t ZSTD_decompressSequences(
3119*01826a49SYabin Cui                                void* ctx,
3120*01826a49SYabin Cui                                void* dst, size_t maxDstSize,
3121*01826a49SYabin Cui                          const void* seqStart, size_t seqSize)
3122*01826a49SYabin Cui {
3123*01826a49SYabin Cui     ZSTD_DCtx* dctx = (ZSTD_DCtx*)ctx;
3124*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)seqStart;
3125*01826a49SYabin Cui     const BYTE* const iend = ip + seqSize;
3126*01826a49SYabin Cui     BYTE* const ostart = (BYTE* const)dst;
3127*01826a49SYabin Cui     BYTE* op = ostart;
3128*01826a49SYabin Cui     BYTE* const oend = ostart + maxDstSize;
3129*01826a49SYabin Cui     size_t errorCode, dumpsLength;
3130*01826a49SYabin Cui     const BYTE* litPtr = dctx->litPtr;
3131*01826a49SYabin Cui     const BYTE* const litEnd = litPtr + dctx->litSize;
3132*01826a49SYabin Cui     int nbSeq;
3133*01826a49SYabin Cui     const BYTE* dumps;
3134*01826a49SYabin Cui     U32* DTableLL = dctx->LLTable;
3135*01826a49SYabin Cui     U32* DTableML = dctx->MLTable;
3136*01826a49SYabin Cui     U32* DTableOffb = dctx->OffTable;
3137*01826a49SYabin Cui     BYTE* const base = (BYTE*) (dctx->base);
3138*01826a49SYabin Cui 
3139*01826a49SYabin Cui     /* Build Decoding Tables */
3140*01826a49SYabin Cui     errorCode = ZSTD_decodeSeqHeaders(&nbSeq, &dumps, &dumpsLength,
3141*01826a49SYabin Cui                                       DTableLL, DTableML, DTableOffb,
3142*01826a49SYabin Cui                                       ip, iend-ip);
3143*01826a49SYabin Cui     if (ZSTD_isError(errorCode)) return errorCode;
3144*01826a49SYabin Cui     ip += errorCode;
3145*01826a49SYabin Cui 
3146*01826a49SYabin Cui     /* Regen sequences */
3147*01826a49SYabin Cui     {
3148*01826a49SYabin Cui         seq_t sequence;
3149*01826a49SYabin Cui         seqState_t seqState;
3150*01826a49SYabin Cui 
3151*01826a49SYabin Cui         memset(&sequence, 0, sizeof(sequence));
3152*01826a49SYabin Cui         seqState.dumps = dumps;
3153*01826a49SYabin Cui         seqState.dumpsEnd = dumps + dumpsLength;
3154*01826a49SYabin Cui         seqState.prevOffset = 1;
3155*01826a49SYabin Cui         errorCode = BIT_initDStream(&(seqState.DStream), ip, iend-ip);
3156*01826a49SYabin Cui         if (ERR_isError(errorCode)) return ERROR(corruption_detected);
3157*01826a49SYabin Cui         FSE_initDState(&(seqState.stateLL), &(seqState.DStream), DTableLL);
3158*01826a49SYabin Cui         FSE_initDState(&(seqState.stateOffb), &(seqState.DStream), DTableOffb);
3159*01826a49SYabin Cui         FSE_initDState(&(seqState.stateML), &(seqState.DStream), DTableML);
3160*01826a49SYabin Cui 
3161*01826a49SYabin Cui         for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (nbSeq>0) ; )
3162*01826a49SYabin Cui         {
3163*01826a49SYabin Cui             size_t oneSeqSize;
3164*01826a49SYabin Cui             nbSeq--;
3165*01826a49SYabin Cui             ZSTD_decodeSequence(&sequence, &seqState);
3166*01826a49SYabin Cui             oneSeqSize = ZSTD_execSequence(op, sequence, &litPtr, litEnd, base, oend);
3167*01826a49SYabin Cui             if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
3168*01826a49SYabin Cui             op += oneSeqSize;
3169*01826a49SYabin Cui         }
3170*01826a49SYabin Cui 
3171*01826a49SYabin Cui         /* check if reached exact end */
3172*01826a49SYabin Cui         if ( !BIT_endOfDStream(&(seqState.DStream)) ) return ERROR(corruption_detected);   /* requested too much : data is corrupted */
3173*01826a49SYabin Cui         if (nbSeq<0) return ERROR(corruption_detected);   /* requested too many sequences : data is corrupted */
3174*01826a49SYabin Cui 
3175*01826a49SYabin Cui         /* last literal segment */
3176*01826a49SYabin Cui         {
3177*01826a49SYabin Cui             size_t lastLLSize = litEnd - litPtr;
3178*01826a49SYabin Cui             if (litPtr > litEnd) return ERROR(corruption_detected);
3179*01826a49SYabin Cui             if (op+lastLLSize > oend) return ERROR(dstSize_tooSmall);
3180*01826a49SYabin Cui             if (lastLLSize > 0) {
3181*01826a49SYabin Cui                 if (op != litPtr) memmove(op, litPtr, lastLLSize);
3182*01826a49SYabin Cui                 op += lastLLSize;
3183*01826a49SYabin Cui             }
3184*01826a49SYabin Cui         }
3185*01826a49SYabin Cui     }
3186*01826a49SYabin Cui 
3187*01826a49SYabin Cui     return op-ostart;
3188*01826a49SYabin Cui }
3189*01826a49SYabin Cui 
3190*01826a49SYabin Cui 
ZSTD_decompressBlock(void * ctx,void * dst,size_t maxDstSize,const void * src,size_t srcSize)3191*01826a49SYabin Cui static size_t ZSTD_decompressBlock(
3192*01826a49SYabin Cui                             void* ctx,
3193*01826a49SYabin Cui                             void* dst, size_t maxDstSize,
3194*01826a49SYabin Cui                       const void* src, size_t srcSize)
3195*01826a49SYabin Cui {
3196*01826a49SYabin Cui     /* blockType == blockCompressed */
3197*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
3198*01826a49SYabin Cui 
3199*01826a49SYabin Cui     /* Decode literals sub-block */
3200*01826a49SYabin Cui     size_t litCSize = ZSTD_decodeLiteralsBlock(ctx, src, srcSize);
3201*01826a49SYabin Cui     if (ZSTD_isError(litCSize)) return litCSize;
3202*01826a49SYabin Cui     ip += litCSize;
3203*01826a49SYabin Cui     srcSize -= litCSize;
3204*01826a49SYabin Cui 
3205*01826a49SYabin Cui     return ZSTD_decompressSequences(ctx, dst, maxDstSize, ip, srcSize);
3206*01826a49SYabin Cui }
3207*01826a49SYabin Cui 
3208*01826a49SYabin Cui 
ZSTD_decompressDCtx(void * ctx,void * dst,size_t maxDstSize,const void * src,size_t srcSize)3209*01826a49SYabin Cui static size_t ZSTD_decompressDCtx(void* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
3210*01826a49SYabin Cui {
3211*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
3212*01826a49SYabin Cui     const BYTE* iend = ip + srcSize;
3213*01826a49SYabin Cui     BYTE* const ostart = (BYTE* const)dst;
3214*01826a49SYabin Cui     BYTE* op = ostart;
3215*01826a49SYabin Cui     BYTE* const oend = ostart + maxDstSize;
3216*01826a49SYabin Cui     size_t remainingSize = srcSize;
3217*01826a49SYabin Cui     U32 magicNumber;
3218*01826a49SYabin Cui     blockProperties_t blockProperties;
3219*01826a49SYabin Cui 
3220*01826a49SYabin Cui     /* Frame Header */
3221*01826a49SYabin Cui     if (srcSize < ZSTD_frameHeaderSize+ZSTD_blockHeaderSize) return ERROR(srcSize_wrong);
3222*01826a49SYabin Cui     magicNumber = MEM_readLE32(src);
3223*01826a49SYabin Cui     if (magicNumber != ZSTD_magicNumber) return ERROR(prefix_unknown);
3224*01826a49SYabin Cui     ip += ZSTD_frameHeaderSize; remainingSize -= ZSTD_frameHeaderSize;
3225*01826a49SYabin Cui 
3226*01826a49SYabin Cui     /* Loop on each block */
3227*01826a49SYabin Cui     while (1)
3228*01826a49SYabin Cui     {
3229*01826a49SYabin Cui         size_t decodedSize=0;
3230*01826a49SYabin Cui         size_t cBlockSize = ZSTD_getcBlockSize(ip, iend-ip, &blockProperties);
3231*01826a49SYabin Cui         if (ZSTD_isError(cBlockSize)) return cBlockSize;
3232*01826a49SYabin Cui 
3233*01826a49SYabin Cui         ip += ZSTD_blockHeaderSize;
3234*01826a49SYabin Cui         remainingSize -= ZSTD_blockHeaderSize;
3235*01826a49SYabin Cui         if (cBlockSize > remainingSize) return ERROR(srcSize_wrong);
3236*01826a49SYabin Cui 
3237*01826a49SYabin Cui         switch(blockProperties.blockType)
3238*01826a49SYabin Cui         {
3239*01826a49SYabin Cui         case bt_compressed:
3240*01826a49SYabin Cui             decodedSize = ZSTD_decompressBlock(ctx, op, oend-op, ip, cBlockSize);
3241*01826a49SYabin Cui             break;
3242*01826a49SYabin Cui         case bt_raw :
3243*01826a49SYabin Cui             decodedSize = ZSTD_copyUncompressedBlock(op, oend-op, ip, cBlockSize);
3244*01826a49SYabin Cui             break;
3245*01826a49SYabin Cui         case bt_rle :
3246*01826a49SYabin Cui             return ERROR(GENERIC);   /* not yet supported */
3247*01826a49SYabin Cui             break;
3248*01826a49SYabin Cui         case bt_end :
3249*01826a49SYabin Cui             /* end of frame */
3250*01826a49SYabin Cui             if (remainingSize) return ERROR(srcSize_wrong);
3251*01826a49SYabin Cui             break;
3252*01826a49SYabin Cui         default:
3253*01826a49SYabin Cui             return ERROR(GENERIC);   /* impossible */
3254*01826a49SYabin Cui         }
3255*01826a49SYabin Cui         if (cBlockSize == 0) break;   /* bt_end */
3256*01826a49SYabin Cui 
3257*01826a49SYabin Cui         if (ZSTD_isError(decodedSize)) return decodedSize;
3258*01826a49SYabin Cui         op += decodedSize;
3259*01826a49SYabin Cui         ip += cBlockSize;
3260*01826a49SYabin Cui         remainingSize -= cBlockSize;
3261*01826a49SYabin Cui     }
3262*01826a49SYabin Cui 
3263*01826a49SYabin Cui     return op-ostart;
3264*01826a49SYabin Cui }
3265*01826a49SYabin Cui 
ZSTD_decompress(void * dst,size_t maxDstSize,const void * src,size_t srcSize)3266*01826a49SYabin Cui static size_t ZSTD_decompress(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
3267*01826a49SYabin Cui {
3268*01826a49SYabin Cui     ZSTD_DCtx ctx;
3269*01826a49SYabin Cui     ctx.base = dst;
3270*01826a49SYabin Cui     return ZSTD_decompressDCtx(&ctx, dst, maxDstSize, src, srcSize);
3271*01826a49SYabin Cui }
3272*01826a49SYabin Cui 
3273*01826a49SYabin Cui /* ZSTD_errorFrameSizeInfoLegacy() :
3274*01826a49SYabin Cui    assumes `cSize` and `dBound` are _not_ NULL */
ZSTD_errorFrameSizeInfoLegacy(size_t * cSize,unsigned long long * dBound,size_t ret)3275*01826a49SYabin Cui static void ZSTD_errorFrameSizeInfoLegacy(size_t* cSize, unsigned long long* dBound, size_t ret)
3276*01826a49SYabin Cui {
3277*01826a49SYabin Cui     *cSize = ret;
3278*01826a49SYabin Cui     *dBound = ZSTD_CONTENTSIZE_ERROR;
3279*01826a49SYabin Cui }
3280*01826a49SYabin Cui 
ZSTDv02_findFrameSizeInfoLegacy(const void * src,size_t srcSize,size_t * cSize,unsigned long long * dBound)3281*01826a49SYabin Cui void ZSTDv02_findFrameSizeInfoLegacy(const void *src, size_t srcSize, size_t* cSize, unsigned long long* dBound)
3282*01826a49SYabin Cui {
3283*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
3284*01826a49SYabin Cui     size_t remainingSize = srcSize;
3285*01826a49SYabin Cui     size_t nbBlocks = 0;
3286*01826a49SYabin Cui     U32 magicNumber;
3287*01826a49SYabin Cui     blockProperties_t blockProperties;
3288*01826a49SYabin Cui 
3289*01826a49SYabin Cui     /* Frame Header */
3290*01826a49SYabin Cui     if (srcSize < ZSTD_frameHeaderSize+ZSTD_blockHeaderSize) {
3291*01826a49SYabin Cui         ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
3292*01826a49SYabin Cui         return;
3293*01826a49SYabin Cui     }
3294*01826a49SYabin Cui     magicNumber = MEM_readLE32(src);
3295*01826a49SYabin Cui     if (magicNumber != ZSTD_magicNumber) {
3296*01826a49SYabin Cui         ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(prefix_unknown));
3297*01826a49SYabin Cui         return;
3298*01826a49SYabin Cui     }
3299*01826a49SYabin Cui     ip += ZSTD_frameHeaderSize; remainingSize -= ZSTD_frameHeaderSize;
3300*01826a49SYabin Cui 
3301*01826a49SYabin Cui     /* Loop on each block */
3302*01826a49SYabin Cui     while (1)
3303*01826a49SYabin Cui     {
3304*01826a49SYabin Cui         size_t cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
3305*01826a49SYabin Cui         if (ZSTD_isError(cBlockSize)) {
3306*01826a49SYabin Cui             ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, cBlockSize);
3307*01826a49SYabin Cui             return;
3308*01826a49SYabin Cui         }
3309*01826a49SYabin Cui 
3310*01826a49SYabin Cui         ip += ZSTD_blockHeaderSize;
3311*01826a49SYabin Cui         remainingSize -= ZSTD_blockHeaderSize;
3312*01826a49SYabin Cui         if (cBlockSize > remainingSize) {
3313*01826a49SYabin Cui             ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
3314*01826a49SYabin Cui             return;
3315*01826a49SYabin Cui         }
3316*01826a49SYabin Cui 
3317*01826a49SYabin Cui         if (cBlockSize == 0) break;   /* bt_end */
3318*01826a49SYabin Cui 
3319*01826a49SYabin Cui         ip += cBlockSize;
3320*01826a49SYabin Cui         remainingSize -= cBlockSize;
3321*01826a49SYabin Cui         nbBlocks++;
3322*01826a49SYabin Cui     }
3323*01826a49SYabin Cui 
3324*01826a49SYabin Cui     *cSize = ip - (const BYTE*)src;
3325*01826a49SYabin Cui     *dBound = nbBlocks * BLOCKSIZE;
3326*01826a49SYabin Cui }
3327*01826a49SYabin Cui 
3328*01826a49SYabin Cui /*******************************
3329*01826a49SYabin Cui *  Streaming Decompression API
3330*01826a49SYabin Cui *******************************/
3331*01826a49SYabin Cui 
ZSTD_resetDCtx(ZSTD_DCtx * dctx)3332*01826a49SYabin Cui static size_t ZSTD_resetDCtx(ZSTD_DCtx* dctx)
3333*01826a49SYabin Cui {
3334*01826a49SYabin Cui     dctx->expected = ZSTD_frameHeaderSize;
3335*01826a49SYabin Cui     dctx->phase = 0;
3336*01826a49SYabin Cui     dctx->previousDstEnd = NULL;
3337*01826a49SYabin Cui     dctx->base = NULL;
3338*01826a49SYabin Cui     return 0;
3339*01826a49SYabin Cui }
3340*01826a49SYabin Cui 
ZSTD_createDCtx(void)3341*01826a49SYabin Cui static ZSTD_DCtx* ZSTD_createDCtx(void)
3342*01826a49SYabin Cui {
3343*01826a49SYabin Cui     ZSTD_DCtx* dctx = (ZSTD_DCtx*)malloc(sizeof(ZSTD_DCtx));
3344*01826a49SYabin Cui     if (dctx==NULL) return NULL;
3345*01826a49SYabin Cui     ZSTD_resetDCtx(dctx);
3346*01826a49SYabin Cui     return dctx;
3347*01826a49SYabin Cui }
3348*01826a49SYabin Cui 
ZSTD_freeDCtx(ZSTD_DCtx * dctx)3349*01826a49SYabin Cui static size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
3350*01826a49SYabin Cui {
3351*01826a49SYabin Cui     free(dctx);
3352*01826a49SYabin Cui     return 0;
3353*01826a49SYabin Cui }
3354*01826a49SYabin Cui 
ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx * dctx)3355*01826a49SYabin Cui static size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx)
3356*01826a49SYabin Cui {
3357*01826a49SYabin Cui     return dctx->expected;
3358*01826a49SYabin Cui }
3359*01826a49SYabin Cui 
ZSTD_decompressContinue(ZSTD_DCtx * ctx,void * dst,size_t maxDstSize,const void * src,size_t srcSize)3360*01826a49SYabin Cui static size_t ZSTD_decompressContinue(ZSTD_DCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
3361*01826a49SYabin Cui {
3362*01826a49SYabin Cui     /* Sanity check */
3363*01826a49SYabin Cui     if (srcSize != ctx->expected) return ERROR(srcSize_wrong);
3364*01826a49SYabin Cui     if (dst != ctx->previousDstEnd)  /* not contiguous */
3365*01826a49SYabin Cui         ctx->base = dst;
3366*01826a49SYabin Cui 
3367*01826a49SYabin Cui     /* Decompress : frame header */
3368*01826a49SYabin Cui     if (ctx->phase == 0)
3369*01826a49SYabin Cui     {
3370*01826a49SYabin Cui         /* Check frame magic header */
3371*01826a49SYabin Cui         U32 magicNumber = MEM_readLE32(src);
3372*01826a49SYabin Cui         if (magicNumber != ZSTD_magicNumber) return ERROR(prefix_unknown);
3373*01826a49SYabin Cui         ctx->phase = 1;
3374*01826a49SYabin Cui         ctx->expected = ZSTD_blockHeaderSize;
3375*01826a49SYabin Cui         return 0;
3376*01826a49SYabin Cui     }
3377*01826a49SYabin Cui 
3378*01826a49SYabin Cui     /* Decompress : block header */
3379*01826a49SYabin Cui     if (ctx->phase == 1)
3380*01826a49SYabin Cui     {
3381*01826a49SYabin Cui         blockProperties_t bp;
3382*01826a49SYabin Cui         size_t blockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
3383*01826a49SYabin Cui         if (ZSTD_isError(blockSize)) return blockSize;
3384*01826a49SYabin Cui         if (bp.blockType == bt_end)
3385*01826a49SYabin Cui         {
3386*01826a49SYabin Cui             ctx->expected = 0;
3387*01826a49SYabin Cui             ctx->phase = 0;
3388*01826a49SYabin Cui         }
3389*01826a49SYabin Cui         else
3390*01826a49SYabin Cui         {
3391*01826a49SYabin Cui             ctx->expected = blockSize;
3392*01826a49SYabin Cui             ctx->bType = bp.blockType;
3393*01826a49SYabin Cui             ctx->phase = 2;
3394*01826a49SYabin Cui         }
3395*01826a49SYabin Cui 
3396*01826a49SYabin Cui         return 0;
3397*01826a49SYabin Cui     }
3398*01826a49SYabin Cui 
3399*01826a49SYabin Cui     /* Decompress : block content */
3400*01826a49SYabin Cui     {
3401*01826a49SYabin Cui         size_t rSize;
3402*01826a49SYabin Cui         switch(ctx->bType)
3403*01826a49SYabin Cui         {
3404*01826a49SYabin Cui         case bt_compressed:
3405*01826a49SYabin Cui             rSize = ZSTD_decompressBlock(ctx, dst, maxDstSize, src, srcSize);
3406*01826a49SYabin Cui             break;
3407*01826a49SYabin Cui         case bt_raw :
3408*01826a49SYabin Cui             rSize = ZSTD_copyUncompressedBlock(dst, maxDstSize, src, srcSize);
3409*01826a49SYabin Cui             break;
3410*01826a49SYabin Cui         case bt_rle :
3411*01826a49SYabin Cui             return ERROR(GENERIC);   /* not yet handled */
3412*01826a49SYabin Cui             break;
3413*01826a49SYabin Cui         case bt_end :   /* should never happen (filtered at phase 1) */
3414*01826a49SYabin Cui             rSize = 0;
3415*01826a49SYabin Cui             break;
3416*01826a49SYabin Cui         default:
3417*01826a49SYabin Cui             return ERROR(GENERIC);
3418*01826a49SYabin Cui         }
3419*01826a49SYabin Cui         ctx->phase = 1;
3420*01826a49SYabin Cui         ctx->expected = ZSTD_blockHeaderSize;
3421*01826a49SYabin Cui         if (ZSTD_isError(rSize)) return rSize;
3422*01826a49SYabin Cui         ctx->previousDstEnd = (void*)( ((char*)dst) + rSize);
3423*01826a49SYabin Cui         return rSize;
3424*01826a49SYabin Cui     }
3425*01826a49SYabin Cui 
3426*01826a49SYabin Cui }
3427*01826a49SYabin Cui 
3428*01826a49SYabin Cui 
3429*01826a49SYabin Cui /* wrapper layer */
3430*01826a49SYabin Cui 
ZSTDv02_isError(size_t code)3431*01826a49SYabin Cui unsigned ZSTDv02_isError(size_t code)
3432*01826a49SYabin Cui {
3433*01826a49SYabin Cui     return ZSTD_isError(code);
3434*01826a49SYabin Cui }
3435*01826a49SYabin Cui 
ZSTDv02_decompress(void * dst,size_t maxOriginalSize,const void * src,size_t compressedSize)3436*01826a49SYabin Cui size_t ZSTDv02_decompress( void* dst, size_t maxOriginalSize,
3437*01826a49SYabin Cui                      const void* src, size_t compressedSize)
3438*01826a49SYabin Cui {
3439*01826a49SYabin Cui     return ZSTD_decompress(dst, maxOriginalSize, src, compressedSize);
3440*01826a49SYabin Cui }
3441*01826a49SYabin Cui 
ZSTDv02_createDCtx(void)3442*01826a49SYabin Cui ZSTDv02_Dctx* ZSTDv02_createDCtx(void)
3443*01826a49SYabin Cui {
3444*01826a49SYabin Cui     return (ZSTDv02_Dctx*)ZSTD_createDCtx();
3445*01826a49SYabin Cui }
3446*01826a49SYabin Cui 
ZSTDv02_freeDCtx(ZSTDv02_Dctx * dctx)3447*01826a49SYabin Cui size_t ZSTDv02_freeDCtx(ZSTDv02_Dctx* dctx)
3448*01826a49SYabin Cui {
3449*01826a49SYabin Cui     return ZSTD_freeDCtx((ZSTD_DCtx*)dctx);
3450*01826a49SYabin Cui }
3451*01826a49SYabin Cui 
ZSTDv02_resetDCtx(ZSTDv02_Dctx * dctx)3452*01826a49SYabin Cui size_t ZSTDv02_resetDCtx(ZSTDv02_Dctx* dctx)
3453*01826a49SYabin Cui {
3454*01826a49SYabin Cui     return ZSTD_resetDCtx((ZSTD_DCtx*)dctx);
3455*01826a49SYabin Cui }
3456*01826a49SYabin Cui 
ZSTDv02_nextSrcSizeToDecompress(ZSTDv02_Dctx * dctx)3457*01826a49SYabin Cui size_t ZSTDv02_nextSrcSizeToDecompress(ZSTDv02_Dctx* dctx)
3458*01826a49SYabin Cui {
3459*01826a49SYabin Cui     return ZSTD_nextSrcSizeToDecompress((ZSTD_DCtx*)dctx);
3460*01826a49SYabin Cui }
3461*01826a49SYabin Cui 
ZSTDv02_decompressContinue(ZSTDv02_Dctx * dctx,void * dst,size_t maxDstSize,const void * src,size_t srcSize)3462*01826a49SYabin Cui size_t ZSTDv02_decompressContinue(ZSTDv02_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
3463*01826a49SYabin Cui {
3464*01826a49SYabin Cui     return ZSTD_decompressContinue((ZSTD_DCtx*)dctx, dst, maxDstSize, src, srcSize);
3465*01826a49SYabin Cui }
3466