hex_codec.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """Python 'hex_codec' Codec - 2-digit hex content transfer encoding.
  2. This codec de/encodes from bytes to bytes.
  3. Written by Marc-Andre Lemburg (mal@lemburg.com).
  4. """
  5. import codecs
  6. import binascii
  7. ### Codec APIs
  8. def hex_encode(input, errors='strict'):
  9. assert errors == 'strict'
  10. return (binascii.b2a_hex(input), len(input))
  11. def hex_decode(input, errors='strict'):
  12. assert errors == 'strict'
  13. return (binascii.a2b_hex(input), len(input))
  14. class Codec(codecs.Codec):
  15. def encode(self, input, errors='strict'):
  16. return hex_encode(input, errors)
  17. def decode(self, input, errors='strict'):
  18. return hex_decode(input, errors)
  19. class IncrementalEncoder(codecs.IncrementalEncoder):
  20. def encode(self, input, final=False):
  21. assert self.errors == 'strict'
  22. return binascii.b2a_hex(input)
  23. class IncrementalDecoder(codecs.IncrementalDecoder):
  24. def decode(self, input, final=False):
  25. assert self.errors == 'strict'
  26. return binascii.a2b_hex(input)
  27. class StreamWriter(Codec, codecs.StreamWriter):
  28. charbuffertype = bytes
  29. class StreamReader(Codec, codecs.StreamReader):
  30. charbuffertype = bytes
  31. ### encodings module API
  32. def getregentry():
  33. return codecs.CodecInfo(
  34. name='hex',
  35. encode=hex_encode,
  36. decode=hex_decode,
  37. incrementalencoder=IncrementalEncoder,
  38. incrementaldecoder=IncrementalDecoder,
  39. streamwriter=StreamWriter,
  40. streamreader=StreamReader,
  41. _is_text_encoding=False,
  42. )