--- /dev/null
+""" Python 'bz2_codec' Codec - bz2 compression encoding\r
+\r
+ Unlike most of the other codecs which target Unicode, this codec\r
+ will return Python string objects for both encode and decode.\r
+\r
+ Adapted by Raymond Hettinger from zlib_codec.py which was written\r
+ by Marc-Andre Lemburg (mal@lemburg.com).\r
+\r
+"""\r
+import codecs\r
+import bz2 # this codec needs the optional bz2 module !\r
+\r
+### Codec APIs\r
+\r
+def bz2_encode(input,errors='strict'):\r
+\r
+ """ Encodes the object input and returns a tuple (output\r
+ object, length consumed).\r
+\r
+ errors defines the error handling to apply. It defaults to\r
+ 'strict' handling which is the only currently supported\r
+ error handling for this codec.\r
+\r
+ """\r
+ assert errors == 'strict'\r
+ output = bz2.compress(input)\r
+ return (output, len(input))\r
+\r
+def bz2_decode(input,errors='strict'):\r
+\r
+ """ Decodes the object input and returns a tuple (output\r
+ object, length consumed).\r
+\r
+ input must be an object which provides the bf_getreadbuf\r
+ buffer slot. Python strings, buffer objects and memory\r
+ mapped files are examples of objects providing this slot.\r
+\r
+ errors defines the error handling to apply. It defaults to\r
+ 'strict' handling which is the only currently supported\r
+ error handling for this codec.\r
+\r
+ """\r
+ assert errors == 'strict'\r
+ output = bz2.decompress(input)\r
+ return (output, len(input))\r
+\r
+class Codec(codecs.Codec):\r
+\r
+ def encode(self, input, errors='strict'):\r
+ return bz2_encode(input, errors)\r
+ def decode(self, input, errors='strict'):\r
+ return bz2_decode(input, errors)\r
+\r
+class IncrementalEncoder(codecs.IncrementalEncoder):\r
+ def __init__(self, errors='strict'):\r
+ assert errors == 'strict'\r
+ self.errors = errors\r
+ self.compressobj = bz2.BZ2Compressor()\r
+\r
+ def encode(self, input, final=False):\r
+ if final:\r
+ c = self.compressobj.compress(input)\r
+ return c + self.compressobj.flush()\r
+ else:\r
+ return self.compressobj.compress(input)\r
+\r
+ def reset(self):\r
+ self.compressobj = bz2.BZ2Compressor()\r
+\r
+class IncrementalDecoder(codecs.IncrementalDecoder):\r
+ def __init__(self, errors='strict'):\r
+ assert errors == 'strict'\r
+ self.errors = errors\r
+ self.decompressobj = bz2.BZ2Decompressor()\r
+\r
+ def decode(self, input, final=False):\r
+ try:\r
+ return self.decompressobj.decompress(input)\r
+ except EOFError:\r
+ return ''\r
+\r
+ def reset(self):\r
+ self.decompressobj = bz2.BZ2Decompressor()\r
+\r
+class StreamWriter(Codec,codecs.StreamWriter):\r
+ pass\r
+\r
+class StreamReader(Codec,codecs.StreamReader):\r
+ pass\r
+\r
+### encodings module API\r
+\r
+def getregentry():\r
+ return codecs.CodecInfo(\r
+ name="bz2",\r
+ encode=bz2_encode,\r
+ decode=bz2_decode,\r
+ incrementalencoder=IncrementalEncoder,\r
+ incrementaldecoder=IncrementalDecoder,\r
+ streamwriter=StreamWriter,\r
+ streamreader=StreamReader,\r
+ )\r