compress-utils 0.12.2

Unified interface to zstd, brotli, zlib, gzip, bzip2, lz4, xz/lzma and snappy compression, over a single C core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*
 * brotli.c — Brotli vtable for compress-utils.
 *
 * Brotli's wire format never carries the decompressed size, so:
 *   - cu_decompress_size_hint returns CU_ERR_SIZE_UNKNOWN.
 *   - one-shot decompress uses BrotliDecoderDecompressStream into the
 *     caller's buffer and returns SIZE_UNKNOWN if it doesn't fit.
 *
 * Streaming uses BrotliEncoderCompressStream / BrotliDecoderDecompressStream
 * with the standard stashed-tail protocol.
 */

#include "algorithm_registry.h"
#include "compress_utils.h"
#include "utils/single_stream.h"

#include "brotli/decode.h"
#include "brotli/encode.h"

#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

static int brotli_native_level(int user_level) {
    /* Brotli quality 0..11. User 1..10 -> 1..11. */
    if (user_level < 1) return 1;
    if (user_level > 11) return 11;
    return user_level + (user_level == 10 ? 1 : 0);
    /* user 10 -> 11 (best), others map 1:1 to their numeric value. */
}

/* ============================================================================
 * One-shot
 * ============================================================================ */

static size_t brotli_compress_bound(size_t in_len) {
    /* BrotliEncoderMaxCompressedSize gives the right bound. */
    size_t b = BrotliEncoderMaxCompressedSize(in_len);
    if (b == 0) {
        /* Brotli returns 0 for inputs too large; fall back to a generous
         * estimate. */
        return in_len + (in_len >> 2) + 256;
    }
    return b;
}

static cu_status_t brotli_compress(
    const uint8_t* in, size_t in_len,
    uint8_t* out, size_t* out_len,
    int level
) {
    size_t cap = *out_len;
    size_t needed = brotli_compress_bound(in_len);
    if (cap < needed) {
        *out_len = needed;
        return CU_ERR_BUF_TOO_SMALL;
    }
    size_t encoded = cap;
    BROTLI_BOOL ok = BrotliEncoderCompress(
        brotli_native_level(level),
        BROTLI_DEFAULT_WINDOW,
        BROTLI_DEFAULT_MODE,
        in_len, in,
        &encoded, out
    );
    if (!ok) {
        cu_set_last_error("brotli: compression failed");
        return CU_ERR_COMPRESSION;
    }
    *out_len = encoded;
    return CU_OK;
}

static cu_status_t brotli_decompress(
    const uint8_t* in, size_t in_len,
    uint8_t* out, size_t* out_len
) {
    if (in_len == 0) {
        cu_set_last_error("brotli: empty input");
        return CU_ERR_TRUNCATED;
    }
    BrotliDecoderState* st = BrotliDecoderCreateInstance(NULL, NULL, NULL);
    if (!st) { cu_set_last_error("brotli: oom"); return CU_ERR_OOM; }

    const uint8_t* next_in = in;
    size_t avail_in = in_len;
    uint8_t* next_out = out;
    size_t avail_out = *out_len;
    size_t cap_limit = cu_get_max_decompressed_size();

    BrotliDecoderResult r = BrotliDecoderDecompressStream(
        st, &avail_in, &next_in, &avail_out, &next_out, NULL
    );
    cu_status_t ret;
    if (r == BROTLI_DECODER_RESULT_SUCCESS) {
        size_t produced = (size_t)(next_out - out);
        if (cap_limit > 0 && produced > cap_limit) {
            cu_set_last_errorf("brotli: decompressed size %zu exceeds cap %zu", produced, cap_limit);
            ret = CU_ERR_SIZE_LIMIT;
        } else {
            *out_len = produced;
            ret = CU_OK;
        }
    } else if (r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
        cu_set_last_error("brotli: output buffer too small (size not encoded in stream)");
        ret = CU_ERR_SIZE_UNKNOWN;
    } else if (r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT) {
        cu_set_last_error("brotli: truncated input");
        ret = CU_ERR_TRUNCATED;
    } else {
        BrotliDecoderErrorCode e = BrotliDecoderGetErrorCode(st);
        cu_set_last_errorf("brotli: %s", BrotliDecoderErrorString(e));
        ret = CU_ERR_DECOMPRESSION;
    }
    BrotliDecoderDestroyInstance(st);
    return ret;
}

static cu_status_t brotli_decompress_size_hint(
    const uint8_t* in, size_t in_len, size_t* out_size
) {
    (void)in; (void)in_len; (void)out_size;
    return CU_ERR_SIZE_UNKNOWN;
}

/* ============================================================================
 * Streaming compression
 * ============================================================================ */

typedef struct {
    BrotliEncoderState* enc;
    uint8_t* pending;
    size_t   pending_len;
    size_t   pending_cap;
    int      finishing;
    int      finished;
} brotli_cstream_state_t;

static cu_status_t cstream_pending_append(brotli_cstream_state_t* st,
                                          const uint8_t* src, size_t n) {
    if (n == 0) return CU_OK;
    size_t need = st->pending_len + n;
    if (need > st->pending_cap) {
        size_t new_cap = st->pending_cap ? st->pending_cap * 2 : 16 * 1024;
        while (new_cap < need) new_cap *= 2;
        uint8_t* p = realloc(st->pending, new_cap);
        if (!p) { cu_set_last_error("brotli: oom"); return CU_ERR_OOM; }
        st->pending = p;
        st->pending_cap = new_cap;
    }
    memcpy(st->pending + st->pending_len, src, n);
    st->pending_len += n;
    return CU_OK;
}

static cu_status_t brotli_cstream_create(int level, void** out_state) {
    brotli_cstream_state_t* st = calloc(1, sizeof(*st));
    if (!st) { cu_set_last_error("brotli: oom"); return CU_ERR_OOM; }
    st->enc = BrotliEncoderCreateInstance(NULL, NULL, NULL);
    if (!st->enc) {
        free(st);
        cu_set_last_error("brotli: BrotliEncoderCreateInstance failed");
        return CU_ERR_OOM;
    }
    BrotliEncoderSetParameter(st->enc, BROTLI_PARAM_QUALITY, brotli_native_level(level));
    *out_state = st;
    return CU_OK;
}

static cu_status_t cstream_pump(brotli_cstream_state_t* st, BrotliEncoderOperation op,
                                uint8_t* out, size_t* out_len) {
    size_t cap = *out_len;
    size_t written = 0;
    const uint8_t* next_in = st->pending;
    size_t avail_in = st->pending_len;

    for (;;) {
        uint8_t* next_out = out + written;
        size_t avail_out = cap - written;
        BROTLI_BOOL ok = BrotliEncoderCompressStream(
            st->enc, op, &avail_in, &next_in, &avail_out, &next_out, NULL
        );
        if (!ok) {
            cu_set_last_error("brotli: encode error");
            return CU_ERR_COMPRESSION;
        }
        written = cap - avail_out;
        if (op == BROTLI_OPERATION_FINISH && BrotliEncoderIsFinished(st->enc)) {
            st->finished = 1;
            /* Compact pending. */
            size_t consumed = st->pending_len - avail_in;
            if (consumed > 0 && avail_in > 0) {
                memmove(st->pending, st->pending + consumed, avail_in);
            }
            st->pending_len = avail_in;
            *out_len = written;
            return CU_OK;
        }
        if (avail_out == 0 && (avail_in > 0 || BrotliEncoderHasMoreOutput(st->enc))) {
            /* Buffer full and more to do. */
            size_t consumed = st->pending_len - avail_in;
            if (consumed > 0 && avail_in > 0) {
                memmove(st->pending, st->pending + consumed, avail_in);
            }
            st->pending_len = avail_in;
            *out_len = written;
            return CU_ERR_BUF_TOO_SMALL;
        }
        /* Process and flush are done once input is consumed and nothing is
         * held. Finish isn't done until the encoder says so: a call that only
         * completes an earlier flush leaves it unfinished. */
        if (op != BROTLI_OPERATION_FINISH && avail_in == 0 &&
            !BrotliEncoderHasMoreOutput(st->enc)) {
            st->pending_len = 0;
            *out_len = written;
            return CU_OK;
        }
        /* Otherwise loop and write more. */
    }
}

static cu_status_t brotli_cstream_write(
    void* state, const uint8_t* in, size_t in_len,
    uint8_t* out, size_t* out_len
) {
    brotli_cstream_state_t* st = (brotli_cstream_state_t*)state;
    if (st->finishing) {
        cu_set_last_error("brotli: write after finish");
        return CU_ERR_STREAM_STATE;
    }
    cu_status_t s = cstream_pending_append(st, in, in_len);
    if (s != CU_OK) return s;
    return cstream_pump(st, BROTLI_OPERATION_PROCESS, out, out_len);
}

static cu_status_t brotli_cstream_finish(
    void* state, uint8_t* out, size_t* out_len
) {
    brotli_cstream_state_t* st = (brotli_cstream_state_t*)state;
    st->finishing = 1;
    if (st->finished) { *out_len = 0; return CU_OK; }
    return cstream_pump(st, BROTLI_OPERATION_FINISH, out, out_len);
}

/* BROTLI_OPERATION_FLUSH ends the current meta-block, so everything written
 * so far can be decoded; the stream stays open. It is complete once all
 * input is consumed and the encoder holds no output, which is when the pump
 * returns CU_OK. */
static cu_status_t brotli_cstream_flush(
    void* state, uint8_t* out, size_t* out_len
) {
    brotli_cstream_state_t* st = (brotli_cstream_state_t*)state;
    if (st->finishing) {
        cu_set_last_error("brotli: flush after finish");
        return CU_ERR_STREAM_STATE;
    }
    return cstream_pump(st, BROTLI_OPERATION_FLUSH, out, out_len);
}

static void brotli_cstream_destroy(void* state) {
    brotli_cstream_state_t* st = (brotli_cstream_state_t*)state;
    if (!st) return;
    if (st->enc) BrotliEncoderDestroyInstance(st->enc);
    free(st->pending);
    free(st);
}

/* ============================================================================
 * Streaming decompression
 * ============================================================================ */

typedef struct {
    BrotliDecoderState* dec;
    uint8_t* pending;    /* unconsumed input: live bytes are [pending_off, pending_len) */
    size_t   pending_off;
    size_t   pending_len;
    size_t   pending_cap;
    int      finished;
    int      single;     /* CU_DSTREAM_SINGLE: keep input after the end */
    cu_unused_t unused;  /* single: input received after the end */
} brotli_dstream_state_t;

/* Appends to the live pending bytes, first moving them to the front. Pumping
 * only advances pending_off, so each byte is moved at most once per append
 * instead of once per output window. */
static cu_status_t dstream_pending_append(brotli_dstream_state_t* st,
                                          const uint8_t* src, size_t n) {
    if (n == 0) return CU_OK;
    if (st->pending_off > 0) {
        st->pending_len -= st->pending_off;
        memmove(st->pending, st->pending + st->pending_off, st->pending_len);
        st->pending_off = 0;
    }
    size_t need = st->pending_len + n;
    if (need > st->pending_cap) {
        size_t new_cap = st->pending_cap ? st->pending_cap * 2 : 16 * 1024;
        while (new_cap < need) new_cap *= 2;
        uint8_t* p = realloc(st->pending, new_cap);
        if (!p) { cu_set_last_error("brotli: oom"); return CU_ERR_OOM; }
        st->pending = p;
        st->pending_cap = new_cap;
    }
    memcpy(st->pending + st->pending_len, src, n);
    st->pending_len += n;
    return CU_OK;
}

static cu_status_t brotli_dstream_create(void** out_state) {
    brotli_dstream_state_t* st = calloc(1, sizeof(*st));
    if (!st) { cu_set_last_error("brotli: oom"); return CU_ERR_OOM; }
    st->dec = BrotliDecoderCreateInstance(NULL, NULL, NULL);
    if (!st->dec) {
        free(st);
        cu_set_last_error("brotli: BrotliDecoderCreateInstance failed");
        return CU_ERR_OOM;
    }
    *out_state = st;
    return CU_OK;
}

static cu_status_t brotli_dstream_create_single(void** out_state) {
    cu_status_t s = brotli_dstream_create(out_state);
    if (s == CU_OK) ((brotli_dstream_state_t*)*out_state)->single = 1;
    return s;
}

static cu_status_t dstream_pump(brotli_dstream_state_t* st,
                                uint8_t* out, size_t* out_len) {
    size_t cap = *out_len;
    size_t written = 0;
    /* pending is NULL until the first input arrives; NULL + 0 is undefined. */
    const uint8_t* next_in = st->pending ? st->pending + st->pending_off : NULL;
    size_t avail_in = st->pending_len - st->pending_off;

    for (;;) {
        uint8_t* next_out = out + written;
        size_t avail_out = cap - written;
        BrotliDecoderResult r = BrotliDecoderDecompressStream(
            st->dec, &avail_in, &next_in, &avail_out, &next_out, NULL
        );
        written = cap - avail_out;
        if (r == BROTLI_DECODER_RESULT_SUCCESS) {
            st->finished = 1;
            /* Single mode: brotli reports success only once all output is
             * out, and hands back the whole bytes it didn't use. */
            if (st->single) {
                cu_status_t a = cu_unused_append(&st->unused, next_in, avail_in);
                st->pending_off = st->pending_len = 0;
                *out_len = written;
                return a;
            }
            st->pending_off = st->pending_len - avail_in;  /* should be 0 left; if not, trailing data error */
            if (avail_in > 0) {
                cu_set_last_error("brotli: trailing data after end of stream");
                return CU_ERR_DECOMPRESSION;
            }
            *out_len = written;
            return CU_OK;
        }
        if (r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT) {
            /* All pending consumed. Brotli reports this even when the output
             * filled with decoded data still held back; the drain call then
             * collects it. */
            st->pending_off = st->pending_len = 0;
            *out_len = written;
            return BrotliDecoderHasMoreOutput(st->dec) ? CU_ERR_BUF_TOO_SMALL : CU_OK;
        }
        if (r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
            /* Buffer full; the unconsumed tail stays pending. */
            st->pending_off = st->pending_len - avail_in;
            *out_len = written;
            return CU_ERR_BUF_TOO_SMALL;
        }
        /* ERROR */
        BrotliDecoderErrorCode e = BrotliDecoderGetErrorCode(st->dec);
        cu_set_last_errorf("brotli: %s", BrotliDecoderErrorString(e));
        return CU_ERR_DECOMPRESSION;
    }
}

static cu_status_t brotli_dstream_write(
    void* state, const uint8_t* in, size_t in_len,
    uint8_t* out, size_t* out_len
) {
    brotli_dstream_state_t* st = (brotli_dstream_state_t*)state;
    if (st->single && st->finished) {
        *out_len = 0;
        return CU_OK;
    }
    if (st->finished && in_len > 0) {
        cu_set_last_error("brotli: data after end of stream");
        return CU_ERR_DECOMPRESSION;
    }
    cu_status_t s = dstream_pending_append(st, in, in_len);
    if (s != CU_OK) return s;
    return dstream_pump(st, out, out_len);
}

static cu_status_t brotli_dstream_finish(
    void* state, uint8_t* out, size_t* out_len
) {
    brotli_dstream_state_t* st = (brotli_dstream_state_t*)state;
    cu_status_t s = dstream_pump(st, out, out_len);
    if (s != CU_OK) return s;
    if (!st->finished) {
        cu_set_last_error("brotli: truncated stream at finish");
        return CU_ERR_TRUNCATED;
    }
    return CU_OK;
}

static void brotli_dstream_destroy(void* state) {
    brotli_dstream_state_t* st = (brotli_dstream_state_t*)state;
    if (!st) return;
    if (st->dec) BrotliDecoderDestroyInstance(st->dec);
    free(st->pending);
    cu_unused_free(&st->unused);
    free(st);
}

static int brotli_dstream_end(const void* state, const uint8_t** unused, size_t* unused_len) {
    const brotli_dstream_state_t* st = (const brotli_dstream_state_t*)state;
    if (!st->single || !st->finished) return 0;
    cu_unused_get(&st->unused, unused, unused_len);
    return 1;
}

/* ============================================================================
 * Vtable
 * ============================================================================ */

const cu_algorithm_vtbl_t cu_brotli_vtbl = {
    .name                      = "brotli",
    /* Direction split (#7): see zstd.c for the CU_OMIT_* rationale. */
#ifndef CU_OMIT_COMPRESS
    .compress_bound            = brotli_compress_bound,
    .compress                  = brotli_compress,
    .compress_stream_create    = brotli_cstream_create,
    .compress_stream_write     = brotli_cstream_write,
    .compress_stream_finish    = brotli_cstream_finish,
    .compress_stream_flush     = brotli_cstream_flush,
    .compress_stream_destroy   = brotli_cstream_destroy,
#endif
#ifndef CU_OMIT_DECOMPRESS
    .decompress                = brotli_decompress,
    .decompress_size_hint      = brotli_decompress_size_hint,
    .decompress_stream_create  = brotli_dstream_create,
    .decompress_stream_write   = brotli_dstream_write,
    .decompress_stream_finish  = brotli_dstream_finish,
    .decompress_stream_destroy = brotli_dstream_destroy,
    .decompress_stream_create_single = brotli_dstream_create_single,
    .decompress_stream_end     = brotli_dstream_end,
#endif
};