blob: 2694f15511608c24c000021aaf5766897c30914f [file] [log] [blame]
Marc-André Lemburg2d920412001-05-15 12:00:02 +00001""" Python 'zlib_codec' Codec - zlib compression encoding
2
3 Unlike most of the other codecs which target Unicode, this codec
4 will return Python string objects for both encode and decode.
5
6 Written by Marc-Andre Lemburg (mal@lemburg.com).
7
8"""
9import codecs
10import zlib # this codec needs the optional zlib module !
11
12### Codec APIs
13
14def zlib_encode(input,errors='strict'):
15
16 """ Encodes the object input and returns a tuple (output
17 object, length consumed).
18
19 errors defines the error handling to apply. It defaults to
20 'strict' handling which is the only currently supported
21 error handling for this codec.
22
23 """
24 assert errors == 'strict'
25 output = zlib.compress(input)
26 return (output, len(input))
27
28def zlib_decode(input,errors='strict'):
29
30 """ Decodes the object input and returns a tuple (output
31 object, length consumed).
32
33 input must be an object which provides the bf_getreadbuf
34 buffer slot. Python strings, buffer objects and memory
35 mapped files are examples of objects providing this slot.
36
37 errors defines the error handling to apply. It defaults to
38 'strict' handling which is the only currently supported
39 error handling for this codec.
40
41 """
42 assert errors == 'strict'
43 output = zlib.decompress(input)
44 return (output, len(input))
45
46class Codec(codecs.Codec):
47
Marc-André Lemburg26e3b682001-09-20 10:33:38 +000048 def encode(self, input, errors='strict'):
49 return zlib_encode(input, errors)
50 def decode(self, input, errors='strict'):
51 return zlib_decode(input, errors)
Marc-André Lemburg2d920412001-05-15 12:00:02 +000052
Walter Dörwaldabb02e52006-03-15 11:35:15 +000053class IncrementalEncoder(codecs.IncrementalEncoder):
54 def encode(self, input, final=False):
55 assert self.errors == 'strict'
56 return zlib.compress(input)
57
58class IncrementalDecoder(codecs.IncrementalDecoder):
59 def decode(self, input, final=False):
60 assert self.errors == 'strict'
61 return zlib.decompress(input)
62
Marc-André Lemburg2d920412001-05-15 12:00:02 +000063class StreamWriter(Codec,codecs.StreamWriter):
64 pass
Tim Peters469cdad2002-08-08 20:19:19 +000065
Marc-André Lemburg2d920412001-05-15 12:00:02 +000066class StreamReader(Codec,codecs.StreamReader):
67 pass
68
69### encodings module API
70
71def getregentry():
Walter Dörwaldabb02e52006-03-15 11:35:15 +000072 return codecs.CodecInfo(
73 name='zlib',
74 encode=zlib_encode,
75 decode=zlib_decode,
76 incrementalencoder=IncrementalEncoder,
77 incrementaldecoder=IncrementalDecoder,
78 streamreader=StreamReader,
79 streamwriter=StreamWriter,
80 )