compress-utils 0.12.1

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
/*
 * bz2.c — bzip2 vtable for compress-utils.
 *
 * bzip2's wire format does not carry the decompressed size:
 *   - cu_decompress_size_hint returns CU_ERR_SIZE_UNKNOWN.
 *   - one-shot decompress uses BZ2_bzBuffToBuffDecompress into the
 *     caller's buffer and returns SIZE_UNKNOWN if BZ_OUTBUFF_FULL.
 *
 * Streaming uses BZ2_bzCompress / BZ2_bzDecompress with the stashed-tail
 * protocol.
 */

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

#include <bzlib.h>

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

/* bzip2: user 1..10 → bz2 native 1..9 (clamp). */
static int bz2_native_level(int user_level) {
    return cu_clamp_level(user_level, 1, 9);
}

static const char* bz2_errstr(int code) {
    switch (code) {
        case BZ_OK:                return "ok";
        case BZ_RUN_OK:            return "run ok";
        case BZ_FLUSH_OK:          return "flush ok";
        case BZ_FINISH_OK:         return "finish ok";
        case BZ_STREAM_END:        return "stream end";
        case BZ_SEQUENCE_ERROR:    return "sequence error";
        case BZ_PARAM_ERROR:       return "param error";
        case BZ_MEM_ERROR:         return "out of memory";
        case BZ_DATA_ERROR:        return "corrupted data";
        case BZ_DATA_ERROR_MAGIC:  return "bad magic";
        case BZ_IO_ERROR:          return "io error";
        case BZ_UNEXPECTED_EOF:    return "unexpected eof";
        case BZ_OUTBUFF_FULL:      return "output buffer full";
        case BZ_CONFIG_ERROR:      return "config error";
        default:                   return "unknown";
    }
}

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

static size_t bz2_compress_bound(size_t in_len) {
    /* bzip2 docs: worst case is input + 1% + 600 bytes. */
    return in_len + (in_len / 100) + 600;
}

static cu_status_t bz2_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 = bz2_compress_bound(in_len);
    if (cap < needed) {
        *out_len = needed;
        return CU_ERR_BUF_TOO_SMALL;
    }
    unsigned int dest_len = (unsigned int)cap;
    int r = BZ2_bzBuffToBuffCompress(
        (char*)out, &dest_len,
        (char*)(uintptr_t)in, (unsigned int)in_len,
        bz2_native_level(level),
        0,  /* verbosity */
        0   /* workFactor (default 30) */
    );
    if (r != BZ_OK) {
        cu_set_last_errorf("bz2: %s", bz2_errstr(r));
        return r == BZ_MEM_ERROR ? CU_ERR_OOM : CU_ERR_COMPRESSION;
    }
    *out_len = dest_len;
    return CU_OK;
}

static cu_status_t bz2_decompress(
    const uint8_t* in, size_t in_len,
    uint8_t* out, size_t* out_len
) {
    if (in_len == 0) {
        cu_set_last_error("bz2: empty input");
        return CU_ERR_TRUNCATED;
    }
    unsigned int dest_len = (unsigned int)*out_len;
    size_t cap_limit = cu_get_max_decompressed_size();
    int r = BZ2_bzBuffToBuffDecompress(
        (char*)out, &dest_len,
        (char*)(uintptr_t)in, (unsigned int)in_len,
        0, 0
    );
    if (r == BZ_OK) {
        if (cap_limit > 0 && dest_len > cap_limit) {
            cu_set_last_errorf("bz2: decompressed size %u exceeds cap %zu", dest_len, cap_limit);
            return CU_ERR_SIZE_LIMIT;
        }
        *out_len = dest_len;
        return CU_OK;
    }
    if (r == BZ_OUTBUFF_FULL) {
        cu_set_last_error("bz2: output buffer too small (size not encoded in stream)");
        return CU_ERR_SIZE_UNKNOWN;
    }
    if (r == BZ_UNEXPECTED_EOF) {
        cu_set_last_error("bz2: truncated input");
        return CU_ERR_TRUNCATED;
    }
    cu_set_last_errorf("bz2: %s", bz2_errstr(r));
    return CU_ERR_DECOMPRESSION;
}

static cu_status_t bz2_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 {
    bz_stream strm;
    int       strm_inited;
    uint8_t*  pending;
    size_t    pending_len;
    size_t    pending_cap;
    int      finishing;
    int      stream_end;
} bz2_cstream_state_t;

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

static cu_status_t bz2_cstream_create(int level, void** out_state) {
    bz2_cstream_state_t* st = calloc(1, sizeof(*st));
    if (!st) { cu_set_last_error("bz2: oom"); return CU_ERR_OOM; }
    int r = BZ2_bzCompressInit(&st->strm, bz2_native_level(level), 0, 0);
    if (r != BZ_OK) {
        cu_set_last_errorf("bz2: %s", bz2_errstr(r));
        free(st);
        return r == BZ_MEM_ERROR ? CU_ERR_OOM : CU_ERR_COMPRESSION;
    }
    st->strm_inited = 1;
    *out_state = st;
    return CU_OK;
}

static cu_status_t cstream_pump(bz2_cstream_state_t* st, int action,
                                uint8_t* out, size_t* out_len) {
    size_t cap = *out_len;
    size_t written = 0;

    st->strm.next_in  = (char*)st->pending;
    st->strm.avail_in = (unsigned int)st->pending_len;
    for (;;) {
        st->strm.next_out  = (char*)(out + written);
        st->strm.avail_out = (unsigned int)(cap - written);
        unsigned int avail_out_before = st->strm.avail_out;
        int r = BZ2_bzCompress(&st->strm, action);
        size_t produced = (size_t)(avail_out_before - st->strm.avail_out);
        written += produced;
        if (r == BZ_STREAM_END) {
            st->stream_end = 1;
            size_t consumed = st->pending_len - st->strm.avail_in;
            if (consumed > 0 && st->strm.avail_in > 0) {
                memmove(st->pending, st->pending + consumed, st->strm.avail_in);
            }
            st->pending_len = st->strm.avail_in;
            *out_len = written;
            return CU_OK;
        }
        /* While running, a call that makes no progress (a drain call with
         * nothing held back) reports BZ_PARAM_ERROR: nothing more to emit. */
        if (r == BZ_PARAM_ERROR && action == BZ_RUN && st->strm.avail_in == 0 && produced == 0) {
            st->pending_len = 0;
            *out_len = written;
            return CU_OK;
        }
        if (r == BZ_RUN_OK || r == BZ_FINISH_OK || r == BZ_FLUSH_OK) {
            /* A full output returns BUF_TOO_SMALL even when all input was
             * consumed, since bzip2 may still hold output; the drain call then
             * runs it again. */
            if (st->strm.avail_out == 0) {
                size_t consumed = st->pending_len - st->strm.avail_in;
                if (consumed > 0 && st->strm.avail_in > 0) {
                    memmove(st->pending, st->pending + consumed, st->strm.avail_in);
                }
                st->pending_len = st->strm.avail_in;
                *out_len = written;
                return CU_ERR_BUF_TOO_SMALL;
            }
            if (action == BZ_RUN && st->strm.avail_in == 0) {
                st->pending_len = 0;
                *out_len = written;
                return CU_OK;
            }
            /* otherwise loop and produce more */
            continue;
        }
        cu_set_last_errorf("bz2: %s", bz2_errstr(r));
        return CU_ERR_COMPRESSION;
    }
}

static cu_status_t bz2_cstream_write(
    void* state, const uint8_t* in, size_t in_len,
    uint8_t* out, size_t* out_len
) {
    bz2_cstream_state_t* st = (bz2_cstream_state_t*)state;
    if (st->finishing) {
        cu_set_last_error("bz2: write after finish");
        return CU_ERR_STREAM_STATE;
    }
    cu_status_t s = pending_append(&st->pending, &st->pending_len, &st->pending_cap, in, in_len);
    if (s != CU_OK) return s;
    return cstream_pump(st, BZ_RUN, out, out_len);
}

static cu_status_t bz2_cstream_finish(
    void* state, uint8_t* out, size_t* out_len
) {
    bz2_cstream_state_t* st = (bz2_cstream_state_t*)state;
    st->finishing = 1;
    if (st->stream_end) { *out_len = 0; return CU_OK; }
    return cstream_pump(st, BZ_FINISH, out, out_len);
}

static void bz2_cstream_destroy(void* state) {
    bz2_cstream_state_t* st = (bz2_cstream_state_t*)state;
    if (!st) return;
    if (st->strm_inited) BZ2_bzCompressEnd(&st->strm);
    free(st->pending);
    free(st);
}

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

typedef struct {
    bz_stream strm;
    int       strm_inited;
    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       stream_end;
    int       single;      /* CU_DSTREAM_SINGLE: keep input after the end */
    cu_unused_t unused;    /* single: input received after the end */
} bz2_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(bz2_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;
    }
    return pending_append(&st->pending, &st->pending_len, &st->pending_cap, src, n);
}

static cu_status_t bz2_dstream_create(void** out_state) {
    bz2_dstream_state_t* st = calloc(1, sizeof(*st));
    if (!st) { cu_set_last_error("bz2: oom"); return CU_ERR_OOM; }
    int r = BZ2_bzDecompressInit(&st->strm, 0, 0);
    if (r != BZ_OK) {
        cu_set_last_errorf("bz2: %s", bz2_errstr(r));
        free(st);
        return r == BZ_MEM_ERROR ? CU_ERR_OOM : CU_ERR_DECOMPRESSION;
    }
    st->strm_inited = 1;
    *out_state = st;
    return CU_OK;
}

static cu_status_t bz2_dstream_create_single(void** out_state) {
    cu_status_t s = bz2_dstream_create(out_state);
    if (s == CU_OK) ((bz2_dstream_state_t*)*out_state)->single = 1;
    return s;
}

/* Single mode: once the stream has ended (bzip2 reports that only after all
 * output is out), whatever input is left pending came after it. */
static cu_status_t bz2_keep_unused(bz2_dstream_state_t* st, cu_status_t s) {
    if (s != CU_OK || !st->single || !st->stream_end) return s;
    if (st->pending_off == st->pending_len) return s;
    s = cu_unused_append(&st->unused, st->pending + st->pending_off,
                         st->pending_len - st->pending_off);
    st->pending_off = st->pending_len = 0;
    return s;
}

static cu_status_t dstream_pump(bz2_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. */
    st->strm.next_in  = st->pending ? (char*)(st->pending + st->pending_off) : NULL;
    st->strm.avail_in = (unsigned int)(st->pending_len - st->pending_off);

    for (;;) {
        st->strm.next_out  = (char*)(out + written);
        st->strm.avail_out = (unsigned int)(cap - written);
        unsigned int avail_out_before = st->strm.avail_out;
        int r = BZ2_bzDecompress(&st->strm);
        size_t produced = (size_t)(avail_out_before - st->strm.avail_out);
        written += produced;

        if (r == BZ_STREAM_END) {
            st->stream_end = 1;
            st->pending_off = st->pending_len - st->strm.avail_in;
            *out_len = written;
            return CU_OK;
        }
        if (r == BZ_OK) {
            /* A full output returns BUF_TOO_SMALL even when all input was
             * consumed: bzip2 decodes a whole block (up to 900 KB) at once and
             * may still hold most of it. The drain call then runs it again. */
            if (st->strm.avail_out == 0) {
                st->pending_off = st->pending_len - st->strm.avail_in;
                *out_len = written;
                return CU_ERR_BUF_TOO_SMALL;
            }
            if (st->strm.avail_in == 0) {
                /* All current input consumed, not yet at stream end. */
                st->pending_off = st->pending_len = 0;
                *out_len = written;
                return CU_OK;
            }
            continue;
        }
        cu_set_last_errorf("bz2: %s", bz2_errstr(r));
        return CU_ERR_DECOMPRESSION;
    }
}

static cu_status_t bz2_dstream_write(
    void* state, const uint8_t* in, size_t in_len,
    uint8_t* out, size_t* out_len
) {
    bz2_dstream_state_t* st = (bz2_dstream_state_t*)state;
    if (st->stream_end) {
        if (in_len > 0) {
            cu_set_last_error("bz2: data after end of stream");
            return CU_ERR_DECOMPRESSION;
        }
        /* Nothing left; BZ2_bzDecompress would return BZ_SEQUENCE_ERROR. */
        *out_len = 0;
        return CU_OK;
    }
    cu_status_t s = dstream_pending_append(st, in, in_len);
    if (s != CU_OK) return s;
    return bz2_keep_unused(st, dstream_pump(st, out, out_len));
}

static cu_status_t bz2_dstream_finish(
    void* state, uint8_t* out, size_t* out_len
) {
    bz2_dstream_state_t* st = (bz2_dstream_state_t*)state;
    /* If the stream is already complete and there's no pending input,
     * skip the pump (BZ2_bzDecompress would return BZ_SEQUENCE_ERROR). */
    if (st->stream_end && st->pending_off == st->pending_len) {
        *out_len = 0;
        return CU_OK;
    }
    cu_status_t s = bz2_keep_unused(st, dstream_pump(st, out, out_len));
    if (s != CU_OK) return s;
    if (!st->stream_end) {
        cu_set_last_error("bz2: truncated stream at finish");
        return CU_ERR_TRUNCATED;
    }
    return CU_OK;
}

static void bz2_dstream_destroy(void* state) {
    bz2_dstream_state_t* st = (bz2_dstream_state_t*)state;
    if (!st) return;
    if (st->strm_inited) BZ2_bzDecompressEnd(&st->strm);
    free(st->pending);
    cu_unused_free(&st->unused);
    free(st);
}

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

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

const cu_algorithm_vtbl_t cu_bz2_vtbl = {
    .name                      = "bz2",
    /* Direction split (#7): see zstd.c for the CU_OMIT_* rationale. */
#ifndef CU_OMIT_COMPRESS
    .compress_bound            = bz2_compress_bound,
    .compress                  = bz2_compress,
    .compress_stream_create    = bz2_cstream_create,
    .compress_stream_write     = bz2_cstream_write,
    .compress_stream_finish    = bz2_cstream_finish,
    /* No flush: libbzip2 byte-aligns its bit buffer only at end of stream,
     * so a BZ_FLUSH'd block can't be decoded until more data follows. */
    .compress_stream_destroy   = bz2_cstream_destroy,
#endif
#ifndef CU_OMIT_DECOMPRESS
    .decompress                = bz2_decompress,
    .decompress_size_hint      = bz2_decompress_size_hint,
    .decompress_stream_create  = bz2_dstream_create,
    .decompress_stream_write   = bz2_dstream_write,
    .decompress_stream_finish  = bz2_dstream_finish,
    .decompress_stream_destroy = bz2_dstream_destroy,
    .decompress_stream_create_single = bz2_dstream_create_single,
    .decompress_stream_end     = bz2_dstream_end,
#endif
};