Coverage Report

Created: 2026-12-01 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/lz4/lib/lz4hc.c
Line
Count
Source
1
/*
2
    LZ4 HC - High Compression Mode of LZ4
3
    Copyright (c) Yann Collet. All rights reserved.
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
       - LZ4 source repository : https://github.com/lz4/lz4
32
       - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
33
*/
34
/* note : lz4hc is not an independent module, it requires lz4.h/lz4.c for proper compilation */
35
36
37
/* *************************************
38
*  Tuning Parameter
39
***************************************/
40
41
/*! HEAPMODE :
42
 *  Select how stateless HC compression functions like `LZ4_compress_HC()`
43
 *  allocate memory for their workspace:
44
 *  in stack (0:fastest), or in heap (1:default, requires malloc()).
45
 *  Since workspace is rather large, heap mode is recommended.
46
 *  Stack mode is the default when there is no allocator
47
 *  (LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION without LZ4_USER_MEMORY_FUNCTIONS, see lz4.c).
48
**/
49
#ifndef LZ4HC_HEAPMODE
50
#  if defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) && !defined(LZ4_USER_MEMORY_FUNCTIONS)
51
#    define LZ4HC_HEAPMODE 0
52
#  else
53
#    define LZ4HC_HEAPMODE 1
54
#  endif
55
#endif
56
57
58
/*===    Dependency    ===*/
59
#ifndef LZ4_DISABLE_DEPRECATE_WARNINGS
60
#  define LZ4_DISABLE_DEPRECATE_WARNINGS   /* LZ4_createHC() invokes LZ4_createStreamHC() */
61
#endif
62
#define LZ4_HC_STATIC_LINKING_ONLY
63
#include "lz4hc.h"
64
#include <limits.h>
65
66
67
/*===   Shared lz4.c code   ===*/
68
#ifndef LZ4_SRC_INCLUDED
69
# if defined(__GNUC__)
70
#  pragma GCC diagnostic ignored "-Wunused-function"
71
# endif
72
# if defined (__clang__)
73
#  pragma clang diagnostic ignored "-Wunused-function"
74
# endif
75
# define LZ4_COMMONDEFS_ONLY
76
# include "lz4.c"   /* LZ4_count, constants, mem */
77
#endif
78
79
80
/*===   Enums   ===*/
81
typedef enum { noDictCtx, usingDictCtxHc } dictCtx_directive;
82
83
84
/*===   Constants   ===*/
85
0
#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)
86
0
#define LZ4_OPT_NUM   (1<<12)
87
88
89
/*===   Macros   ===*/
90
#undef MIN
91
0
#define MIN(a,b)   ( (a) < (b) ? (a) : (b) )
92
#undef MAX
93
0
#define MAX(a,b)   ( (a) > (b) ? (a) : (b) )
94
95
96
/*===   Levels definition   ===*/
97
typedef enum { lz4mid, lz4hc, lz4opt } lz4hc_strat_e;
98
typedef struct {
99
    lz4hc_strat_e strat;
100
    int nbSearches;
101
    U32 targetLength;
102
    int nbSearchesSeq;   /* lz4opt with favorDecSpeed only : budget at positions only worth searching to save a sequence */
103
    int dictCopyMin;     /* attached dictionary : from this input size, its tables (256 KB) are copied rather than referenced (dictCtx),
104
                          * which compresses as well or better, and pays off sooner at levels which search more */
105
} cParams_t;
106
static const cParams_t k_clTable[LZ4HC_CLEVEL_MAX+1] = {
107
    { lz4mid,    2, 16,  0, 4 KB },  /* 0, unused */
108
    { lz4mid,    2, 16,  0, 4 KB },  /* 1, unused */
109
    { lz4mid,    2, 16,  0, 4 KB },  /* 2 */
110
    { lz4hc,     4, 16,  0, 4 KB },  /* 3 */
111
    { lz4hc,     8, 16,  0, 4 KB },  /* 4 */
112
    { lz4hc,    16, 16,  0, 4 KB },  /* 5 */
113
    { lz4hc,    32, 16,  0, 4 KB },  /* 6 */
114
    { lz4hc,    64, 16,  0, 4 KB },  /* 7 */
115
    { lz4hc,   128, 16,  0, 4 KB },  /* 8 */
116
    { lz4hc,   256, 16,  0, 4 KB },  /* 9 */
117
    { lz4opt,   96, 64,  1, 4 KB },  /*10==LZ4HC_CLEVEL_OPT_MIN*/
118
    { lz4opt,  512,128,  2, 2 KB },  /*11 */
119
    { lz4opt,16384,LZ4_OPT_NUM, 64, 1 KB },  /* 12==LZ4HC_CLEVEL_MAX */
120
};
121
122
static cParams_t LZ4HC_getCLevelParams(int cLevel)
123
0
{
124
    /* note : clevel convention is a bit different from lz4frame,
125
     * possibly something worth revisiting for consistency */
126
0
    if (cLevel < 1)
127
0
        cLevel = LZ4HC_CLEVEL_DEFAULT;
128
0
    cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel);
129
0
    return k_clTable[cLevel];
130
0
}
131
132
133
/*===   Hashing   ===*/
134
0
#define LZ4HC_HASHSIZE 4
135
0
#define HASH_FUNCTION(i)      (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG))
136
0
static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }
137
138
#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
139
/* lie to the compiler about data alignment; use with caution */
140
static U64 LZ4_read64(const void* memPtr) { return *(const U64*) memPtr; }
141
142
#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
143
/* __pack instructions are safer, but compiler specific */
144
LZ4_PACK(typedef struct { U64 u64; }) LZ4_unalign64;
145
0
static U64 LZ4_read64(const void* ptr) { return ((const LZ4_unalign64*)ptr)->u64; }
146
147
#else  /* safe and portable access using memcpy() */
148
static U64 LZ4_read64(const void* memPtr)
149
{
150
    U64 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;
151
}
152
153
#endif /* LZ4_FORCE_MEMORY_ACCESS */
154
155
0
#define LZ4MID_HASHSIZE 8
156
0
#define LZ4MID_HASHLOG (LZ4HC_HASH_LOG-1)
157
0
#define LZ4MID_HASHTABLESIZE (1 << LZ4MID_HASHLOG)
158
159
0
static U32 LZ4MID_hash4(U32 v) { return (v * 2654435761U) >> (32-LZ4MID_HASHLOG); }
160
0
static U32 LZ4MID_hash4Ptr(const void* ptr) { return LZ4MID_hash4(LZ4_read32(ptr)); }
161
/* note: hash7 hashes the lower 56-bits.
162
 * It presumes input was read using little endian.*/
163
0
static U32 LZ4MID_hash7(U64 v) { return (U32)(((v  << (64-56)) * 58295818150454627ULL) >> (64-LZ4MID_HASHLOG)) ; }
164
static U64 LZ4_readLE64(const void* memPtr);
165
0
static U32 LZ4MID_hash8Ptr(const void* ptr) { return LZ4MID_hash7(LZ4_readLE64(ptr)); }
166
167
static U64 LZ4_readLE64(const void* memPtr)
168
0
{
169
0
    if (LZ4_isLittleEndian()) {
170
0
        return LZ4_read64(memPtr);
171
0
    } else {
172
0
        const BYTE* p = (const BYTE*)memPtr;
173
        /* note: relies on the compiler to simplify this expression */
174
0
        return (U64)p[0] | ((U64)p[1]<<8) | ((U64)p[2]<<16) | ((U64)p[3]<<24)
175
0
            | ((U64)p[4]<<32) | ((U64)p[5]<<40) | ((U64)p[6]<<48) | ((U64)p[7]<<56);
176
0
    }
177
0
}
178
179
180
/*===   Count match length   ===*/
181
LZ4_FORCE_INLINE
182
unsigned LZ4HC_NbCommonBytes32(U32 val)
183
0
{
184
0
    assert(val != 0);
185
0
    if (LZ4_isLittleEndian()) {
186
#     if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT)
187
        unsigned long r;
188
        _BitScanReverse(&r, val);
189
        return (unsigned)((31 - r) >> 3);
190
#     elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
191
                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
192
                                        !defined(LZ4_FORCE_SW_BITCOUNT)
193
        return (unsigned)__builtin_clz(val) >> 3;
194
#     else
195
        val >>= 8;
196
        val = ((((val + 0x00FFFF00) | 0x00FFFFFF) + val) |
197
              (val + 0x00FF0000)) >> 24;
198
        return (unsigned)val ^ 3;
199
#     endif
200
0
    } else {
201
#     if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT)
202
        unsigned long r;
203
        _BitScanForward(&r, val);
204
        return (unsigned)(r >> 3);
205
#     elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
206
                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
207
                                        !defined(LZ4_FORCE_SW_BITCOUNT)
208
        return (unsigned)__builtin_ctz(val) >> 3;
209
#     else
210
        const U32 m = 0x01010101;
211
        return (unsigned)((((val - 1) ^ val) & (m - 1)) * m) >> 24;
212
#     endif
213
0
    }
214
0
}
215
216
/** LZ4HC_countBack() :
217
 * @return : negative value, nb of common bytes before ip/match */
218
LZ4_FORCE_INLINE
219
int LZ4HC_countBack(const BYTE* const ip, const BYTE* const match,
220
                    const BYTE* const iMin, const BYTE* const mMin)
221
0
{
222
0
    int back = 0;
223
0
    int const min = (int)MAX(iMin - ip, mMin - match);
224
0
    assert(min <= 0);
225
0
    assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31));
226
0
    assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31));
227
228
0
    while ((back - min) > 3) {
229
0
        U32 const v = LZ4_read32(ip + back - 4) ^ LZ4_read32(match + back - 4);
230
0
        if (v) {
231
0
            return (back - (int)LZ4HC_NbCommonBytes32(v));
232
0
        } else back -= 4; /* 4-byte step */
233
0
    }
234
    /* check remainder if any */
235
0
    while ( (back > min)
236
0
         && (ip[back-1] == match[back-1]) )
237
0
            back--;
238
0
    return back;
239
0
}
240
241
/*===   Chain table updates   ===*/
242
0
#define DELTANEXTU16(table, pos) table[(U16)(pos)]   /* faster */
243
/* Make fields passed to, and updated by LZ4HC_encodeSequence explicit */
244
0
#define UPDATABLE(ip, op, anchor) &ip, &op, &anchor
245
246
247
/**************************************
248
*  Init
249
**************************************/
250
static void LZ4HC_clearTables (LZ4HC_CCtx_internal* hc4)
251
0
{
252
0
    MEM_INIT(hc4->hashTable, 0, sizeof(hc4->hashTable));
253
0
    MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable));
254
0
}
255
256
static void LZ4HC_init_internal (LZ4HC_CCtx_internal* hc4, const BYTE* start)
257
0
{
258
0
    size_t const bufferSize = (size_t)(hc4->end - hc4->prefixStart);
259
0
    size_t newStartingOffset = bufferSize + hc4->dictLimit;
260
0
    DEBUGLOG(5, "LZ4HC_init_internal");
261
0
    assert(newStartingOffset >= bufferSize);  /* check overflow */
262
0
    if (newStartingOffset > 1 GB) {
263
0
        LZ4HC_clearTables(hc4);
264
0
        newStartingOffset = 0;
265
0
    }
266
0
    newStartingOffset += 64 KB;
267
0
    hc4->nextToUpdate = (U32)newStartingOffset;
268
0
    hc4->prefixStart = start;
269
0
    hc4->end = start;
270
0
    hc4->dictStart = start;
271
0
    hc4->dictLimit = (U32)newStartingOffset;
272
0
    hc4->lowLimit = (U32)newStartingOffset;
273
0
}
274
275
276
/**************************************
277
*  Encode
278
**************************************/
279
#if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 2)
280
# define RAWLOG(...) fprintf(stderr, __VA_ARGS__)
281
void LZ4HC_hexOut(const void* src, size_t len)
282
{
283
    const BYTE* p = (const BYTE*)src;
284
    size_t n;
285
    for (n=0; n<len; n++) {
286
        RAWLOG("%02X ", p[n]);
287
    }
288
    RAWLOG(" \n");
289
}
290
291
# define HEX_CMP(_lev, _ptr, _ref, _len) \
292
    if (LZ4_DEBUG >= _lev) {            \
293
        RAWLOG("match bytes: ");        \
294
        LZ4HC_hexOut(_ptr, _len);       \
295
        RAWLOG("ref bytes: ");          \
296
        LZ4HC_hexOut(_ref, _len);       \
297
    }
298
299
#else
300
# define HEX_CMP(l,p,r,_l)
301
#endif
302
303
/* LZ4HC_encodeSequence() :
304
 * @return : 0 if ok,
305
 *           1 if buffer issue detected : @ip, @op and @anchor are then unchanged */
306
LZ4_FORCE_INLINE int LZ4HC_encodeSequence (
307
    const BYTE** _ip,
308
    BYTE** _op,
309
    const BYTE** _anchor,
310
    int matchLength,
311
    int offset,
312
    limitedOutput_directive limit,
313
    BYTE* oend)
314
0
{
315
0
#define ip      (*_ip)
316
0
#define op      (*_op)
317
0
#define anchor  (*_anchor)
318
319
0
    BYTE* const token = op++;
320
321
#if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 6)
322
    static const BYTE* start = NULL;
323
    static U32 totalCost = 0;
324
    U32 const pos = (start==NULL) ? 0 : (U32)(anchor - start); /* only works for single segment */
325
    U32 const ll = (U32)(ip - anchor);
326
    U32 const llAdd = (ll>=15) ? ((ll-15) / 255) + 1 : 0;
327
    U32 const mlAdd = (matchLength>=19) ? ((matchLength-19) / 255) + 1 : 0;
328
    U32 const cost = 1 + llAdd + ll + 2 + mlAdd;
329
    if (start==NULL) start = anchor;  /* only works for single segment */
330
    DEBUGLOG(6, "pos:%7u -- literals:%4u, match:%4i, offset:%5i, cost:%4u + %5u",
331
                pos,
332
                (U32)(ip - anchor), matchLength, offset,
333
                cost, totalCost);
334
# if 1 /* only works on single segment data */
335
    HEX_CMP(7, ip, ip-offset, matchLength);
336
# endif
337
    totalCost += cost;
338
#endif
339
340
    /* Encode Literal length */
341
0
    {   size_t litLen = (size_t)(ip - anchor);
342
0
        LZ4_STATIC_ASSERT(notLimited == 0);
343
        /* Check output limit : compares sizes, as op + size could exceed the address space (32-bit).
344
         * Signed : in fillOutput mode, oend precedes op when dst is too small for any sequence */
345
0
        if (limit && (oend - op < (ptrdiff_t)((litLen / 255) + litLen + (2 + 1 + LASTLITERALS)))) {
346
0
            DEBUGLOG(6, "Not enough room to write %i literals (%i bytes remaining)",
347
0
                    (int)litLen, (int)(oend - op));
348
0
            op = token;
349
0
            return 1;
350
0
        }
351
0
        if (litLen >= RUN_MASK) {
352
0
            size_t len = litLen - RUN_MASK;
353
0
            *token = (RUN_MASK << ML_BITS);
354
0
            for(; len >= 255 ; len -= 255) *op++ = 255;
355
0
            *op++ = (BYTE)len;
356
0
        } else {
357
0
            *token = (BYTE)(litLen << ML_BITS);
358
0
        }
359
360
        /* Copy Literals */
361
0
        LZ4_wildCopy8(op, anchor, op + litLen);
362
0
        op += litLen;
363
0
    }
364
365
    /* Encode Offset */
366
0
    assert(offset <= LZ4_DISTANCE_MAX );
367
0
    assert(offset > 0);
368
0
    LZ4_writeLE16(op, (U16)(offset)); op += 2;
369
370
    /* Encode MatchLength */
371
0
    assert(matchLength >= MINMATCH);
372
0
    {   size_t mlCode = (size_t)matchLength - MINMATCH;
373
0
        if (limit && (oend - op < (ptrdiff_t)((mlCode / 255) + (1 + LASTLITERALS)))) {
374
0
            DEBUGLOG(6, "Not enough room to write match length");
375
0
            op = token;
376
0
            return 1;
377
0
        }
378
0
        if (mlCode >= ML_MASK) {
379
0
            *token += ML_MASK;
380
0
            mlCode -= ML_MASK;
381
0
            for(; mlCode >= 510 ; mlCode -= 510) { *op++ = 255; *op++ = 255; }
382
0
            if (mlCode >= 255) { mlCode -= 255; *op++ = 255; }
383
0
            *op++ = (BYTE)mlCode;
384
0
        } else {
385
0
            *token += (BYTE)(mlCode);
386
0
    }   }
387
388
    /* Prepare next loop */
389
0
    ip += matchLength;
390
0
    anchor = ip;
391
392
0
    return 0;
393
394
0
#undef ip
395
0
#undef op
396
0
#undef anchor
397
0
}
398
399
/* LZ4HC_encodeLastLiterals() :
400
 * Encode the final run of literals, from @anchor to @iend.
401
 * In fillOutput mode, the run may be truncated, to fit into dst.
402
 * @oend : same as LZ4HC_encodeSequence() : end of dst, minus LASTLITERALS in fillOutput mode
403
 * @return : 0 if ok,
404
 *           1 if dst is too small (limitedOutput) */
405
static int LZ4HC_encodeLastLiterals (
406
    const BYTE** _ip,
407
    BYTE** _op,
408
    const BYTE** _anchor,
409
    const BYTE* iend,
410
    limitedOutput_directive limit,
411
    BYTE* oend)
412
0
{
413
0
#define ip      (*_ip)
414
0
#define op      (*_op)
415
0
#define anchor  (*_anchor)
416
417
0
    BYTE* const dstEnd = (limit == fillOutput) ? oend + LASTLITERALS : oend;
418
0
    size_t lastRunSize = (size_t)(iend - anchor);  /* literals */
419
0
    size_t llAdd = (lastRunSize + 255 - RUN_MASK) / 255;
420
0
    size_t const totalSize = 1 + llAdd + lastRunSize;
421
0
    assert(!limit || op <= dstEnd);
422
0
    if (limit && ((size_t)(dstEnd - op) < totalSize)) {   /* compares sizes, as op + totalSize could exceed the address space */
423
0
        if (limit == limitedOutput) return 1;  /* not enough space in dst */
424
        /* adapt lastRunSize to fill dst */
425
0
        lastRunSize  = (size_t)(dstEnd - op) - 1 /*token*/;
426
0
        llAdd = (lastRunSize + 256 - RUN_MASK) / 256;
427
0
        lastRunSize -= llAdd;
428
0
    }
429
0
    DEBUGLOG(6, "Final literal run : %i literals", (int)lastRunSize);
430
0
    ip = anchor + lastRunSize;  /* can be != iend if limit==fillOutput */
431
432
0
    if (lastRunSize >= RUN_MASK) {
433
0
        size_t accumulator = lastRunSize - RUN_MASK;
434
0
        *op++ = (RUN_MASK << ML_BITS);
435
0
        for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255;
436
0
        *op++ = (BYTE) accumulator;
437
0
    } else {
438
0
        *op++ = (BYTE)(lastRunSize << ML_BITS);
439
0
    }
440
0
    assert(lastRunSize <= (size_t)(dstEnd - op));
441
0
    LZ4_memcpy(op, anchor, lastRunSize);
442
0
    op += lastRunSize;
443
0
    return 0;
444
445
0
#undef ip
446
0
#undef op
447
0
#undef anchor
448
0
}
449
450
/* LZ4HC_encodeLastSequence_fillOutput() :
451
 * fillOutput mode only : current sequence doesn't fit into dst.
452
 * Encode it anyway if all its literals fit, shortening its match if need be,
453
 * but only if it leaves enough room for the final run of literals (MFLIMIT).
454
 * @op : start of this sequence (before the failed LZ4HC_encodeSequence())
455
 * @oend : same as LZ4HC_encodeSequence() : end of dst minus LASTLITERALS */
456
static void LZ4HC_encodeLastSequence_fillOutput (
457
    const BYTE** _ip,
458
    BYTE** _op,
459
    const BYTE** _anchor,
460
    int matchLength,
461
    int offset,
462
    BYTE* oend)
463
0
{
464
0
#define ip      (*_ip)
465
0
#define op      (*_op)
466
0
#define anchor  (*_anchor)
467
468
0
    BYTE* const dstEnd = oend + LASTLITERALS;
469
0
    size_t const ll = (size_t)(ip - anchor);
470
0
    size_t const ll_addbytes = (ll + 240) / 255;
471
0
    size_t const ll_totalCost = 1 + ll_addbytes + ll;
472
0
    BYTE* const maxLitPos = oend - 3; /* 2 for offset, 1 for token */
473
0
    DEBUGLOG(6, "Last sequence is overflowing : %u literals, %u remaining space",
474
0
                (unsigned)ll, (unsigned)(oend - op));
475
0
    if ((op <= maxLitPos) && (ll_totalCost <= (size_t)(maxLitPos - op))) {   /* compares sizes, as op + ll_totalCost could exceed the address space */
476
        /* ll validated; now adjust match length */
477
0
        size_t const bytesLeftForMl = (size_t)(maxLitPos - (op+ll_totalCost));
478
0
        size_t const maxMlSize = MINMATCH + (ML_MASK-1) + (bytesLeftForMl * 255);
479
0
        assert(maxMlSize < INT_MAX); assert(matchLength >= 0);
480
0
        if ((size_t)matchLength > maxMlSize) matchLength = (int)maxMlSize;
481
0
        if (dstEnd - (op + ll_totalCost + 2) - 1 + matchLength >= MFLIMIT) {
482
0
            DEBUGLOG(6, "Let's encode a last sequence (ll=%u, ml=%i)", (unsigned)ll, matchLength);
483
0
            LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), matchLength, offset, notLimited, oend);
484
0
    }   }
485
486
0
#undef ip
487
0
#undef op
488
0
#undef anchor
489
0
}
490
491
492
typedef struct {
493
    int off;
494
    int len;
495
    int back;  /* negative value */
496
} LZ4HC_match_t;
497
498
static LZ4HC_match_t LZ4HC_searchExtDict(const BYTE* ip, U32 ipIndex,
499
        const BYTE* const iLowLimit, const BYTE* const iHighLimit,
500
        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex,
501
        int currentBestML, int nbAttempts)
502
0
{
503
0
    size_t const lDictEndIndex = (size_t)(dictCtx->end - dictCtx->prefixStart) + dictCtx->dictLimit;
504
0
    U32 lDictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)];
505
0
    U32 matchIndex = lDictMatchIndex + gDictEndIndex - (U32)lDictEndIndex;
506
0
    int offset = 0, sBack = 0;
507
0
    assert(lDictEndIndex <= 1 GB);
508
0
    if (lDictMatchIndex>0)
509
0
        DEBUGLOG(7, "lDictEndIndex = %zu, lDictMatchIndex = %u", lDictEndIndex, lDictMatchIndex);
510
0
    while (ipIndex - matchIndex <= LZ4_DISTANCE_MAX && nbAttempts--) {
511
0
        const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + lDictMatchIndex;
512
513
0
        if (LZ4_read32(matchPtr) == LZ4_read32(ip)) {
514
0
            int mlt;
515
0
            int back = 0;
516
0
            const BYTE* vLimit = ip + (lDictEndIndex - lDictMatchIndex);
517
0
            if (vLimit > iHighLimit) vLimit = iHighLimit;
518
0
            mlt = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
519
0
            back = (ip > iLowLimit) ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictCtx->prefixStart) : 0;
520
0
            mlt -= back;
521
0
            if (mlt > currentBestML) {
522
0
                currentBestML = mlt;
523
0
                offset = (int)(ipIndex - matchIndex);
524
0
                sBack = back;
525
0
                DEBUGLOG(7, "found match of length %i within extDictCtx", currentBestML);
526
0
        }   }
527
528
0
        {   U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, lDictMatchIndex);
529
0
            lDictMatchIndex -= nextOffset;
530
0
            matchIndex -= nextOffset;
531
0
    }   }
532
533
0
    {   LZ4HC_match_t md;
534
0
        md.len = currentBestML;
535
0
        md.off = offset;
536
0
        md.back = sBack;
537
0
        return md;
538
0
    }
539
0
}
540
541
typedef LZ4HC_match_t (*LZ4MID_searchIntoDict_f)(const BYTE* ip, U32 ipIndex,
542
        const BYTE* const iHighLimit,
543
        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex);
544
545
static LZ4HC_match_t LZ4MID_searchHCDict(const BYTE* ip, U32 ipIndex,
546
        const BYTE* const iHighLimit,
547
        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex)
548
0
{
549
0
    return LZ4HC_searchExtDict(ip,ipIndex,
550
0
                            ip, iHighLimit,
551
0
                            dictCtx, gDictEndIndex,
552
0
                            MINMATCH-1, 2);
553
0
}
554
555
static LZ4HC_match_t LZ4MID_searchExtDict(const BYTE* ip, U32 ipIndex,
556
        const BYTE* const iHighLimit,
557
        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex)
558
0
{
559
0
    size_t const lDictEndIndex = (size_t)(dictCtx->end - dictCtx->prefixStart) + dictCtx->dictLimit;
560
0
    const U32* const hash4Table = dictCtx->hashTable;
561
0
    const U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
562
0
    DEBUGLOG(7, "LZ4MID_searchExtDict (ipIdx=%u)", ipIndex);
563
564
    /* search long match first */
565
0
    {   U32 l8DictMatchIndex = hash8Table[LZ4MID_hash8Ptr(ip)];
566
0
        U32 m8Index = l8DictMatchIndex + gDictEndIndex - (U32)lDictEndIndex;
567
0
        assert(lDictEndIndex <= 1 GB);
568
0
        if (ipIndex - m8Index <= LZ4_DISTANCE_MAX) {
569
0
            const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + l8DictMatchIndex;
570
0
            const size_t safeLen = MIN(lDictEndIndex - l8DictMatchIndex, (size_t)(iHighLimit - ip));
571
0
            int mlt = (int)LZ4_count(ip, matchPtr, ip + safeLen);
572
0
            if (mlt >= MINMATCH) {
573
0
                LZ4HC_match_t md;
574
0
                DEBUGLOG(7, "Found long ExtDict match of len=%u", mlt);
575
0
                md.len = mlt;
576
0
                md.off = (int)(ipIndex - m8Index);
577
0
                md.back = 0;
578
0
                return md;
579
0
            }
580
0
        }
581
0
    }
582
583
    /* search for short match second */
584
0
    {   U32 l4DictMatchIndex = hash4Table[LZ4MID_hash4Ptr(ip)];
585
0
        U32 m4Index = l4DictMatchIndex + gDictEndIndex - (U32)lDictEndIndex;
586
0
        if (ipIndex - m4Index <= LZ4_DISTANCE_MAX) {
587
0
            const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + l4DictMatchIndex;
588
0
            const size_t safeLen = MIN(lDictEndIndex - l4DictMatchIndex, (size_t)(iHighLimit - ip));
589
0
            int mlt = (int)LZ4_count(ip, matchPtr, ip + safeLen);
590
0
            if (mlt >= MINMATCH) {
591
0
                LZ4HC_match_t md;
592
0
                DEBUGLOG(7, "Found short ExtDict match of len=%u", mlt);
593
0
                md.len = mlt;
594
0
                md.off = (int)(ipIndex - m4Index);
595
0
                md.back = 0;
596
0
                return md;
597
0
            }
598
0
        }
599
0
    }
600
601
    /* nothing found */
602
0
    {   LZ4HC_match_t const md = {0, 0, 0 };
603
0
        return md;
604
0
    }
605
0
}
606
607
/* LZ4HC_dropPositions() :
608
 * In fillOutput mode, compression can stop at @start, before positions the parser has already referenced.
609
 * The next block compresses them : it must not find them as matches.
610
 * Remove their references from the hash table, up to @end (excluded).
611
 * Costs one pass on these positions, or on the hash table, whichever is shorter. */
612
static void
613
LZ4HC_dropPositions(LZ4HC_CCtx_internal* ctx, const BYTE* start, const BYTE* end, lz4hc_strat_e strat)
614
0
{
615
0
    U32* const hashTable = ctx->hashTable;
616
0
    U32 const startIdx = ctx->dictLimit + (U32)(start - ctx->prefixStart);
617
0
    if (end - start > LZ4HC_HASHTABLESIZE) {
618
0
        int i;
619
0
        for (i = 0; i < LZ4HC_HASHTABLESIZE; i++) {
620
            /* branchless, so that it can be vectorized */
621
0
            hashTable[i] = (hashTable[i] >= startIdx) ? 0 : hashTable[i];
622
0
        }
623
0
    } else {
624
0
        U32 idx = startIdx;
625
0
        const BYTE* p;
626
0
        for (p = start; p < end; p++, idx++) {
627
0
            if (strat == lz4mid) {
628
0
                U32 const h4 = LZ4MID_hash4Ptr(p);
629
0
                U32 const h8 = LZ4MID_HASHTABLESIZE + LZ4MID_hash8Ptr(p);
630
0
                if (hashTable[h4] == idx) hashTable[h4] = 0;
631
0
                if (hashTable[h8] == idx) hashTable[h8] = 0;
632
0
            } else {
633
0
                U32 const h = LZ4HC_hashPtr(p);
634
0
                if (hashTable[h] == idx) hashTable[h] = 0;
635
0
    }   }   }
636
0
}
637
638
/**************************************
639
*  Mid Compression (level 2)
640
**************************************/
641
642
LZ4_FORCE_INLINE void
643
LZ4MID_addPosition(U32* hTable, U32 hValue, U32 index)
644
0
{
645
0
    hTable[hValue] = index;
646
0
}
647
648
0
#define ADDPOS8(_p, _idx) LZ4MID_addPosition(hash8Table, LZ4MID_hash8Ptr(_p), _idx)
649
0
#define ADDPOS4(_p, _idx) LZ4MID_addPosition(hash4Table, LZ4MID_hash4Ptr(_p), _idx)
650
651
/* Fill hash tables with references into dictionary.
652
 * The resulting table is only exploitable by LZ4MID (level 2) */
653
static void
654
LZ4MID_fillHTable (LZ4HC_CCtx_internal* cctx, const void* dict, size_t size)
655
0
{
656
0
    U32* const hash4Table = cctx->hashTable;
657
0
    U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
658
0
    const BYTE* const prefixPtr = (const BYTE*)dict;
659
0
    U32 const prefixIdx = cctx->dictLimit;
660
0
    U32 const target = prefixIdx + (U32)size - LZ4MID_HASHSIZE;
661
0
    U32 idx = cctx->nextToUpdate;
662
0
    assert(dict == cctx->prefixStart);
663
0
    DEBUGLOG(4, "LZ4MID_fillHTable (size:%zu)", size);
664
0
    if (size <= LZ4MID_HASHSIZE)
665
0
        return;
666
667
0
    for (; idx < target; idx += 3) {
668
0
        ADDPOS4(prefixPtr+idx-prefixIdx, idx);
669
0
        ADDPOS8(prefixPtr+idx+1-prefixIdx, idx+1);
670
0
    }
671
672
0
    idx = (size > 32 KB + LZ4MID_HASHSIZE) ? target - 32 KB : cctx->nextToUpdate;
673
0
    for (; idx < target; idx += 1) {
674
0
        ADDPOS8(prefixPtr+idx-prefixIdx, idx);
675
0
    }
676
677
0
    cctx->nextToUpdate = target;
678
0
}
679
680
static LZ4MID_searchIntoDict_f select_searchDict_function(const LZ4HC_CCtx_internal* dictCtx)
681
0
{
682
0
    if (dictCtx == NULL) return NULL;
683
0
    if (LZ4HC_getCLevelParams(dictCtx->compressionLevel).strat == lz4mid)
684
0
        return LZ4MID_searchExtDict;
685
0
    return LZ4MID_searchHCDict;
686
0
}
687
688
/* Length of the match between @ip and the candidate at index @pos (in prefix or extDict),
689
 * or 0 if the candidate is out of reach */
690
LZ4_FORCE_INLINE unsigned
691
LZ4MID_countMatch(const BYTE* ip, U32 ipIndex, U32 pos, const BYTE* matchlimit,
692
                  const BYTE* prefixPtr, U32 prefixIdx,
693
                  const BYTE* dictStart, U32 dictIdx)
694
0
{
695
0
    if (ipIndex - pos > LZ4_DISTANCE_MAX) return 0;
696
0
    if (pos >= prefixIdx) {
697
0
        const BYTE* const matchPtr = prefixPtr + (pos - prefixIdx);
698
0
        assert(matchPtr < ip);
699
0
        return LZ4_count(ip, matchPtr, matchlimit);
700
0
    }
701
0
    if (pos >= dictIdx) {
702
        /* extDict : the match stops at the end of the dictionary */
703
0
        const BYTE* const matchPtr = dictStart + (pos - dictIdx);
704
0
        size_t const safeLen = MIN(prefixIdx - pos, (size_t)(matchlimit - ip));
705
0
        return LZ4_count(ip, matchPtr, ip + safeLen);
706
0
    }
707
0
    return 0;
708
0
}
709
710
/* preconditions:
711
 * - *srcSizePtr within [1, LZ4_MAX_INPUT_SIZE]
712
 * - src is valid
713
 * - maxOutputSize >= 1
714
 * - dst is valid
715
 */
716
static int LZ4MID_compress (
717
    LZ4HC_CCtx_internal* const ctx,
718
    const char* const src,
719
    char* const dst,
720
    int* srcSizePtr,
721
    int const maxOutputSize,
722
    const limitedOutput_directive limit,
723
    const dictCtx_directive dict
724
    )
725
0
{
726
0
    U32* const hash4Table = ctx->hashTable;
727
0
    U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
728
0
    const BYTE* ip = (const BYTE*)src;
729
0
    const BYTE* anchor = ip;
730
0
    const BYTE* const iend = ip + *srcSizePtr;
731
0
    const BYTE* mflimit;      /* set after the size check : would precede a small input */
732
0
    const BYTE* matchlimit;
733
0
    const BYTE* ilimit;
734
0
    BYTE* op = (BYTE*)dst;
735
    /* fillOutput : keep room for the final run of literals (LZ4 format restriction) */
736
0
    BYTE* const oend = op + maxOutputSize - ((limit == fillOutput) ? LASTLITERALS : 0);
737
738
0
    const BYTE* const prefixPtr = ctx->prefixStart;
739
0
    const U32 prefixIdx = ctx->dictLimit;
740
0
    U32 ilimitIdx;
741
0
    const BYTE* const dictStart = ctx->dictStart;
742
0
    const U32 dictIdx = ctx->lowLimit;
743
0
    const U32 gDictEndIndex = ctx->lowLimit;
744
0
    const LZ4MID_searchIntoDict_f searchIntoDict = (dict == usingDictCtxHc) ? select_searchDict_function(ctx->dictCtx) : NULL;
745
0
    const BYTE* refEnd = ip;   /* fillOutput : the hash tables reference positions before MAX(refEnd, ip) */
746
747
0
    DEBUGLOG(5, "LZ4MID_compress (%i bytes)", *srcSizePtr);
748
749
    /* preconditions verifications */
750
0
    if (dict == usingDictCtxHc) DEBUGLOG(5, "usingDictCtxHc");
751
0
    assert(*srcSizePtr > 0);
752
0
    assert(*srcSizePtr <= LZ4_MAX_INPUT_SIZE);
753
0
    assert(src != NULL);
754
0
    assert(maxOutputSize >= 1);
755
0
    assert(dst != NULL);
756
757
0
    if (*srcSizePtr < LZ4_minLength)
758
0
        goto _lz4mid_last_literals;  /* Input too small, no compression (all literals) */
759
0
    mflimit = iend - MFLIMIT;
760
0
    matchlimit = (iend - LASTLITERALS);
761
0
    ilimit = (iend - LZ4MID_HASHSIZE);
762
0
    ilimitIdx = (U32)(ilimit - prefixPtr) + prefixIdx;
763
764
    /* main loop */
765
0
    while (ip <= mflimit) {
766
0
        const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx;
767
0
        unsigned matchLength;
768
0
        unsigned matchDistance;
769
        /* search long match */
770
0
        {   U32 const h8 = LZ4MID_hash8Ptr(ip);
771
0
            U32 const pos8 = hash8Table[h8];
772
0
            assert(h8 < LZ4MID_HASHTABLESIZE);
773
0
            assert(pos8 < ipIndex);
774
0
            LZ4MID_addPosition(hash8Table, h8, ipIndex);
775
0
            matchLength = LZ4MID_countMatch(ip, ipIndex, pos8, matchlimit, prefixPtr, prefixIdx, dictStart, dictIdx);
776
0
            matchDistance = ipIndex - pos8;
777
0
        }
778
        /* search short match */
779
0
        if (matchLength < MINMATCH) {
780
0
            U32 const h4 = LZ4MID_hash4Ptr(ip);
781
0
            U32 const pos4 = hash4Table[h4];
782
0
            assert(h4 < LZ4MID_HASHTABLESIZE);
783
0
            assert(pos4 < ipIndex);
784
0
            LZ4MID_addPosition(hash4Table, h4, ipIndex);
785
0
            matchLength = LZ4MID_countMatch(ip, ipIndex, pos4, matchlimit, prefixPtr, prefixIdx, dictStart, dictIdx);
786
0
            matchDistance = ipIndex - pos4;
787
0
        }
788
0
        if (matchLength >= MINMATCH) {
789
0
            if ((matchLength < 8) && likely(ip < mflimit)) {
790
                /* short match : check ip+1 for longer, except ip itself */
791
0
                U32 const h8 = LZ4MID_hash8Ptr(ip+1);
792
0
                U32 const pos8 = hash8Table[h8];
793
0
                unsigned const ml2 = LZ4MID_countMatch(ip+1, ipIndex+1, pos8, matchlimit, prefixPtr, prefixIdx, dictStart, dictIdx);
794
0
                if ((ml2 > matchLength) && (pos8 != ipIndex)) {
795
0
                    LZ4MID_addPosition(hash8Table, h8, ipIndex+1);
796
0
                    ip++;
797
0
                    matchLength = ml2;
798
0
                    matchDistance = ipIndex + 1 - pos8;
799
0
            }   }
800
0
            goto _lz4mid_encode_sequence;
801
0
        }
802
        /* no match found in prefix nor extDict : search into the attached dictionary */
803
0
        if ( (dict == usingDictCtxHc)
804
0
          && (ipIndex - gDictEndIndex < LZ4_DISTANCE_MAX - 8) ) {
805
0
            LZ4HC_match_t const dMatch = searchIntoDict(ip, ipIndex,
806
0
                    matchlimit,
807
0
                    ctx->dictCtx, gDictEndIndex);
808
0
            assert(dMatch.back == 0);
809
0
            matchLength = (unsigned)dMatch.len;
810
0
            matchDistance = (unsigned)dMatch.off;
811
0
            if (matchLength >= MINMATCH) goto _lz4mid_encode_sequence;
812
0
        }
813
        /* no match found */
814
0
        ip += 1 + ((ip-anchor) >> 9);  /* skip faster over incompressible data */
815
0
        continue;
816
817
0
_lz4mid_encode_sequence:
818
        /* match found at ip : matchLength, matchDistance */
819
0
        DEBUGLOG(7, "found match at pos %u (len=%u, distance=%u)",
820
0
                    (U32)(ip - prefixPtr) + prefixIdx, matchLength, matchDistance);
821
822
        /* catch back */
823
0
        while (((ip > anchor) & ((U32)(ip-prefixPtr) > matchDistance)) && (unlikely(ip[-1] == ip[-(int)matchDistance-1]))) {
824
0
            ip--;  matchLength++;
825
0
        };
826
827
        /* fill table with beginning of match
828
         * note : ip may have moved since ipIndex (longer match at ip+1, catch back) */
829
0
        {   U32 const startMatchIdx = (U32)(ip-prefixPtr) + prefixIdx;
830
0
            ADDPOS8(ip+1, startMatchIdx+1);
831
0
            ADDPOS8(ip+2, startMatchIdx+2);
832
0
            ADDPOS4(ip+1, startMatchIdx+1);
833
0
        }
834
835
        /* encode */
836
0
        if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
837
0
                (int)matchLength, (int)matchDistance,
838
0
                limit, oend) ) {
839
0
            if (limit != fillOutput) return 0;  /* compression failed */
840
0
            refEnd = ip + matchLength;
841
0
            LZ4HC_encodeLastSequence_fillOutput(UPDATABLE(ip, op, anchor),
842
0
                                (int)matchLength, (int)matchDistance, oend);
843
0
            break;
844
0
        }
845
846
        /* fill table with end of match */
847
0
        {   U32 endMatchIdx = (U32)(ip-prefixPtr) + prefixIdx;
848
0
            U32 pos_m2 = endMatchIdx - 2;
849
0
            if (pos_m2 < ilimitIdx) {
850
0
                if (likely(ip - prefixPtr > 5)) {
851
0
                    ADDPOS8(ip-5, endMatchIdx - 5);
852
0
                }
853
0
                ADDPOS8(ip-3, endMatchIdx - 3);
854
0
                ADDPOS8(ip-2, endMatchIdx - 2);
855
0
                ADDPOS4(ip-2, endMatchIdx - 2);
856
0
                ADDPOS4(ip-1, endMatchIdx - 1);
857
0
            }
858
0
        }
859
0
    }
860
861
0
_lz4mid_last_literals:
862
0
    if (refEnd < ip) refEnd = ip;
863
0
    if (LZ4HC_encodeLastLiterals(UPDATABLE(ip, op, anchor), iend, limit, oend))
864
0
        return 0;  /* not enough space in @dst */
865
0
    if (ip < refEnd)   /* fillOutput : the rest of input is left to the next block (input >= LZ4_minLength) */
866
0
        LZ4HC_dropPositions(ctx, ip, MIN(refEnd, iend - LZ4MID_HASHSIZE), lz4mid);
867
868
    /* End */
869
0
    DEBUGLOG(5, "compressed %i bytes into %i bytes", *srcSizePtr, (int)((char*)op - dst));
870
0
    assert(ip >= (const BYTE*)src);
871
0
    assert(ip <= iend);
872
0
    *srcSizePtr = (int)(ip - (const BYTE*)src);
873
0
    assert((char*)op >= dst);
874
0
    assert((char*)op - dst <= maxOutputSize);
875
0
    assert((char*)op - dst < INT_MAX);
876
0
    return (int)((char*)op - dst);
877
0
}
878
879
880
/**************************************
881
*  HC Compression - Search
882
**************************************/
883
884
/* Update chains up to ip (excluded) */
885
LZ4_FORCE_INLINE void LZ4HC_Insert (LZ4HC_CCtx_internal* hc4, const BYTE* ip)
886
0
{
887
0
    U16* const chainTable = hc4->chainTable;
888
0
    U32* const hashTable  = hc4->hashTable;
889
0
    const BYTE* const prefixPtr = hc4->prefixStart;
890
0
    U32 const prefixIdx = hc4->dictLimit;
891
0
    U32 const target = (U32)(ip - prefixPtr) + prefixIdx;
892
0
    U32 idx = hc4->nextToUpdate;
893
0
    assert(ip >= prefixPtr);
894
0
    assert(target >= prefixIdx);
895
896
0
    while (idx < target) {
897
0
        U32 const h = LZ4HC_hashPtr(prefixPtr+idx-prefixIdx);
898
0
        size_t delta = idx - hashTable[h];
899
0
        if (delta>LZ4_DISTANCE_MAX) delta = LZ4_DISTANCE_MAX;
900
0
        DELTANEXTU16(chainTable, idx) = (U16)delta;
901
0
        hashTable[h] = idx;
902
0
        idx++;
903
0
    }
904
905
0
    hc4->nextToUpdate = target;
906
0
}
907
908
#if defined(_MSC_VER)
909
#  define LZ4HC_rotl32(x,r) _rotl(x,r)
910
#else
911
0
#  define LZ4HC_rotl32(x,r) ((x << r) | (x >> (32 - r)))
912
#endif
913
914
915
static U32 LZ4HC_rotatePattern(size_t const rotate, U32 const pattern)
916
0
{
917
0
    size_t const bitsToRotate = (rotate & (sizeof(pattern) - 1)) << 3;
918
0
    if (bitsToRotate == 0) return pattern;
919
0
    return LZ4HC_rotl32(pattern, (int)bitsToRotate);
920
0
}
921
922
/* LZ4HC_countPattern() :
923
 * pattern32 must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!) */
924
static unsigned
925
LZ4HC_countPattern(const BYTE* ip, const BYTE* const iEnd, U32 const pattern32)
926
0
{
927
0
    const BYTE* const iStart = ip;
928
0
    reg_t const pattern = (sizeof(pattern)==8) ?
929
0
        (reg_t)pattern32 + (((reg_t)pattern32) << (sizeof(pattern)*4)) : pattern32;
930
931
0
    while (likely(ip < iEnd-(sizeof(pattern)-1))) {
932
0
        reg_t const diff = LZ4_read_ARCH(ip) ^ pattern;
933
0
        if (!diff) { ip+=sizeof(pattern); continue; }
934
0
        ip += LZ4_NbCommonBytes(diff);
935
0
        return (unsigned)(ip - iStart);
936
0
    }
937
938
0
    if (LZ4_isLittleEndian()) {
939
0
        reg_t patternByte = pattern;
940
0
        while ((ip<iEnd) && (*ip == (BYTE)patternByte)) {
941
0
            ip++; patternByte >>= 8;
942
0
        }
943
0
    } else {  /* big endian */
944
0
        U32 bitOffset = (sizeof(pattern)*8) - 8;
945
0
        while (ip < iEnd) {
946
0
            BYTE const byte = (BYTE)(pattern >> bitOffset);
947
0
            if (*ip != byte) break;
948
0
            ip ++; bitOffset -= 8;
949
0
    }   }
950
951
0
    return (unsigned)(ip - iStart);
952
0
}
953
954
/* LZ4HC_reverseCountPattern() :
955
 * pattern must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!)
956
 * read using natural platform endianness */
957
static unsigned
958
LZ4HC_reverseCountPattern(const BYTE* ip, const BYTE* const iLow, U32 pattern)
959
0
{
960
0
    const BYTE* const iStart = ip;
961
962
0
    while (likely(ip >= iLow+4)) {
963
0
        if (LZ4_read32(ip-4) != pattern) break;
964
0
        ip -= 4;
965
0
    }
966
0
    {   const BYTE* bytePtr = (const BYTE*)(&pattern) + 3; /* works for any endianness */
967
0
        while (likely(ip>iLow)) {
968
0
            if (ip[-1] != *bytePtr) break;
969
0
            ip--; bytePtr--;
970
0
    }   }
971
0
    return (unsigned)(iStart - ip);
972
0
}
973
974
/* LZ4HC_protectDictEnd() :
975
 * Checks if the match is in the last 3 bytes of the dictionary, so reading the
976
 * 4 byte MINMATCH would overflow.
977
 * @returns true if the match index is okay.
978
 */
979
static int LZ4HC_protectDictEnd(U32 const dictLimit, U32 const matchIndex)
980
0
{
981
0
    return ((U32)((dictLimit - 1) - matchIndex) >= 3);
982
0
}
983
984
typedef enum { rep_untested, rep_not, rep_confirmed } repeat_state_e;
985
986
/* LZ4HC_sparsestChain() :
987
 * A longer match must also match at every position of the current one (at @matchIndex, @longest bytes).
988
 * Finds, among these positions, the chain jumping farthest back (sampled, with acceleration).
989
 * @return : distance to the next candidate of that chain (1 if none is better),
990
 *           *matchChainPosPtr is set to its position within the match, if better */
991
LZ4_FORCE_INLINE U32
992
LZ4HC_sparsestChain(const U16* chainTable, U32 matchIndex, int longest, U32* matchChainPosPtr)
993
0
{
994
0
    int const kTrigger = 4;
995
0
    U32 distanceToNextMatch = 1;
996
0
    int const end = longest - MINMATCH + 1;
997
0
    int step = 1;
998
0
    int accel = 1 << kTrigger;
999
0
    int pos;
1000
0
    for (pos = 0; pos < end; pos += step) {
1001
0
        U32 const candidateDist = DELTANEXTU16(chainTable, matchIndex + (U32)pos);
1002
0
        step = (accel++ >> kTrigger);
1003
0
        if (candidateDist > distanceToNextMatch) {
1004
0
            distanceToNextMatch = candidateDist;
1005
0
            *matchChainPosPtr = (U32)pos;
1006
0
            accel = 1 << kTrigger;
1007
0
    }   }
1008
0
    return distanceToNextMatch;
1009
0
}
1010
1011
/* LZ4HC_patternSegment() :
1012
 * Measures the run of @pattern (a repeated byte, or 2 alternating bytes) around @candidateIdx,
1013
 * across the external dictionary / prefix boundary, without going below @lowestMatchIndex.
1014
 * @return : 0 if @pattern isn't present at @candidateIdx,
1015
 *           1 otherwise, with *forwardPtr bytes from @candidateIdx (included) and *backPtr bytes before it */
1016
LZ4_FORCE_INLINE int
1017
LZ4HC_patternSegment(const LZ4HC_CCtx_internal* hc4, U32 candidateIdx, U32 pattern,
1018
                     const BYTE* iHighLimit, U32 lowestMatchIndex,
1019
                     size_t* forwardPtr, size_t* backPtr)
1020
0
{
1021
0
    const BYTE* const prefixPtr = hc4->prefixStart;
1022
0
    U32 const prefixIdx = hc4->dictLimit;
1023
0
    const BYTE* const dictStart = hc4->dictStart;
1024
0
    U32 const dictIdx = hc4->lowLimit;
1025
0
    const BYTE* const dictEnd = dictStart + prefixIdx - dictIdx;
1026
0
    int const extDict = candidateIdx < prefixIdx;
1027
0
    const BYTE* const matchPtr = extDict ? dictStart + (candidateIdx - dictIdx) : prefixPtr + (candidateIdx - prefixIdx);
1028
0
    size_t forward, back;
1029
0
    if (LZ4_read32(matchPtr) != pattern) return 0;
1030
1031
0
    {   const BYTE* const iLimit = extDict ? dictEnd : iHighLimit;
1032
0
        forward = LZ4HC_countPattern(matchPtr+sizeof(pattern), iLimit, pattern) + sizeof(pattern);
1033
0
        if (extDict && matchPtr + forward == iLimit) {   /* continues into the prefix */
1034
0
            U32 const rotatedPattern = LZ4HC_rotatePattern(forward, pattern);
1035
0
            forward += LZ4HC_countPattern(prefixPtr, iHighLimit, rotatedPattern);
1036
0
    }   }
1037
1038
0
    back = LZ4HC_reverseCountPattern(matchPtr, extDict ? dictStart : prefixPtr, pattern);
1039
0
    if (!extDict && matchPtr - back == prefixPtr && dictIdx < prefixIdx) {   /* continues into the external dictionary */
1040
0
        U32 const rotatedPattern = LZ4HC_rotatePattern((U32)(-(int)back), pattern);
1041
0
        back += LZ4HC_reverseCountPattern(dictEnd, dictStart, rotatedPattern);
1042
0
    }
1043
    /* don't go below lowestMatchIndex */
1044
0
    back = candidateIdx - MAX(candidateIdx - (U32)back, lowestMatchIndex);
1045
0
    assert(candidateIdx - back >= lowestMatchIndex);
1046
1047
0
    *forwardPtr = forward;
1048
0
    *backPtr = back;
1049
0
    return 1;
1050
0
}
1051
typedef enum { favorCompressionRatio=0, favorDecompressionSpeed } HCfavor_e;
1052
1053
1054
LZ4_FORCE_INLINE LZ4HC_match_t
1055
LZ4HC_InsertAndGetWiderMatch (
1056
        LZ4HC_CCtx_internal* const hc4,
1057
        const BYTE* const ip,
1058
        const BYTE* const iLowLimit, const BYTE* const iHighLimit,
1059
        int longest,
1060
        const int maxNbAttempts,
1061
        const int patternAnalysis, const int chainSwap,
1062
        const dictCtx_directive dict,
1063
        const HCfavor_e favorDecSpeed)
1064
0
{
1065
0
    U16* const chainTable = hc4->chainTable;
1066
0
    U32* const hashTable = hc4->hashTable;
1067
0
    const LZ4HC_CCtx_internal* const dictCtx = hc4->dictCtx;
1068
0
    const BYTE* const prefixPtr = hc4->prefixStart;
1069
0
    const U32 prefixIdx = hc4->dictLimit;
1070
0
    const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx;
1071
0
    const int withinStartDistance = (hc4->lowLimit + (LZ4_DISTANCE_MAX + 1) > ipIndex);
1072
0
    const U32 lowestMatchIndex = (withinStartDistance) ? hc4->lowLimit : ipIndex - LZ4_DISTANCE_MAX;
1073
0
    const BYTE* const dictStart = hc4->dictStart;
1074
0
    const U32 dictIdx = hc4->lowLimit;
1075
0
    int const lookBackLength = (int)(ip-iLowLimit);
1076
0
    int const maxLength = (int)(iHighLimit-iLowLimit);   /* no match can be longer */
1077
0
    int nbAttempts = maxNbAttempts;
1078
0
    U32 matchChainPos = 0;
1079
0
    U32 const pattern = LZ4_read32(ip);
1080
0
    U32 matchIndex;
1081
0
    repeat_state_e repeat = rep_untested;
1082
0
    size_t srcPatternLength = 0;
1083
0
    int offset = 0, sBack = 0;
1084
1085
0
    DEBUGLOG(7, "LZ4HC_InsertAndGetWiderMatch");
1086
    /* First Match */
1087
0
    LZ4HC_Insert(hc4, ip);  /* insert all prior positions up to ip (excluded) */
1088
0
    matchIndex = hashTable[LZ4HC_hashPtr(ip)];
1089
0
    DEBUGLOG(7, "First candidate match for pos %u found at index %u / %u (lowestMatchIndex)",
1090
0
                ipIndex, matchIndex, lowestMatchIndex);
1091
1092
    /* Candidates only replace the current match if strictly longer,
1093
     * so stopping once @longest reaches @maxLength doesn't change the result. */
1094
0
    while ((matchIndex>=lowestMatchIndex) && (nbAttempts>0) && (longest<maxLength)) {
1095
0
        int matchLength=0;
1096
0
        nbAttempts--;
1097
0
        assert(matchIndex < ipIndex);
1098
0
        if (favorDecSpeed && (ipIndex - matchIndex < 8)) {
1099
            /* do nothing:
1100
             * favorDecSpeed intentionally skips matches with offset < 8 */
1101
0
        } else if (matchIndex >= prefixIdx) {   /* within current Prefix */
1102
0
            const BYTE* const matchPtr = prefixPtr + (matchIndex - prefixIdx);
1103
0
            assert(matchPtr < ip);
1104
0
            assert(longest >= 1);
1105
0
            if (LZ4_read16(iLowLimit + longest - 1) == LZ4_read16(matchPtr - lookBackLength + longest - 1)) {
1106
0
                if (LZ4_read32(matchPtr) == pattern) {
1107
0
                    int const back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, prefixPtr) : 0;
1108
0
                    matchLength = MINMATCH + (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit);
1109
0
                    matchLength -= back;
1110
0
                    if (matchLength > longest) {
1111
0
                        longest = matchLength;
1112
0
                        offset = (int)(ipIndex - matchIndex);
1113
0
                        sBack = back;
1114
0
                        DEBUGLOG(7, "Found match of len=%i within prefix, offset=%i, back=%i", longest, offset, -back);
1115
0
                        HEX_CMP(7, ip + back, ip + back - offset, (size_t)matchLength);
1116
0
            }   }   }
1117
0
        } else {   /* lowestMatchIndex <= matchIndex < dictLimit : within Ext Dict */
1118
0
            const BYTE* const matchPtr = dictStart + (matchIndex - dictIdx);
1119
0
            assert(matchIndex >= dictIdx);
1120
0
            if ( likely(matchIndex <= prefixIdx - 4)
1121
0
              && (LZ4_read32(matchPtr) == pattern) ) {
1122
0
                int back = 0;
1123
0
                const BYTE* vLimit = ip + (prefixIdx - matchIndex);
1124
0
                if (vLimit > iHighLimit) vLimit = iHighLimit;
1125
0
                matchLength = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
1126
0
                if ((ip+matchLength == vLimit) && (vLimit < iHighLimit))
1127
0
                    matchLength += LZ4_count(ip+matchLength, prefixPtr, iHighLimit);
1128
0
                back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictStart) : 0;
1129
0
                matchLength -= back;
1130
0
                if (matchLength > longest) {
1131
0
                    longest = matchLength;
1132
0
                    offset = (int)(ipIndex - matchIndex);
1133
0
                    sBack = back;
1134
0
                    DEBUGLOG(7, "Found match of len=%i within dict, offset=%i, back=%i", longest, offset, -back);
1135
0
                    HEX_CMP(7, ip + back, matchPtr + back, (size_t)matchLength);
1136
0
        }   }   }
1137
1138
0
        if (chainSwap && matchLength==longest && matchIndex + (U32)longest <= ipIndex) {   /* better match => select a better chain */
1139
0
            U32 const distanceToNextMatch = LZ4HC_sparsestChain(chainTable, matchIndex, longest, &matchChainPos);
1140
0
            assert(lookBackLength==0);   /* search forward only */
1141
0
            if (distanceToNextMatch > 1) {
1142
0
                if (distanceToNextMatch > matchIndex) break;   /* avoid overflow */
1143
0
                matchIndex -= distanceToNextMatch;
1144
0
                continue;
1145
0
        }   }
1146
1147
0
        {   U32 const distNextMatch = DELTANEXTU16(chainTable, matchIndex);
1148
0
            if (patternAnalysis && distNextMatch==1 && matchChainPos==0) {
1149
0
                U32 const matchCandidateIdx = matchIndex-1;
1150
0
                size_t forwardPatternLength, backLength;
1151
                /* may be a repeated pattern */
1152
0
                if (repeat == rep_untested) {
1153
0
                    if ( ((pattern & 0xFFFF) == (pattern >> 16))
1154
0
                      &  ((pattern & 0xFF)   == (pattern >> 24)) ) {
1155
0
                        DEBUGLOG(7, "Repeat pattern detected, char %02X", pattern >> 24);
1156
0
                        repeat = rep_confirmed;
1157
0
                        srcPatternLength = LZ4HC_countPattern(ip+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern);
1158
0
                    } else {
1159
0
                        repeat = rep_not;
1160
0
                }   }
1161
0
                if ( (repeat == rep_confirmed) && (matchCandidateIdx >= lowestMatchIndex)
1162
0
                  && LZ4HC_protectDictEnd(prefixIdx, matchCandidateIdx)
1163
0
                  && LZ4HC_patternSegment(hc4, matchCandidateIdx, pattern, iHighLimit, lowestMatchIndex,
1164
0
                                          &forwardPatternLength, &backLength) ) {
1165
0
                    size_t const currentSegmentLength = backLength + forwardPatternLength;
1166
                    /* if the full source pattern fits (and hasn't been reached yet), jump to its best position :
1167
                     * at the end of the segment, it might be followed by more match.
1168
                     * Otherwise, jump to the farthest position in the segment : the longest match, plus maybe some back */
1169
0
                    int const fullPatternFits = (currentSegmentLength >= srcPatternLength)
1170
0
                                             && (forwardPatternLength <= srcPatternLength);
1171
0
                    U32 const newMatchIndex = fullPatternFits ?
1172
0
                                              matchCandidateIdx + (U32)forwardPatternLength - (U32)srcPatternLength :
1173
0
                                              matchCandidateIdx - (U32)backLength;
1174
0
                    if (!LZ4HC_protectDictEnd(prefixIdx, newMatchIndex)) {
1175
                        /* Can only happen if started in the prefix */
1176
0
                        assert(newMatchIndex >= prefixIdx - 3 && newMatchIndex < prefixIdx && matchCandidateIdx >= prefixIdx);
1177
0
                        matchIndex = prefixIdx;
1178
0
                        continue;
1179
0
                    }
1180
0
                    matchIndex = newMatchIndex;
1181
0
                    if (!fullPatternFits && lookBackLength==0) {  /* no back possible : the match length is known */
1182
0
                        size_t const maxML = MIN(currentSegmentLength, srcPatternLength);
1183
0
                        if ((size_t)longest < maxML) {
1184
0
                            assert(prefixPtr - prefixIdx + matchIndex != ip);
1185
0
                            if ((size_t)(ip - prefixPtr) + prefixIdx - matchIndex > LZ4_DISTANCE_MAX) break;
1186
0
                            assert(maxML < 2 GB);
1187
0
                            longest = (int)maxML;
1188
0
                            offset = (int)(ipIndex - matchIndex);
1189
0
                            assert(sBack == 0);
1190
0
                            DEBUGLOG(7, "Found repeat pattern match of len=%i, offset=%i", longest, offset);
1191
0
                        }
1192
0
                        {   U32 const distToNextPattern = DELTANEXTU16(chainTable, matchIndex);
1193
0
                            if (distToNextPattern > matchIndex) break;  /* avoid overflow */
1194
0
                            matchIndex -= distToNextPattern;
1195
0
                    }   }
1196
0
                    continue;
1197
0
                }
1198
0
        }   }   /* PA optimization */
1199
1200
        /* follow current chain */
1201
0
        matchIndex -= DELTANEXTU16(chainTable, matchIndex + matchChainPos);
1202
1203
0
    }  /* while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) */
1204
1205
0
    if ( dict == usingDictCtxHc
1206
0
      && nbAttempts > 0
1207
0
      && longest < maxLength
1208
0
      && withinStartDistance) {
1209
0
        size_t const dictEndOffset = (size_t)(dictCtx->end - dictCtx->prefixStart) + dictCtx->dictLimit;
1210
0
        U32 dictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)];
1211
0
        assert(dictEndOffset <= 1 GB);
1212
0
        matchIndex = dictMatchIndex + lowestMatchIndex - (U32)dictEndOffset;
1213
0
        if (dictMatchIndex>0) DEBUGLOG(7, "dictEndOffset = %zu, dictMatchIndex = %u => relative matchIndex = %i", dictEndOffset, dictMatchIndex, (int)dictMatchIndex - (int)dictEndOffset);
1214
0
        while (ipIndex - matchIndex <= LZ4_DISTANCE_MAX && longest < maxLength && nbAttempts--) {
1215
0
            const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + dictMatchIndex;
1216
1217
0
            if (LZ4_read32(matchPtr) == pattern) {
1218
0
                int mlt;
1219
0
                int back = 0;
1220
0
                const BYTE* vLimit = ip + (dictEndOffset - dictMatchIndex);
1221
0
                if (vLimit > iHighLimit) vLimit = iHighLimit;
1222
0
                mlt = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
1223
0
                back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictCtx->prefixStart) : 0;
1224
0
                mlt -= back;
1225
0
                if (mlt > longest) {
1226
0
                    longest = mlt;
1227
0
                    offset = (int)(ipIndex - matchIndex);
1228
0
                    sBack = back;
1229
0
                    DEBUGLOG(7, "found match of length %i within extDictCtx", longest);
1230
0
            }   }
1231
1232
0
            {   U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, dictMatchIndex);
1233
0
                dictMatchIndex -= nextOffset;
1234
0
                matchIndex -= nextOffset;
1235
0
    }   }   }
1236
1237
0
    {   LZ4HC_match_t md;
1238
0
        assert(longest >= 0);
1239
0
        md.len = longest;
1240
0
        md.off = offset;
1241
0
        md.back = sBack;
1242
0
        return md;
1243
0
    }
1244
0
}
1245
1246
LZ4_FORCE_INLINE LZ4HC_match_t
1247
LZ4HC_InsertAndFindBestMatch(LZ4HC_CCtx_internal* const hc4,   /* Index table will be updated */
1248
                       const BYTE* const ip, const BYTE* const iLimit,
1249
                       const int maxNbAttempts,
1250
                       const int patternAnalysis,
1251
                       const dictCtx_directive dict)
1252
0
{
1253
0
    DEBUGLOG(7, "LZ4HC_InsertAndFindBestMatch");
1254
    /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),
1255
     * but this won't be the case here, as we define iLowLimit==ip,
1256
     * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
1257
0
    return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio);
1258
0
}
1259
1260
1261
/* preconditions:
1262
 * - *srcSizePtr within [1, LZ4_MAX_INPUT_SIZE]
1263
 * - src is valid
1264
 * - maxOutputSize >= 1
1265
 * - dst is valid
1266
 */
1267
LZ4_FORCE_INLINE int LZ4HC_compress_hashChain (
1268
    LZ4HC_CCtx_internal* const ctx,
1269
    const char* const src,
1270
    char* const dst,
1271
    int* srcSizePtr,
1272
    int const maxOutputSize,
1273
    int maxNbAttempts,
1274
    const limitedOutput_directive limit,
1275
    const dictCtx_directive dict
1276
    )
1277
0
{
1278
0
    const int inputSize = *srcSizePtr;
1279
0
    const int patternAnalysis = (maxNbAttempts > 128);   /* levels 9+ */
1280
1281
0
    const BYTE* ip = (const BYTE*)src;
1282
0
    const BYTE* anchor = ip;
1283
0
    const BYTE* const iend = ip + inputSize;
1284
0
    const BYTE* mflimit;      /* set after the size check : would precede a small input */
1285
0
    const BYTE* matchlimit;
1286
1287
0
    BYTE* op = (BYTE*) dst;
1288
    /* fillOutput : keep room for the final run of literals (LZ4 format restriction) */
1289
0
    BYTE* const oend = op + maxOutputSize - ((limit == fillOutput) ? LASTLITERALS : 0);
1290
1291
0
    const BYTE* start0;
1292
0
    const BYTE* start2 = NULL;
1293
0
    const BYTE* start3 = NULL;
1294
0
    LZ4HC_match_t m0, m1, m2, m3;
1295
0
    const LZ4HC_match_t nomatch = {0, 0, 0};
1296
1297
    /* init */
1298
0
    DEBUGLOG(5, "LZ4HC_compress_hashChain (dict?=>%i)", dict);
1299
1300
    /* preconditions verifications */
1301
0
    assert(*srcSizePtr >= 1);
1302
0
    assert(src != NULL);
1303
0
    assert(maxOutputSize >= 1);
1304
0
    assert(dst != NULL);
1305
1306
0
    *srcSizePtr = 0;
1307
0
    if (inputSize < LZ4_minLength) goto _last_literals;             /* Input too small, no compression (all literals) */
1308
0
    mflimit = iend - MFLIMIT;
1309
0
    matchlimit = (iend - LASTLITERALS);
1310
1311
    /* Main Loop */
1312
0
    while (ip <= mflimit) {
1313
0
        m1 = LZ4HC_InsertAndFindBestMatch(ctx, ip, matchlimit, maxNbAttempts, patternAnalysis, dict);
1314
0
        if (m1.len<MINMATCH) { ip++; continue; }
1315
1316
        /* saved, in case we would skip too much */
1317
0
        start0 = ip; m0 = m1;
1318
1319
0
_Search2:
1320
        /* m1 (at ip) is the next match to encode, m0 (at start0 <= ip) its fallback.
1321
         * Search a longer match m2, starting before the end of m1. */
1322
0
        DEBUGLOG(7, "_Search2 (currently found match of size %i)", m1.len);
1323
0
        if (ip+m1.len <= mflimit) {
1324
0
            start2 = ip + m1.len - 2;
1325
0
            m2 = LZ4HC_InsertAndGetWiderMatch(ctx,
1326
0
                            start2, ip + 0, matchlimit, m1.len,
1327
0
                            maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
1328
0
            start2 += m2.back;
1329
0
        } else {
1330
0
            m2 = nomatch;  /* do not search further */
1331
0
        }
1332
1333
0
        if (m2.len <= m1.len) { /* No better match => encode m1 immediately */
1334
0
            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1335
0
                    m1.len, m1.off,
1336
0
                    limit, oend) )
1337
0
                goto _dest_overflow;
1338
0
            continue;
1339
0
        }
1340
1341
0
        if ((start0 < ip) && (start2 < ip + m0.len)) {
1342
            /* m1 was skipped at least once, and m2 starts early enough : restore m0 */
1343
0
            ip = start0; m1 = m0;
1344
0
        }
1345
1346
0
        if ((start2 - ip) < 3) {  /* m1 too short before m2 : removed */
1347
0
            ip = start2;
1348
0
            m1 = m2;
1349
0
            goto _Search2;
1350
0
        }
1351
1352
        /* m2 (at start2) is the candidate after m1.
1353
         * Search a longer match m3, starting before the end of m2. */
1354
0
        while (1) {
1355
            /* m1 will be cut where m2 starts, but keeps up to OPTIMAL_ML bytes (no extra length byte) :
1356
             * m2 is shifted after them, as long as it keeps at least MINMATCH bytes. */
1357
0
            if ((start2 - ip) < OPTIMAL_ML) {
1358
0
                int const gap = (int)(start2 - ip);
1359
0
                int newML = MIN(m1.len, OPTIMAL_ML);
1360
0
                if (newML > gap + m2.len - MINMATCH)
1361
0
                    newML = gap + m2.len - MINMATCH;
1362
0
                if (newML > gap) {   /* shift m2 */
1363
0
                    start2 += newML - gap;
1364
0
                    m2.len -= newML - gap;
1365
0
                }
1366
0
            }
1367
1368
0
            if (start2 + m2.len <= mflimit) {
1369
0
                start3 = start2 + m2.len - 3;
1370
0
                m3 = LZ4HC_InsertAndGetWiderMatch(ctx,
1371
0
                                start3, start2, matchlimit, m2.len,
1372
0
                                maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
1373
0
                start3 += m3.back;
1374
0
            } else {
1375
0
                m3 = nomatch;  /* do not search further */
1376
0
            }
1377
1378
0
            if ((m3.len > m2.len) && (start3 < ip+m1.len+3)) {  /* not enough room for m2 between m1 and m3 */
1379
0
                if (start3 >= (ip+m1.len)) {
1380
                    /* m3 starts after m1 : encode m1, then m3 becomes m1,
1381
                     * and m2, moved after m1 if needed (replaced by m3 if too short), becomes the fallback m0 */
1382
0
                    if (start2 < ip+m1.len) {
1383
0
                        int correction = (int)(ip+m1.len - start2);
1384
0
                        start2 += correction;
1385
0
                        m2.len -= correction;
1386
0
                        if (m2.len < MINMATCH) {
1387
0
                            start2 = start3;
1388
0
                            m2 = m3;
1389
0
                        }
1390
0
                    }
1391
1392
0
                    if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1393
0
                            m1.len, m1.off,
1394
0
                            limit, oend) )
1395
0
                        goto _dest_overflow;
1396
0
                    ip  = start3;
1397
0
                    m1 = m3;
1398
1399
0
                    start0 = start2;
1400
0
                    m0 = m2;
1401
0
                    goto _Search2;
1402
0
                }
1403
1404
                /* m3 starts within m1 : m3 replaces m2 */
1405
0
                start2 = start3;
1406
0
                m2 = m3;
1407
0
                continue;
1408
0
            }
1409
1410
            /* encode m1, cut where m2 starts */
1411
0
            if (start2 < ip+m1.len) m1.len = (int)(start2 - ip);
1412
0
            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1413
0
                    m1.len, m1.off,
1414
0
                    limit, oend) )
1415
0
                goto _dest_overflow;
1416
1417
            /* m2 becomes m1 */
1418
0
            ip = start2; m1 = m2;
1419
1420
0
            if (m3.len <= m1.len) {  /* No better match => encode m1 (former m2) */
1421
0
                if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1422
0
                        m1.len, m1.off,
1423
0
                        limit, oend) )
1424
0
                    goto _dest_overflow;
1425
0
                break;
1426
0
            }
1427
1428
            /* m3 becomes m2 */
1429
0
            start2 = start3; m2 = m3;
1430
0
        }
1431
0
    }
1432
1433
0
_last_literals:
1434
0
    if (LZ4HC_encodeLastLiterals(UPDATABLE(ip, op, anchor), iend, limit, oend))
1435
0
        return 0;  /* not enough space in @dst */
1436
1437
    /* End */
1438
0
    *srcSizePtr = (int) (((const char*)ip) - src);
1439
0
    return (int) (((char*)op)-dst);
1440
1441
0
_dest_overflow:
1442
0
    if (limit != fillOutput) return 0;  /* compression failed */
1443
0
    LZ4HC_encodeLastSequence_fillOutput(UPDATABLE(ip, op, anchor), m1.len, m1.off, oend);
1444
0
    goto _last_literals;
1445
0
}
1446
1447
1448
static int LZ4HC_compress_optimal( LZ4HC_CCtx_internal* ctx,
1449
    const char* const source, char* dst,
1450
    int* srcSizePtr, int dstCapacity,
1451
    int const nbSearches, int const nbSearchesSeq, int const targetLength,
1452
    const limitedOutput_directive limit,
1453
    const dictCtx_directive dict,
1454
    const HCfavor_e favorDecSpeed);
1455
1456
static int
1457
LZ4HC_compress_generic_internal (
1458
            LZ4HC_CCtx_internal* const ctx,
1459
            const char* const src,
1460
            char* const dst,
1461
            int* const srcSizePtr,
1462
            int const dstCapacity,
1463
            int cLevel,
1464
            const limitedOutput_directive limit,
1465
            const dictCtx_directive dict
1466
            )
1467
0
{
1468
0
    DEBUGLOG(5, "LZ4HC_compress_generic_internal(src=%p, srcSize=%d, dstCapacity=%d)",
1469
0
                src, *srcSizePtr, dstCapacity);
1470
1471
    /* input sanitization */
1472
0
    if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0;  /* Unsupported input size (too large or negative) */
1473
0
    if (dstCapacity < 1) return 0;   /* Invalid: impossible to store anything */
1474
0
    assert(dst); /* since dstCapacity >= 1, dst must be valid */
1475
0
    if (*srcSizePtr == 0) { *dst = 0; return 1; }
1476
0
    assert(src != NULL); /* since *srcSizePtr >= 1, src must be valid */
1477
1478
0
    ctx->end += *srcSizePtr;
1479
0
    {   cParams_t const cParam = LZ4HC_getCLevelParams(cLevel);
1480
0
        HCfavor_e const favor = ctx->favorDecSpeed ? favorDecompressionSpeed : favorCompressionRatio;
1481
0
        int const srcSize = *srcSizePtr;
1482
0
        int result;
1483
1484
0
        if (cParam.strat == lz4mid) {
1485
0
            result = LZ4MID_compress(ctx,
1486
0
                                src, dst, srcSizePtr, dstCapacity,
1487
0
                                limit, dict);
1488
0
        } else if (cParam.strat == lz4hc) {
1489
0
            result = LZ4HC_compress_hashChain(ctx,
1490
0
                                src, dst, srcSizePtr, dstCapacity,
1491
0
                                cParam.nbSearches, limit, dict);
1492
0
        } else {
1493
0
            assert(cParam.strat == lz4opt);
1494
0
            result = LZ4HC_compress_optimal(ctx,
1495
0
                                src, dst, srcSizePtr, dstCapacity,
1496
0
                                cParam.nbSearches, cParam.nbSearchesSeq, (int)cParam.targetLength, limit,
1497
0
                                dict, favor);
1498
0
        }
1499
0
        if ((limit == fillOutput) && (result > 0) && (*srcSizePtr < srcSize)) {
1500
            /* fillOutput : compression stopped before the end of input.
1501
             * The rest of input is left to the next block : it isn't history yet,
1502
             * and the positions already inserted into it are dropped (lz4mid drops its own).
1503
             * Note : a failed compression is different : lz4frame stores its block uncompressed,
1504
             * and the next block still references it. */
1505
0
            const BYTE* const consumedEnd = (const BYTE*)src + *srcSizePtr;
1506
0
            U32 const consumedIdx = ctx->dictLimit + (U32)(consumedEnd - ctx->prefixStart);
1507
0
            if ((cParam.strat != lz4mid) && (ctx->nextToUpdate > consumedIdx)) {
1508
0
                LZ4HC_dropPositions(ctx, consumedEnd, consumedEnd + (ctx->nextToUpdate - consumedIdx), cParam.strat);
1509
0
                ctx->nextToUpdate = consumedIdx;
1510
0
            }
1511
0
            ctx->end = consumedEnd;
1512
0
        }
1513
0
        return result;
1514
0
    }
1515
0
}
1516
1517
static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock);
1518
1519
static int
1520
LZ4HC_compress_generic_noDictCtx (
1521
        LZ4HC_CCtx_internal* const ctx,
1522
        const char* const src,
1523
        char* const dst,
1524
        int* const srcSizePtr,
1525
        int const dstCapacity,
1526
        int cLevel,
1527
        limitedOutput_directive limit
1528
        )
1529
0
{
1530
0
    assert(ctx->dictCtx == NULL);
1531
0
    return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, noDictCtx);
1532
0
}
1533
1534
static int isStateCompatible(const LZ4HC_CCtx_internal* ctx1, const LZ4HC_CCtx_internal* ctx2)
1535
0
{
1536
0
    int const isMid1 = LZ4HC_getCLevelParams(ctx1->compressionLevel).strat == lz4mid;
1537
0
    int const isMid2 = LZ4HC_getCLevelParams(ctx2->compressionLevel).strat == lz4mid;
1538
0
    return !(isMid1 ^ isMid2);
1539
0
}
1540
1541
static int
1542
LZ4HC_compress_generic_dictCtx (
1543
        LZ4HC_CCtx_internal* const ctx,
1544
        const char* const src,
1545
        char* const dst,
1546
        int* const srcSizePtr,
1547
        int const dstCapacity,
1548
        int cLevel,
1549
        limitedOutput_directive limit
1550
        )
1551
0
{
1552
0
    const size_t position = (size_t)(ctx->end - ctx->prefixStart) + (ctx->dictLimit - ctx->lowLimit);
1553
0
    assert(ctx->dictCtx != NULL);
1554
0
    if (position >= 64 KB) {
1555
0
        ctx->dictCtx = NULL;
1556
0
        return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
1557
0
    } else if (position == 0 && *srcSizePtr >= LZ4HC_getCLevelParams(cLevel).dictCopyMin && isStateCompatible(ctx, ctx->dictCtx)) {
1558
        /* parameters and extension belong to the working context, not to the dictionary */
1559
0
        LZ4_i8 const favorDecSpeed = ctx->favorDecSpeed;
1560
0
        LZ4_i8 const hasWorkspace = ctx->hasWorkspace;
1561
0
        LZ4_memcpy(ctx, ctx->dictCtx, sizeof(LZ4HC_CCtx_internal));
1562
0
        LZ4HC_setExternalDict(ctx, (const BYTE *)src);
1563
0
        ctx->compressionLevel = (short)cLevel;
1564
0
        ctx->favorDecSpeed = favorDecSpeed;
1565
0
        ctx->hasWorkspace = hasWorkspace;
1566
0
        return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
1567
0
    } else {
1568
0
        return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, usingDictCtxHc);
1569
0
    }
1570
0
}
1571
1572
static int
1573
LZ4HC_compress_generic (
1574
        LZ4HC_CCtx_internal* const ctx,
1575
        const char* const src,
1576
        char* const dst,
1577
        int* const srcSizePtr,
1578
        int const dstCapacity,
1579
        int cLevel,
1580
        limitedOutput_directive limit
1581
        )
1582
0
{
1583
0
    if (ctx->dictCtx == NULL) {
1584
0
        return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
1585
0
    } else {
1586
0
        return LZ4HC_compress_generic_dictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
1587
0
    }
1588
0
}
1589
1590
1591
0
int LZ4_sizeofStateHC(void) { return (int)sizeof(LZ4_streamHC_t); }
1592
1593
static size_t LZ4_streamHC_t_alignment(void)
1594
0
{
1595
0
#if LZ4_ALIGN_TEST
1596
0
    typedef struct { char c; LZ4_streamHC_t t; } t_a;
1597
0
    return sizeof(t_a) - sizeof(LZ4_streamHC_t);
1598
#else
1599
    return 1;  /* effectively disabled */
1600
#endif
1601
0
}
1602
1603
/* state is presumed correctly initialized,
1604
 * in which case its size and alignment have already been validate */
1605
int LZ4_compress_HC_extStateHC_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)
1606
0
{
1607
0
    LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)state)->internal_donotuse;
1608
0
    if (!LZ4_isAligned(state, LZ4_streamHC_t_alignment())) return 0;
1609
0
    LZ4_resetStreamHC_fast((LZ4_streamHC_t*)state, compressionLevel);
1610
0
    LZ4HC_init_internal (ctx, (const BYTE*)src);
1611
0
    if (dstCapacity < LZ4_compressBound(srcSize))
1612
0
        return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, limitedOutput);
1613
0
    else
1614
0
        return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, notLimited);
1615
0
}
1616
1617
int LZ4_compress_HC_extStateHC (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)
1618
0
{
1619
0
    LZ4_streamHC_t* const ctx = LZ4_initStreamHC(state, sizeof(*ctx));
1620
0
    if (ctx==NULL) return 0;   /* init failure */
1621
0
    return LZ4_compress_HC_extStateHC_fastReset(state, src, dst, srcSize, dstCapacity, compressionLevel);
1622
0
}
1623
1624
int LZ4_compress_HC(const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)
1625
0
{
1626
0
    int cSize;
1627
0
    DEBUGLOG(5, "LZ4_compress_HC")
1628
0
#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
1629
0
    {   /* extended state : a single allocation, including the temporary buffer of levels >= 10 */
1630
0
        LZ4_streamHC_t* const statePtr = LZ4_initStreamHC(ALLOC(LZ4_STREAMHC_EXTSIZE), LZ4_STREAMHC_EXTSIZE);
1631
0
        if (statePtr==NULL) return 0;
1632
0
        cSize = LZ4_compress_HC_extStateHC_fastReset(statePtr, src, dst, srcSize, dstCapacity, compressionLevel);
1633
0
        FREEMEM(statePtr);
1634
0
    }
1635
#else
1636
    {   LZ4_streamHC_t state;
1637
        cSize = LZ4_compress_HC_extStateHC(&state, src, dst, srcSize, dstCapacity, compressionLevel);
1638
    }
1639
#endif
1640
0
    return cSize;
1641
0
}
1642
1643
/* state is presumed sized correctly (>= sizeof(LZ4_streamHC_t)) */
1644
int LZ4_compress_HC_destSize(void* state, const char* source, char* dest, int* sourceSizePtr, int targetDestSize, int cLevel)
1645
0
{
1646
0
    LZ4_streamHC_t* const ctx = LZ4_initStreamHC(state, sizeof(*ctx));
1647
0
    if (ctx==NULL) return 0;   /* init failure */
1648
0
    LZ4HC_init_internal(&ctx->internal_donotuse, (const BYTE*) source);
1649
0
    LZ4_setCompressionLevel(ctx, cLevel);
1650
0
    return LZ4HC_compress_generic(&ctx->internal_donotuse, source, dest, sourceSizePtr, targetDestSize, cLevel, fillOutput);
1651
0
}
1652
1653
1654
1655
/**************************************
1656
*  Streaming Functions
1657
**************************************/
1658
/* allocation */
1659
LZ4_streamHC_t* LZ4_createStreamHC(void)
1660
0
{
1661
0
    LZ4_streamHC_t* const state =
1662
0
        (LZ4_streamHC_t*)ALLOC_AND_ZERO(LZ4_STREAMHC_EXTSIZE);   /* zeroed : initialized */
1663
0
    if (state == NULL) return NULL;
1664
0
    state->internal_donotuse.hasWorkspace = 1;
1665
0
    LZ4_setCompressionLevel(state, LZ4HC_CLEVEL_DEFAULT);
1666
0
    return state;
1667
0
}
1668
1669
int LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr)
1670
0
{
1671
0
    DEBUGLOG(4, "LZ4_freeStreamHC(%p)", LZ4_streamHCPtr);
1672
0
    if (!LZ4_streamHCPtr) return 0;  /* support free on NULL */
1673
0
    FREEMEM(LZ4_streamHCPtr);
1674
0
    return 0;
1675
0
}
1676
1677
1678
LZ4_streamHC_t* LZ4_initStreamHC (void* buffer, size_t size)
1679
0
{
1680
0
    LZ4_streamHC_t* const LZ4_streamHCPtr = (LZ4_streamHC_t*)buffer;
1681
0
    DEBUGLOG(4, "LZ4_initStreamHC(%p, %u)", buffer, (unsigned)size);
1682
    /* check conditions */
1683
0
    if (buffer == NULL) return NULL;
1684
0
    if (size < sizeof(LZ4_streamHC_t)) return NULL;
1685
0
    if (!LZ4_isAligned(buffer, LZ4_streamHC_t_alignment())) return NULL;
1686
    /* init */
1687
0
    { LZ4HC_CCtx_internal* const hcstate = &(LZ4_streamHCPtr->internal_donotuse);
1688
0
      MEM_INIT(hcstate, 0, sizeof(*hcstate));
1689
0
      hcstate->hasWorkspace = (size >= LZ4_STREAMHC_EXTSIZE); }
1690
0
    LZ4_setCompressionLevel(LZ4_streamHCPtr, LZ4HC_CLEVEL_DEFAULT);
1691
0
    return LZ4_streamHCPtr;
1692
0
}
1693
1694
/* size of an initialized state, to initialize it again : extended states are followed by their buffer */
1695
static size_t LZ4HC_sizeofState(const LZ4_streamHC_t* s)
1696
0
{
1697
0
    return s->internal_donotuse.hasWorkspace ? LZ4_STREAMHC_EXTSIZE : sizeof(*s);
1698
0
}
1699
1700
/* initializes arbitrary data, as LZ4_initStreamHC() : its extension marker can't be trusted */
1701
void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
1702
0
{
1703
0
    LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));
1704
0
    LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
1705
0
}
1706
1707
void LZ4_resetStreamHC_fast (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
1708
0
{
1709
0
    LZ4HC_CCtx_internal* const s = &LZ4_streamHCPtr->internal_donotuse;
1710
0
    DEBUGLOG(5, "LZ4_resetStreamHC_fast(%p, %d)", LZ4_streamHCPtr, compressionLevel);
1711
    /* also after a failed compression : its positions are below @end, hence out of reach of the next stream */
1712
0
    assert(s->end >= s->prefixStart);
1713
0
    s->dictLimit += (U32)(s->end - s->prefixStart);
1714
0
    s->prefixStart = NULL;
1715
0
    s->end = NULL;
1716
0
    s->dictCtx = NULL;
1717
0
    LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
1718
0
}
1719
1720
void LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
1721
0
{
1722
0
    DEBUGLOG(5, "LZ4_setCompressionLevel(%p, %d)", LZ4_streamHCPtr, compressionLevel);
1723
0
    if (compressionLevel < 1) compressionLevel = LZ4HC_CLEVEL_DEFAULT;
1724
0
    if (compressionLevel > LZ4HC_CLEVEL_MAX) compressionLevel = LZ4HC_CLEVEL_MAX;
1725
0
    LZ4_streamHCPtr->internal_donotuse.compressionLevel = (short)compressionLevel;
1726
0
}
1727
1728
void LZ4_favorDecompressionSpeed(LZ4_streamHC_t* LZ4_streamHCPtr, int favor)
1729
0
{
1730
0
    LZ4_streamHCPtr->internal_donotuse.favorDecSpeed = (favor!=0);
1731
0
}
1732
1733
/* LZ4_loadDictHC() :
1734
 * LZ4_streamHCPtr is presumed properly initialized */
1735
int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr,
1736
              const char* dictionary, int dictSize)
1737
0
{
1738
0
    LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;
1739
0
    cParams_t cp;
1740
0
    DEBUGLOG(4, "LZ4_loadDictHC(ctx:%p, dict:%p, dictSize:%d, clevel=%d)", LZ4_streamHCPtr, dictionary, dictSize, ctxPtr->compressionLevel);
1741
0
    assert(LZ4_streamHCPtr != NULL);
1742
0
    if (dictSize < 0) dictSize = 0;   /* invalid size : no dictionary */
1743
0
    if (dictSize > 64 KB) {
1744
0
        dictionary += (size_t)dictSize - 64 KB;
1745
0
        dictSize = 64 KB;
1746
0
    }
1747
    /* need a full initialization, there are bad side-effects when using resetFast(),
1748
     * but preserve parameters */
1749
0
    {   int const cLevel = ctxPtr->compressionLevel;
1750
0
        LZ4_i8 const favorDecSpeed = ctxPtr->favorDecSpeed;
1751
0
        LZ4_initStreamHC(LZ4_streamHCPtr, LZ4HC_sizeofState(LZ4_streamHCPtr));
1752
0
        LZ4_setCompressionLevel(LZ4_streamHCPtr, cLevel);
1753
0
        ctxPtr->favorDecSpeed = favorDecSpeed;
1754
0
        cp = LZ4HC_getCLevelParams(cLevel);
1755
0
    }
1756
0
    LZ4HC_init_internal (ctxPtr, (const BYTE*)dictionary);
1757
0
    ctxPtr->end = (const BYTE*)dictionary + dictSize;
1758
0
    if (cp.strat == lz4mid) {
1759
0
        LZ4MID_fillHTable (ctxPtr, dictionary, (size_t)dictSize);
1760
0
    } else {
1761
0
        if (dictSize >= LZ4HC_HASHSIZE) LZ4HC_Insert (ctxPtr, ctxPtr->end-3);
1762
0
    }
1763
0
    return dictSize;
1764
0
}
1765
1766
void LZ4_attach_HC_dictionary(LZ4_streamHC_t *working_stream, const LZ4_streamHC_t *dictionary_stream)
1767
0
{
1768
0
    const LZ4HC_CCtx_internal* dictCtx = (dictionary_stream == NULL) ? NULL :
1769
0
        &(dictionary_stream->internal_donotuse);
1770
1771
    /* A state without content (new, or reset since loading) is an empty dictionary, as in LZ4_attach_dictionary() :
1772
     * its tables don't match any buffer, so it's not attached */
1773
0
    if ((dictCtx != NULL) && (dictCtx->end == dictCtx->prefixStart)) {
1774
0
        dictCtx = NULL;
1775
0
    }
1776
    /* The dictionary replaces the stream history (see lz4hc.h) : drop it, as LZ4F_initStream() does */
1777
0
    if ((dictCtx != NULL) && (working_stream->internal_donotuse.prefixStart != NULL)) {
1778
0
        LZ4_resetStreamHC_fast(working_stream, working_stream->internal_donotuse.compressionLevel);
1779
0
    }
1780
0
    working_stream->internal_donotuse.dictCtx = dictCtx;
1781
0
}
1782
1783
/* compression */
1784
1785
static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock)
1786
0
{
1787
0
    DEBUGLOG(4, "LZ4HC_setExternalDict(%p, %p)", ctxPtr, newBlock);
1788
0
    if (LZ4HC_getCLevelParams(ctxPtr->compressionLevel).strat != lz4mid) {
1789
0
        U32 const endIdx = ctxPtr->dictLimit + (U32)(ctxPtr->end - ctxPtr->prefixStart);
1790
0
        U32 idx;
1791
0
        if (ctxPtr->end >= ctxPtr->prefixStart + 4)
1792
0
            LZ4HC_Insert (ctxPtr, ctxPtr->end-3);  /* Referencing remaining dictionary content */
1793
        /* last positions can't be inserted : don't leave stale chains from previous history */
1794
0
        for (idx = ctxPtr->nextToUpdate; idx < endIdx; idx++)
1795
0
            DELTANEXTU16(ctxPtr->chainTable, idx) = 0;
1796
0
    }
1797
1798
    /* Only one memory segment for extDict, so any previous extDict is lost at this stage */
1799
0
    ctxPtr->lowLimit  = ctxPtr->dictLimit;
1800
0
    ctxPtr->dictStart  = ctxPtr->prefixStart;
1801
0
    ctxPtr->dictLimit += (U32)(ctxPtr->end - ctxPtr->prefixStart);
1802
0
    ctxPtr->prefixStart = newBlock;
1803
0
    ctxPtr->end  = newBlock;
1804
0
    ctxPtr->nextToUpdate = ctxPtr->dictLimit;   /* match referencing will resume from there */
1805
1806
    /* cannot reference an extDict and a dictCtx at the same time */
1807
0
    ctxPtr->dictCtx = NULL;
1808
0
}
1809
1810
static int
1811
LZ4_compressHC_continue_generic (LZ4_streamHC_t* LZ4_streamHCPtr,
1812
                                 const char* src, char* dst,
1813
                                 int* srcSizePtr, int dstCapacity,
1814
                                 limitedOutput_directive limit)
1815
0
{
1816
0
    LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;
1817
0
    DEBUGLOG(5, "LZ4_compressHC_continue_generic(ctx=%p, src=%p, srcSize=%d, limit=%d)",
1818
0
                LZ4_streamHCPtr, src, *srcSizePtr, limit);
1819
0
    assert(ctxPtr != NULL);
1820
    /* auto-init if forgotten */
1821
0
    if (ctxPtr->prefixStart == NULL)
1822
0
        LZ4HC_init_internal (ctxPtr, (const BYTE*) src);
1823
1824
    /* Check overflow */
1825
0
    if ((size_t)(ctxPtr->end - ctxPtr->prefixStart) + ctxPtr->dictLimit > 2 GB) {
1826
0
        size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->prefixStart);
1827
0
        if (dictSize > 64 KB) dictSize = 64 KB;
1828
0
        LZ4_loadDictHC(LZ4_streamHCPtr, (const char*)(ctxPtr->end) - dictSize, (int)dictSize);
1829
0
    }
1830
1831
    /* Check if blocks follow each other */
1832
0
    if ((const BYTE*)src != ctxPtr->end)
1833
0
        LZ4HC_setExternalDict(ctxPtr, (const BYTE*)src);
1834
1835
    /* Check overlapping input/dictionary space */
1836
0
    {   const BYTE* sourceEnd = (const BYTE*) src + *srcSizePtr;
1837
0
        const BYTE* const dictBegin = ctxPtr->dictStart;
1838
0
        const BYTE* const dictEnd   = ctxPtr->dictStart + (ctxPtr->dictLimit - ctxPtr->lowLimit);
1839
0
        if ((sourceEnd > dictBegin) && ((const BYTE*)src < dictEnd)) {
1840
0
            if (sourceEnd > dictEnd) sourceEnd = dictEnd;
1841
0
            ctxPtr->lowLimit += (U32)(sourceEnd - ctxPtr->dictStart);
1842
0
            ctxPtr->dictStart += (U32)(sourceEnd - ctxPtr->dictStart);
1843
            /* invalidate dictionary is it's too small */
1844
0
            if (ctxPtr->dictLimit - ctxPtr->lowLimit < LZ4HC_HASHSIZE) {
1845
0
                ctxPtr->lowLimit = ctxPtr->dictLimit;
1846
0
                ctxPtr->dictStart = ctxPtr->prefixStart;
1847
0
    }   }   }
1848
1849
0
    return LZ4HC_compress_generic (ctxPtr, src, dst, srcSizePtr, dstCapacity, ctxPtr->compressionLevel, limit);
1850
0
}
1851
1852
int LZ4_compress_HC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int srcSize, int dstCapacity)
1853
0
{
1854
0
    DEBUGLOG(5, "LZ4_compress_HC_continue");
1855
0
    if (dstCapacity < LZ4_compressBound(srcSize))
1856
0
        return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, limitedOutput);
1857
0
    else
1858
0
        return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, notLimited);
1859
0
}
1860
1861
int LZ4_compress_HC_continue_destSize (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int* srcSizePtr, int targetDestSize)
1862
0
{
1863
0
    return LZ4_compressHC_continue_generic(LZ4_streamHCPtr, src, dst, srcSizePtr, targetDestSize, fillOutput);
1864
0
}
1865
1866
1867
/* LZ4_saveDictHC :
1868
 * save history content
1869
 * into a user-provided buffer
1870
 * which is then used to continue compression
1871
 */
1872
int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictSize)
1873
0
{
1874
0
    LZ4HC_CCtx_internal* const streamPtr = &LZ4_streamHCPtr->internal_donotuse;
1875
0
    size_t const prefixSize = (size_t)(streamPtr->end - streamPtr->prefixStart);   /* can exceed INT_MAX */
1876
0
    DEBUGLOG(5, "LZ4_saveDictHC(%p, %p, %d)", LZ4_streamHCPtr, safeBuffer, dictSize);
1877
    /* nothing compressed yet (new or reset stream) : nothing to save,
1878
     * the stream remains to be initialized by next compression (attached dictionary included) */
1879
0
    if (streamPtr->prefixStart == NULL) return 0;
1880
0
    assert(streamPtr->end >= streamPtr->prefixStart);
1881
0
    if (dictSize > 64 KB) dictSize = 64 KB;
1882
0
    if (dictSize < 4) dictSize = 0;
1883
0
    if ((size_t)dictSize > prefixSize) dictSize = (int)prefixSize;   /* 0 <= dictSize <= 64 KB : prefixSize fits */
1884
0
    if (safeBuffer == NULL) assert(dictSize == 0); /* a NULL buffer with !0 size is invalid */
1885
0
    if (dictSize > 0)
1886
0
        LZ4_memmove(safeBuffer, streamPtr->end - dictSize, (size_t)dictSize);
1887
0
    {   U32 const endIndex = (U32)(streamPtr->end - streamPtr->prefixStart) + streamPtr->dictLimit;
1888
0
        streamPtr->end = (safeBuffer == NULL) ? NULL : (const BYTE*)safeBuffer + dictSize;
1889
0
        streamPtr->prefixStart = (const BYTE*)safeBuffer;
1890
0
        streamPtr->dictLimit = endIndex - (U32)dictSize;
1891
0
        streamPtr->lowLimit = endIndex - (U32)dictSize;
1892
0
        streamPtr->dictStart = streamPtr->prefixStart;
1893
0
        if (streamPtr->nextToUpdate < streamPtr->dictLimit)
1894
0
            streamPtr->nextToUpdate = streamPtr->dictLimit;
1895
0
    }
1896
0
    return dictSize;
1897
0
}
1898
1899
1900
/* ================================================
1901
 *  LZ4 Optimal parser (levels [LZ4HC_CLEVEL_OPT_MIN - LZ4HC_CLEVEL_MAX])
1902
 * ===============================================*/
1903
typedef struct {
1904
    int price;
1905
    int off;
1906
    int mlen;   /* 1 means literal */
1907
    int litlen;
1908
} LZ4HC_optimal_t;
1909
1910
0
#define TRAILING_LITERALS 3
1911
1912
/* Prices are in 1/LZ4HC_PRICE_SCALE byte,
1913
 * leaving room for a price per sequence, lower than a byte. */
1914
0
#define LZ4HC_PRICE_SCALE 4
1915
1916
/* favorDecSpeed : each sequence costs decoding time, so it also costs LZ4HC_SEQ_PRICE_FDS.
1917
 * Removing a sequence almost always costs at least one byte,
1918
 * so this price, lower than a byte, mostly acts as a tie-breaker :
1919
 * among solutions of the same size, the one with fewer sequences is preferred.
1920
 * They are found at positions only worth searching to save a sequence,
1921
 * which are searched if at most LZ4HC_SEQ_SEARCH_DIST before the end of the furthest match. */
1922
0
#define LZ4HC_SEQ_PRICE_FDS    1
1923
0
#define LZ4HC_SEQ_SEARCH_DIST  4
1924
1925
LZ4_FORCE_INLINE int LZ4HC_literalsPrice(int const litlen)
1926
0
{
1927
0
    int price = litlen;
1928
0
    assert(litlen >= 0);
1929
0
    if (litlen >= (int)RUN_MASK)
1930
0
        price += 1 + ((litlen-(int)RUN_MASK) / 255);
1931
0
    return price * LZ4HC_PRICE_SCALE;
1932
0
}
1933
1934
/* requires mlen >= MINMATCH */
1935
LZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen)
1936
0
{
1937
0
    int price = 1 + 2 ; /* token + 16-bit offset */
1938
0
    assert(litlen >= 0);
1939
0
    assert(mlen >= MINMATCH);
1940
1941
0
    if (mlen >= (int)(ML_MASK+MINMATCH))
1942
0
        price += 1 + ((mlen-(int)(ML_MASK+MINMATCH)) / 255);
1943
1944
0
    return price * LZ4HC_PRICE_SCALE + LZ4HC_literalsPrice(litlen);
1945
0
}
1946
1947
/* LZ4HC_pricedLitlen() :
1948
 * All solutions of a window start with the same run of @llen literals,
1949
 * so only price differences matter, and they depend on @llen
1950
 * only through its position relative to the 255-steps of the literal length field.
1951
 * Reduce it accordingly : scaled prices of long runs would overflow. */
1952
LZ4_FORCE_INLINE int LZ4HC_pricedLitlen(int const llen)
1953
0
{
1954
0
    int const reduceFrom = (int)RUN_MASK + 255;
1955
0
    assert(llen >= 0);
1956
0
    if (llen < reduceFrom) return llen;
1957
0
    return reduceFrom + ((llen - (int)RUN_MASK) % 255);
1958
0
}
1959
1960
LZ4_FORCE_INLINE LZ4HC_match_t
1961
LZ4HC_FindLongestMatch(LZ4HC_CCtx_internal* const ctx,
1962
                       const BYTE* ip, const BYTE* const iHighLimit,
1963
                       int nbSearches,
1964
                       const dictCtx_directive dict,
1965
                       const HCfavor_e favorDecSpeed)
1966
0
{
1967
0
    LZ4HC_match_t const match0 = { 0 , 0, 0 };
1968
    /* note : LZ4HC_InsertAndGetWiderMatch() can extend a match backward (md.back < 0),
1969
     * but not here, since iLowLimit == ip */
1970
0
    LZ4HC_match_t md = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, MINMATCH-1, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed);
1971
0
    assert(md.back == 0);
1972
0
    if (md.len < MINMATCH) return match0;
1973
0
    if (favorDecSpeed) {
1974
0
        if ((md.len>18) & (md.len<=36)) md.len=18;   /* favor dec.speed (shortcut) */
1975
0
    }
1976
0
    return md;
1977
0
}
1978
1979
LZ4_FORCE_INLINE void
1980
LZ4HC_setLiteral(LZ4HC_optimal_t* opt, int pos, int litlen, int price)
1981
0
{
1982
0
    opt[pos].mlen = 1;
1983
0
    opt[pos].off = 0;
1984
0
    opt[pos].litlen = litlen;
1985
0
    opt[pos].price = price;
1986
0
    DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)", pos, price, litlen);
1987
0
}
1988
1989
LZ4_FORCE_INLINE void
1990
LZ4HC_setMatch(LZ4HC_optimal_t* opt, int pos, int mlen, int off, int price)
1991
0
{
1992
0
    opt[pos].mlen = mlen;
1993
0
    opt[pos].off = off;
1994
0
    opt[pos].litlen = 0;
1995
0
    opt[pos].price = price;
1996
0
    DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i)", pos, price, mlen);
1997
0
}
1998
1999
/* price at the start of the literal run ending at @pos
2000
 * (0 if this run started before position 0, i.e. it includes literals since anchor) */
2001
LZ4_FORCE_INLINE int LZ4HC_runStartPrice(const LZ4HC_optimal_t* opt, int pos)
2002
0
{
2003
0
    int const ll = opt[pos].litlen;
2004
0
    return (ll <= pos) ? opt[pos - ll].price : 0;
2005
0
}
2006
2007
/* LZ4HC_addMatch() :
2008
 * Update prices of positions reachable from @cur using @match.
2009
 * Positions beyond @lastPos + TRAILING_LITERALS are not reached yet.
2010
 * @return : updated @lastPos (end of the furthest match) */
2011
LZ4_FORCE_INLINE int
2012
LZ4HC_addMatch(LZ4HC_optimal_t* opt, int cur, LZ4HC_match_t match,
2013
               int lastPos, const HCfavor_e favorDecSpeed)
2014
0
{
2015
0
    int const ll = opt[cur].litlen;
2016
0
    int const basePrice = LZ4HC_runStartPrice(opt, cur) + (favorDecSpeed ? LZ4HC_SEQ_PRICE_FDS : 0);
2017
0
    int ml;
2018
0
    assert(cur + match.len < LZ4_OPT_NUM);
2019
0
    assert((U32)favorDecSpeed <= 1);
2020
0
    for (ml = MINMATCH; ml <= match.len; ml++) {
2021
0
        int const pos = cur + ml;
2022
0
        int const price = basePrice + LZ4HC_sequencePrice(ll, ml);
2023
        /* on equal price, favorDecSpeed keeps the existing solution */
2024
0
        if ( pos > lastPos + TRAILING_LITERALS
2025
0
          || price <= opt[pos].price - (int)favorDecSpeed) {
2026
0
            LZ4HC_setMatch(opt, pos, ml, match.off, price);
2027
0
            if ((ml == match.len) && (lastPos < pos)) lastPos = pos;
2028
0
    }   }
2029
2030
    /* complete following positions with literals */
2031
0
    {   int addLit;
2032
0
        assert(opt[lastPos].mlen >= MINMATCH);
2033
0
        for (addLit = 1; addLit <= TRAILING_LITERALS; addLit++)
2034
0
            LZ4HC_setLiteral(opt, lastPos + addLit, addLit,
2035
0
                             opt[lastPos].price + LZ4HC_literalsPrice(addLit));
2036
0
    }
2037
0
    return lastPos;
2038
0
}
2039
2040
2041
/* preconditions:
2042
 * - *srcSizePtr within [1, LZ4_MAX_INPUT_SIZE]
2043
 * - src is valid
2044
 * - maxOutputSize >= 1
2045
 * - dst is valid
2046
 * - @opt : table of LZ4_OPT_NUM + TRAILING_LITERALS cells
2047
 */
2048
LZ4_FORCE_INLINE int
2049
LZ4HC_compress_optimal_internal(LZ4HC_CCtx_internal* ctx,
2050
                                const char* const source,
2051
                                char* dst,
2052
                                int* srcSizePtr,
2053
                                int dstCapacity,
2054
                                int const nbSearches,
2055
                                int const nbSearchesSeq,
2056
                                int const targetLength,
2057
                                const limitedOutput_directive limit,
2058
                                const dictCtx_directive dict,
2059
                                const HCfavor_e favorDecSpeed,
2060
                                LZ4HC_optimal_t* const opt)
2061
0
{
2062
0
    const BYTE* ip = (const BYTE*) source;
2063
0
    const BYTE* anchor = ip;
2064
0
    const int inputSize = *srcSizePtr;
2065
0
    const BYTE* const iend = ip + inputSize;
2066
0
    const BYTE* mflimit;      /* set after the size check : would precede a small input */
2067
0
    const BYTE* matchlimit;
2068
0
    BYTE* op = (BYTE*) dst;
2069
    /* fillOutput : keep room for the final run of literals (LZ4 format restriction) */
2070
0
    BYTE* const oend = op + dstCapacity - ((limit == fillOutput) ? LASTLITERALS : 0);
2071
0
    int const sufficientLen = MIN(targetLength, LZ4_OPT_NUM-1);
2072
2073
0
    DEBUGLOG(5, "LZ4HC_compress_optimal(dst=%p, dstCapa=%u)", dst, (unsigned)dstCapacity);
2074
2075
    /* preconditions verifications */
2076
0
    assert(dstCapacity > 0);
2077
0
    assert(dst != NULL);
2078
0
    assert(*srcSizePtr > 0);
2079
0
    assert(source != NULL);
2080
0
    assert(opt != NULL);
2081
0
    assert(nbSearchesSeq >= 1);
2082
2083
0
    *srcSizePtr = 0;
2084
0
    if (inputSize < LZ4_minLength) goto _last_literals;
2085
0
    mflimit = iend - MFLIMIT;
2086
0
    matchlimit = iend - LASTLITERALS;
2087
2088
    /* Main Loop */
2089
0
    while (ip <= mflimit) {
2090
0
        int const llen = LZ4HC_pricedLitlen((int)(ip - anchor));
2091
0
        int cur, lastPos;
2092
0
        int lastSeqPos;         /* position of the last sequence to encode */
2093
0
        LZ4HC_match_t lastSeq;
2094
2095
0
        LZ4HC_match_t const firstMatch = LZ4HC_FindLongestMatch(ctx, ip, matchlimit, nbSearches, dict, favorDecSpeed);
2096
0
        if (firstMatch.len==0) { ip++; continue; }
2097
2098
0
        if (firstMatch.len > sufficientLen) {
2099
            /* good enough solution : immediate encoding */
2100
0
            lastSeqPos = 0;
2101
0
            lastSeq = firstMatch;
2102
0
            goto encode;
2103
0
        }
2104
2105
        /* set prices for first positions (literals) */
2106
0
        {   int rPos;
2107
0
            for (rPos = 0 ; rPos < MINMATCH ; rPos++)
2108
0
                LZ4HC_setLiteral(opt, rPos, llen + rPos, LZ4HC_literalsPrice(llen + rPos));
2109
0
        }
2110
0
        lastPos = LZ4HC_addMatch(opt, 0, firstMatch, 0, favorDecSpeed);
2111
2112
        /* check further positions */
2113
0
        for (cur = 1; cur < lastPos; cur++) {
2114
0
            const BYTE* const curPtr = ip + cur;
2115
0
            LZ4HC_match_t newMatch;
2116
0
            int nbS = nbSearches;
2117
2118
0
            if (curPtr > mflimit) break;
2119
0
            DEBUGLOG(7, "rPos:%u[%u] vs [%u]%u",
2120
0
                    cur, opt[cur].price, opt[cur+1].price, cur+1);
2121
            /* not useful to search here if next position has same (or lower) cost */
2122
0
            if (opt[cur+1].price <= opt[cur].price) continue;
2123
            /* favorDecSpeed : next position costs less than one more byte, the difference comes from sequences.
2124
             * A match starting here might save some : worth a cheaper search, if close to lastPos */
2125
0
            if (favorDecSpeed && (opt[cur+1].price < opt[cur].price + LZ4HC_PRICE_SCALE)) {
2126
0
                if (lastPos - cur > LZ4HC_SEQ_SEARCH_DIST) continue;
2127
0
                nbS = nbSearchesSeq;
2128
0
            }
2129
2130
0
            newMatch = LZ4HC_FindLongestMatch(ctx, curPtr, matchlimit, nbS, dict, favorDecSpeed);
2131
0
            if (!newMatch.len) continue;
2132
2133
0
            if ( (newMatch.len > sufficientLen)
2134
0
              || (newMatch.len + cur >= LZ4_OPT_NUM) ) {
2135
                /* immediate encoding */
2136
0
                lastSeqPos = cur;
2137
0
                lastSeq = newMatch;
2138
0
                goto encode;
2139
0
            }
2140
2141
0
            lastPos = LZ4HC_addMatch(opt, cur, newMatch, lastPos, favorDecSpeed);
2142
0
        }  /* for (cur = 1; cur < lastPos; cur++) */
2143
2144
0
        assert(lastPos < LZ4_OPT_NUM + TRAILING_LITERALS);
2145
0
        lastSeq.len = opt[lastPos].mlen;
2146
0
        lastSeq.off = opt[lastPos].off;
2147
0
        lastSeqPos = lastPos - lastSeq.len;
2148
2149
0
encode: /* lastSeqPos and lastSeq must be set */
2150
0
        assert(0 <= lastSeqPos && lastSeqPos < LZ4_OPT_NUM);
2151
0
        DEBUGLOG(6, "reverse traversal, looking for shortest path (lastSeqPos=%i)", lastSeqPos);
2152
        /* opt[pos] describes the step ending at pos.
2153
         * Walk the path backward, moving each step to its starting position instead */
2154
0
        {   int pos = lastSeqPos;
2155
0
            int mlen = lastSeq.len;
2156
0
            int off = lastSeq.off;
2157
0
            while (pos > 0) {
2158
0
                int const prevMlen = opt[pos].mlen;
2159
0
                int const prevOff = opt[pos].off;
2160
0
                opt[pos].mlen = mlen;
2161
0
                opt[pos].off = off;
2162
0
                mlen = prevMlen;
2163
0
                off = prevOff;
2164
0
                assert(0 < mlen && mlen <= pos);
2165
0
                pos -= mlen;
2166
0
            }
2167
            /* first step of the path; note : opt[0] isn't necessarily initialized */
2168
0
            opt[0].mlen = mlen;
2169
0
            opt[0].off = off;
2170
0
        }
2171
2172
        /* encode all recorded sequences in order */
2173
0
        {   int rPos = 0;  /* relative position (to ip) */
2174
0
            while (rPos <= lastSeqPos) {
2175
0
                int const ml = opt[rPos].mlen;
2176
0
                int const offset = opt[rPos].off;
2177
0
                if (ml == 1) { ip++; rPos++; continue; }  /* literal */
2178
0
                rPos += ml;
2179
0
                assert(ml >= MINMATCH);
2180
0
                assert((offset >= 1) && (offset <= LZ4_DISTANCE_MAX));
2181
0
                if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, offset, limit, oend) ) {  /* updates ip, op and anchor */
2182
0
                    if (limit != fillOutput) return 0;  /* compression failed */
2183
0
                    LZ4HC_encodeLastSequence_fillOutput(UPDATABLE(ip, op, anchor), ml, offset, oend);
2184
0
                    goto _last_literals;
2185
0
        }   }   }
2186
0
    }  /* while (ip <= mflimit) */
2187
2188
0
_last_literals:
2189
0
    if (LZ4HC_encodeLastLiterals(UPDATABLE(ip, op, anchor), iend, limit, oend))
2190
0
        return 0;  /* not enough space in @dst */
2191
2192
    /* End */
2193
0
    *srcSizePtr = (int) (((const char*)ip) - source);
2194
0
    return (int) ((char*)op-dst);
2195
0
}
2196
2197
static int LZ4HC_compress_optimal ( LZ4HC_CCtx_internal* ctx,
2198
                                    const char* const source,
2199
                                    char* dst,
2200
                                    int* srcSizePtr,
2201
                                    int dstCapacity,
2202
                                    int const nbSearches,
2203
                                    int const nbSearchesSeq,
2204
                                    int const targetLength,
2205
                                    const limitedOutput_directive limit,
2206
                                    const dictCtx_directive dict,
2207
                                    const HCfavor_e favorDecSpeed)
2208
0
{
2209
0
    LZ4_STATIC_ASSERT(LZ4_STREAMHC_EXTSIZE == sizeof(LZ4_streamHC_t) + sizeof(LZ4HC_optimal_t) * (LZ4_OPT_NUM + TRAILING_LITERALS));
2210
0
    if (ctx->hasWorkspace) {   /* extended state : the buffer follows it */
2211
0
        LZ4HC_optimal_t* const opt = (LZ4HC_optimal_t*)(void*)((BYTE*)ctx + sizeof(LZ4_streamHC_t));
2212
0
        return LZ4HC_compress_optimal_internal(ctx, source, dst, srcSizePtr, dstCapacity,
2213
0
                    nbSearches, nbSearchesSeq, targetLength, limit, dict, favorDecSpeed, opt);
2214
0
    }
2215
0
  { /* plain state */
2216
0
#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
2217
0
    LZ4HC_optimal_t* const opt = (LZ4HC_optimal_t*)ALLOC(sizeof(LZ4HC_optimal_t) * (LZ4_OPT_NUM + TRAILING_LITERALS));
2218
0
    int result;
2219
0
    if (opt == NULL) return 0;
2220
0
    result = LZ4HC_compress_optimal_internal(ctx, source, dst, srcSizePtr, dstCapacity,
2221
0
                    nbSearches, nbSearchesSeq, targetLength, limit, dict, favorDecSpeed, opt);
2222
0
    FREEMEM(opt);
2223
0
    return result;
2224
#else
2225
    LZ4HC_optimal_t opt[LZ4_OPT_NUM + TRAILING_LITERALS];   /* ~64 KB, which can be a bit large for some stacks... */
2226
    return LZ4HC_compress_optimal_internal(ctx, source, dst, srcSizePtr, dstCapacity,
2227
                    nbSearches, nbSearchesSeq, targetLength, limit, dict, favorDecSpeed, opt);
2228
#endif
2229
0
  }
2230
0
}
2231
2232
2233
/***************************************************
2234
*  Obsolete functions, removed from lz4hc.h (v1.11.0)
2235
*  still exported, for programs linked to previous versions
2236
***************************************************/
2237
#if defined (__cplusplus)
2238
extern "C" {
2239
#endif
2240
2241
LZ4LIB_API int LZ4_compressHC (const char* source, char* dest, int inputSize);
2242
LZ4LIB_API int LZ4_compressHC_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize);
2243
LZ4LIB_API int LZ4_compressHC2 (const char* source, char* dest, int inputSize, int compressionLevel);
2244
LZ4LIB_API int LZ4_compressHC2_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);
2245
LZ4LIB_API int LZ4_compressHC_withStateHC (void* state, const char* source, char* dest, int inputSize);
2246
LZ4LIB_API int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
2247
LZ4LIB_API int LZ4_compressHC2_withStateHC (void* state, const char* source, char* dest, int inputSize, int compressionLevel);
2248
LZ4LIB_API int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);
2249
LZ4LIB_API int LZ4_compressHC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize);
2250
LZ4LIB_API int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
2251
LZ4LIB_API void* LZ4_createHC (const char* inputBuffer);
2252
LZ4LIB_API int   LZ4_freeHC (void* LZ4HC_Data);
2253
LZ4LIB_API char* LZ4_slideInputBufferHC (void* LZ4HC_Data);
2254
LZ4LIB_API int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int compressionLevel);
2255
LZ4LIB_API int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);
2256
LZ4LIB_API int   LZ4_sizeofStreamStateHC(void);
2257
LZ4LIB_API int   LZ4_resetStreamStateHC(void* state, char* inputBuffer);
2258
2259
#if defined (__cplusplus)
2260
}
2261
#endif
2262
2263
/* Wrappers for deprecated compression functions */
2264
0
int LZ4_compressHC(const char* src, char* dst, int srcSize) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
2265
0
int LZ4_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, 0); }
2266
0
int LZ4_compressHC2(const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
2267
0
int LZ4_compressHC2_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, cLevel); }
2268
0
int LZ4_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
2269
0
int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize, 0); }
2270
0
int LZ4_compressHC2_withStateHC (void* state, const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
2271
0
int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, maxDstSize, cLevel); }
2272
0
int LZ4_compressHC_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, LZ4_compressBound(srcSize)); }
2273
0
int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); }
2274
2275
2276
/* Deprecated streaming functions */
2277
0
int LZ4_sizeofStreamStateHC(void) { return sizeof(LZ4_streamHC_t); }
2278
2279
/* state is presumed correctly sized, aka >= sizeof(LZ4_streamHC_t)
2280
 * @return : 0 on success, !=0 if error */
2281
int LZ4_resetStreamStateHC(void* state, char* inputBuffer)
2282
0
{
2283
0
    LZ4_streamHC_t* const hc4 = LZ4_initStreamHC(state, sizeof(*hc4));
2284
0
    if (hc4 == NULL) return 1;   /* init failed */
2285
0
    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
2286
0
    return 0;
2287
0
}
2288
2289
void* LZ4_createHC (const char* inputBuffer)
2290
0
{
2291
0
    LZ4_streamHC_t* const hc4 = LZ4_createStreamHC();
2292
0
    if (hc4 == NULL) return NULL;   /* not enough memory */
2293
0
    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
2294
0
    return hc4;
2295
0
}
2296
2297
int LZ4_freeHC (void* LZ4HC_Data)
2298
0
{
2299
0
    if (!LZ4HC_Data) return 0;  /* support free on NULL */
2300
0
    FREEMEM(LZ4HC_Data);
2301
0
    return 0;
2302
0
}
2303
2304
/* LZ4_compress_HC_continue() at level @cLevel : notably, restarts the stream after LZ4_slideInputBufferHC() */
2305
int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int cLevel)
2306
0
{
2307
0
    LZ4_setCompressionLevel((LZ4_streamHC_t*)LZ4HC_Data, cLevel);
2308
0
    return LZ4_compress_HC_continue((LZ4_streamHC_t*)LZ4HC_Data, src, dst, srcSize, LZ4_compressBound(srcSize));
2309
0
}
2310
2311
int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int dstCapacity, int cLevel)
2312
0
{
2313
0
    LZ4_setCompressionLevel((LZ4_streamHC_t*)LZ4HC_Data, cLevel);
2314
0
    return LZ4_compress_HC_continue((LZ4_streamHC_t*)LZ4HC_Data, src, dst, srcSize, dstCapacity);
2315
0
}
2316
2317
char* LZ4_slideInputBufferHC(void* LZ4HC_Data)
2318
0
{
2319
0
    LZ4HC_CCtx_internal* const s = &((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse;
2320
0
    const BYTE* const bufferStart = s->prefixStart - s->dictLimit + s->lowLimit;
2321
0
    LZ4_resetStreamHC_fast((LZ4_streamHC_t*)LZ4HC_Data, s->compressionLevel);
2322
    /* ugly conversion trick, required to evade (const char*) -> (char*) cast-qual warning :( */
2323
0
    return (char*)(uptrval)bufferStart;
2324
0
}