summaryrefslogtreecommitdiffhomepage
path: root/src/nxt_zlib.c
blob: 2dcc53a83d400d2bd31f06df287bd76760f8811d (plain) (blame)
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
/*
 *
 */

#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>

#include <zlib.h>

#include <nxt_http_compression.h>

static void nxt_zlib_gzip_init(nxt_http_comp_compressor_ctx_t *ctx)
{
    int ret;
    z_stream *z = &ctx->zlib_ctx;

    *z = (z_stream){ };

    ret = deflateInit2(z, ctx->level, Z_DEFLATED, 9 + 16, 8,
                       Z_DEFAULT_STRATEGY);
}

static void nxt_zlib_deflate_init(nxt_http_comp_compressor_ctx_t *ctx)
{
    int ret;
    z_stream *z = &ctx->zlib_ctx;

    *z = (z_stream){ };

    ret = deflateInit2(z, ctx->level, Z_DEFLATED, 9, 8, Z_DEFAULT_STRATEGY);
}

static size_t nxt_zlib_compressed_size(const nxt_http_comp_compressor_ctx_t *ctx,
                                       size_t in_len)
{
    z_stream *z = &ctx->zlib_ctx;

    return deflateBound(z, in_len);
}

static ssize_t nxt_zlib_deflate(nxt_http_comp_compressor_ctx_t *ctx,
                                const uint8_t *in_buf, size_t in_len,
                                uint8_t *out_buf, size_t out_len, bool last)
{
    int ret;
    z_stream *z = &ctx->zlib_ctx;
    size_t compressed_bytes = z->total_out;

    z->avail_in = in_len;
    z->next_in = (z_const Bytef *)in_buf;

    z->avail_out = out_len;
    z->next_out = out_buf;

    ret = deflate(z, last ? Z_FINISH : Z_SYNC_FLUSH);
    if (ret == Z_STREAM_ERROR || ret == Z_BUF_ERROR) {
        deflateEnd(z);
        printf("%s: ret = %d\n", __func__, ret);
        return -1;
    }

    if (last)
        deflateEnd(z);

    return z->total_out - compressed_bytes;
}

const nxt_http_comp_operations_t  nxt_comp_deflate_ops = {
    .init               = nxt_zlib_deflate_init,
    .compressed_size    = nxt_zlib_compressed_size,
    .deflate            = nxt_zlib_deflate,
};

const nxt_http_comp_operations_t  nxt_comp_gzip_ops = {
    .init               = nxt_zlib_gzip_init,
    .compressed_size    = nxt_zlib_compressed_size,
    .deflate            = nxt_zlib_deflate,
};