hex_codec.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """ Python 'hex_codec' Codec - 2-digit hex content transfer encoding
  2. Unlike most of the other codecs which target Unicode, this codec
  3. will return Python string objects for both encode and decode.
  4. Written by Marc-Andre Lemburg ([email protected]).
  5. """
  6. import codecs, binascii
  7. ### Codec APIs
  8. def hex_encode(input,errors='strict'):
  9. """ Encodes the object input and returns a tuple (output
  10. object, length consumed).
  11. errors defines the error handling to apply. It defaults to
  12. 'strict' handling which is the only currently supported
  13. error handling for this codec.
  14. """
  15. assert errors == 'strict'
  16. output = binascii.b2a_hex(input)
  17. return (output, len(input))
  18. def hex_decode(input,errors='strict'):
  19. """ Decodes the object input and returns a tuple (output
  20. object, length consumed).
  21. input must be an object which provides the bf_getreadbuf
  22. buffer slot. Python strings, buffer objects and memory
  23. mapped files are examples of objects providing this slot.
  24. errors defines the error handling to apply. It defaults to
  25. 'strict' handling which is the only currently supported
  26. error handling for this codec.
  27. """
  28. assert errors == 'strict'
  29. output = binascii.a2b_hex(input)
  30. return (output, len(input))
  31. class Codec(codecs.Codec):
  32. def encode(self, input,errors='strict'):
  33. return hex_encode(input,errors)
  34. def decode(self, input,errors='strict'):
  35. return hex_decode(input,errors)
  36. class StreamWriter(Codec,codecs.StreamWriter):
  37. pass
  38. class StreamReader(Codec,codecs.StreamReader):
  39. pass
  40. ### encodings module API
  41. def getregentry():
  42. return (hex_encode,hex_decode,StreamReader,StreamWriter)