Skip to content

Commit

Permalink
playing with zlib
Browse files Browse the repository at this point in the history
  • Loading branch information
Wiladams committed Dec 6, 2019
1 parent 4032ac6 commit 2b57be7
Show file tree
Hide file tree
Showing 3 changed files with 128 additions and 0 deletions.
54 changes: 54 additions & 0 deletions experimental/compress.lua
@@ -0,0 +1,54 @@
--[[
Implementation of compress routine from zlib
https://github.com/madler/zlib
]]

--[[
compress2
dest Bytef *
destlen uLongf *
source const Bytef *
sourceLen uLong
level int
]]
local function compress2(dest, destLen, source, sourceLen, level)
local stream
local err
local max = math.hugemin
local left = destLen;
destLen = 0

local err = deflateInit(stream, level)
if err ~= Z_OK then
return err;
end

stream.next_out = dest;
stream.avail_out = 0;
stream.next_in = (z_const Byteef *)source
stream.avail_in = 0;

do
while err == Z_OK

*destLen = stream.total_out;
deflateEnd(stream)

return err == Z_STREAM_END ? Z_OK : err
end

local function compress(dest, destLen, source, sourceLen)
return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION)
end

local function compressBound(sourceLen)
return sourceLen + rshift(sourceLen, 12) + rshift(sourceLen, 14) +
rshift(sourceLen, 25) + 13;
end

return {
compress = compress;
compress2 = compress2;
compressBound = compressBound;
}
65 changes: 65 additions & 0 deletions experimental/deflate.lua
@@ -0,0 +1,65 @@
--[[
zlib implementation of deflate
https://github.com/madler/zlib/blob/master/deflate.h
]]
local ffi = require("ffi")

local zutil = require("zutil")

local ex = {
LENGTH_CODES = 29;
LITERALS = 256;
D_CODES = 30;
BL_CODES = 19;
MAX_BITS = 15;
Buf_size = 16;
INIT_STATE = 42;
GZIP_STATE = 57;
EXTRA_STATE = 69;
NAME_STATE = 73;
COMMENT_STATE = 91;
HCRC_STATE = 103;
BUSY_STATE = 113;
FINISH_STATE = 666; -- stream complete
}


ex.L_CODES = ex.LITERALS+1+ex.LENGTH_CODES;
ex.HEAP_SIZE = 2*ex.L_CODES+1;

ffi.cdef[[
typedef struct ct_data_s {
union {
ush freq; // frequency count for huffman
ush code; // bit string
} fc;

union {
ush dad; // father node in huffman tree
ush len; // length of bit string
} dl;
} ct_data;
]]


ffi.cdef[[
typedef struct static_tree_desc_s static_tree_desc;

typedef struct tree_desc_s {
ct_data *dyn_tree;
int max_code;
const static_tree_desc *stat_desc;
}
]]

ffi.cdef[[
typedef ush Pos;
typedef Pos Posf;
typedef unsigned IPos;
]]




return ex
9 changes: 9 additions & 0 deletions experimental/zutil.lua
@@ -0,0 +1,9 @@
local ffi = require("ffi")

ffi.cdef[[
typedef unsigned char uch;
typedef uch echf;
typedef unsigned short ush;
typedef ush ushf;
typedef unsigned long ulg;
]]

0 comments on commit 2b57be7

Please sign in to comment.