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