jpayne@68: """Python 'zlib_codec' Codec - zlib compression encoding. jpayne@68: jpayne@68: This codec de/encodes from bytes to bytes. jpayne@68: jpayne@68: Written by Marc-Andre Lemburg (mal@lemburg.com). jpayne@68: """ jpayne@68: jpayne@68: import codecs jpayne@68: import zlib # this codec needs the optional zlib module ! jpayne@68: jpayne@68: ### Codec APIs jpayne@68: jpayne@68: def zlib_encode(input, errors='strict'): jpayne@68: assert errors == 'strict' jpayne@68: return (zlib.compress(input), len(input)) jpayne@68: jpayne@68: def zlib_decode(input, errors='strict'): jpayne@68: assert errors == 'strict' jpayne@68: return (zlib.decompress(input), len(input)) jpayne@68: jpayne@68: class Codec(codecs.Codec): jpayne@68: def encode(self, input, errors='strict'): jpayne@68: return zlib_encode(input, errors) jpayne@68: def decode(self, input, errors='strict'): jpayne@68: return zlib_decode(input, errors) jpayne@68: jpayne@68: class IncrementalEncoder(codecs.IncrementalEncoder): jpayne@68: def __init__(self, errors='strict'): jpayne@68: assert errors == 'strict' jpayne@68: self.errors = errors jpayne@68: self.compressobj = zlib.compressobj() jpayne@68: jpayne@68: def encode(self, input, final=False): jpayne@68: if final: jpayne@68: c = self.compressobj.compress(input) jpayne@68: return c + self.compressobj.flush() jpayne@68: else: jpayne@68: return self.compressobj.compress(input) jpayne@68: jpayne@68: def reset(self): jpayne@68: self.compressobj = zlib.compressobj() jpayne@68: jpayne@68: class IncrementalDecoder(codecs.IncrementalDecoder): jpayne@68: def __init__(self, errors='strict'): jpayne@68: assert errors == 'strict' jpayne@68: self.errors = errors jpayne@68: self.decompressobj = zlib.decompressobj() jpayne@68: jpayne@68: def decode(self, input, final=False): jpayne@68: if final: jpayne@68: c = self.decompressobj.decompress(input) jpayne@68: return c + self.decompressobj.flush() jpayne@68: else: jpayne@68: return self.decompressobj.decompress(input) jpayne@68: jpayne@68: def reset(self): jpayne@68: self.decompressobj = zlib.decompressobj() jpayne@68: jpayne@68: class StreamWriter(Codec, codecs.StreamWriter): jpayne@68: charbuffertype = bytes jpayne@68: jpayne@68: class StreamReader(Codec, codecs.StreamReader): jpayne@68: charbuffertype = bytes jpayne@68: jpayne@68: ### encodings module API jpayne@68: jpayne@68: def getregentry(): jpayne@68: return codecs.CodecInfo( jpayne@68: name='zlib', jpayne@68: encode=zlib_encode, jpayne@68: decode=zlib_decode, jpayne@68: incrementalencoder=IncrementalEncoder, jpayne@68: incrementaldecoder=IncrementalDecoder, jpayne@68: streamreader=StreamReader, jpayne@68: streamwriter=StreamWriter, jpayne@68: _is_text_encoding=False, jpayne@68: )