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