Skip to content

Instantly share code, notes, and snippets.

@mnot
Created November 25, 2009 04:03
Show Gist options
  • Save mnot/242459 to your computer and use it in GitHub Desktop.
Save mnot/242459 to your computer and use it in GitHub Desktop.
c_zlib.py: zlib for Python using ctypes
#!/usr/bin/env python
"""
c_zlib - zlib for Python using ctypes.
This is a quick and nasty implementation of zlib using Python ctypes, in order to expose the ability
to set a compression dictionary (which isn't available in the zlib module).
"""
__license__ = """
Copyright (c) 2009-2012 Mark Nottingham <mnot@pobox.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import ctypes as C
from ctypes import util
_zlib = C.cdll.LoadLibrary(util.find_library('z'))
assert _zlib._name, "Can't find libz"
class _z_stream(C.Structure):
_fields_ = [
("next_in", C.POINTER(C.c_ubyte)),
("avail_in", C.c_uint),
("total_in", C.c_ulong),
("next_out", C.POINTER(C.c_ubyte)),
("avail_out", C.c_uint),
("total_out", C.c_ulong),
("msg", C.c_char_p),
("state", C.c_void_p),
("zalloc", C.c_void_p),
("zfree", C.c_void_p),
("opaque", C.c_void_p),
("data_type", C.c_int),
("adler", C.c_ulong),
("reserved", C.c_ulong),
]
# TODO: get zlib version with ctypes
ZLIB_VERSION = C.c_char_p("1.2.3")
Z_NULL = 0x00
Z_OK = 0x00
Z_STREAM_END = 0x01
Z_NEED_DICT = 0x02
Z_NO_FLUSH = 0x00
Z_FINISH = 0x04
CHUNK = 1024 * 32
def compress(input, level=6, dictionary=None):
out = []
st = _z_stream()
st.avail_in = len(input)
st.next_in = C.cast(C.c_char_p(input), C.POINTER(C.c_ubyte))
st.avail_out = Z_NULL
st.next_out = C.cast(Z_NULL, C.POINTER(C.c_ubyte))
err = _zlib.deflateInit_(C.byref(st), level, ZLIB_VERSION, C.sizeof(st))
assert err == Z_OK, err
if dictionary:
err = _zlib.deflateSetDictionary(C.byref(st), C.cast(C.c_char_p(dictionary), C.POINTER(C.c_ubyte)), len(dictionary))
assert err == Z_OK, err
while True:
st.avail_out = CHUNK
outbuf = C.create_string_buffer(CHUNK)
st.next_out = C.cast(outbuf, C.POINTER(C.c_ubyte))
err = _zlib.deflate(C.byref(st), Z_FINISH)
out.append(outbuf[:CHUNK-st.avail_out])
if err == Z_STREAM_END: break
elif err == Z_OK: pass
else:
raise AssertionError, err
err = _zlib.deflateEnd(C.byref(st))
assert err == Z_OK, err
return "".join(out)
def decompress(input, dictionary=None):
out = []
st = _z_stream()
st.avail_in = len(input)
st.next_in = C.cast(C.c_char_p(input), C.POINTER(C.c_ubyte))
st.avail_out = Z_NULL
st.next_out = C.cast(Z_NULL, C.POINTER(C.c_ubyte))
err = _zlib.inflateInit2_(C.byref(st), 15, ZLIB_VERSION, C.sizeof(st))
assert err == Z_OK, err
while True:
st.avail_out = CHUNK
outbuf = C.create_string_buffer(CHUNK)
st.next_out = C.cast(outbuf, C.POINTER(C.c_ubyte))
err = _zlib.inflate(C.byref(st), Z_NO_FLUSH)
if err == Z_NEED_DICT:
assert dictionary, "no dictionary provided"
err = _zlib.inflateSetDictionary(C.byref(st), C.cast(C.c_char_p(dictionary), C.POINTER(C.c_ubyte)), len(dictionary))
assert err == Z_OK, err
elif err in [Z_OK, Z_STREAM_END]:
out.append(outbuf[:CHUNK-st.avail_out])
else:
raise AssertionError, err
if err == Z_STREAM_END:
break
err = _zlib.inflateEnd(C.byref(st))
assert err == Z_OK, err
return "".join(out)
def _test():
import zlib, time, sys
input = open(sys.argv[1]).read()
# compression tests
start = time.time()
ct_archive = compress(input, 6)
print "ctypes zlib compress: %2.2f seconds" % (time.time() - start)
start = time.time()
zl_archive = zlib.compress(input, 6)
print "zlib module compress: %2.2f seconds" % (time.time() - start)
assert ct_archive == zl_archive, "%s != %s" % (len(ct_archive), len(zl_archive))
# decompressions tests
start = time.time()
ct_orig = decompress(ct_archive)
print "ctypes zlib decompress: %2.2f seconds" % (time.time() - start)
start = time.time()
zl_orig = zlib.decompress(ct_archive)
print "zlib module decompress: %2.2f seconds" % (time.time() - start)
assert ct_orig == zl_orig, "%s != %s" % (len(ct_orig), len(zl_orig))
# dictionary compression
dictionary = "andofthemyhisherforanother"
di_archive = compress(input, 6, dictionary)
di_orig = decompress(di_archive, dictionary)
assert input == di_orig, "%s != %s" % (len(orig), len(di_orig))
print "done."
if __name__ == '__main__':
_test()
@lrowe
Copy link

lrowe commented Mar 14, 2012

Note that Python's zlib default compression level is zlib.Z_DEFAULT_COMPRESSION which on my Mac is -1 rather than the 6 documented on docs.python.org and can give radically different compression levels.

@mnot
Copy link
Author

mnot commented Mar 21, 2012

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment