summaryrefslogtreecommitdiffstats
path: root/server/resty/session/compressors/zlib.lua
blob: 1d23be027196c24d4f94ba6d86e1f336fc0f2485 (plain)
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
local zlib   = require "ffi-zlib"
local sio    = require "pl.stringio"

local concat = table.concat

local function gzip(func, input)
    local stream = sio.open(input)
    local output = {}
    local n = 0

    local ok, err = func(function(size)
        return stream:read(size)
    end, function(data)
        n = n + 1
        output[n] = data
    end, 8192)

    if not ok then
        return nil, err
    end

    if n == 0 then
        return ""
    end

    return concat(output, nil, 1, n)
end

local compressor = {}

function compressor.new()
    return compressor
end

function compressor.compress(_, data)
    return gzip(zlib.deflateGzip, data)
end

function compressor.decompress(_, data)
    return gzip(zlib.inflateGzip, data)
end

return compressor