public
Last active

c_zlib.py: zlib for Python using ctypes

  • Download Gist
c_zlib.py
Python
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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
#!/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()

_zlib = C.cdll.LoadLibrary(util.find_library('libz'))

has to be replaced with

_zlib = C.cdll.LoadLibrary(util.find_library('z'))

Interesting; what platform are you on? 'libz' worked on mine (Darwin and Linux).

Cheers,

On 10/02/2012, at 5:59 PM, Ivan Boldyrev wrote:

_zlib = C.cdll.LoadLibrary(util.find_library('libz'))

has to be replaced with

_zlib = C.cdll.LoadLibrary(util.find_library('z'))


Reply to this email directly or view it on GitHub:
https://gist.github.com/242459

Mark Nottingham http://www.mnot.net/

Gentoo Linux (64bit). But I think it may be python-depended: I used python 2.7. Documentation says that find_library' argument is "the library name without any prefix like lib, suffix like .so, .dylib or version number (this is the form used for the posix linker option -l)."

Confirmed. Weird; I guess it's somehow changed since I wrote this a couple of years ago (IIRC it worked on both Linux and OSX). Anyway, try it again; there's an assert in there to make sure it loads now.

Thanks!

Works now, thank you.

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.