Coverage Report

Created: 2026-11-20 06:49

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