bz2_codec.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """Python 'bz2_codec' Codec - bz2 compression encoding.
  2. This codec de/encodes from bytes to bytes and is therefore usable with
  3. bytes.transform() and bytes.untransform().
  4. Adapted by Raymond Hettinger from zlib_codec.py which was written
  5. by Marc-Andre Lemburg (mal@lemburg.com).
  6. """
  7. import codecs
  8. import bz2 # this codec needs the optional bz2 module !
  9. ### Codec APIs
  10. def bz2_encode(input, errors='strict'):
  11. assert errors == 'strict'
  12. return (bz2.compress(input), len(input))
  13. def bz2_decode(input, errors='strict'):
  14. assert errors == 'strict'
  15. return (bz2.decompress(input), len(input))
  16. class Codec(codecs.Codec):
  17. def encode(self, input, errors='strict'):
  18. return bz2_encode(input, errors)
  19. def decode(self, input, errors='strict'):
  20. return bz2_decode(input, errors)
  21. class IncrementalEncoder(codecs.IncrementalEncoder):
  22. def __init__(self, errors='strict'):
  23. assert errors == 'strict'
  24. self.errors = errors
  25. self.compressobj = bz2.BZ2Compressor()
  26. def encode(self, input, final=False):
  27. if final:
  28. c = self.compressobj.compress(input)
  29. return c + self.compressobj.flush()
  30. else:
  31. return self.compressobj.compress(input)
  32. def reset(self):
  33. self.compressobj = bz2.BZ2Compressor()
  34. class IncrementalDecoder(codecs.IncrementalDecoder):
  35. def __init__(self, errors='strict'):
  36. assert errors == 'strict'
  37. self.errors = errors
  38. self.decompressobj = bz2.BZ2Decompressor()
  39. def decode(self, input, final=False):
  40. try:
  41. return self.decompressobj.decompress(input)
  42. except EOFError:
  43. return ''
  44. def reset(self):
  45. self.decompressobj = bz2.BZ2Decompressor()
  46. class StreamWriter(Codec, codecs.StreamWriter):
  47. charbuffertype = bytes
  48. class StreamReader(Codec, codecs.StreamReader):
  49. charbuffertype = bytes
  50. ### encodings module API
  51. def getregentry():
  52. return codecs.CodecInfo(
  53. name="bz2",
  54. encode=bz2_encode,
  55. decode=bz2_decode,
  56. incrementalencoder=IncrementalEncoder,
  57. incrementaldecoder=IncrementalDecoder,
  58. streamwriter=StreamWriter,
  59. streamreader=StreamReader,
  60. _is_text_encoding=False,
  61. )