Coverage Report

Created: 2026-12-01 07:04

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
2.61M
#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)
86
16.5M
#define LZ4_OPT_NUM   (1<<12)
87
88
89
/*===   Macros   ===*/
90
#undef MIN
91
220M
#define MIN(a,b)   ( (a) < (b) ? (a) : (b) )
92
#undef MAX
93
660M
#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
45.5k
{
124
    /* note : clevel convention is a bit different from lz4frame,
125
     * possibly something worth revisiting for consistency */
126
45.5k
    if (cLevel < 1)
127
0
        cLevel = LZ4HC_CLEVEL_DEFAULT;
128
45.5k
    cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel);
129
45.5k
    return k_clTable[cLevel];
130
45.5k
}
131
132
133
/*===   Hashing   ===*/
134
0
#define LZ4HC_HASHSIZE 4
135
1.63G
#define HASH_FUNCTION(i)      (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG))
136
1.63G
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
97.6M
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.28k
#define LZ4MID_HASHSIZE 8
156
163M
#define LZ4MID_HASHLOG (LZ4HC_HASH_LOG-1)
157
8.34k
#define LZ4MID_HASHTABLESIZE (1 << LZ4MID_HASHLOG)
158
159
66.0M
static U32 LZ4MID_hash4(U32 v) { return (v * 2654435761U) >> (32-LZ4MID_HASHLOG); }
160
66.0M
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
97.6M
static U32 LZ4MID_hash7(U64 v) { return (U32)(((v  << (64-56)) * 58295818150454627ULL) >> (64-LZ4MID_HASHLOG)) ; }
164
static U64 LZ4_readLE64(const void* memPtr);
165
97.6M
static U32 LZ4MID_hash8Ptr(const void* ptr) { return LZ4MID_hash7(LZ4_readLE64(ptr)); }
166
167
static U64 LZ4_readLE64(const void* memPtr)
168
97.6M
{
169
97.6M
    if (LZ4_isLittleEndian()) {
170
97.6M
        return LZ4_read64(memPtr);
171
97.6M
    } 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
97.6M
}
178
179
180
/*===   Count match length   ===*/
181
LZ4_FORCE_INLINE
182
unsigned LZ4HC_NbCommonBytes32(U32 val)
183
285M
{
184
285M
    assert(val != 0);
185
285M
    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
285M
    } 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
285M
}
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
328M
{
222
328M
    int back = 0;
223
328M
    int const min = (int)MAX(iMin - ip, mMin - match);
224
328M
    assert(min <= 0);
225
328M
    assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31));
226
328M
    assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31));
227
228
711M
    while ((back - min) > 3) {
229
669M
        U32 const v = LZ4_read32(ip + back - 4) ^ LZ4_read32(match + back - 4);
230
669M
        if (v) {
231
285M
            return (back - (int)LZ4HC_NbCommonBytes32(v));
232
383M
        } else back -= 4; /* 4-byte step */
233
669M
    }
234
    /* check remainder if any */
235
68.5M
    while ( (back > min)
236
66.6M
         && (ip[back-1] == match[back-1]) )
237
25.8M
            back--;
238
42.7M
    return back;
239
328M
}
240
241
/*===   Chain table updates   ===*/
242
11.8G
#define DELTANEXTU16(table, pos) table[(U16)(pos)]   /* faster */
243
/* Make fields passed to, and updated by LZ4HC_encodeSequence explicit */
244
36.0M
#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
37.3k
{
258
37.3k
    size_t const bufferSize = (size_t)(hc4->end - hc4->prefixStart);
259
37.3k
    size_t newStartingOffset = bufferSize + hc4->dictLimit;
260
37.3k
    DEBUGLOG(5, "LZ4HC_init_internal");
261
37.3k
    assert(newStartingOffset >= bufferSize);  /* check overflow */
262
37.3k
    if (newStartingOffset > 1 GB) {
263
0
        LZ4HC_clearTables(hc4);
264
0
        newStartingOffset = 0;
265
0
    }
266
37.3k
    newStartingOffset += 64 KB;
267
37.3k
    hc4->nextToUpdate = (U32)newStartingOffset;
268
37.3k
    hc4->prefixStart = start;
269
37.3k
    hc4->end = start;
270
37.3k
    hc4->dictStart = start;
271
37.3k
    hc4->dictLimit = (U32)newStartingOffset;
272
37.3k
    hc4->lowLimit = (U32)newStartingOffset;
273
37.3k
}
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
36.0M
{
315
108M
#define ip      (*_ip)
316
297M
#define op      (*_op)
317
108M
#define anchor  (*_anchor)
318
319
36.0M
    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
36.0M
    {   size_t litLen = (size_t)(ip - anchor);
342
36.0M
        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
36.0M
        if (limit && (oend - op < (ptrdiff_t)((litLen / 255) + litLen + (2 + 1 + LASTLITERALS)))) {
346
5.64k
            DEBUGLOG(6, "Not enough room to write %i literals (%i bytes remaining)",
347
5.64k
                    (int)litLen, (int)(oend - op));
348
5.64k
            op = token;
349
5.64k
            return 1;
350
5.64k
        }
351
36.0M
        if (litLen >= RUN_MASK) {
352
1.32M
            size_t len = litLen - RUN_MASK;
353
1.32M
            *token = (RUN_MASK << ML_BITS);
354
2.13M
            for(; len >= 255 ; len -= 255) *op++ = 255;
355
1.32M
            *op++ = (BYTE)len;
356
34.7M
        } else {
357
34.7M
            *token = (BYTE)(litLen << ML_BITS);
358
34.7M
        }
359
360
        /* Copy Literals */
361
36.0M
        LZ4_wildCopy8(op, anchor, op + litLen);
362
36.0M
        op += litLen;
363
36.0M
    }
364
365
    /* Encode Offset */
366
36.0M
    assert(offset <= LZ4_DISTANCE_MAX );
367
36.0M
    assert(offset > 0);
368
36.0M
    LZ4_writeLE16(op, (U16)(offset)); op += 2;
369
370
    /* Encode MatchLength */
371
36.0M
    assert(matchLength >= MINMATCH);
372
36.0M
    {   size_t mlCode = (size_t)matchLength - MINMATCH;
373
36.0M
        if (limit && (oend - op < (ptrdiff_t)((mlCode / 255) + (1 + LASTLITERALS)))) {
374
260
            DEBUGLOG(6, "Not enough room to write match length");
375
260
            op = token;
376
260
            return 1;
377
260
        }
378
36.0M
        if (mlCode >= ML_MASK) {
379
4.08M
            *token += ML_MASK;
380
4.08M
            mlCode -= ML_MASK;
381
5.56M
            for(; mlCode >= 510 ; mlCode -= 510) { *op++ = 255; *op++ = 255; }
382
4.08M
            if (mlCode >= 255) { mlCode -= 255; *op++ = 255; }
383
4.08M
            *op++ = (BYTE)mlCode;
384
31.9M
        } else {
385
31.9M
            *token += (BYTE)(mlCode);
386
31.9M
    }   }
387
388
    /* Prepare next loop */
389
36.0M
    ip += matchLength;
390
36.0M
    anchor = ip;
391
392
36.0M
    return 0;
393
394
36.0M
#undef ip
395
36.0M
#undef op
396
36.0M
#undef anchor
397
36.0M
}
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
39.6k
{
413
39.6k
#define ip      (*_ip)
414
182k
#define op      (*_op)
415
75.2k
#define anchor  (*_anchor)
416
417
39.6k
    BYTE* const dstEnd = (limit == fillOutput) ? oend + LASTLITERALS : oend;
418
39.6k
    size_t lastRunSize = (size_t)(iend - anchor);  /* literals */
419
39.6k
    size_t llAdd = (lastRunSize + 255 - RUN_MASK) / 255;
420
39.6k
    size_t const totalSize = 1 + llAdd + lastRunSize;
421
39.6k
    assert(!limit || op <= dstEnd);
422
39.6k
    if (limit && ((size_t)(dstEnd - op) < totalSize)) {   /* compares sizes, as op + totalSize could exceed the address space */
423
4.02k
        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
35.6k
    DEBUGLOG(6, "Final literal run : %i literals", (int)lastRunSize);
430
35.6k
    ip = anchor + lastRunSize;  /* can be != iend if limit==fillOutput */
431
432
35.6k
    if (lastRunSize >= RUN_MASK) {
433
4.33k
        size_t accumulator = lastRunSize - RUN_MASK;
434
4.33k
        *op++ = (RUN_MASK << ML_BITS);
435
71.9k
        for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255;
436
4.33k
        *op++ = (BYTE) accumulator;
437
31.2k
    } else {
438
31.2k
        *op++ = (BYTE)(lastRunSize << ML_BITS);
439
31.2k
    }
440
35.6k
    assert(lastRunSize <= (size_t)(dstEnd - op));
441
35.6k
    LZ4_memcpy(op, anchor, lastRunSize);
442
35.6k
    op += lastRunSize;
443
35.6k
    return 0;
444
445
35.6k
#undef ip
446
35.6k
#undef op
447
35.6k
#undef anchor
448
35.6k
}
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
64
{
615
64
    U32* const hashTable = ctx->hashTable;
616
64
    U32 const startIdx = ctx->dictLimit + (U32)(start - ctx->prefixStart);
617
64
    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
64
    } else {
624
64
        U32 idx = startIdx;
625
64
        const BYTE* p;
626
64
        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
64
}
637
638
/**************************************
639
*  Mid Compression (level 2)
640
**************************************/
641
642
LZ4_FORCE_INLINE void
643
LZ4MID_addPosition(U32* hTable, U32 hValue, U32 index)
644
158M
{
645
158M
    hTable[hValue] = index;
646
158M
}
647
648
51.3M
#define ADDPOS8(_p, _idx) LZ4MID_addPosition(hash8Table, LZ4MID_hash8Ptr(_p), _idx)
649
30.7M
#define ADDPOS4(_p, _idx) LZ4MID_addPosition(hash4Table, LZ4MID_hash4Ptr(_p), _idx)
650
651
/* Fill hash tables with references into dictionary.
652
 * The resulting table is only exploitable by LZ4MID (level 2) */
653
static void
654
LZ4MID_fillHTable (LZ4HC_CCtx_internal* cctx, const void* dict, size_t size)
655
0
{
656
0
    U32* const hash4Table = cctx->hashTable;
657
0
    U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
658
0
    const BYTE* const prefixPtr = (const BYTE*)dict;
659
0
    U32 const prefixIdx = cctx->dictLimit;
660
0
    U32 const target = prefixIdx + (U32)size - LZ4MID_HASHSIZE;
661
0
    U32 idx = cctx->nextToUpdate;
662
0
    assert(dict == cctx->prefixStart);
663
0
    DEBUGLOG(4, "LZ4MID_fillHTable (size:%zu)", size);
664
0
    if (size <= LZ4MID_HASHSIZE)
665
0
        return;
666
667
0
    for (; idx < target; idx += 3) {
668
0
        ADDPOS4(prefixPtr+idx-prefixIdx, idx);
669
0
        ADDPOS8(prefixPtr+idx+1-prefixIdx, idx+1);
670
0
    }
671
672
0
    idx = (size > 32 KB + LZ4MID_HASHSIZE) ? target - 32 KB : cctx->nextToUpdate;
673
0
    for (; idx < target; idx += 1) {
674
0
        ADDPOS8(prefixPtr+idx-prefixIdx, idx);
675
0
    }
676
677
0
    cctx->nextToUpdate = target;
678
0
}
679
680
static LZ4MID_searchIntoDict_f select_searchDict_function(const LZ4HC_CCtx_internal* dictCtx)
681
0
{
682
0
    if (dictCtx == NULL) return NULL;
683
0
    if (LZ4HC_getCLevelParams(dictCtx->compressionLevel).strat == lz4mid)
684
0
        return LZ4MID_searchExtDict;
685
0
    return LZ4MID_searchHCDict;
686
0
}
687
688
/* Length of the match between @ip and the candidate at index @pos (in prefix or extDict),
689
 * or 0 if the candidate is out of reach */
690
LZ4_FORCE_INLINE unsigned
691
LZ4MID_countMatch(const BYTE* ip, U32 ipIndex, U32 pos, const BYTE* matchlimit,
692
                  const BYTE* prefixPtr, U32 prefixIdx,
693
                  const BYTE* dictStart, U32 dictIdx)
694
81.6M
{
695
81.6M
    if (ipIndex - pos > LZ4_DISTANCE_MAX) return 0;
696
48.4M
    if (pos >= prefixIdx) {
697
48.4M
        const BYTE* const matchPtr = prefixPtr + (pos - prefixIdx);
698
48.4M
        assert(matchPtr < ip);
699
48.4M
        return LZ4_count(ip, matchPtr, matchlimit);
700
48.4M
    }
701
0
    if (pos >= dictIdx) {
702
        /* extDict : the match stops at the end of the dictionary */
703
0
        const BYTE* const matchPtr = dictStart + (pos - dictIdx);
704
0
        size_t const safeLen = MIN(prefixIdx - pos, (size_t)(matchlimit - ip));
705
0
        return LZ4_count(ip, matchPtr, ip + safeLen);
706
0
    }
707
0
    return 0;
708
0
}
709
710
/* preconditions:
711
 * - *srcSizePtr within [1, LZ4_MAX_INPUT_SIZE]
712
 * - src is valid
713
 * - maxOutputSize >= 1
714
 * - dst is valid
715
 */
716
static int LZ4MID_compress (
717
    LZ4HC_CCtx_internal* const ctx,
718
    const char* const src,
719
    char* const dst,
720
    int* srcSizePtr,
721
    int const maxOutputSize,
722
    const limitedOutput_directive limit,
723
    const dictCtx_directive dict
724
    )
725
8.34k
{
726
8.34k
    U32* const hash4Table = ctx->hashTable;
727
8.34k
    U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
728
8.34k
    const BYTE* ip = (const BYTE*)src;
729
8.34k
    const BYTE* anchor = ip;
730
8.34k
    const BYTE* const iend = ip + *srcSizePtr;
731
8.34k
    const BYTE* mflimit;      /* set after the size check : would precede a small input */
732
8.34k
    const BYTE* matchlimit;
733
8.34k
    const BYTE* ilimit;
734
8.34k
    BYTE* op = (BYTE*)dst;
735
    /* fillOutput : keep room for the final run of literals (LZ4 format restriction) */
736
8.34k
    BYTE* const oend = op + maxOutputSize - ((limit == fillOutput) ? LASTLITERALS : 0);
737
738
8.34k
    const BYTE* const prefixPtr = ctx->prefixStart;
739
8.34k
    const U32 prefixIdx = ctx->dictLimit;
740
8.34k
    U32 ilimitIdx;
741
8.34k
    const BYTE* const dictStart = ctx->dictStart;
742
8.34k
    const U32 dictIdx = ctx->lowLimit;
743
8.34k
    const U32 gDictEndIndex = ctx->lowLimit;
744
8.34k
    const LZ4MID_searchIntoDict_f searchIntoDict = (dict == usingDictCtxHc) ? select_searchDict_function(ctx->dictCtx) : NULL;
745
8.34k
    const BYTE* refEnd = ip;   /* fillOutput : the hash tables reference positions before MAX(refEnd, ip) */
746
747
8.34k
    DEBUGLOG(5, "LZ4MID_compress (%i bytes)", *srcSizePtr);
748
749
    /* preconditions verifications */
750
8.34k
    if (dict == usingDictCtxHc) DEBUGLOG(5, "usingDictCtxHc");
751
8.34k
    assert(*srcSizePtr > 0);
752
8.34k
    assert(*srcSizePtr <= LZ4_MAX_INPUT_SIZE);
753
8.34k
    assert(src != NULL);
754
8.34k
    assert(maxOutputSize >= 1);
755
8.34k
    assert(dst != NULL);
756
757
8.34k
    if (*srcSizePtr < LZ4_minLength)
758
61
        goto _lz4mid_last_literals;  /* Input too small, no compression (all literals) */
759
8.28k
    mflimit = iend - MFLIMIT;
760
8.28k
    matchlimit = (iend - LASTLITERALS);
761
8.28k
    ilimit = (iend - LZ4MID_HASHSIZE);
762
8.28k
    ilimitIdx = (U32)(ilimit - prefixPtr) + prefixIdx;
763
764
    /* main loop */
765
40.0M
    while (ip <= mflimit) {
766
39.9M
        const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx;
767
39.9M
        unsigned matchLength;
768
39.9M
        unsigned matchDistance;
769
        /* search long match */
770
39.9M
        {   U32 const h8 = LZ4MID_hash8Ptr(ip);
771
39.9M
            U32 const pos8 = hash8Table[h8];
772
39.9M
            assert(h8 < LZ4MID_HASHTABLESIZE);
773
39.9M
            assert(pos8 < ipIndex);
774
39.9M
            LZ4MID_addPosition(hash8Table, h8, ipIndex);
775
39.9M
            matchLength = LZ4MID_countMatch(ip, ipIndex, pos8, matchlimit, prefixPtr, prefixIdx, dictStart, dictIdx);
776
39.9M
            matchDistance = ipIndex - pos8;
777
39.9M
        }
778
        /* search short match */
779
39.9M
        if (matchLength < MINMATCH) {
780
35.2M
            U32 const h4 = LZ4MID_hash4Ptr(ip);
781
35.2M
            U32 const pos4 = hash4Table[h4];
782
35.2M
            assert(h4 < LZ4MID_HASHTABLESIZE);
783
35.2M
            assert(pos4 < ipIndex);
784
35.2M
            LZ4MID_addPosition(hash4Table, h4, ipIndex);
785
35.2M
            matchLength = LZ4MID_countMatch(ip, ipIndex, pos4, matchlimit, prefixPtr, prefixIdx, dictStart, dictIdx);
786
35.2M
            matchDistance = ipIndex - pos4;
787
35.2M
        }
788
39.9M
        if (matchLength >= MINMATCH) {
789
10.2M
            if ((matchLength < 8) && likely(ip < mflimit)) {
790
                /* short match : check ip+1 for longer, except ip itself */
791
6.39M
                U32 const h8 = LZ4MID_hash8Ptr(ip+1);
792
6.39M
                U32 const pos8 = hash8Table[h8];
793
6.39M
                unsigned const ml2 = LZ4MID_countMatch(ip+1, ipIndex+1, pos8, matchlimit, prefixPtr, prefixIdx, dictStart, dictIdx);
794
6.39M
                if ((ml2 > matchLength) && (pos8 != ipIndex)) {
795
1.18M
                    LZ4MID_addPosition(hash8Table, h8, ipIndex+1);
796
1.18M
                    ip++;
797
1.18M
                    matchLength = ml2;
798
1.18M
                    matchDistance = ipIndex + 1 - pos8;
799
1.18M
            }   }
800
10.2M
            goto _lz4mid_encode_sequence;
801
10.2M
        }
802
        /* no match found in prefix nor extDict : search into the attached dictionary */
803
29.7M
        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
29.7M
        ip += 1 + ((ip-anchor) >> 9);  /* skip faster over incompressible data */
815
29.7M
        continue;
816
817
10.2M
_lz4mid_encode_sequence:
818
        /* match found at ip : matchLength, matchDistance */
819
10.2M
        DEBUGLOG(7, "found match at pos %u (len=%u, distance=%u)",
820
10.2M
                    (U32)(ip - prefixPtr) + prefixIdx, matchLength, matchDistance);
821
822
        /* catch back */
823
11.1M
        while (((ip > anchor) & ((U32)(ip-prefixPtr) > matchDistance)) && (unlikely(ip[-1] == ip[-(int)matchDistance-1]))) {
824
871k
            ip--;  matchLength++;
825
871k
        };
826
827
        /* fill table with beginning of match
828
         * note : ip may have moved since ipIndex (longer match at ip+1, catch back) */
829
10.2M
        {   U32 const startMatchIdx = (U32)(ip-prefixPtr) + prefixIdx;
830
10.2M
            ADDPOS8(ip+1, startMatchIdx+1);
831
10.2M
            ADDPOS8(ip+2, startMatchIdx+2);
832
10.2M
            ADDPOS4(ip+1, startMatchIdx+1);
833
10.2M
        }
834
835
        /* encode */
836
10.2M
        if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
837
10.2M
                (int)matchLength, (int)matchDistance,
838
10.2M
                limit, oend) ) {
839
1.04k
            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
1.04k
        }
845
846
        /* fill table with end of match */
847
10.2M
        {   U32 endMatchIdx = (U32)(ip-prefixPtr) + prefixIdx;
848
10.2M
            U32 pos_m2 = endMatchIdx - 2;
849
10.2M
            if (pos_m2 < ilimitIdx) {
850
10.2M
                if (likely(ip - prefixPtr > 5)) {
851
10.2M
                    ADDPOS8(ip-5, endMatchIdx - 5);
852
10.2M
                }
853
10.2M
                ADDPOS8(ip-3, endMatchIdx - 3);
854
10.2M
                ADDPOS8(ip-2, endMatchIdx - 2);
855
10.2M
                ADDPOS4(ip-2, endMatchIdx - 2);
856
10.2M
                ADDPOS4(ip-1, endMatchIdx - 1);
857
10.2M
            }
858
10.2M
        }
859
10.2M
    }
860
861
7.30k
_lz4mid_last_literals:
862
7.30k
    if (refEnd < ip) refEnd = ip;
863
7.30k
    if (LZ4HC_encodeLastLiterals(UPDATABLE(ip, op, anchor), iend, limit, oend))
864
775
        return 0;  /* not enough space in @dst */
865
6.52k
    if (ip < refEnd)   /* fillOutput : the rest of input is left to the next block (input >= LZ4_minLength) */
866
64
        LZ4HC_dropPositions(ctx, ip, MIN(refEnd, iend - LZ4MID_HASHSIZE), lz4mid);
867
868
    /* End */
869
6.52k
    DEBUGLOG(5, "compressed %i bytes into %i bytes", *srcSizePtr, (int)((char*)op - dst));
870
6.52k
    assert(ip >= (const BYTE*)src);
871
6.52k
    assert(ip <= iend);
872
6.52k
    *srcSizePtr = (int)(ip - (const BYTE*)src);
873
6.52k
    assert((char*)op >= dst);
874
6.52k
    assert((char*)op - dst <= maxOutputSize);
875
6.52k
    assert((char*)op - dst < INT_MAX);
876
6.52k
    return (int)((char*)op - dst);
877
6.52k
}
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
373M
{
887
373M
    U16* const chainTable = hc4->chainTable;
888
373M
    U32* const hashTable  = hc4->hashTable;
889
373M
    const BYTE* const prefixPtr = hc4->prefixStart;
890
373M
    U32 const prefixIdx = hc4->dictLimit;
891
373M
    U32 const target = (U32)(ip - prefixPtr) + prefixIdx;
892
373M
    U32 idx = hc4->nextToUpdate;
893
373M
    assert(ip >= prefixPtr);
894
373M
    assert(target >= prefixIdx);
895
896
1.63G
    while (idx < target) {
897
1.26G
        U32 const h = LZ4HC_hashPtr(prefixPtr+idx-prefixIdx);
898
1.26G
        size_t delta = idx - hashTable[h];
899
1.26G
        if (delta>LZ4_DISTANCE_MAX) delta = LZ4_DISTANCE_MAX;
900
1.26G
        DELTANEXTU16(chainTable, idx) = (U16)delta;
901
1.26G
        hashTable[h] = idx;
902
1.26G
        idx++;
903
1.26G
    }
904
905
373M
    hc4->nextToUpdate = target;
906
373M
}
907
908
#if defined(_MSC_VER)
909
#  define LZ4HC_rotl32(x,r) _rotl(x,r)
910
#else
911
0
#  define LZ4HC_rotl32(x,r) ((x << r) | (x >> (32 - r)))
912
#endif
913
914
915
static U32 LZ4HC_rotatePattern(size_t const rotate, U32 const pattern)
916
0
{
917
0
    size_t const bitsToRotate = (rotate & (sizeof(pattern) - 1)) << 3;
918
0
    if (bitsToRotate == 0) return pattern;
919
0
    return LZ4HC_rotl32(pattern, (int)bitsToRotate);
920
0
}
921
922
/* LZ4HC_countPattern() :
923
 * pattern32 must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!) */
924
static unsigned
925
LZ4HC_countPattern(const BYTE* ip, const BYTE* const iEnd, U32 const pattern32)
926
336M
{
927
336M
    const BYTE* const iStart = ip;
928
336M
    reg_t const pattern = (sizeof(pattern)==8) ?
929
336M
        (reg_t)pattern32 + (((reg_t)pattern32) << (sizeof(pattern)*4)) : pattern32;
930
931
529M
    while (likely(ip < iEnd-(sizeof(pattern)-1))) {
932
529M
        reg_t const diff = LZ4_read_ARCH(ip) ^ pattern;
933
529M
        if (!diff) { ip+=sizeof(pattern); continue; }
934
336M
        ip += LZ4_NbCommonBytes(diff);
935
336M
        return (unsigned)(ip - iStart);
936
529M
    }
937
938
37.8k
    if (LZ4_isLittleEndian()) {
939
37.8k
        reg_t patternByte = pattern;
940
155k
        while ((ip<iEnd) && (*ip == (BYTE)patternByte)) {
941
117k
            ip++; patternByte >>= 8;
942
117k
        }
943
37.8k
    } 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
37.8k
    return (unsigned)(ip - iStart);
952
336M
}
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
332M
{
960
332M
    const BYTE* const iStart = ip;
961
962
3.35G
    while (likely(ip >= iLow+4)) {
963
3.35G
        if (LZ4_read32(ip-4) != pattern) break;
964
3.02G
        ip -= 4;
965
3.02G
    }
966
332M
    {   const BYTE* bytePtr = (const BYTE*)(&pattern) + 3; /* works for any endianness */
967
820M
        while (likely(ip>iLow)) {
968
820M
            if (ip[-1] != *bytePtr) break;
969
488M
            ip--; bytePtr--;
970
488M
    }   }
971
332M
    return (unsigned)(iStart - ip);
972
332M
}
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
667M
{
981
667M
    return ((U32)((dictLimit - 1) - matchIndex) >= 3);
982
667M
}
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
40.0M
{
994
40.0M
    int const kTrigger = 4;
995
40.0M
    U32 distanceToNextMatch = 1;
996
40.0M
    int const end = longest - MINMATCH + 1;
997
40.0M
    int step = 1;
998
40.0M
    int accel = 1 << kTrigger;
999
40.0M
    int pos;
1000
1.38G
    for (pos = 0; pos < end; pos += step) {
1001
1.34G
        U32 const candidateDist = DELTANEXTU16(chainTable, matchIndex + (U32)pos);
1002
1.34G
        step = (accel++ >> kTrigger);
1003
1.34G
        if (candidateDist > distanceToNextMatch) {
1004
54.3M
            distanceToNextMatch = candidateDist;
1005
54.3M
            *matchChainPosPtr = (U32)pos;
1006
54.3M
            accel = 1 << kTrigger;
1007
54.3M
    }   }
1008
40.0M
    return distanceToNextMatch;
1009
40.0M
}
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
335M
{
1021
335M
    const BYTE* const prefixPtr = hc4->prefixStart;
1022
335M
    U32 const prefixIdx = hc4->dictLimit;
1023
335M
    const BYTE* const dictStart = hc4->dictStart;
1024
335M
    U32 const dictIdx = hc4->lowLimit;
1025
335M
    const BYTE* const dictEnd = dictStart + prefixIdx - dictIdx;
1026
335M
    int const extDict = candidateIdx < prefixIdx;
1027
335M
    const BYTE* const matchPtr = extDict ? dictStart + (candidateIdx - dictIdx) : prefixPtr + (candidateIdx - prefixIdx);
1028
335M
    size_t forward, back;
1029
335M
    if (LZ4_read32(matchPtr) != pattern) return 0;
1030
1031
332M
    {   const BYTE* const iLimit = extDict ? dictEnd : iHighLimit;
1032
332M
        forward = LZ4HC_countPattern(matchPtr+sizeof(pattern), iLimit, pattern) + sizeof(pattern);
1033
332M
        if (extDict && matchPtr + forward == iLimit) {   /* continues into the prefix */
1034
0
            U32 const rotatedPattern = LZ4HC_rotatePattern(forward, pattern);
1035
0
            forward += LZ4HC_countPattern(prefixPtr, iHighLimit, rotatedPattern);
1036
0
    }   }
1037
1038
332M
    back = LZ4HC_reverseCountPattern(matchPtr, extDict ? dictStart : prefixPtr, pattern);
1039
332M
    if (!extDict && matchPtr - back == prefixPtr && dictIdx < prefixIdx) {   /* continues into the external dictionary */
1040
0
        U32 const rotatedPattern = LZ4HC_rotatePattern((U32)(-(int)back), pattern);
1041
0
        back += LZ4HC_reverseCountPattern(dictEnd, dictStart, rotatedPattern);
1042
0
    }
1043
    /* don't go below lowestMatchIndex */
1044
332M
    back = candidateIdx - MAX(candidateIdx - (U32)back, lowestMatchIndex);
1045
332M
    assert(candidateIdx - back >= lowestMatchIndex);
1046
1047
332M
    *forwardPtr = forward;
1048
332M
    *backPtr = back;
1049
332M
    return 1;
1050
332M
}
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
373M
{
1065
373M
    U16* const chainTable = hc4->chainTable;
1066
373M
    U32* const hashTable = hc4->hashTable;
1067
373M
    const LZ4HC_CCtx_internal* const dictCtx = hc4->dictCtx;
1068
373M
    const BYTE* const prefixPtr = hc4->prefixStart;
1069
373M
    const U32 prefixIdx = hc4->dictLimit;
1070
373M
    const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx;
1071
373M
    const int withinStartDistance = (hc4->lowLimit + (LZ4_DISTANCE_MAX + 1) > ipIndex);
1072
373M
    const U32 lowestMatchIndex = (withinStartDistance) ? hc4->lowLimit : ipIndex - LZ4_DISTANCE_MAX;
1073
373M
    const BYTE* const dictStart = hc4->dictStart;
1074
373M
    const U32 dictIdx = hc4->lowLimit;
1075
373M
    int const lookBackLength = (int)(ip-iLowLimit);
1076
373M
    int const maxLength = (int)(iHighLimit-iLowLimit);   /* no match can be longer */
1077
373M
    int nbAttempts = maxNbAttempts;
1078
373M
    U32 matchChainPos = 0;
1079
373M
    U32 const pattern = LZ4_read32(ip);
1080
373M
    U32 matchIndex;
1081
373M
    repeat_state_e repeat = rep_untested;
1082
373M
    size_t srcPatternLength = 0;
1083
373M
    int offset = 0, sBack = 0;
1084
1085
373M
    DEBUGLOG(7, "LZ4HC_InsertAndGetWiderMatch");
1086
    /* First Match */
1087
373M
    LZ4HC_Insert(hc4, ip);  /* insert all prior positions up to ip (excluded) */
1088
373M
    matchIndex = hashTable[LZ4HC_hashPtr(ip)];
1089
373M
    DEBUGLOG(7, "First candidate match for pos %u found at index %u / %u (lowestMatchIndex)",
1090
373M
                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
5.08G
    while ((matchIndex>=lowestMatchIndex) && (nbAttempts>0) && (longest<maxLength)) {
1095
4.71G
        int matchLength=0;
1096
4.71G
        nbAttempts--;
1097
4.71G
        assert(matchIndex < ipIndex);
1098
4.71G
        if (favorDecSpeed && (ipIndex - matchIndex < 8)) {
1099
            /* do nothing:
1100
             * favorDecSpeed intentionally skips matches with offset < 8 */
1101
4.71G
        } else if (matchIndex >= prefixIdx) {   /* within current Prefix */
1102
4.71G
            const BYTE* const matchPtr = prefixPtr + (matchIndex - prefixIdx);
1103
4.71G
            assert(matchPtr < ip);
1104
4.71G
            assert(longest >= 1);
1105
4.71G
            if (LZ4_read16(iLowLimit + longest - 1) == LZ4_read16(matchPtr - lookBackLength + longest - 1)) {
1106
610M
                if (LZ4_read32(matchPtr) == pattern) {
1107
496M
                    int const back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, prefixPtr) : 0;
1108
496M
                    matchLength = MINMATCH + (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit);
1109
496M
                    matchLength -= back;
1110
496M
                    if (matchLength > longest) {
1111
72.7M
                        longest = matchLength;
1112
72.7M
                        offset = (int)(ipIndex - matchIndex);
1113
72.7M
                        sBack = back;
1114
72.7M
                        DEBUGLOG(7, "Found match of len=%i within prefix, offset=%i, back=%i", longest, offset, -back);
1115
72.7M
                        HEX_CMP(7, ip + back, ip + back - offset, (size_t)matchLength);
1116
72.7M
            }   }   }
1117
4.71G
        } else {   /* lowestMatchIndex <= matchIndex < dictLimit : within Ext Dict */
1118
0
            const BYTE* const matchPtr = dictStart + (matchIndex - dictIdx);
1119
0
            assert(matchIndex >= dictIdx);
1120
0
            if ( likely(matchIndex <= prefixIdx - 4)
1121
0
              && (LZ4_read32(matchPtr) == pattern) ) {
1122
0
                int back = 0;
1123
0
                const BYTE* vLimit = ip + (prefixIdx - matchIndex);
1124
0
                if (vLimit > iHighLimit) vLimit = iHighLimit;
1125
0
                matchLength = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
1126
0
                if ((ip+matchLength == vLimit) && (vLimit < iHighLimit))
1127
0
                    matchLength += LZ4_count(ip+matchLength, prefixPtr, iHighLimit);
1128
0
                back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictStart) : 0;
1129
0
                matchLength -= back;
1130
0
                if (matchLength > longest) {
1131
0
                    longest = matchLength;
1132
0
                    offset = (int)(ipIndex - matchIndex);
1133
0
                    sBack = back;
1134
0
                    DEBUGLOG(7, "Found match of len=%i within dict, offset=%i, back=%i", longest, offset, -back);
1135
0
                    HEX_CMP(7, ip + back, matchPtr + back, (size_t)matchLength);
1136
0
        }   }   }
1137
1138
4.71G
        if (chainSwap && matchLength==longest && matchIndex + (U32)longest <= ipIndex) {   /* better match => select a better chain */
1139
40.0M
            U32 const distanceToNextMatch = LZ4HC_sparsestChain(chainTable, matchIndex, longest, &matchChainPos);
1140
40.0M
            assert(lookBackLength==0);   /* search forward only */
1141
40.0M
            if (distanceToNextMatch > 1) {
1142
38.8M
                if (distanceToNextMatch > matchIndex) break;   /* avoid overflow */
1143
38.8M
                matchIndex -= distanceToNextMatch;
1144
38.8M
                continue;
1145
38.8M
        }   }
1146
1147
4.67G
        {   U32 const distNextMatch = DELTANEXTU16(chainTable, matchIndex);
1148
4.67G
            if (patternAnalysis && distNextMatch==1 && matchChainPos==0) {
1149
355M
                U32 const matchCandidateIdx = matchIndex-1;
1150
355M
                size_t forwardPatternLength, backLength;
1151
                /* may be a repeated pattern */
1152
355M
                if (repeat == rep_untested) {
1153
3.60M
                    if ( ((pattern & 0xFFFF) == (pattern >> 16))
1154
3.60M
                      &  ((pattern & 0xFF)   == (pattern >> 24)) ) {
1155
3.53M
                        DEBUGLOG(7, "Repeat pattern detected, char %02X", pattern >> 24);
1156
3.53M
                        repeat = rep_confirmed;
1157
3.53M
                        srcPatternLength = LZ4HC_countPattern(ip+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern);
1158
3.53M
                    } else {
1159
61.3k
                        repeat = rep_not;
1160
61.3k
                }   }
1161
355M
                if ( (repeat == rep_confirmed) && (matchCandidateIdx >= lowestMatchIndex)
1162
335M
                  && LZ4HC_protectDictEnd(prefixIdx, matchCandidateIdx)
1163
335M
                  && LZ4HC_patternSegment(hc4, matchCandidateIdx, pattern, iHighLimit, lowestMatchIndex,
1164
335M
                                          &forwardPatternLength, &backLength) ) {
1165
332M
                    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
332M
                    int const fullPatternFits = (currentSegmentLength >= srcPatternLength)
1170
218M
                                             && (forwardPatternLength <= srcPatternLength);
1171
332M
                    U32 const newMatchIndex = fullPatternFits ?
1172
93.9M
                                              matchCandidateIdx + (U32)forwardPatternLength - (U32)srcPatternLength :
1173
332M
                                              matchCandidateIdx - (U32)backLength;
1174
332M
                    if (!LZ4HC_protectDictEnd(prefixIdx, newMatchIndex)) {
1175
                        /* Can only happen if started in the prefix */
1176
0
                        assert(newMatchIndex >= prefixIdx - 3 && newMatchIndex < prefixIdx && matchCandidateIdx >= prefixIdx);
1177
0
                        matchIndex = prefixIdx;
1178
0
                        continue;
1179
0
                    }
1180
332M
                    matchIndex = newMatchIndex;
1181
332M
                    if (!fullPatternFits && lookBackLength==0) {  /* no back possible : the match length is known */
1182
217M
                        size_t const maxML = MIN(currentSegmentLength, srcPatternLength);
1183
217M
                        if ((size_t)longest < maxML) {
1184
1.37M
                            assert(prefixPtr - prefixIdx + matchIndex != ip);
1185
1.37M
                            if ((size_t)(ip - prefixPtr) + prefixIdx - matchIndex > LZ4_DISTANCE_MAX) break;
1186
1.37M
                            assert(maxML < 2 GB);
1187
1.37M
                            longest = (int)maxML;
1188
1.37M
                            offset = (int)(ipIndex - matchIndex);
1189
1.37M
                            assert(sBack == 0);
1190
1.37M
                            DEBUGLOG(7, "Found repeat pattern match of len=%i, offset=%i", longest, offset);
1191
1.37M
                        }
1192
217M
                        {   U32 const distToNextPattern = DELTANEXTU16(chainTable, matchIndex);
1193
217M
                            if (distToNextPattern > matchIndex) break;  /* avoid overflow */
1194
217M
                            matchIndex -= distToNextPattern;
1195
217M
                    }   }
1196
332M
                    continue;
1197
332M
                }
1198
355M
        }   }   /* PA optimization */
1199
1200
        /* follow current chain */
1201
4.34G
        matchIndex -= DELTANEXTU16(chainTable, matchIndex + matchChainPos);
1202
1203
4.34G
    }  /* while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) */
1204
1205
373M
    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
373M
    {   LZ4HC_match_t md;
1238
373M
        assert(longest >= 0);
1239
373M
        md.len = longest;
1240
373M
        md.off = offset;
1241
373M
        md.back = sBack;
1242
373M
        return md;
1243
373M
    }
1244
373M
}
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
186M
{
1253
186M
    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
186M
    return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio);
1258
186M
}
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
20.4k
{
1278
20.4k
    const int inputSize = *srcSizePtr;
1279
20.4k
    const int patternAnalysis = (maxNbAttempts > 128);   /* levels 9+ */
1280
1281
20.4k
    const BYTE* ip = (const BYTE*)src;
1282
20.4k
    const BYTE* anchor = ip;
1283
20.4k
    const BYTE* const iend = ip + inputSize;
1284
20.4k
    const BYTE* mflimit;      /* set after the size check : would precede a small input */
1285
20.4k
    const BYTE* matchlimit;
1286
1287
20.4k
    BYTE* op = (BYTE*) dst;
1288
    /* fillOutput : keep room for the final run of literals (LZ4 format restriction) */
1289
20.4k
    BYTE* const oend = op + maxOutputSize - ((limit == fillOutput) ? LASTLITERALS : 0);
1290
1291
20.4k
    const BYTE* start0;
1292
20.4k
    const BYTE* start2 = NULL;
1293
20.4k
    const BYTE* start3 = NULL;
1294
20.4k
    LZ4HC_match_t m0, m1, m2, m3;
1295
20.4k
    const LZ4HC_match_t nomatch = {0, 0, 0};
1296
1297
    /* init */
1298
20.4k
    DEBUGLOG(5, "LZ4HC_compress_hashChain (dict?=>%i)", dict);
1299
1300
    /* preconditions verifications */
1301
20.4k
    assert(*srcSizePtr >= 1);
1302
20.4k
    assert(src != NULL);
1303
20.4k
    assert(maxOutputSize >= 1);
1304
20.4k
    assert(dst != NULL);
1305
1306
20.4k
    *srcSizePtr = 0;
1307
20.4k
    if (inputSize < LZ4_minLength) goto _last_literals;             /* Input too small, no compression (all literals) */
1308
20.3k
    mflimit = iend - MFLIMIT;
1309
20.3k
    matchlimit = (iend - LASTLITERALS);
1310
1311
    /* Main Loop */
1312
186M
    while (ip <= mflimit) {
1313
186M
        m1 = LZ4HC_InsertAndFindBestMatch(ctx, ip, matchlimit, maxNbAttempts, patternAnalysis, dict);
1314
186M
        if (m1.len<MINMATCH) { ip++; continue; }
1315
1316
        /* saved, in case we would skip too much */
1317
14.9M
        start0 = ip; m0 = m1;
1318
1319
18.9M
_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
18.9M
        DEBUGLOG(7, "_Search2 (currently found match of size %i)", m1.len);
1323
18.9M
        if (ip+m1.len <= mflimit) {
1324
18.9M
            start2 = ip + m1.len - 2;
1325
18.9M
            m2 = LZ4HC_InsertAndGetWiderMatch(ctx,
1326
18.9M
                            start2, ip + 0, matchlimit, m1.len,
1327
18.9M
                            maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
1328
18.9M
            start2 += m2.back;
1329
18.9M
        } else {
1330
11.2k
            m2 = nomatch;  /* do not search further */
1331
11.2k
        }
1332
1333
18.9M
        if (m2.len <= m1.len) { /* No better match => encode m1 immediately */
1334
13.7M
            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1335
13.7M
                    m1.len, m1.off,
1336
13.7M
                    limit, oend) )
1337
2.11k
                goto _dest_overflow;
1338
13.7M
            continue;
1339
13.7M
        }
1340
1341
5.21M
        if ((start0 < ip) && (start2 < ip + m0.len)) {
1342
            /* m1 was skipped at least once, and m2 starts early enough : restore m0 */
1343
552k
            ip = start0; m1 = m0;
1344
552k
        }
1345
1346
5.21M
        if ((start2 - ip) < 3) {  /* m1 too short before m2 : removed */
1347
3.16M
            ip = start2;
1348
3.16M
            m1 = m2;
1349
3.16M
            goto _Search2;
1350
3.16M
        }
1351
1352
        /* m2 (at start2) is the candidate after m1.
1353
         * Search a longer match m3, starting before the end of m2. */
1354
2.61M
        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
2.61M
            if ((start2 - ip) < OPTIMAL_ML) {
1358
2.45M
                int const gap = (int)(start2 - ip);
1359
2.45M
                int newML = MIN(m1.len, OPTIMAL_ML);
1360
2.45M
                if (newML > gap + m2.len - MINMATCH)
1361
1.19k
                    newML = gap + m2.len - MINMATCH;
1362
2.45M
                if (newML > gap) {   /* shift m2 */
1363
2.21M
                    start2 += newML - gap;
1364
2.21M
                    m2.len -= newML - gap;
1365
2.21M
                }
1366
2.45M
            }
1367
1368
2.61M
            if (start2 + m2.len <= mflimit) {
1369
2.61M
                start3 = start2 + m2.len - 3;
1370
2.61M
                m3 = LZ4HC_InsertAndGetWiderMatch(ctx,
1371
2.61M
                                start3, start2, matchlimit, m2.len,
1372
2.61M
                                maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
1373
2.61M
                start3 += m3.back;
1374
2.61M
            } else {
1375
2.45k
                m3 = nomatch;  /* do not search further */
1376
2.45k
            }
1377
1378
2.61M
            if ((m3.len > m2.len) && (start3 < ip+m1.len+3)) {  /* not enough room for m2 between m1 and m3 */
1379
957k
                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
903k
                    if (start2 < ip+m1.len) {
1383
22.3k
                        int correction = (int)(ip+m1.len - start2);
1384
22.3k
                        start2 += correction;
1385
22.3k
                        m2.len -= correction;
1386
22.3k
                        if (m2.len < MINMATCH) {
1387
308
                            start2 = start3;
1388
308
                            m2 = m3;
1389
308
                        }
1390
22.3k
                    }
1391
1392
903k
                    if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1393
903k
                            m1.len, m1.off,
1394
903k
                            limit, oend) )
1395
165
                        goto _dest_overflow;
1396
903k
                    ip  = start3;
1397
903k
                    m1 = m3;
1398
1399
903k
                    start0 = start2;
1400
903k
                    m0 = m2;
1401
903k
                    goto _Search2;
1402
903k
                }
1403
1404
                /* m3 starts within m1 : m3 replaces m2 */
1405
53.9k
                start2 = start3;
1406
53.9k
                m2 = m3;
1407
53.9k
                continue;
1408
957k
            }
1409
1410
            /* encode m1, cut where m2 starts */
1411
1.66M
            if (start2 < ip+m1.len) m1.len = (int)(start2 - ip);
1412
1.66M
            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1413
1.66M
                    m1.len, m1.off,
1414
1.66M
                    limit, oend) )
1415
418
                goto _dest_overflow;
1416
1417
            /* m2 becomes m1 */
1418
1.65M
            ip = start2; m1 = m2;
1419
1420
1.65M
            if (m3.len <= m1.len) {  /* No better match => encode m1 (former m2) */
1421
1.14M
                if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
1422
1.14M
                        m1.len, m1.off,
1423
1.14M
                        limit, oend) )
1424
131
                    goto _dest_overflow;
1425
1.14M
                break;
1426
1.14M
            }
1427
1428
            /* m3 becomes m2 */
1429
516k
            start2 = start3; m2 = m3;
1430
516k
        }
1431
2.04M
    }
1432
1433
17.6k
_last_literals:
1434
17.6k
    if (LZ4HC_encodeLastLiterals(UPDATABLE(ip, op, anchor), iend, limit, oend))
1435
1.42k
        return 0;  /* not enough space in @dst */
1436
1437
    /* End */
1438
16.2k
    *srcSizePtr = (int) (((const char*)ip) - src);
1439
16.2k
    return (int) (((char*)op)-dst);
1440
1441
2.82k
_dest_overflow:
1442
2.82k
    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
2.82k
}
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
45.5k
{
1468
45.5k
    DEBUGLOG(5, "LZ4HC_compress_generic_internal(src=%p, srcSize=%d, dstCapacity=%d)",
1469
45.5k
                src, *srcSizePtr, dstCapacity);
1470
1471
    /* input sanitization */
1472
45.5k
    if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0;  /* Unsupported input size (too large or negative) */
1473
45.5k
    if (dstCapacity < 1) return 0;   /* Invalid: impossible to store anything */
1474
45.5k
    assert(dst); /* since dstCapacity >= 1, dst must be valid */
1475
45.5k
    if (*srcSizePtr == 0) { *dst = 0; return 1; }
1476
45.5k
    assert(src != NULL); /* since *srcSizePtr >= 1, src must be valid */
1477
1478
45.5k
    ctx->end += *srcSizePtr;
1479
45.5k
    {   cParams_t const cParam = LZ4HC_getCLevelParams(cLevel);
1480
45.5k
        HCfavor_e const favor = ctx->favorDecSpeed ? favorDecompressionSpeed : favorCompressionRatio;
1481
45.5k
        int const srcSize = *srcSizePtr;
1482
45.5k
        int result;
1483
1484
45.5k
        if (cParam.strat == lz4mid) {
1485
8.34k
            result = LZ4MID_compress(ctx,
1486
8.34k
                                src, dst, srcSizePtr, dstCapacity,
1487
8.34k
                                limit, dict);
1488
37.2k
        } else if (cParam.strat == lz4hc) {
1489
20.4k
            result = LZ4HC_compress_hashChain(ctx,
1490
20.4k
                                src, dst, srcSizePtr, dstCapacity,
1491
20.4k
                                cParam.nbSearches, limit, dict);
1492
20.4k
        } else {
1493
16.7k
            assert(cParam.strat == lz4opt);
1494
16.7k
            result = LZ4HC_compress_optimal(ctx,
1495
16.7k
                                src, dst, srcSizePtr, dstCapacity,
1496
16.7k
                                cParam.nbSearches, cParam.nbSearchesSeq, (int)cParam.targetLength, limit,
1497
16.7k
                                dict, favor);
1498
16.7k
        }
1499
45.5k
        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
45.5k
        return result;
1514
45.5k
    }
1515
45.5k
}
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
45.5k
{
1530
45.5k
    assert(ctx->dictCtx == NULL);
1531
45.5k
    return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, noDictCtx);
1532
45.5k
}
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
45.5k
{
1583
45.5k
    if (ctx->dictCtx == NULL) {
1584
45.5k
        return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
1585
45.5k
    } else {
1586
0
        return LZ4HC_compress_generic_dictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
1587
0
    }
1588
45.5k
}
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
67.1k
{
1595
67.1k
#if LZ4_ALIGN_TEST
1596
67.1k
    typedef struct { char c; LZ4_streamHC_t t; } t_a;
1597
67.1k
    return sizeof(t_a) - sizeof(LZ4_streamHC_t);
1598
#else
1599
    return 1;  /* effectively disabled */
1600
#endif
1601
67.1k
}
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
34.5k
{
1607
34.5k
    LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)state)->internal_donotuse;
1608
34.5k
    if (!LZ4_isAligned(state, LZ4_streamHC_t_alignment())) return 0;
1609
34.5k
    LZ4_resetStreamHC_fast((LZ4_streamHC_t*)state, compressionLevel);
1610
34.5k
    LZ4HC_init_internal (ctx, (const BYTE*)src);
1611
34.5k
    if (dstCapacity < LZ4_compressBound(srcSize))
1612
34.5k
        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
34.5k
}
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
32.5k
{
1680
32.5k
    LZ4_streamHC_t* const LZ4_streamHCPtr = (LZ4_streamHC_t*)buffer;
1681
32.5k
    DEBUGLOG(4, "LZ4_initStreamHC(%p, %u)", buffer, (unsigned)size);
1682
    /* check conditions */
1683
32.5k
    if (buffer == NULL) return NULL;
1684
32.5k
    if (size < sizeof(LZ4_streamHC_t)) return NULL;
1685
32.5k
    if (!LZ4_isAligned(buffer, LZ4_streamHC_t_alignment())) return NULL;
1686
    /* init */
1687
32.5k
    { LZ4HC_CCtx_internal* const hcstate = &(LZ4_streamHCPtr->internal_donotuse);
1688
32.5k
      MEM_INIT(hcstate, 0, sizeof(*hcstate));
1689
32.5k
      hcstate->hasWorkspace = (size >= LZ4_STREAMHC_EXTSIZE); }
1690
32.5k
    LZ4_setCompressionLevel(LZ4_streamHCPtr, LZ4HC_CLEVEL_DEFAULT);
1691
32.5k
    return LZ4_streamHCPtr;
1692
32.5k
}
1693
1694
/* size of an initialized state, to initialize it again : extended states are followed by their buffer */
1695
static size_t LZ4HC_sizeofState(const LZ4_streamHC_t* s)
1696
0
{
1697
0
    return s->internal_donotuse.hasWorkspace ? LZ4_STREAMHC_EXTSIZE : sizeof(*s);
1698
0
}
1699
1700
/* initializes arbitrary data, as LZ4_initStreamHC() : its extension marker can't be trusted */
1701
void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
1702
0
{
1703
0
    LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));
1704
0
    LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
1705
0
}
1706
1707
void LZ4_resetStreamHC_fast (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
1708
71.9k
{
1709
71.9k
    LZ4HC_CCtx_internal* const s = &LZ4_streamHCPtr->internal_donotuse;
1710
71.9k
    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
71.9k
    assert(s->end >= s->prefixStart);
1713
71.9k
    s->dictLimit += (U32)(s->end - s->prefixStart);
1714
71.9k
    s->prefixStart = NULL;
1715
71.9k
    s->end = NULL;
1716
71.9k
    s->dictCtx = NULL;
1717
71.9k
    LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
1718
71.9k
}
1719
1720
void LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
1721
137k
{
1722
137k
    DEBUGLOG(5, "LZ4_setCompressionLevel(%p, %d)", LZ4_streamHCPtr, compressionLevel);
1723
137k
    if (compressionLevel < 1) compressionLevel = LZ4HC_CLEVEL_DEFAULT;
1724
137k
    if (compressionLevel > LZ4HC_CLEVEL_MAX) compressionLevel = LZ4HC_CLEVEL_MAX;
1725
137k
    LZ4_streamHCPtr->internal_donotuse.compressionLevel = (short)compressionLevel;
1726
137k
}
1727
1728
void LZ4_favorDecompressionSpeed(LZ4_streamHC_t* LZ4_streamHCPtr, int favor)
1729
32.5k
{
1730
32.5k
    LZ4_streamHCPtr->internal_donotuse.favorDecSpeed = (favor!=0);
1731
32.5k
}
1732
1733
/* LZ4_loadDictHC() :
1734
 * LZ4_streamHCPtr is presumed properly initialized */
1735
int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr,
1736
              const char* dictionary, int dictSize)
1737
0
{
1738
0
    LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;
1739
0
    cParams_t cp;
1740
0
    DEBUGLOG(4, "LZ4_loadDictHC(ctx:%p, dict:%p, dictSize:%d, clevel=%d)", LZ4_streamHCPtr, dictionary, dictSize, ctxPtr->compressionLevel);
1741
0
    assert(LZ4_streamHCPtr != NULL);
1742
0
    if (dictSize < 0) dictSize = 0;   /* invalid size : no dictionary */
1743
0
    if (dictSize > 64 KB) {
1744
0
        dictionary += (size_t)dictSize - 64 KB;
1745
0
        dictSize = 64 KB;
1746
0
    }
1747
    /* need a full initialization, there are bad side-effects when using resetFast(),
1748
     * but preserve parameters */
1749
0
    {   int const cLevel = ctxPtr->compressionLevel;
1750
0
        LZ4_i8 const favorDecSpeed = ctxPtr->favorDecSpeed;
1751
0
        LZ4_initStreamHC(LZ4_streamHCPtr, LZ4HC_sizeofState(LZ4_streamHCPtr));
1752
0
        LZ4_setCompressionLevel(LZ4_streamHCPtr, cLevel);
1753
0
        ctxPtr->favorDecSpeed = favorDecSpeed;
1754
0
        cp = LZ4HC_getCLevelParams(cLevel);
1755
0
    }
1756
0
    LZ4HC_init_internal (ctxPtr, (const BYTE*)dictionary);
1757
0
    ctxPtr->end = (const BYTE*)dictionary + dictSize;
1758
0
    if (cp.strat == lz4mid) {
1759
0
        LZ4MID_fillHTable (ctxPtr, dictionary, (size_t)dictSize);
1760
0
    } else {
1761
0
        if (dictSize >= LZ4HC_HASHSIZE) LZ4HC_Insert (ctxPtr, ctxPtr->end-3);
1762
0
    }
1763
0
    return dictSize;
1764
0
}
1765
1766
void LZ4_attach_HC_dictionary(LZ4_streamHC_t *working_stream, const LZ4_streamHC_t *dictionary_stream)
1767
0
{
1768
0
    const LZ4HC_CCtx_internal* dictCtx = (dictionary_stream == NULL) ? NULL :
1769
0
        &(dictionary_stream->internal_donotuse);
1770
1771
    /* A state without content (new, or reset since loading) is an empty dictionary, as in LZ4_attach_dictionary() :
1772
     * its tables don't match any buffer, so it's not attached */
1773
0
    if ((dictCtx != NULL) && (dictCtx->end == dictCtx->prefixStart)) {
1774
0
        dictCtx = NULL;
1775
0
    }
1776
    /* The dictionary replaces the stream history (see lz4hc.h) : drop it, as LZ4F_initStream() does */
1777
0
    if ((dictCtx != NULL) && (working_stream->internal_donotuse.prefixStart != NULL)) {
1778
0
        LZ4_resetStreamHC_fast(working_stream, working_stream->internal_donotuse.compressionLevel);
1779
0
    }
1780
0
    working_stream->internal_donotuse.dictCtx = dictCtx;
1781
0
}
1782
1783
/* compression */
1784
1785
static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock)
1786
0
{
1787
0
    DEBUGLOG(4, "LZ4HC_setExternalDict(%p, %p)", ctxPtr, newBlock);
1788
0
    if (LZ4HC_getCLevelParams(ctxPtr->compressionLevel).strat != lz4mid) {
1789
0
        U32 const endIdx = ctxPtr->dictLimit + (U32)(ctxPtr->end - ctxPtr->prefixStart);
1790
0
        U32 idx;
1791
0
        if (ctxPtr->end >= ctxPtr->prefixStart + 4)
1792
0
            LZ4HC_Insert (ctxPtr, ctxPtr->end-3);  /* Referencing remaining dictionary content */
1793
        /* last positions can't be inserted : don't leave stale chains from previous history */
1794
0
        for (idx = ctxPtr->nextToUpdate; idx < endIdx; idx++)
1795
0
            DELTANEXTU16(ctxPtr->chainTable, idx) = 0;
1796
0
    }
1797
1798
    /* Only one memory segment for extDict, so any previous extDict is lost at this stage */
1799
0
    ctxPtr->lowLimit  = ctxPtr->dictLimit;
1800
0
    ctxPtr->dictStart  = ctxPtr->prefixStart;
1801
0
    ctxPtr->dictLimit += (U32)(ctxPtr->end - ctxPtr->prefixStart);
1802
0
    ctxPtr->prefixStart = newBlock;
1803
0
    ctxPtr->end  = newBlock;
1804
0
    ctxPtr->nextToUpdate = ctxPtr->dictLimit;   /* match referencing will resume from there */
1805
1806
    /* cannot reference an extDict and a dictCtx at the same time */
1807
0
    ctxPtr->dictCtx = NULL;
1808
0
}
1809
1810
static int
1811
LZ4_compressHC_continue_generic (LZ4_streamHC_t* LZ4_streamHCPtr,
1812
                                 const char* src, char* dst,
1813
                                 int* srcSizePtr, int dstCapacity,
1814
                                 limitedOutput_directive limit)
1815
10.9k
{
1816
10.9k
    LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;
1817
10.9k
    DEBUGLOG(5, "LZ4_compressHC_continue_generic(ctx=%p, src=%p, srcSize=%d, limit=%d)",
1818
10.9k
                LZ4_streamHCPtr, src, *srcSizePtr, limit);
1819
10.9k
    assert(ctxPtr != NULL);
1820
    /* auto-init if forgotten */
1821
10.9k
    if (ctxPtr->prefixStart == NULL)
1822
2.79k
        LZ4HC_init_internal (ctxPtr, (const BYTE*) src);
1823
1824
    /* Check overflow */
1825
10.9k
    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
10.9k
    if ((const BYTE*)src != ctxPtr->end)
1833
0
        LZ4HC_setExternalDict(ctxPtr, (const BYTE*)src);
1834
1835
    /* Check overlapping input/dictionary space */
1836
10.9k
    {   const BYTE* sourceEnd = (const BYTE*) src + *srcSizePtr;
1837
10.9k
        const BYTE* const dictBegin = ctxPtr->dictStart;
1838
10.9k
        const BYTE* const dictEnd   = ctxPtr->dictStart + (ctxPtr->dictLimit - ctxPtr->lowLimit);
1839
10.9k
        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
10.9k
    return LZ4HC_compress_generic (ctxPtr, src, dst, srcSizePtr, dstCapacity, ctxPtr->compressionLevel, limit);
1850
10.9k
}
1851
1852
int LZ4_compress_HC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int srcSize, int dstCapacity)
1853
10.9k
{
1854
10.9k
    DEBUGLOG(5, "LZ4_compress_HC_continue");
1855
10.9k
    if (dstCapacity < LZ4_compressBound(srcSize))
1856
10.9k
        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
10.9k
}
1860
1861
int LZ4_compress_HC_continue_destSize (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int* srcSizePtr, int targetDestSize)
1862
0
{
1863
0
    return LZ4_compressHC_continue_generic(LZ4_streamHCPtr, src, dst, srcSizePtr, targetDestSize, fillOutput);
1864
0
}
1865
1866
1867
/* LZ4_saveDictHC :
1868
 * save history content
1869
 * into a user-provided buffer
1870
 * which is then used to continue compression
1871
 */
1872
int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictSize)
1873
0
{
1874
0
    LZ4HC_CCtx_internal* const streamPtr = &LZ4_streamHCPtr->internal_donotuse;
1875
0
    size_t const prefixSize = (size_t)(streamPtr->end - streamPtr->prefixStart);   /* can exceed INT_MAX */
1876
0
    DEBUGLOG(5, "LZ4_saveDictHC(%p, %p, %d)", LZ4_streamHCPtr, safeBuffer, dictSize);
1877
    /* nothing compressed yet (new or reset stream) : nothing to save,
1878
     * the stream remains to be initialized by next compression (attached dictionary included) */
1879
0
    if (streamPtr->prefixStart == NULL) return 0;
1880
0
    assert(streamPtr->end >= streamPtr->prefixStart);
1881
0
    if (dictSize > 64 KB) dictSize = 64 KB;
1882
0
    if (dictSize < 4) dictSize = 0;
1883
0
    if ((size_t)dictSize > prefixSize) dictSize = (int)prefixSize;   /* 0 <= dictSize <= 64 KB : prefixSize fits */
1884
0
    if (safeBuffer == NULL) assert(dictSize == 0); /* a NULL buffer with !0 size is invalid */
1885
0
    if (dictSize > 0)
1886
0
        LZ4_memmove(safeBuffer, streamPtr->end - dictSize, (size_t)dictSize);
1887
0
    {   U32 const endIndex = (U32)(streamPtr->end - streamPtr->prefixStart) + streamPtr->dictLimit;
1888
0
        streamPtr->end = (safeBuffer == NULL) ? NULL : (const BYTE*)safeBuffer + dictSize;
1889
0
        streamPtr->prefixStart = (const BYTE*)safeBuffer;
1890
0
        streamPtr->dictLimit = endIndex - (U32)dictSize;
1891
0
        streamPtr->lowLimit = endIndex - (U32)dictSize;
1892
0
        streamPtr->dictStart = streamPtr->prefixStart;
1893
0
        if (streamPtr->nextToUpdate < streamPtr->dictLimit)
1894
0
            streamPtr->nextToUpdate = streamPtr->dictLimit;
1895
0
    }
1896
0
    return dictSize;
1897
0
}
1898
1899
1900
/* ================================================
1901
 *  LZ4 Optimal parser (levels [LZ4HC_CLEVEL_OPT_MIN - LZ4HC_CLEVEL_MAX])
1902
 * ===============================================*/
1903
typedef struct {
1904
    int price;
1905
    int off;
1906
    int mlen;   /* 1 means literal */
1907
    int litlen;
1908
} LZ4HC_optimal_t;
1909
1910
1.75G
#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
1.77G
#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
13.7M
#define LZ4HC_SEQ_PRICE_FDS    1
1923
4.46M
#define LZ4HC_SEQ_SEARCH_DIST  4
1924
1925
LZ4_FORCE_INLINE int LZ4HC_literalsPrice(int const litlen)
1926
927M
{
1927
927M
    int price = litlen;
1928
927M
    assert(litlen >= 0);
1929
927M
    if (litlen >= (int)RUN_MASK)
1930
9.87M
        price += 1 + ((litlen-(int)RUN_MASK) / 255);
1931
927M
    return price * LZ4HC_PRICE_SCALE;
1932
927M
}
1933
1934
/* requires mlen >= MINMATCH */
1935
LZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen)
1936
830M
{
1937
830M
    int price = 1 + 2 ; /* token + 16-bit offset */
1938
830M
    assert(litlen >= 0);
1939
830M
    assert(mlen >= MINMATCH);
1940
1941
830M
    if (mlen >= (int)(ML_MASK+MINMATCH))
1942
653M
        price += 1 + ((mlen-(int)(ML_MASK+MINMATCH)) / 255);
1943
1944
830M
    return price * LZ4HC_PRICE_SCALE + LZ4HC_literalsPrice(litlen);
1945
830M
}
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
141M
{
1954
141M
    int const reduceFrom = (int)RUN_MASK + 255;
1955
141M
    assert(llen >= 0);
1956
141M
    if (llen < reduceFrom) return llen;
1957
107M
    return reduceFrom + ((llen - (int)RUN_MASK) % 255);
1958
141M
}
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
164M
{
1967
164M
    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
164M
    LZ4HC_match_t md = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, MINMATCH-1, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed);
1971
164M
    assert(md.back == 0);
1972
164M
    if (md.len < MINMATCH) return match0;
1973
23.3M
    if (favorDecSpeed) {
1974
13.7M
        if ((md.len>18) & (md.len<=36)) md.len=18;   /* favor dec.speed (shortcut) */
1975
13.7M
    }
1976
23.3M
    return md;
1977
164M
}
1978
1979
LZ4_FORCE_INLINE void
1980
LZ4HC_setLiteral(LZ4HC_optimal_t* opt, int pos, int litlen, int price)
1981
96.4M
{
1982
96.4M
    opt[pos].mlen = 1;
1983
96.4M
    opt[pos].off = 0;
1984
96.4M
    opt[pos].litlen = litlen;
1985
96.4M
    opt[pos].price = price;
1986
96.4M
    DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)", pos, price, litlen);
1987
96.4M
}
1988
1989
LZ4_FORCE_INLINE void
1990
LZ4HC_setMatch(LZ4HC_optimal_t* opt, int pos, int mlen, int off, int price)
1991
180M
{
1992
180M
    opt[pos].mlen = mlen;
1993
180M
    opt[pos].off = off;
1994
180M
    opt[pos].litlen = 0;
1995
180M
    opt[pos].price = price;
1996
180M
    DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i)", pos, price, mlen);
1997
180M
}
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
23.2M
{
2003
23.2M
    int const ll = opt[pos].litlen;
2004
23.2M
    return (ll <= pos) ? opt[pos - ll].price : 0;
2005
23.2M
}
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
23.2M
{
2015
23.2M
    int const ll = opt[cur].litlen;
2016
23.2M
    int const basePrice = LZ4HC_runStartPrice(opt, cur) + (favorDecSpeed ? LZ4HC_SEQ_PRICE_FDS : 0);
2017
23.2M
    int ml;
2018
23.2M
    assert(cur + match.len < LZ4_OPT_NUM);
2019
23.2M
    assert((U32)favorDecSpeed <= 1);
2020
853M
    for (ml = MINMATCH; ml <= match.len; ml++) {
2021
830M
        int const pos = cur + ml;
2022
830M
        int const price = basePrice + LZ4HC_sequencePrice(ll, ml);
2023
        /* on equal price, favorDecSpeed keeps the existing solution */
2024
830M
        if ( pos > lastPos + TRAILING_LITERALS
2025
671M
          || price <= opt[pos].price - (int)favorDecSpeed) {
2026
180M
            LZ4HC_setMatch(opt, pos, ml, match.off, price);
2027
180M
            if ((ml == match.len) && (lastPos < pos)) lastPos = pos;
2028
180M
    }   }
2029
2030
    /* complete following positions with literals */
2031
23.2M
    {   int addLit;
2032
23.2M
        assert(opt[lastPos].mlen >= MINMATCH);
2033
92.9M
        for (addLit = 1; addLit <= TRAILING_LITERALS; addLit++)
2034
69.7M
            LZ4HC_setLiteral(opt, lastPos + addLit, addLit,
2035
69.7M
                             opt[lastPos].price + LZ4HC_literalsPrice(addLit));
2036
23.2M
    }
2037
23.2M
    return lastPos;
2038
23.2M
}
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.7k
{
2062
16.7k
    const BYTE* ip = (const BYTE*) source;
2063
16.7k
    const BYTE* anchor = ip;
2064
16.7k
    const int inputSize = *srcSizePtr;
2065
16.7k
    const BYTE* const iend = ip + inputSize;
2066
16.7k
    const BYTE* mflimit;      /* set after the size check : would precede a small input */
2067
16.7k
    const BYTE* matchlimit;
2068
16.7k
    BYTE* op = (BYTE*) dst;
2069
    /* fillOutput : keep room for the final run of literals (LZ4 format restriction) */
2070
16.7k
    BYTE* const oend = op + dstCapacity - ((limit == fillOutput) ? LASTLITERALS : 0);
2071
16.7k
    int const sufficientLen = MIN(targetLength, LZ4_OPT_NUM-1);
2072
2073
16.7k
    DEBUGLOG(5, "LZ4HC_compress_optimal(dst=%p, dstCapa=%u)", dst, (unsigned)dstCapacity);
2074
2075
    /* preconditions verifications */
2076
16.7k
    assert(dstCapacity > 0);
2077
16.7k
    assert(dst != NULL);
2078
16.7k
    assert(*srcSizePtr > 0);
2079
16.7k
    assert(source != NULL);
2080
16.7k
    assert(opt != NULL);
2081
16.7k
    assert(nbSearchesSeq >= 1);
2082
2083
16.7k
    *srcSizePtr = 0;
2084
16.7k
    if (inputSize < LZ4_minLength) goto _last_literals;
2085
16.5k
    mflimit = iend - MFLIMIT;
2086
16.5k
    matchlimit = iend - LASTLITERALS;
2087
2088
    /* Main Loop */
2089
141M
    while (ip <= mflimit) {
2090
141M
        int const llen = LZ4HC_pricedLitlen((int)(ip - anchor));
2091
141M
        int cur, lastPos;
2092
141M
        int lastSeqPos;         /* position of the last sequence to encode */
2093
141M
        LZ4HC_match_t lastSeq;
2094
2095
141M
        LZ4HC_match_t const firstMatch = LZ4HC_FindLongestMatch(ctx, ip, matchlimit, nbSearches, dict, favorDecSpeed);
2096
141M
        if (firstMatch.len==0) { ip++; continue; }
2097
2098
6.70M
        if (firstMatch.len > sufficientLen) {
2099
            /* good enough solution : immediate encoding */
2100
45.2k
            lastSeqPos = 0;
2101
45.2k
            lastSeq = firstMatch;
2102
45.2k
            goto encode;
2103
45.2k
        }
2104
2105
        /* set prices for first positions (literals) */
2106
6.66M
        {   int rPos;
2107
33.3M
            for (rPos = 0 ; rPos < MINMATCH ; rPos++)
2108
26.6M
                LZ4HC_setLiteral(opt, rPos, llen + rPos, LZ4HC_literalsPrice(llen + rPos));
2109
6.66M
        }
2110
6.66M
        lastPos = LZ4HC_addMatch(opt, 0, firstMatch, 0, favorDecSpeed);
2111
2112
        /* check further positions */
2113
183M
        for (cur = 1; cur < lastPos; cur++) {
2114
177M
            const BYTE* const curPtr = ip + cur;
2115
177M
            LZ4HC_match_t newMatch;
2116
177M
            int nbS = nbSearches;
2117
2118
177M
            if (curPtr > mflimit) break;
2119
177M
            DEBUGLOG(7, "rPos:%u[%u] vs [%u]%u",
2120
177M
                    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
177M
            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
26.2M
            if (favorDecSpeed && (opt[cur+1].price < opt[cur].price + LZ4HC_PRICE_SCALE)) {
2126
4.46M
                if (lastPos - cur > LZ4HC_SEQ_SEARCH_DIST) continue;
2127
1.56M
                nbS = nbSearchesSeq;
2128
1.56M
            }
2129
2130
23.3M
            newMatch = LZ4HC_FindLongestMatch(ctx, curPtr, matchlimit, nbS, dict, favorDecSpeed);
2131
23.3M
            if (!newMatch.len) continue;
2132
2133
16.5M
            if ( (newMatch.len > sufficientLen)
2134
16.5M
              || (newMatch.len + cur >= LZ4_OPT_NUM) ) {
2135
                /* immediate encoding */
2136
14.0k
                lastSeqPos = cur;
2137
14.0k
                lastSeq = newMatch;
2138
14.0k
                goto encode;
2139
14.0k
            }
2140
2141
16.5M
            lastPos = LZ4HC_addMatch(opt, cur, newMatch, lastPos, favorDecSpeed);
2142
16.5M
        }  /* for (cur = 1; cur < lastPos; cur++) */
2143
2144
6.66M
        assert(lastPos < LZ4_OPT_NUM + TRAILING_LITERALS);
2145
6.64M
        lastSeq.len = opt[lastPos].mlen;
2146
6.64M
        lastSeq.off = opt[lastPos].off;
2147
6.64M
        lastSeqPos = lastPos - lastSeq.len;
2148
2149
6.70M
encode: /* lastSeqPos and lastSeq must be set */
2150
6.70M
        assert(0 <= lastSeqPos && lastSeqPos < LZ4_OPT_NUM);
2151
6.70M
        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
6.70M
        {   int pos = lastSeqPos;
2155
6.70M
            int mlen = lastSeq.len;
2156
6.70M
            int off = lastSeq.off;
2157
11.0M
            while (pos > 0) {
2158
4.33M
                int const prevMlen = opt[pos].mlen;
2159
4.33M
                int const prevOff = opt[pos].off;
2160
4.33M
                opt[pos].mlen = mlen;
2161
4.33M
                opt[pos].off = off;
2162
4.33M
                mlen = prevMlen;
2163
4.33M
                off = prevOff;
2164
4.33M
                assert(0 < mlen && mlen <= pos);
2165
4.33M
                pos -= mlen;
2166
4.33M
            }
2167
            /* first step of the path; note : opt[0] isn't necessarily initialized */
2168
6.70M
            opt[0].mlen = mlen;
2169
6.70M
            opt[0].off = off;
2170
6.70M
        }
2171
2172
        /* encode all recorded sequences in order */
2173
6.70M
        {   int rPos = 0;  /* relative position (to ip) */
2174
17.7M
            while (rPos <= lastSeqPos) {
2175
11.0M
                int const ml = opt[rPos].mlen;
2176
11.0M
                int const offset = opt[rPos].off;
2177
11.0M
                if (ml == 1) { ip++; rPos++; continue; }  /* literal */
2178
8.32M
                rPos += ml;
2179
8.32M
                assert(ml >= MINMATCH);
2180
8.32M
                assert((offset >= 1) && (offset <= LZ4_DISTANCE_MAX));
2181
8.32M
                if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, offset, limit, oend) ) {  /* updates ip, op and anchor */
2182
2.03k
                    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
2.03k
        }   }   }
2186
6.70M
    }  /* while (ip <= mflimit) */
2187
2188
14.7k
_last_literals:
2189
14.7k
    if (LZ4HC_encodeLastLiterals(UPDATABLE(ip, op, anchor), iend, limit, oend))
2190
1.82k
        return 0;  /* not enough space in @dst */
2191
2192
    /* End */
2193
12.8k
    *srcSizePtr = (int) (((const char*)ip) - source);
2194
12.8k
    return (int) ((char*)op-dst);
2195
14.7k
}
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.7k
{
2209
16.7k
    LZ4_STATIC_ASSERT(LZ4_STREAMHC_EXTSIZE == sizeof(LZ4_streamHC_t) + sizeof(LZ4HC_optimal_t) * (LZ4_OPT_NUM + TRAILING_LITERALS));
2210
16.7k
    if (ctx->hasWorkspace) {   /* extended state : the buffer follows it */
2211
16.7k
        LZ4HC_optimal_t* const opt = (LZ4HC_optimal_t*)(void*)((BYTE*)ctx + sizeof(LZ4_streamHC_t));
2212
16.7k
        return LZ4HC_compress_optimal_internal(ctx, source, dst, srcSizePtr, dstCapacity,
2213
16.7k
                    nbSearches, nbSearchesSeq, targetLength, limit, dict, favorDecSpeed, opt);
2214
16.7k
    }
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
}