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
567k
#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)
86
2.23M
#define LZ4_OPT_NUM   (1<<12)
87
88
89
/*===   Macros   ===*/
90
#undef MIN
91
51.6M
#define MIN(a,b)   ( (a) < (b) ? (a) : (b) )
92
#undef MAX
93
223M
#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
51.2k
{
124
    /* note : clevel convention is a bit different from lz4frame,
125
     * possibly something worth revisiting for consistency */
126
51.2k
    if (cLevel < 1)
127
0
        cLevel = LZ4HC_CLEVEL_DEFAULT;
128
51.2k
    cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel);
129
51.2k
    return k_clTable[cLevel];
130
51.2k
}
131
132
133
/*===   Hashing   ===*/
134
1.45k
#define LZ4HC_HASHSIZE 4
135
453M
#define HASH_FUNCTION(i)      (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG))
136
453M
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
33.2M
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
8.57k
#define LZ4MID_HASHSIZE 8
156
55.6M
#define LZ4MID_HASHLOG (LZ4HC_HASH_LOG-1)
157
10.5k
#define LZ4MID_HASHTABLESIZE (1 << LZ4MID_HASHLOG)
158
159
22.3M
static U32 LZ4MID_hash4(U32 v) { return (v * 2654435761U) >> (32-LZ4MID_HASHLOG); }
160
22.3M
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
33.2M
static U32 LZ4MID_hash7(U64 v) { return (U32)(((v  << (64-56)) * 58295818150454627ULL) >> (64-LZ4MID_HASHLOG)) ; }
164
static U64 LZ4_readLE64(const void* memPtr);
165
33.2M
static U32 LZ4MID_hash8Ptr(const void* ptr) { return LZ4MID_hash7(LZ4_readLE64(ptr)); }
166
167
static U64 LZ4_readLE64(const void* memPtr)
168
33.2M
{
169
33.2M
    if (LZ4_isLittleEndian()) {
170
33.2M
        return LZ4_read64(memPtr);
171
33.2M
    } 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
33.2M
}
178
179
180
/*===   Count match length   ===*/
181
LZ4_FORCE_INLINE
182
unsigned LZ4HC_NbCommonBytes32(U32 val)
183
112M
{
184
112M
    assert(val != 0);
185
112M
    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
112M
    } 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
112M
}
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
131M
{
222
131M
    int back = 0;
223
131M
    int const min = (int)MAX(iMin - ip, mMin - match);
224
131M
    assert(min <= 0);
225
131M
    assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31));
226
131M
    assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31));
227
228
468M
    while ((back - min) > 3) {
229
449M
        U32 const v = LZ4_read32(ip + back - 4) ^ LZ4_read32(match + back - 4);
230
449M
        if (v) {
231
112M
            return (back - (int)LZ4HC_NbCommonBytes32(v));
232
336M
        } else back -= 4; /* 4-byte step */
233
449M
    }
234
    /* check remainder if any */
235
28.7M
    while ( (back > min)
236
28.3M
         && (ip[back-1] == match[back-1]) )
237
9.66M
            back--;
238
19.0M
    return back;
239
131M
}
240
241
/*===   Chain table updates   ===*/
242
1.58G
#define DELTANEXTU16(table, pos) table[(U16)(pos)]   /* faster */
243
/* Make fields passed to, and updated by LZ4HC_encodeSequence explicit */
244
5.69M
#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
36.5k
{
258
36.5k
    size_t const bufferSize = (size_t)(hc4->end - hc4->prefixStart);
259
36.5k
    size_t newStartingOffset = bufferSize + hc4->dictLimit;
260
36.5k
    DEBUGLOG(5, "LZ4HC_init_internal");
261
36.5k
    assert(newStartingOffset >= bufferSize);  /* check overflow */
262
36.5k
    if (newStartingOffset > 1 GB) {
263
0
        LZ4HC_clearTables(hc4);
264
0
        newStartingOffset = 0;
265
0
    }
266
36.5k
    newStartingOffset += 64 KB;
267
36.5k
    hc4->nextToUpdate = (U32)newStartingOffset;
268
36.5k
    hc4->prefixStart = start;
269
36.5k
    hc4->end = start;
270
36.5k
    hc4->dictStart = start;
271
36.5k
    hc4->dictLimit = (U32)newStartingOffset;
272
36.5k
    hc4->lowLimit = (U32)newStartingOffset;
273
36.5k
}
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
5.64M
{
315
16.9M
#define ip      (*_ip)
316
48.1M
#define op      (*_op)
317
16.9M
#define anchor  (*_anchor)
318
319
5.64M
    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
5.64M
    {   size_t litLen = (size_t)(ip - anchor);
342
5.64M
        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
5.64M
        if (limit && (oend - op < (ptrdiff_t)((litLen / 255) + litLen + (2 + 1 + LASTLITERALS)))) {
346
1.77k
            DEBUGLOG(6, "Not enough room to write %i literals (%i bytes remaining)",
347
1.77k
                    (int)litLen, (int)(oend - op));
348
1.77k
            op = token;
349
1.77k
            return 1;
350
1.77k
        }
351
5.64M
        if (litLen >= RUN_MASK) {
352
465k
            size_t len = litLen - RUN_MASK;
353
465k
            *token = (RUN_MASK << ML_BITS);
354
602k
            for(; len >= 255 ; len -= 255) *op++ = 255;
355
465k
            *op++ = (BYTE)len;
356
5.18M
        } else {
357
5.18M
            *token = (BYTE)(litLen << ML_BITS);
358
5.18M
        }
359
360
        /* Copy Literals */
361
5.64M
        LZ4_wildCopy8(op, anchor, op + litLen);
362
5.64M
        op += litLen;
363
5.64M
    }
364
365
    /* Encode Offset */
366
5.64M
    assert(offset <= LZ4_DISTANCE_MAX );
367
5.64M
    assert(offset > 0);
368
5.64M
    LZ4_writeLE16(op, (U16)(offset)); op += 2;
369
370
    /* Encode MatchLength */
371
5.64M
    assert(matchLength >= MINMATCH);
372
5.64M
    {   size_t mlCode = (size_t)matchLength - MINMATCH;
373
5.64M
        if (limit && (oend - op < (ptrdiff_t)((mlCode / 255) + (1 + LASTLITERALS)))) {
374
110
            DEBUGLOG(6, "Not enough room to write match length");
375
110
            op = token;
376
110
            return 1;
377
110
        }
378
5.64M
        if (mlCode >= ML_MASK) {
379
959k
            *token += ML_MASK;
380
959k
            mlCode -= ML_MASK;
381
1.62M
            for(; mlCode >= 510 ; mlCode -= 510) { *op++ = 255; *op++ = 255; }
382
959k
            if (mlCode >= 255) { mlCode -= 255; *op++ = 255; }
383
959k
            *op++ = (BYTE)mlCode;
384
4.68M
        } else {
385
4.68M
            *token += (BYTE)(mlCode);
386
4.68M
    }   }
387
388
    /* Prepare next loop */
389
5.64M
    ip += matchLength;
390
5.64M
    anchor = ip;
391
392
5.64M
    return 0;
393
394
5.64M
#undef ip
395
5.64M
#undef op
396
5.64M
#undef anchor
397
5.64M
}
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
47.2k
{
413
47.2k
#define ip      (*_ip)
414
115k
#define op      (*_op)
415
73.4k
#define anchor  (*_anchor)
416
417
47.2k
    BYTE* const dstEnd = (limit == fillOutput) ? oend + LASTLITERALS : oend;
418
47.2k
    size_t lastRunSize = (size_t)(iend - anchor);  /* literals */
419
47.2k
    size_t llAdd = (lastRunSize + 255 - RUN_MASK) / 255;
420
47.2k
    size_t const totalSize = 1 + llAdd + lastRunSize;
421
47.2k
    assert(!limit || op <= dstEnd);
422
47.2k
    if (limit && ((size_t)(dstEnd - op) < totalSize)) {   /* compares sizes, as op + totalSize could exceed the address space */
423
21.0k
        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
26.2k
    DEBUGLOG(6, "Final literal run : %i literals", (int)lastRunSize);
430
26.2k
    ip = anchor + lastRunSize;  /* can be != iend if limit==fillOutput */
431
432
26.2k
    if (lastRunSize >= RUN_MASK) {
433
1.94k
        size_t accumulator = lastRunSize - RUN_MASK;
434
1.94k
        *op++ = (RUN_MASK << ML_BITS);
435
15.3k
        for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255;
436
1.94k
        *op++ = (BYTE) accumulator;
437
24.2k
    } else {
438
24.2k
        *op++ = (BYTE)(lastRunSize << ML_BITS);
439
24.2k
    }
440
26.2k
    assert(lastRunSize <= (size_t)(dstEnd - op));
441
26.2k
    LZ4_memcpy(op, anchor, lastRunSize);
442
26.2k
    op += lastRunSize;
443
26.2k
    return 0;
444
445
26.2k
#undef ip
446
26.2k
#undef op
447
26.2k
#undef anchor
448
26.2k
}
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
14
{
615
14
    U32* const hashTable = ctx->hashTable;
616
14
    U32 const startIdx = ctx->dictLimit + (U32)(start - ctx->prefixStart);
617
14
    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
14
    } else {
624
14
        U32 idx = startIdx;
625
14
        const BYTE* p;
626
14
        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
14
}
637
638
/**************************************
639
*  Mid Compression (level 2)
640
**************************************/
641
642
LZ4_FORCE_INLINE void
643
LZ4MID_addPosition(U32* hTable, U32 hValue, U32 index)
644
54.8M
{
645
54.8M
    hTable[hValue] = index;
646
54.8M
}
647
648
17.6M
#define ADDPOS8(_p, _idx) LZ4MID_addPosition(hash8Table, LZ4MID_hash8Ptr(_p), _idx)
649
8.41M
#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
476
{
656
476
    U32* const hash4Table = cctx->hashTable;
657
476
    U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
658
476
    const BYTE* const prefixPtr = (const BYTE*)dict;
659
476
    U32 const prefixIdx = cctx->dictLimit;
660
476
    U32 const target = prefixIdx + (U32)size - LZ4MID_HASHSIZE;
661
476
    U32 idx = cctx->nextToUpdate;
662
476
    assert(dict == cctx->prefixStart);
663
476
    DEBUGLOG(4, "LZ4MID_fillHTable (size:%zu)", size);
664
476
    if (size <= LZ4MID_HASHSIZE)
665
78
        return;
666
667
3.86M
    for (; idx < target; idx += 3) {
668
3.86M
        ADDPOS4(prefixPtr+idx-prefixIdx, idx);
669
3.86M
        ADDPOS8(prefixPtr+idx+1-prefixIdx, idx+1);
670
3.86M
    }
671
672
398
    idx = (size > 32 KB + LZ4MID_HASHSIZE) ? target - 32 KB : cctx->nextToUpdate;
673
6.19M
    for (; idx < target; idx += 1) {
674
6.19M
        ADDPOS8(prefixPtr+idx-prefixIdx, idx);
675
6.19M
    }
676
677
398
    cctx->nextToUpdate = target;
678
398
}
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
29.5M
{
695
29.5M
    if (ipIndex - pos > LZ4_DISTANCE_MAX) return 0;
696
18.2M
    if (pos >= prefixIdx) {
697
18.2M
        const BYTE* const matchPtr = prefixPtr + (pos - prefixIdx);
698
18.2M
        assert(matchPtr < ip);
699
18.2M
        return LZ4_count(ip, matchPtr, matchlimit);
700
18.2M
    }
701
904
    if (pos >= dictIdx) {
702
        /* extDict : the match stops at the end of the dictionary */
703
904
        const BYTE* const matchPtr = dictStart + (pos - dictIdx);
704
904
        size_t const safeLen = MIN(prefixIdx - pos, (size_t)(matchlimit - ip));
705
904
        return LZ4_count(ip, matchPtr, ip + safeLen);
706
904
    }
707
0
    return 0;
708
904
}
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
10.0k
{
726
10.0k
    U32* const hash4Table = ctx->hashTable;
727
10.0k
    U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
728
10.0k
    const BYTE* ip = (const BYTE*)src;
729
10.0k
    const BYTE* anchor = ip;
730
10.0k
    const BYTE* const iend = ip + *srcSizePtr;
731
10.0k
    const BYTE* mflimit;      /* set after the size check : would precede a small input */
732
10.0k
    const BYTE* matchlimit;
733
10.0k
    const BYTE* ilimit;
734
10.0k
    BYTE* op = (BYTE*)dst;
735
    /* fillOutput : keep room for the final run of literals (LZ4 format restriction) */
736
10.0k
    BYTE* const oend = op + maxOutputSize - ((limit == fillOutput) ? LASTLITERALS : 0);
737
738
10.0k
    const BYTE* const prefixPtr = ctx->prefixStart;
739
10.0k
    const U32 prefixIdx = ctx->dictLimit;
740
10.0k
    U32 ilimitIdx;
741
10.0k
    const BYTE* const dictStart = ctx->dictStart;
742
10.0k
    const U32 dictIdx = ctx->lowLimit;
743
10.0k
    const U32 gDictEndIndex = ctx->lowLimit;
744
10.0k
    const LZ4MID_searchIntoDict_f searchIntoDict = (dict == usingDictCtxHc) ? select_searchDict_function(ctx->dictCtx) : NULL;
745
10.0k
    const BYTE* refEnd = ip;   /* fillOutput : the hash tables reference positions before MAX(refEnd, ip) */
746
747
10.0k
    DEBUGLOG(5, "LZ4MID_compress (%i bytes)", *srcSizePtr);
748
749
    /* preconditions verifications */
750
10.0k
    if (dict == usingDictCtxHc) DEBUGLOG(5, "usingDictCtxHc");
751
10.0k
    assert(*srcSizePtr > 0);
752
10.0k
    assert(*srcSizePtr <= LZ4_MAX_INPUT_SIZE);
753
10.0k
    assert(src != NULL);
754
10.0k
    assert(maxOutputSize >= 1);
755
10.0k
    assert(dst != NULL);
756
757
10.0k
    if (*srcSizePtr < LZ4_minLength)
758
2.81k
        goto _lz4mid_last_literals;  /* Input too small, no compression (all literals) */
759
7.22k
    mflimit = iend - MFLIMIT;
760
7.22k
    matchlimit = (iend - LASTLITERALS);
761
7.22k
    ilimit = (iend - LZ4MID_HASHSIZE);
762
7.22k
    ilimitIdx = (U32)(ilimit - prefixPtr) + prefixIdx;
763
764
    /* main loop */
765
14.7M
    while (ip <= mflimit) {
766
14.7M
        const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx;
767
14.7M
        unsigned matchLength;
768
14.7M
        unsigned matchDistance;
769
        /* search long match */
770
14.7M
        {   U32 const h8 = LZ4MID_hash8Ptr(ip);
771
14.7M
            U32 const pos8 = hash8Table[h8];
772
14.7M
            assert(h8 < LZ4MID_HASHTABLESIZE);
773
14.7M
            assert(pos8 < ipIndex);
774
14.7M
            LZ4MID_addPosition(hash8Table, h8, ipIndex);
775
14.7M
            matchLength = LZ4MID_countMatch(ip, ipIndex, pos8, matchlimit, prefixPtr, prefixIdx, dictStart, dictIdx);
776
14.7M
            matchDistance = ipIndex - pos8;
777
14.7M
        }
778
        /* search short match */
779
14.7M
        if (matchLength < MINMATCH) {
780
13.9M
            U32 const h4 = LZ4MID_hash4Ptr(ip);
781
13.9M
            U32 const pos4 = hash4Table[h4];
782
13.9M
            assert(h4 < LZ4MID_HASHTABLESIZE);
783
13.9M
            assert(pos4 < ipIndex);
784
13.9M
            LZ4MID_addPosition(hash4Table, h4, ipIndex);
785
13.9M
            matchLength = LZ4MID_countMatch(ip, ipIndex, pos4, matchlimit, prefixPtr, prefixIdx, dictStart, dictIdx);
786
13.9M
            matchDistance = ipIndex - pos4;
787
13.9M
        }
788
14.7M
        if (matchLength >= MINMATCH) {
789
1.52M
            if ((matchLength < 8) && likely(ip < mflimit)) {
790
                /* short match : check ip+1 for longer, except ip itself */
791
828k
                U32 const h8 = LZ4MID_hash8Ptr(ip+1);
792
828k
                U32 const pos8 = hash8Table[h8];
793
828k
                unsigned const ml2 = LZ4MID_countMatch(ip+1, ipIndex+1, pos8, matchlimit, prefixPtr, prefixIdx, dictStart, dictIdx);
794
828k
                if ((ml2 > matchLength) && (pos8 != ipIndex)) {
795
106k
                    LZ4MID_addPosition(hash8Table, h8, ipIndex+1);
796
106k
                    ip++;
797
106k
                    matchLength = ml2;
798
106k
                    matchDistance = ipIndex + 1 - pos8;
799
106k
            }   }
800
1.52M
            goto _lz4mid_encode_sequence;
801
1.52M
        }
802
        /* no match found in prefix nor extDict : search into the attached dictionary */
803
13.2M
        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
13.2M
        ip += 1 + ((ip-anchor) >> 9);  /* skip faster over incompressible data */
815
13.2M
        continue;
816
817
1.52M
_lz4mid_encode_sequence:
818
        /* match found at ip : matchLength, matchDistance */
819
1.52M
        DEBUGLOG(7, "found match at pos %u (len=%u, distance=%u)",
820
1.52M
                    (U32)(ip - prefixPtr) + prefixIdx, matchLength, matchDistance);
821
822
        /* catch back */
823
1.62M
        while (((ip > anchor) & ((U32)(ip-prefixPtr) > matchDistance)) && (unlikely(ip[-1] == ip[-(int)matchDistance-1]))) {
824
102k
            ip--;  matchLength++;
825
102k
        };
826
827
        /* fill table with beginning of match
828
         * note : ip may have moved since ipIndex (longer match at ip+1, catch back) */
829
1.52M
        {   U32 const startMatchIdx = (U32)(ip-prefixPtr) + prefixIdx;
830
1.52M
            ADDPOS8(ip+1, startMatchIdx+1);
831
1.52M
            ADDPOS8(ip+2, startMatchIdx+2);
832
1.52M
            ADDPOS4(ip+1, startMatchIdx+1);
833
1.52M
        }
834
835
        /* encode */
836
1.52M
        if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
837
1.52M
                (int)matchLength, (int)matchDistance,
838
1.52M
                limit, oend) ) {
839
315
            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
315
        }
845
846
        /* fill table with end of match */
847
1.52M
        {   U32 endMatchIdx = (U32)(ip-prefixPtr) + prefixIdx;
848
1.52M
            U32 pos_m2 = endMatchIdx - 2;
849
1.52M
            if (pos_m2 < ilimitIdx) {
850
1.51M
                if (likely(ip - prefixPtr > 5)) {
851
1.51M
                    ADDPOS8(ip-5, endMatchIdx - 5);
852
1.51M
                }
853
1.51M
                ADDPOS8(ip-3, endMatchIdx - 3);
854
1.51M
                ADDPOS8(ip-2, endMatchIdx - 2);
855
1.51M
                ADDPOS4(ip-2, endMatchIdx - 2);
856
1.51M
                ADDPOS4(ip-1, endMatchIdx - 1);
857
1.51M
            }
858
1.52M
        }
859
1.52M
    }
860
861
9.72k
_lz4mid_last_literals:
862
9.72k
    if (refEnd < ip) refEnd = ip;
863
9.72k
    if (LZ4HC_encodeLastLiterals(UPDATABLE(ip, op, anchor), iend, limit, oend))
864
3.95k
        return 0;  /* not enough space in @dst */
865
5.76k
    if (ip < refEnd)   /* fillOutput : the rest of input is left to the next block (input >= LZ4_minLength) */
866
14
        LZ4HC_dropPositions(ctx, ip, MIN(refEnd, iend - LZ4MID_HASHSIZE), lz4mid);
867
868
    /* End */
869
5.76k
    DEBUGLOG(5, "compressed %i bytes into %i bytes", *srcSizePtr, (int)((char*)op - dst));
870
5.76k
    assert(ip >= (const BYTE*)src);
871
5.76k
    assert(ip <= iend);
872
5.76k
    *srcSizePtr = (int)(ip - (const BYTE*)src);
873
5.76k
    assert((char*)op >= dst);
874
5.76k
    assert((char*)op - dst <= maxOutputSize);
875
5.76k
    assert((char*)op - dst < INT_MAX);
876
5.76k
    return (int)((char*)op - dst);
877
5.76k
}
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
75.2M
{
887
75.2M
    U16* const chainTable = hc4->chainTable;
888
75.2M
    U32* const hashTable  = hc4->hashTable;
889
75.2M
    const BYTE* const prefixPtr = hc4->prefixStart;
890
75.2M
    U32 const prefixIdx = hc4->dictLimit;
891
75.2M
    U32 const target = (U32)(ip - prefixPtr) + prefixIdx;
892
75.2M
    U32 idx = hc4->nextToUpdate;
893
75.2M
    assert(ip >= prefixPtr);
894
75.2M
    assert(target >= prefixIdx);
895
896
453M
    while (idx < target) {
897
378M
        U32 const h = LZ4HC_hashPtr(prefixPtr+idx-prefixIdx);
898
378M
        size_t delta = idx - hashTable[h];
899
378M
        if (delta>LZ4_DISTANCE_MAX) delta = LZ4_DISTANCE_MAX;
900
378M
        DELTANEXTU16(chainTable, idx) = (U16)delta;
901
378M
        hashTable[h] = idx;
902
378M
        idx++;
903
378M
    }
904
905
75.2M
    hc4->nextToUpdate = target;
906
75.2M
}
907
908
#if defined(_MSC_VER)
909
#  define LZ4HC_rotl32(x,r) _rotl(x,r)
910
#else
911
666
#  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
829
{
917
829
    size_t const bitsToRotate = (rotate & (sizeof(pattern) - 1)) << 3;
918
829
    if (bitsToRotate == 0) return pattern;
919
666
    return LZ4HC_rotl32(pattern, (int)bitsToRotate);
920
829
}
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
93.5M
{
927
93.5M
    const BYTE* const iStart = ip;
928
93.5M
    reg_t const pattern = (sizeof(pattern)==8) ?
929
93.5M
        (reg_t)pattern32 + (((reg_t)pattern32) << (sizeof(pattern)*4)) : pattern32;
930
931
168M
    while (likely(ip < iEnd-(sizeof(pattern)-1))) {
932
168M
        reg_t const diff = LZ4_read_ARCH(ip) ^ pattern;
933
168M
        if (!diff) { ip+=sizeof(pattern); continue; }
934
93.5M
        ip += LZ4_NbCommonBytes(diff);
935
93.5M
        return (unsigned)(ip - iStart);
936
168M
    }
937
938
23.6k
    if (LZ4_isLittleEndian()) {
939
23.6k
        reg_t patternByte = pattern;
940
95.5k
        while ((ip<iEnd) && (*ip == (BYTE)patternByte)) {
941
71.8k
            ip++; patternByte >>= 8;
942
71.8k
        }
943
23.6k
    } 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
23.6k
    return (unsigned)(ip - iStart);
952
93.5M
}
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
92.4M
{
960
92.4M
    const BYTE* const iStart = ip;
961
962
1.13G
    while (likely(ip >= iLow+4)) {
963
1.13G
        if (LZ4_read32(ip-4) != pattern) break;
964
1.03G
        ip -= 4;
965
1.03G
    }
966
92.4M
    {   const BYTE* bytePtr = (const BYTE*)(&pattern) + 3; /* works for any endianness */
967
235M
        while (likely(ip>iLow)) {
968
235M
            if (ip[-1] != *bytePtr) break;
969
142M
            ip--; bytePtr--;
970
142M
    }   }
971
92.4M
    return (unsigned)(iStart - ip);
972
92.4M
}
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
184M
{
981
184M
    return ((U32)((dictLimit - 1) - matchIndex) >= 3);
982
184M
}
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
5.10M
{
994
5.10M
    int const kTrigger = 4;
995
5.10M
    U32 distanceToNextMatch = 1;
996
5.10M
    int const end = longest - MINMATCH + 1;
997
5.10M
    int step = 1;
998
5.10M
    int accel = 1 << kTrigger;
999
5.10M
    int pos;
1000
75.0M
    for (pos = 0; pos < end; pos += step) {
1001
69.9M
        U32 const candidateDist = DELTANEXTU16(chainTable, matchIndex + (U32)pos);
1002
69.9M
        step = (accel++ >> kTrigger);
1003
69.9M
        if (candidateDist > distanceToNextMatch) {
1004
6.30M
            distanceToNextMatch = candidateDist;
1005
6.30M
            *matchChainPosPtr = (U32)pos;
1006
6.30M
            accel = 1 << kTrigger;
1007
6.30M
    }   }
1008
5.10M
    return distanceToNextMatch;
1009
5.10M
}
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
92.4M
{
1021
92.4M
    const BYTE* const prefixPtr = hc4->prefixStart;
1022
92.4M
    U32 const prefixIdx = hc4->dictLimit;
1023
92.4M
    const BYTE* const dictStart = hc4->dictStart;
1024
92.4M
    U32 const dictIdx = hc4->lowLimit;
1025
92.4M
    const BYTE* const dictEnd = dictStart + prefixIdx - dictIdx;
1026
92.4M
    int const extDict = candidateIdx < prefixIdx;
1027
92.4M
    const BYTE* const matchPtr = extDict ? dictStart + (candidateIdx - dictIdx) : prefixPtr + (candidateIdx - prefixIdx);
1028
92.4M
    size_t forward, back;
1029
92.4M
    if (LZ4_read32(matchPtr) != pattern) return 0;
1030
1031
92.4M
    {   const BYTE* const iLimit = extDict ? dictEnd : iHighLimit;
1032
92.4M
        forward = LZ4HC_countPattern(matchPtr+sizeof(pattern), iLimit, pattern) + sizeof(pattern);
1033
92.4M
        if (extDict && matchPtr + forward == iLimit) {   /* continues into the prefix */
1034
156
            U32 const rotatedPattern = LZ4HC_rotatePattern(forward, pattern);
1035
156
            forward += LZ4HC_countPattern(prefixPtr, iHighLimit, rotatedPattern);
1036
156
    }   }
1037
1038
92.4M
    back = LZ4HC_reverseCountPattern(matchPtr, extDict ? dictStart : prefixPtr, pattern);
1039
92.4M
    if (!extDict && matchPtr - back == prefixPtr && dictIdx < prefixIdx) {   /* continues into the external dictionary */
1040
673
        U32 const rotatedPattern = LZ4HC_rotatePattern((U32)(-(int)back), pattern);
1041
673
        back += LZ4HC_reverseCountPattern(dictEnd, dictStart, rotatedPattern);
1042
673
    }
1043
    /* don't go below lowestMatchIndex */
1044
92.4M
    back = candidateIdx - MAX(candidateIdx - (U32)back, lowestMatchIndex);
1045
92.4M
    assert(candidateIdx - back >= lowestMatchIndex);
1046
1047
92.4M
    *forwardPtr = forward;
1048
92.4M
    *backPtr = back;
1049
92.4M
    return 1;
1050
92.4M
}
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
75.2M
{
1065
75.2M
    U16* const chainTable = hc4->chainTable;
1066
75.2M
    U32* const hashTable = hc4->hashTable;
1067
75.2M
    const LZ4HC_CCtx_internal* const dictCtx = hc4->dictCtx;
1068
75.2M
    const BYTE* const prefixPtr = hc4->prefixStart;
1069
75.2M
    const U32 prefixIdx = hc4->dictLimit;
1070
75.2M
    const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx;
1071
75.2M
    const int withinStartDistance = (hc4->lowLimit + (LZ4_DISTANCE_MAX + 1) > ipIndex);
1072
75.2M
    const U32 lowestMatchIndex = (withinStartDistance) ? hc4->lowLimit : ipIndex - LZ4_DISTANCE_MAX;
1073
75.2M
    const BYTE* const dictStart = hc4->dictStart;
1074
75.2M
    const U32 dictIdx = hc4->lowLimit;
1075
75.2M
    int const lookBackLength = (int)(ip-iLowLimit);
1076
75.2M
    int const maxLength = (int)(iHighLimit-iLowLimit);   /* no match can be longer */
1077
75.2M
    int nbAttempts = maxNbAttempts;
1078
75.2M
    U32 matchChainPos = 0;
1079
75.2M
    U32 const pattern = LZ4_read32(ip);
1080
75.2M
    U32 matchIndex;
1081
75.2M
    repeat_state_e repeat = rep_untested;
1082
75.2M
    size_t srcPatternLength = 0;
1083
75.2M
    int offset = 0, sBack = 0;
1084
1085
75.2M
    DEBUGLOG(7, "LZ4HC_InsertAndGetWiderMatch");
1086
    /* First Match */
1087
75.2M
    LZ4HC_Insert(hc4, ip);  /* insert all prior positions up to ip (excluded) */
1088
75.2M
    matchIndex = hashTable[LZ4HC_hashPtr(ip)];
1089
75.2M
    DEBUGLOG(7, "First candidate match for pos %u found at index %u / %u (lowestMatchIndex)",
1090
75.2M
                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
668M
    while ((matchIndex>=lowestMatchIndex) && (nbAttempts>0) && (longest<maxLength)) {
1095
592M
        int matchLength=0;
1096
592M
        nbAttempts--;
1097
592M
        assert(matchIndex < ipIndex);
1098
592M
        if (favorDecSpeed && (ipIndex - matchIndex < 8)) {
1099
            /* do nothing:
1100
             * favorDecSpeed intentionally skips matches with offset < 8 */
1101
592M
        } else if (matchIndex >= prefixIdx) {   /* within current Prefix */
1102
583M
            const BYTE* const matchPtr = prefixPtr + (matchIndex - prefixIdx);
1103
583M
            assert(matchPtr < ip);
1104
583M
            assert(longest >= 1);
1105
583M
            if (LZ4_read16(iLowLimit + longest - 1) == LZ4_read16(matchPtr - lookBackLength + longest - 1)) {
1106
162M
                if (LZ4_read32(matchPtr) == pattern) {
1107
155M
                    int const back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, prefixPtr) : 0;
1108
155M
                    matchLength = MINMATCH + (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit);
1109
155M
                    matchLength -= back;
1110
155M
                    if (matchLength > longest) {
1111
12.1M
                        longest = matchLength;
1112
12.1M
                        offset = (int)(ipIndex - matchIndex);
1113
12.1M
                        sBack = back;
1114
12.1M
                        DEBUGLOG(7, "Found match of len=%i within prefix, offset=%i, back=%i", longest, offset, -back);
1115
12.1M
                        HEX_CMP(7, ip + back, ip + back - offset, (size_t)matchLength);
1116
12.1M
            }   }   }
1117
583M
        } else {   /* lowestMatchIndex <= matchIndex < dictLimit : within Ext Dict */
1118
8.80M
            const BYTE* const matchPtr = dictStart + (matchIndex - dictIdx);
1119
8.80M
            assert(matchIndex >= dictIdx);
1120
8.80M
            if ( likely(matchIndex <= prefixIdx - 4)
1121
8.80M
              && (LZ4_read32(matchPtr) == pattern) ) {
1122
7.13M
                int back = 0;
1123
7.13M
                const BYTE* vLimit = ip + (prefixIdx - matchIndex);
1124
7.13M
                if (vLimit > iHighLimit) vLimit = iHighLimit;
1125
7.13M
                matchLength = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
1126
7.13M
                if ((ip+matchLength == vLimit) && (vLimit < iHighLimit))
1127
8.91k
                    matchLength += LZ4_count(ip+matchLength, prefixPtr, iHighLimit);
1128
7.13M
                back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictStart) : 0;
1129
7.13M
                matchLength -= back;
1130
7.13M
                if (matchLength > longest) {
1131
52.0k
                    longest = matchLength;
1132
52.0k
                    offset = (int)(ipIndex - matchIndex);
1133
52.0k
                    sBack = back;
1134
52.0k
                    DEBUGLOG(7, "Found match of len=%i within dict, offset=%i, back=%i", longest, offset, -back);
1135
52.0k
                    HEX_CMP(7, ip + back, matchPtr + back, (size_t)matchLength);
1136
52.0k
        }   }   }
1137
1138
592M
        if (chainSwap && matchLength==longest && matchIndex + (U32)longest <= ipIndex) {   /* better match => select a better chain */
1139
5.10M
            U32 const distanceToNextMatch = LZ4HC_sparsestChain(chainTable, matchIndex, longest, &matchChainPos);
1140
5.10M
            assert(lookBackLength==0);   /* search forward only */
1141
5.10M
            if (distanceToNextMatch > 1) {
1142
4.74M
                if (distanceToNextMatch > matchIndex) break;   /* avoid overflow */
1143
4.74M
                matchIndex -= distanceToNextMatch;
1144
4.74M
                continue;
1145
4.74M
        }   }
1146
1147
588M
        {   U32 const distNextMatch = DELTANEXTU16(chainTable, matchIndex);
1148
588M
            if (patternAnalysis && distNextMatch==1 && matchChainPos==0) {
1149
94.1M
                U32 const matchCandidateIdx = matchIndex-1;
1150
94.1M
                size_t forwardPatternLength, backLength;
1151
                /* may be a repeated pattern */
1152
94.1M
                if (repeat == rep_untested) {
1153
1.10M
                    if ( ((pattern & 0xFFFF) == (pattern >> 16))
1154
1.10M
                      &  ((pattern & 0xFF)   == (pattern >> 24)) ) {
1155
1.09M
                        DEBUGLOG(7, "Repeat pattern detected, char %02X", pattern >> 24);
1156
1.09M
                        repeat = rep_confirmed;
1157
1.09M
                        srcPatternLength = LZ4HC_countPattern(ip+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern);
1158
1.09M
                    } else {
1159
12.0k
                        repeat = rep_not;
1160
12.0k
                }   }
1161
94.1M
                if ( (repeat == rep_confirmed) && (matchCandidateIdx >= lowestMatchIndex)
1162
92.4M
                  && LZ4HC_protectDictEnd(prefixIdx, matchCandidateIdx)
1163
92.4M
                  && LZ4HC_patternSegment(hc4, matchCandidateIdx, pattern, iHighLimit, lowestMatchIndex,
1164
92.4M
                                          &forwardPatternLength, &backLength) ) {
1165
92.4M
                    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
92.4M
                    int const fullPatternFits = (currentSegmentLength >= srcPatternLength)
1170
62.9M
                                             && (forwardPatternLength <= srcPatternLength);
1171
92.4M
                    U32 const newMatchIndex = fullPatternFits ?
1172
27.6M
                                              matchCandidateIdx + (U32)forwardPatternLength - (U32)srcPatternLength :
1173
92.4M
                                              matchCandidateIdx - (U32)backLength;
1174
92.4M
                    if (!LZ4HC_protectDictEnd(prefixIdx, newMatchIndex)) {
1175
                        /* Can only happen if started in the prefix */
1176
4
                        assert(newMatchIndex >= prefixIdx - 3 && newMatchIndex < prefixIdx && matchCandidateIdx >= prefixIdx);
1177
4
                        matchIndex = prefixIdx;
1178
4
                        continue;
1179
4
                    }
1180
92.4M
                    matchIndex = newMatchIndex;
1181
92.4M
                    if (!fullPatternFits && lookBackLength==0) {  /* no back possible : the match length is known */
1182
51.1M
                        size_t const maxML = MIN(currentSegmentLength, srcPatternLength);
1183
51.1M
                        if ((size_t)longest < maxML) {
1184
388k
                            assert(prefixPtr - prefixIdx + matchIndex != ip);
1185
388k
                            if ((size_t)(ip - prefixPtr) + prefixIdx - matchIndex > LZ4_DISTANCE_MAX) break;
1186
388k
                            assert(maxML < 2 GB);
1187
388k
                            longest = (int)maxML;
1188
388k
                            offset = (int)(ipIndex - matchIndex);
1189
388k
                            assert(sBack == 0);
1190
388k
                            DEBUGLOG(7, "Found repeat pattern match of len=%i, offset=%i", longest, offset);
1191
388k
                        }
1192
51.1M
                        {   U32 const distToNextPattern = DELTANEXTU16(chainTable, matchIndex);
1193
51.1M
                            if (distToNextPattern > matchIndex) break;  /* avoid overflow */
1194
51.1M
                            matchIndex -= distToNextPattern;
1195
51.1M
                    }   }
1196
92.4M
                    continue;
1197
92.4M
                }
1198
94.1M
        }   }   /* PA optimization */
1199
1200
        /* follow current chain */
1201
495M
        matchIndex -= DELTANEXTU16(chainTable, matchIndex + matchChainPos);
1202
1203
495M
    }  /* while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) */
1204
1205
75.2M
    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
75.2M
    {   LZ4HC_match_t md;
1238
75.2M
        assert(longest >= 0);
1239
75.2M
        md.len = longest;
1240
75.2M
        md.off = offset;
1241
75.2M
        md.back = sBack;
1242
75.2M
        return md;
1243
75.2M
    }
1244
75.2M
}
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
40.8M
{
1253
40.8M
    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
40.8M
    return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio);
1258
40.8M
}
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
22.8k
{
1278
22.8k
    const int inputSize = *srcSizePtr;
1279
22.8k
    const int patternAnalysis = (maxNbAttempts > 128);   /* levels 9+ */
1280
1281
22.8k
    const BYTE* ip = (const BYTE*)src;
1282
22.8k
    const BYTE* anchor = ip;
1283
22.8k
    const BYTE* const iend = ip + inputSize;
1284
22.8k
    const BYTE* mflimit;      /* set after the size check : would precede a small input */
1285
22.8k
    const BYTE* matchlimit;
1286
1287
22.8k
    BYTE* op = (BYTE*) dst;
1288
    /* fillOutput : keep room for the final run of literals (LZ4 format restriction) */
1289
22.8k
    BYTE* const oend = op + maxOutputSize - ((limit == fillOutput) ? LASTLITERALS : 0);
1290
1291
22.8k
    const BYTE* start0;
1292
22.8k
    const BYTE* start2 = NULL;
1293
22.8k
    const BYTE* start3 = NULL;
1294
22.8k
    LZ4HC_match_t m0, m1, m2, m3;
1295
22.8k
    const LZ4HC_match_t nomatch = {0, 0, 0};
1296
1297
    /* init */
1298
22.8k
    DEBUGLOG(5, "LZ4HC_compress_hashChain (dict?=>%i)", dict);
1299
1300
    /* preconditions verifications */
1301
22.8k
    assert(*srcSizePtr >= 1);
1302
22.8k
    assert(src != NULL);
1303
22.8k
    assert(maxOutputSize >= 1);
1304
22.8k
    assert(dst != NULL);
1305
1306
22.8k
    *srcSizePtr = 0;
1307
22.8k
    if (inputSize < LZ4_minLength) goto _last_literals;             /* Input too small, no compression (all literals) */
1308
15.9k
    mflimit = iend - MFLIMIT;
1309
15.9k
    matchlimit = (iend - LASTLITERALS);
1310
1311
    /* Main Loop */
1312
40.8M
    while (ip <= mflimit) {
1313
40.8M
        m1 = LZ4HC_InsertAndFindBestMatch(ctx, ip, matchlimit, maxNbAttempts, patternAnalysis, dict);
1314
40.8M
        if (m1.len<MINMATCH) { ip++; continue; }
1315
1316
        /* saved, in case we would skip too much */
1317
2.49M
        start0 = ip; m0 = m1;
1318
1319
3.38M
_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
3.38M
        DEBUGLOG(7, "_Search2 (currently found match of size %i)", m1.len);
1323
3.38M
        if (ip+m1.len <= mflimit) {
1324
3.37M
            start2 = ip + m1.len - 2;
1325
3.37M
            m2 = LZ4HC_InsertAndGetWiderMatch(ctx,
1326
3.37M
                            start2, ip + 0, matchlimit, m1.len,
1327
3.37M
                            maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
1328
3.37M
            start2 += m2.back;
1329
3.37M
        } else {
1330
10.2k
            m2 = nomatch;  /* do not search further */
1331
10.2k
        }
1332
1333
3.38M
        if (m2.len <= m1.len) { /* No better match => encode m1 immediately */
1334
2.21M
            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1335
2.21M
                    m1.len, m1.off,
1336
2.21M
                    limit, oend) )
1337
855
                goto _dest_overflow;
1338
2.21M
            continue;
1339
2.21M
        }
1340
1341
1.17M
        if ((start0 < ip) && (start2 < ip + m0.len)) {
1342
            /* m1 was skipped at least once, and m2 starts early enough : restore m0 */
1343
121k
            ip = start0; m1 = m0;
1344
121k
        }
1345
1346
1.17M
        if ((start2 - ip) < 3) {  /* m1 too short before m2 : removed */
1347
728k
            ip = start2;
1348
728k
            m1 = m2;
1349
728k
            goto _Search2;
1350
728k
        }
1351
1352
        /* m2 (at start2) is the candidate after m1.
1353
         * Search a longer match m3, starting before the end of m2. */
1354
567k
        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
567k
            if ((start2 - ip) < OPTIMAL_ML) {
1358
450k
                int const gap = (int)(start2 - ip);
1359
450k
                int newML = MIN(m1.len, OPTIMAL_ML);
1360
450k
                if (newML > gap + m2.len - MINMATCH)
1361
497
                    newML = gap + m2.len - MINMATCH;
1362
450k
                if (newML > gap) {   /* shift m2 */
1363
402k
                    start2 += newML - gap;
1364
402k
                    m2.len -= newML - gap;
1365
402k
                }
1366
450k
            }
1367
1368
567k
            if (start2 + m2.len <= mflimit) {
1369
565k
                start3 = start2 + m2.len - 3;
1370
565k
                m3 = LZ4HC_InsertAndGetWiderMatch(ctx,
1371
565k
                                start3, start2, matchlimit, m2.len,
1372
565k
                                maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
1373
565k
                start3 += m3.back;
1374
565k
            } else {
1375
1.54k
                m3 = nomatch;  /* do not search further */
1376
1.54k
            }
1377
1378
567k
            if ((m3.len > m2.len) && (start3 < ip+m1.len+3)) {  /* not enough room for m2 between m1 and m3 */
1379
180k
                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
165k
                    if (start2 < ip+m1.len) {
1383
14.2k
                        int correction = (int)(ip+m1.len - start2);
1384
14.2k
                        start2 += correction;
1385
14.2k
                        m2.len -= correction;
1386
14.2k
                        if (m2.len < MINMATCH) {
1387
148
                            start2 = start3;
1388
148
                            m2 = m3;
1389
148
                        }
1390
14.2k
                    }
1391
1392
165k
                    if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1393
165k
                            m1.len, m1.off,
1394
165k
                            limit, oend) )
1395
37
                        goto _dest_overflow;
1396
165k
                    ip  = start3;
1397
165k
                    m1 = m3;
1398
1399
165k
                    start0 = start2;
1400
165k
                    m0 = m2;
1401
165k
                    goto _Search2;
1402
165k
                }
1403
1404
                /* m3 starts within m1 : m3 replaces m2 */
1405
15.5k
                start2 = start3;
1406
15.5k
                m2 = m3;
1407
15.5k
                continue;
1408
180k
            }
1409
1410
            /* encode m1, cut where m2 starts */
1411
386k
            if (start2 < ip+m1.len) m1.len = (int)(start2 - ip);
1412
386k
            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1413
386k
                    m1.len, m1.off,
1414
386k
                    limit, oend) )
1415
73
                goto _dest_overflow;
1416
1417
            /* m2 becomes m1 */
1418
386k
            ip = start2; m1 = m2;
1419
1420
386k
            if (m3.len <= m1.len) {  /* No better match => encode m1 (former m2) */
1421
281k
                if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1422
281k
                        m1.len, m1.off,
1423
281k
                        limit, oend) )
1424
52
                    goto _dest_overflow;
1425
281k
                break;
1426
281k
            }
1427
1428
            /* m3 becomes m2 */
1429
105k
            start2 = start3; m2 = m3;
1430
105k
        }
1431
446k
    }
1432
1433
21.8k
_last_literals:
1434
21.8k
    if (LZ4HC_encodeLastLiterals(UPDATABLE(ip, op, anchor), iend, limit, oend))
1435
9.52k
        return 0;  /* not enough space in @dst */
1436
1437
    /* End */
1438
12.3k
    *srcSizePtr = (int) (((const char*)ip) - src);
1439
12.3k
    return (int) (((char*)op)-dst);
1440
1441
1.01k
_dest_overflow:
1442
1.01k
    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
1.01k
}
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
49.1k
{
1468
49.1k
    DEBUGLOG(5, "LZ4HC_compress_generic_internal(src=%p, srcSize=%d, dstCapacity=%d)",
1469
49.1k
                src, *srcSizePtr, dstCapacity);
1470
1471
    /* input sanitization */
1472
49.1k
    if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0;  /* Unsupported input size (too large or negative) */
1473
49.1k
    if (dstCapacity < 1) return 0;   /* Invalid: impossible to store anything */
1474
49.1k
    assert(dst); /* since dstCapacity >= 1, dst must be valid */
1475
49.1k
    if (*srcSizePtr == 0) { *dst = 0; return 1; }
1476
49.1k
    assert(src != NULL); /* since *srcSizePtr >= 1, src must be valid */
1477
1478
49.1k
    ctx->end += *srcSizePtr;
1479
49.1k
    {   cParams_t const cParam = LZ4HC_getCLevelParams(cLevel);
1480
49.1k
        HCfavor_e const favor = ctx->favorDecSpeed ? favorDecompressionSpeed : favorCompressionRatio;
1481
49.1k
        int const srcSize = *srcSizePtr;
1482
49.1k
        int result;
1483
1484
49.1k
        if (cParam.strat == lz4mid) {
1485
10.0k
            result = LZ4MID_compress(ctx,
1486
10.0k
                                src, dst, srcSizePtr, dstCapacity,
1487
10.0k
                                limit, dict);
1488
39.1k
        } else if (cParam.strat == lz4hc) {
1489
22.8k
            result = LZ4HC_compress_hashChain(ctx,
1490
22.8k
                                src, dst, srcSizePtr, dstCapacity,
1491
22.8k
                                cParam.nbSearches, limit, dict);
1492
22.8k
        } else {
1493
16.2k
            assert(cParam.strat == lz4opt);
1494
16.2k
            result = LZ4HC_compress_optimal(ctx,
1495
16.2k
                                src, dst, srcSizePtr, dstCapacity,
1496
16.2k
                                cParam.nbSearches, cParam.nbSearchesSeq, (int)cParam.targetLength, limit,
1497
16.2k
                                dict, favor);
1498
16.2k
        }
1499
49.1k
        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
49.1k
        return result;
1514
49.1k
    }
1515
49.1k
}
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
49.1k
{
1530
49.1k
    assert(ctx->dictCtx == NULL);
1531
49.1k
    return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, noDictCtx);
1532
49.1k
}
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
49.1k
{
1583
49.1k
    if (ctx->dictCtx == NULL) {
1584
49.1k
        return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
1585
49.1k
    } else {
1586
0
        return LZ4HC_compress_generic_dictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
1587
0
    }
1588
49.1k
}
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
60.9k
{
1595
60.9k
#if LZ4_ALIGN_TEST
1596
60.9k
    typedef struct { char c; LZ4_streamHC_t t; } t_a;
1597
60.9k
    return sizeof(t_a) - sizeof(LZ4_streamHC_t);
1598
#else
1599
    return 1;  /* effectively disabled */
1600
#endif
1601
60.9k
}
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
8.87k
{
1607
8.87k
    LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)state)->internal_donotuse;
1608
8.87k
    if (!LZ4_isAligned(state, LZ4_streamHC_t_alignment())) return 0;
1609
8.87k
    LZ4_resetStreamHC_fast((LZ4_streamHC_t*)state, compressionLevel);
1610
8.87k
    LZ4HC_init_internal (ctx, (const BYTE*)src);
1611
8.87k
    if (dstCapacity < LZ4_compressBound(srcSize))
1612
8.87k
        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
8.87k
}
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
52.0k
{
1680
52.0k
    LZ4_streamHC_t* const LZ4_streamHCPtr = (LZ4_streamHC_t*)buffer;
1681
52.0k
    DEBUGLOG(4, "LZ4_initStreamHC(%p, %u)", buffer, (unsigned)size);
1682
    /* check conditions */
1683
52.0k
    if (buffer == NULL) return NULL;
1684
52.0k
    if (size < sizeof(LZ4_streamHC_t)) return NULL;
1685
52.0k
    if (!LZ4_isAligned(buffer, LZ4_streamHC_t_alignment())) return NULL;
1686
    /* init */
1687
52.0k
    { LZ4HC_CCtx_internal* const hcstate = &(LZ4_streamHCPtr->internal_donotuse);
1688
52.0k
      MEM_INIT(hcstate, 0, sizeof(*hcstate));
1689
52.0k
      hcstate->hasWorkspace = (size >= LZ4_STREAMHC_EXTSIZE); }
1690
52.0k
    LZ4_setCompressionLevel(LZ4_streamHCPtr, LZ4HC_CLEVEL_DEFAULT);
1691
52.0k
    return LZ4_streamHCPtr;
1692
52.0k
}
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
1.93k
{
1697
1.93k
    return s->internal_donotuse.hasWorkspace ? LZ4_STREAMHC_EXTSIZE : sizeof(*s);
1698
1.93k
}
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
75.1k
{
1709
75.1k
    LZ4HC_CCtx_internal* const s = &LZ4_streamHCPtr->internal_donotuse;
1710
75.1k
    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
75.1k
    assert(s->end >= s->prefixStart);
1713
75.1k
    s->dictLimit += (U32)(s->end - s->prefixStart);
1714
75.1k
    s->prefixStart = NULL;
1715
75.1k
    s->end = NULL;
1716
75.1k
    s->dictCtx = NULL;
1717
75.1k
    LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
1718
75.1k
}
1719
1720
void LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
1721
179k
{
1722
179k
    DEBUGLOG(5, "LZ4_setCompressionLevel(%p, %d)", LZ4_streamHCPtr, compressionLevel);
1723
179k
    if (compressionLevel < 1) compressionLevel = LZ4HC_CLEVEL_DEFAULT;
1724
179k
    if (compressionLevel > LZ4HC_CLEVEL_MAX) compressionLevel = LZ4HC_CLEVEL_MAX;
1725
179k
    LZ4_streamHCPtr->internal_donotuse.compressionLevel = (short)compressionLevel;
1726
179k
}
1727
1728
void LZ4_favorDecompressionSpeed(LZ4_streamHC_t* LZ4_streamHCPtr, int favor)
1729
66.4k
{
1730
66.4k
    LZ4_streamHCPtr->internal_donotuse.favorDecSpeed = (favor!=0);
1731
66.4k
}
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
1.93k
{
1738
1.93k
    LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;
1739
1.93k
    cParams_t cp;
1740
1.93k
    DEBUGLOG(4, "LZ4_loadDictHC(ctx:%p, dict:%p, dictSize:%d, clevel=%d)", LZ4_streamHCPtr, dictionary, dictSize, ctxPtr->compressionLevel);
1741
1.93k
    assert(LZ4_streamHCPtr != NULL);
1742
1.93k
    if (dictSize < 0) dictSize = 0;   /* invalid size : no dictionary */
1743
1.93k
    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
1.93k
    {   int const cLevel = ctxPtr->compressionLevel;
1750
1.93k
        LZ4_i8 const favorDecSpeed = ctxPtr->favorDecSpeed;
1751
1.93k
        LZ4_initStreamHC(LZ4_streamHCPtr, LZ4HC_sizeofState(LZ4_streamHCPtr));
1752
1.93k
        LZ4_setCompressionLevel(LZ4_streamHCPtr, cLevel);
1753
1.93k
        ctxPtr->favorDecSpeed = favorDecSpeed;
1754
1.93k
        cp = LZ4HC_getCLevelParams(cLevel);
1755
1.93k
    }
1756
1.93k
    LZ4HC_init_internal (ctxPtr, (const BYTE*)dictionary);
1757
1.93k
    ctxPtr->end = (const BYTE*)dictionary + dictSize;
1758
1.93k
    if (cp.strat == lz4mid) {
1759
476
        LZ4MID_fillHTable (ctxPtr, dictionary, (size_t)dictSize);
1760
1.45k
    } else {
1761
1.45k
        if (dictSize >= LZ4HC_HASHSIZE) LZ4HC_Insert (ctxPtr, ctxPtr->end-3);
1762
1.45k
    }
1763
1.93k
    return dictSize;
1764
1.93k
}
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
177
{
1787
177
    DEBUGLOG(4, "LZ4HC_setExternalDict(%p, %p)", ctxPtr, newBlock);
1788
177
    if (LZ4HC_getCLevelParams(ctxPtr->compressionLevel).strat != lz4mid) {
1789
163
        U32 const endIdx = ctxPtr->dictLimit + (U32)(ctxPtr->end - ctxPtr->prefixStart);
1790
163
        U32 idx;
1791
163
        if (ctxPtr->end >= ctxPtr->prefixStart + 4)
1792
161
            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
652
        for (idx = ctxPtr->nextToUpdate; idx < endIdx; idx++)
1795
489
            DELTANEXTU16(ctxPtr->chainTable, idx) = 0;
1796
163
    }
1797
1798
    /* Only one memory segment for extDict, so any previous extDict is lost at this stage */
1799
177
    ctxPtr->lowLimit  = ctxPtr->dictLimit;
1800
177
    ctxPtr->dictStart  = ctxPtr->prefixStart;
1801
177
    ctxPtr->dictLimit += (U32)(ctxPtr->end - ctxPtr->prefixStart);
1802
177
    ctxPtr->prefixStart = newBlock;
1803
177
    ctxPtr->end  = newBlock;
1804
177
    ctxPtr->nextToUpdate = ctxPtr->dictLimit;   /* match referencing will resume from there */
1805
1806
    /* cannot reference an extDict and a dictCtx at the same time */
1807
177
    ctxPtr->dictCtx = NULL;
1808
177
}
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
40.2k
{
1816
40.2k
    LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;
1817
40.2k
    DEBUGLOG(5, "LZ4_compressHC_continue_generic(ctx=%p, src=%p, srcSize=%d, limit=%d)",
1818
40.2k
                LZ4_streamHCPtr, src, *srcSizePtr, limit);
1819
40.2k
    assert(ctxPtr != NULL);
1820
    /* auto-init if forgotten */
1821
40.2k
    if (ctxPtr->prefixStart == NULL)
1822
25.7k
        LZ4HC_init_internal (ctxPtr, (const BYTE*) src);
1823
1824
    /* Check overflow */
1825
40.2k
    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
40.2k
    if ((const BYTE*)src != ctxPtr->end)
1833
177
        LZ4HC_setExternalDict(ctxPtr, (const BYTE*)src);
1834
1835
    /* Check overlapping input/dictionary space */
1836
40.2k
    {   const BYTE* sourceEnd = (const BYTE*) src + *srcSizePtr;
1837
40.2k
        const BYTE* const dictBegin = ctxPtr->dictStart;
1838
40.2k
        const BYTE* const dictEnd   = ctxPtr->dictStart + (ctxPtr->dictLimit - ctxPtr->lowLimit);
1839
40.2k
        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
40.2k
    return LZ4HC_compress_generic (ctxPtr, src, dst, srcSizePtr, dstCapacity, ctxPtr->compressionLevel, limit);
1850
40.2k
}
1851
1852
int LZ4_compress_HC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int srcSize, int dstCapacity)
1853
40.2k
{
1854
40.2k
    DEBUGLOG(5, "LZ4_compress_HC_continue");
1855
40.2k
    if (dstCapacity < LZ4_compressBound(srcSize))
1856
40.2k
        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
40.2k
}
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
1.41k
{
1874
1.41k
    LZ4HC_CCtx_internal* const streamPtr = &LZ4_streamHCPtr->internal_donotuse;
1875
1.41k
    size_t const prefixSize = (size_t)(streamPtr->end - streamPtr->prefixStart);   /* can exceed INT_MAX */
1876
1.41k
    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
1.41k
    if (streamPtr->prefixStart == NULL) return 0;
1880
1.41k
    assert(streamPtr->end >= streamPtr->prefixStart);
1881
339
    if (dictSize > 64 KB) dictSize = 64 KB;
1882
339
    if (dictSize < 4) dictSize = 0;
1883
339
    if ((size_t)dictSize > prefixSize) dictSize = (int)prefixSize;   /* 0 <= dictSize <= 64 KB : prefixSize fits */
1884
339
    if (safeBuffer == NULL) assert(dictSize == 0); /* a NULL buffer with !0 size is invalid */
1885
339
    if (dictSize > 0)
1886
339
        LZ4_memmove(safeBuffer, streamPtr->end - dictSize, (size_t)dictSize);
1887
339
    {   U32 const endIndex = (U32)(streamPtr->end - streamPtr->prefixStart) + streamPtr->dictLimit;
1888
339
        streamPtr->end = (safeBuffer == NULL) ? NULL : (const BYTE*)safeBuffer + dictSize;
1889
339
        streamPtr->prefixStart = (const BYTE*)safeBuffer;
1890
339
        streamPtr->dictLimit = endIndex - (U32)dictSize;
1891
339
        streamPtr->lowLimit = endIndex - (U32)dictSize;
1892
339
        streamPtr->dictStart = streamPtr->prefixStart;
1893
339
        if (streamPtr->nextToUpdate < streamPtr->dictLimit)
1894
58
            streamPtr->nextToUpdate = streamPtr->dictLimit;
1895
339
    }
1896
339
    return dictSize;
1897
339
}
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
177M
#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
180M
#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
1.79M
#define LZ4HC_SEQ_PRICE_FDS    1
1923
587k
#define LZ4HC_SEQ_SEARCH_DIST  4
1924
1925
LZ4_FORCE_INLINE int LZ4HC_literalsPrice(int const litlen)
1926
95.6M
{
1927
95.6M
    int price = litlen;
1928
95.6M
    assert(litlen >= 0);
1929
95.6M
    if (litlen >= (int)RUN_MASK)
1930
4.60M
        price += 1 + ((litlen-(int)RUN_MASK) / 255);
1931
95.6M
    return price * LZ4HC_PRICE_SCALE;
1932
95.6M
}
1933
1934
/* requires mlen >= MINMATCH */
1935
LZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen)
1936
82.6M
{
1937
82.6M
    int price = 1 + 2 ; /* token + 16-bit offset */
1938
82.6M
    assert(litlen >= 0);
1939
82.6M
    assert(mlen >= MINMATCH);
1940
1941
82.6M
    if (mlen >= (int)(ML_MASK+MINMATCH))
1942
64.2M
        price += 1 + ((mlen-(int)(ML_MASK+MINMATCH)) / 255);
1943
1944
82.6M
    return price * LZ4HC_PRICE_SCALE + LZ4HC_literalsPrice(litlen);
1945
82.6M
}
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
27.4M
{
1954
27.4M
    int const reduceFrom = (int)RUN_MASK + 255;
1955
27.4M
    assert(llen >= 0);
1956
27.4M
    if (llen < reduceFrom) return llen;
1957
12.9M
    return reduceFrom + ((llen - (int)RUN_MASK) % 255);
1958
27.4M
}
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
30.4M
{
1967
30.4M
    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
30.4M
    LZ4HC_match_t md = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, MINMATCH-1, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed);
1971
30.4M
    assert(md.back == 0);
1972
30.4M
    if (md.len < MINMATCH) return match0;
1973
3.16M
    if (favorDecSpeed) {
1974
1.81M
        if ((md.len>18) & (md.len<=36)) md.len=18;   /* favor dec.speed (shortcut) */
1975
1.81M
    }
1976
3.16M
    return md;
1977
30.4M
}
1978
1979
LZ4_FORCE_INLINE void
1980
LZ4HC_setLiteral(LZ4HC_optimal_t* opt, int pos, int litlen, int price)
1981
12.9M
{
1982
12.9M
    opt[pos].mlen = 1;
1983
12.9M
    opt[pos].off = 0;
1984
12.9M
    opt[pos].litlen = litlen;
1985
12.9M
    opt[pos].price = price;
1986
12.9M
    DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)", pos, price, litlen);
1987
12.9M
}
1988
1989
LZ4_FORCE_INLINE void
1990
LZ4HC_setMatch(LZ4HC_optimal_t* opt, int pos, int mlen, int off, int price)
1991
19.2M
{
1992
19.2M
    opt[pos].mlen = mlen;
1993
19.2M
    opt[pos].off = off;
1994
19.2M
    opt[pos].litlen = 0;
1995
19.2M
    opt[pos].price = price;
1996
19.2M
    DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i)", pos, price, mlen);
1997
19.2M
}
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
3.12M
{
2003
3.12M
    int const ll = opt[pos].litlen;
2004
3.12M
    return (ll <= pos) ? opt[pos - ll].price : 0;
2005
3.12M
}
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
3.12M
{
2015
3.12M
    int const ll = opt[cur].litlen;
2016
3.12M
    int const basePrice = LZ4HC_runStartPrice(opt, cur) + (favorDecSpeed ? LZ4HC_SEQ_PRICE_FDS : 0);
2017
3.12M
    int ml;
2018
3.12M
    assert(cur + match.len < LZ4_OPT_NUM);
2019
3.12M
    assert((U32)favorDecSpeed <= 1);
2020
85.8M
    for (ml = MINMATCH; ml <= match.len; ml++) {
2021
82.6M
        int const pos = cur + ml;
2022
82.6M
        int const price = basePrice + LZ4HC_sequencePrice(ll, ml);
2023
        /* on equal price, favorDecSpeed keeps the existing solution */
2024
82.6M
        if ( pos > lastPos + TRAILING_LITERALS
2025
65.6M
          || price <= opt[pos].price - (int)favorDecSpeed) {
2026
19.2M
            LZ4HC_setMatch(opt, pos, ml, match.off, price);
2027
19.2M
            if ((ml == match.len) && (lastPos < pos)) lastPos = pos;
2028
19.2M
    }   }
2029
2030
    /* complete following positions with literals */
2031
3.12M
    {   int addLit;
2032
3.12M
        assert(opt[lastPos].mlen >= MINMATCH);
2033
12.5M
        for (addLit = 1; addLit <= TRAILING_LITERALS; addLit++)
2034
9.38M
            LZ4HC_setLiteral(opt, lastPos + addLit, addLit,
2035
9.38M
                             opt[lastPos].price + LZ4HC_literalsPrice(addLit));
2036
3.12M
    }
2037
3.12M
    return lastPos;
2038
3.12M
}
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
16.2k
{
2062
16.2k
    const BYTE* ip = (const BYTE*) source;
2063
16.2k
    const BYTE* anchor = ip;
2064
16.2k
    const int inputSize = *srcSizePtr;
2065
16.2k
    const BYTE* const iend = ip + inputSize;
2066
16.2k
    const BYTE* mflimit;      /* set after the size check : would precede a small input */
2067
16.2k
    const BYTE* matchlimit;
2068
16.2k
    BYTE* op = (BYTE*) dst;
2069
    /* fillOutput : keep room for the final run of literals (LZ4 format restriction) */
2070
16.2k
    BYTE* const oend = op + dstCapacity - ((limit == fillOutput) ? LASTLITERALS : 0);
2071
16.2k
    int const sufficientLen = MIN(targetLength, LZ4_OPT_NUM-1);
2072
2073
16.2k
    DEBUGLOG(5, "LZ4HC_compress_optimal(dst=%p, dstCapa=%u)", dst, (unsigned)dstCapacity);
2074
2075
    /* preconditions verifications */
2076
16.2k
    assert(dstCapacity > 0);
2077
16.2k
    assert(dst != NULL);
2078
16.2k
    assert(*srcSizePtr > 0);
2079
16.2k
    assert(source != NULL);
2080
16.2k
    assert(opt != NULL);
2081
16.2k
    assert(nbSearchesSeq >= 1);
2082
2083
16.2k
    *srcSizePtr = 0;
2084
16.2k
    if (inputSize < LZ4_minLength) goto _last_literals;
2085
10.2k
    mflimit = iend - MFLIMIT;
2086
10.2k
    matchlimit = iend - LASTLITERALS;
2087
2088
    /* Main Loop */
2089
27.4M
    while (ip <= mflimit) {
2090
27.4M
        int const llen = LZ4HC_pricedLitlen((int)(ip - anchor));
2091
27.4M
        int cur, lastPos;
2092
27.4M
        int lastSeqPos;         /* position of the last sequence to encode */
2093
27.4M
        LZ4HC_match_t lastSeq;
2094
2095
27.4M
        LZ4HC_match_t const firstMatch = LZ4HC_FindLongestMatch(ctx, ip, matchlimit, nbSearches, dict, favorDecSpeed);
2096
27.4M
        if (firstMatch.len==0) { ip++; continue; }
2097
2098
921k
        if (firstMatch.len > sufficientLen) {
2099
            /* good enough solution : immediate encoding */
2100
29.5k
            lastSeqPos = 0;
2101
29.5k
            lastSeq = firstMatch;
2102
29.5k
            goto encode;
2103
29.5k
        }
2104
2105
        /* set prices for first positions (literals) */
2106
891k
        {   int rPos;
2107
4.45M
            for (rPos = 0 ; rPos < MINMATCH ; rPos++)
2108
3.56M
                LZ4HC_setLiteral(opt, rPos, llen + rPos, LZ4HC_literalsPrice(llen + rPos));
2109
891k
        }
2110
891k
        lastPos = LZ4HC_addMatch(opt, 0, firstMatch, 0, favorDecSpeed);
2111
2112
        /* check further positions */
2113
20.3M
        for (cur = 1; cur < lastPos; cur++) {
2114
19.5M
            const BYTE* const curPtr = ip + cur;
2115
19.5M
            LZ4HC_match_t newMatch;
2116
19.5M
            int nbS = nbSearches;
2117
2118
19.5M
            if (curPtr > mflimit) break;
2119
19.5M
            DEBUGLOG(7, "rPos:%u[%u] vs [%u]%u",
2120
19.5M
                    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
19.5M
            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
3.24M
            if (favorDecSpeed && (opt[cur+1].price < opt[cur].price + LZ4HC_PRICE_SCALE)) {
2126
587k
                if (lastPos - cur > LZ4HC_SEQ_SEARCH_DIST) continue;
2127
342k
                nbS = nbSearchesSeq;
2128
342k
            }
2129
2130
2.99M
            newMatch = LZ4HC_FindLongestMatch(ctx, curPtr, matchlimit, nbS, dict, favorDecSpeed);
2131
2.99M
            if (!newMatch.len) continue;
2132
2133
2.24M
            if ( (newMatch.len > sufficientLen)
2134
2.23M
              || (newMatch.len + cur >= LZ4_OPT_NUM) ) {
2135
                /* immediate encoding */
2136
6.49k
                lastSeqPos = cur;
2137
6.49k
                lastSeq = newMatch;
2138
6.49k
                goto encode;
2139
6.49k
            }
2140
2141
2.23M
            lastPos = LZ4HC_addMatch(opt, cur, newMatch, lastPos, favorDecSpeed);
2142
2.23M
        }  /* for (cur = 1; cur < lastPos; cur++) */
2143
2144
891k
        assert(lastPos < LZ4_OPT_NUM + TRAILING_LITERALS);
2145
885k
        lastSeq.len = opt[lastPos].mlen;
2146
885k
        lastSeq.off = opt[lastPos].off;
2147
885k
        lastSeqPos = lastPos - lastSeq.len;
2148
2149
921k
encode: /* lastSeqPos and lastSeq must be set */
2150
921k
        assert(0 <= lastSeqPos && lastSeqPos < LZ4_OPT_NUM);
2151
921k
        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
921k
        {   int pos = lastSeqPos;
2155
921k
            int mlen = lastSeq.len;
2156
921k
            int off = lastSeq.off;
2157
1.36M
            while (pos > 0) {
2158
448k
                int const prevMlen = opt[pos].mlen;
2159
448k
                int const prevOff = opt[pos].off;
2160
448k
                opt[pos].mlen = mlen;
2161
448k
                opt[pos].off = off;
2162
448k
                mlen = prevMlen;
2163
448k
                off = prevOff;
2164
448k
                assert(0 < mlen && mlen <= pos);
2165
448k
                pos -= mlen;
2166
448k
            }
2167
            /* first step of the path; note : opt[0] isn't necessarily initialized */
2168
921k
            opt[0].mlen = mlen;
2169
921k
            opt[0].off = off;
2170
921k
        }
2171
2172
        /* encode all recorded sequences in order */
2173
921k
        {   int rPos = 0;  /* relative position (to ip) */
2174
2.29M
            while (rPos <= lastSeqPos) {
2175
1.36M
                int const ml = opt[rPos].mlen;
2176
1.36M
                int const offset = opt[rPos].off;
2177
1.36M
                if (ml == 1) { ip++; rPos++; continue; }  /* literal */
2178
1.07M
                rPos += ml;
2179
1.07M
                assert(ml >= MINMATCH);
2180
1.07M
                assert((offset >= 1) && (offset <= LZ4_DISTANCE_MAX));
2181
1.07M
                if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, offset, limit, oend) ) {  /* updates ip, op and anchor */
2182
553
                    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
553
        }   }   }
2186
921k
    }  /* while (ip <= mflimit) */
2187
2188
15.6k
_last_literals:
2189
15.6k
    if (LZ4HC_encodeLastLiterals(UPDATABLE(ip, op, anchor), iend, limit, oend))
2190
7.57k
        return 0;  /* not enough space in @dst */
2191
2192
    /* End */
2193
8.10k
    *srcSizePtr = (int) (((const char*)ip) - source);
2194
8.10k
    return (int) ((char*)op-dst);
2195
15.6k
}
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
16.2k
{
2209
16.2k
    LZ4_STATIC_ASSERT(LZ4_STREAMHC_EXTSIZE == sizeof(LZ4_streamHC_t) + sizeof(LZ4HC_optimal_t) * (LZ4_OPT_NUM + TRAILING_LITERALS));
2210
16.2k
    if (ctx->hasWorkspace) {   /* extended state : the buffer follows it */
2211
16.2k
        LZ4HC_optimal_t* const opt = (LZ4HC_optimal_t*)(void*)((BYTE*)ctx + sizeof(LZ4_streamHC_t));
2212
16.2k
        return LZ4HC_compress_optimal_internal(ctx, source, dst, srcSizePtr, dstCapacity,
2213
16.2k
                    nbSearches, nbSearchesSeq, targetLength, limit, dict, favorDecSpeed, opt);
2214
16.2k
    }
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
}