Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 1 | """Python 'zlib_codec' Codec - zlib compression encoding. |
| 2 | |
| 3 | This codec de/encodes from bytes to bytes and is therefore usable with |
| 4 | bytes.transform() and bytes.untransform(). |
| 5 | |
| 6 | Written by Marc-Andre Lemburg (mal@lemburg.com). |
| 7 | """ |
| 8 | |
| 9 | import codecs |
| 10 | import zlib # this codec needs the optional zlib module ! |
| 11 | |
| 12 | ### Codec APIs |
| 13 | |
| 14 | def zlib_encode(input, errors='strict'): |
| 15 | assert errors == 'strict' |
| 16 | return (zlib.compress(input), len(input)) |
| 17 | |
| 18 | def zlib_decode(input, errors='strict'): |
| 19 | assert errors == 'strict' |
| 20 | return (zlib.decompress(input), len(input)) |
| 21 | |
| 22 | class Codec(codecs.Codec): |
| 23 | def encode(self, input, errors='strict'): |
| 24 | return zlib_encode(input, errors) |
| 25 | def decode(self, input, errors='strict'): |
| 26 | return zlib_decode(input, errors) |
| 27 | |
| 28 | class IncrementalEncoder(codecs.IncrementalEncoder): |
| 29 | def __init__(self, errors='strict'): |
| 30 | assert errors == 'strict' |
| 31 | self.errors = errors |
| 32 | self.compressobj = zlib.compressobj() |
| 33 | |
| 34 | def encode(self, input, final=False): |
| 35 | if final: |
| 36 | c = self.compressobj.compress(input) |
| 37 | return c + self.compressobj.flush() |
| 38 | else: |
| 39 | return self.compressobj.compress(input) |
| 40 | |
| 41 | def reset(self): |
| 42 | self.compressobj = zlib.compressobj() |
| 43 | |
| 44 | class IncrementalDecoder(codecs.IncrementalDecoder): |
| 45 | def __init__(self, errors='strict'): |
| 46 | assert errors == 'strict' |
| 47 | self.errors = errors |
| 48 | self.decompressobj = zlib.decompressobj() |
| 49 | |
| 50 | def decode(self, input, final=False): |
| 51 | if final: |
| 52 | c = self.decompressobj.decompress(input) |
| 53 | return c + self.decompressobj.flush() |
| 54 | else: |
| 55 | return self.decompressobj.decompress(input) |
| 56 | |
| 57 | def reset(self): |
| 58 | self.decompressobj = zlib.decompressobj() |
| 59 | |
| 60 | class StreamWriter(Codec, codecs.StreamWriter): |
| 61 | charbuffertype = bytes |
| 62 | |
| 63 | class StreamReader(Codec, codecs.StreamReader): |
| 64 | charbuffertype = bytes |
| 65 | |
| 66 | ### encodings module API |
| 67 | |
| 68 | def getregentry(): |
| 69 | return codecs.CodecInfo( |
| 70 | name='zlib', |
| 71 | encode=zlib_encode, |
| 72 | decode=zlib_decode, |
| 73 | incrementalencoder=IncrementalEncoder, |
| 74 | incrementaldecoder=IncrementalDecoder, |
| 75 | streamreader=StreamReader, |
| 76 | streamwriter=StreamWriter, |
| 77 | ) |