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
|
/* SPDX-License-Identifier: GPL-3.0-or-later */
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <zlib.h>
#include "internal.h"
typedef struct {
compressor_t base;
z_stream strm;
bool compress;
size_t block_size;
} zlib_compressor_t;
static void zlib_destroy(compressor_t *base)
{
zlib_compressor_t *zlib = (zlib_compressor_t *)base;
if (zlib->compress) {
deflateEnd(&zlib->strm);
} else {
inflateEnd(&zlib->strm);
}
free(zlib);
}
static ssize_t zlib_do_block(compressor_t *base, const uint8_t *in,
size_t size, uint8_t *out, size_t outsize)
{
zlib_compressor_t *zlib = (zlib_compressor_t *)base;
size_t written;
int ret;
if (zlib->compress) {
ret = deflateReset(&zlib->strm);
} else {
ret = inflateReset(&zlib->strm);
}
if (ret != Z_OK) {
fputs("resetting zlib stream failed\n", stderr);
return -1;
}
zlib->strm.next_in = (void *)in;
zlib->strm.avail_in = size;
zlib->strm.next_out = out;
zlib->strm.avail_out = outsize;
if (zlib->compress) {
ret = deflate(&zlib->strm, Z_FINISH);
} else {
ret = inflate(&zlib->strm, Z_FINISH);
}
if (ret == Z_STREAM_END) {
written = zlib->strm.total_out;
if (zlib->compress && written >= size)
return 0;
return (ssize_t)written;
}
if (ret != Z_OK) {
fputs("zlib block processing failed\n", stderr);
return -1;
}
return 0;
}
compressor_t *create_zlib_compressor(bool compress, size_t block_size)
{
zlib_compressor_t *zlib = calloc(1, sizeof(*zlib));
compressor_t *base = (compressor_t *)zlib;
int ret;
if (zlib == NULL) {
perror("creating zlib stream");
return NULL;
}
zlib->compress = compress;
zlib->block_size = block_size;
base->do_block = zlib_do_block;
base->destroy = zlib_destroy;
if (compress) {
ret = deflateInit(&zlib->strm, Z_BEST_COMPRESSION);
} else {
ret = inflateInit(&zlib->strm);
}
if (ret != Z_OK) {
fputs("internal error creating zlib stream\n", stderr);
free(zlib);
return NULL;
}
return base;
}
|