Skip to content

Instantly share code, notes, and snippets.

@muxueqz
Created August 20, 2013 08:14
Show Gist options
  • Save muxueqz/6278564 to your computer and use it in GitHub Desktop.
Save muxueqz/6278564 to your computer and use it in GitHub Desktop.
#!/usr/bin/env luajit
-- Copyright (C) 2012 by Yichun Zhang (agentzh)
local ffi = require "ffi"
local assert = assert
module(...)
_VERSION = '0.01'
ffi.cdef[[
unsigned long compressBound(unsigned long sourceLen);
int compress2(uint8_t *dest, unsigned long *destLen,
const uint8_t *source, unsigned long sourceLen, int level);
int uncompress(uint8_t *dest, unsigned long *destLen,
const uint8_t *source, unsigned long sourceLen);
]]
local zlib = ffi.load(ffi.os == "Windows" and "zlib1" or "z")
function compress(txt)
local n = zlib.compressBound(#txt)
local buf = ffi.new("uint8_t[?]", n)
local buflen = ffi.new("unsigned long[1]", n)
local res = zlib.compress2(buf, buflen, txt, #txt, 9)
assert(res == 0)
return ffi.string(buf, buflen[0])
end
function uncompress(comp, n)
local buf = ffi.new("uint8_t[?]", n)
local buflen = ffi.new("unsigned long[1]", n)
local res = zlib.uncompress(buf, buflen, comp, #comp)
-- if res == 0 then
-- return ffi.string(buf, buflen[0])
-- end
assert(res == 0)
return ffi.string(buf, buflen[0])
end
---- Simple test code.
--local txt = string.rep("abcd", 1000)
--print("Uncompressed size: ", #txt)
--local c = compress(txt)
--print("Compressed size: ", #c)
--local txt2 = uncompress(c, #txt)
--assert(txt2 == txt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment