Coverage Report

Created: 2026-02-26 07:13

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