jpayne@68: """Python 'hex_codec' Codec - 2-digit hex content transfer encoding. jpayne@68: jpayne@68: This codec de/encodes from bytes to bytes. jpayne@68: jpayne@68: Written by Marc-Andre Lemburg (mal@lemburg.com). jpayne@68: """ jpayne@68: jpayne@68: import codecs jpayne@68: import binascii jpayne@68: jpayne@68: ### Codec APIs jpayne@68: jpayne@68: def hex_encode(input, errors='strict'): jpayne@68: assert errors == 'strict' jpayne@68: return (binascii.b2a_hex(input), len(input)) jpayne@68: jpayne@68: def hex_decode(input, errors='strict'): jpayne@68: assert errors == 'strict' jpayne@68: return (binascii.a2b_hex(input), len(input)) jpayne@68: jpayne@68: class Codec(codecs.Codec): jpayne@68: def encode(self, input, errors='strict'): jpayne@68: return hex_encode(input, errors) jpayne@68: def decode(self, input, errors='strict'): jpayne@68: return hex_decode(input, errors) jpayne@68: jpayne@68: class IncrementalEncoder(codecs.IncrementalEncoder): jpayne@68: def encode(self, input, final=False): jpayne@68: assert self.errors == 'strict' jpayne@68: return binascii.b2a_hex(input) jpayne@68: jpayne@68: class IncrementalDecoder(codecs.IncrementalDecoder): jpayne@68: def decode(self, input, final=False): jpayne@68: assert self.errors == 'strict' jpayne@68: return binascii.a2b_hex(input) jpayne@68: jpayne@68: class StreamWriter(Codec, codecs.StreamWriter): jpayne@68: charbuffertype = bytes jpayne@68: jpayne@68: class StreamReader(Codec, codecs.StreamReader): jpayne@68: charbuffertype = bytes jpayne@68: jpayne@68: ### encodings module API jpayne@68: jpayne@68: def getregentry(): jpayne@68: return codecs.CodecInfo( jpayne@68: name='hex', jpayne@68: encode=hex_encode, jpayne@68: decode=hex_decode, jpayne@68: incrementalencoder=IncrementalEncoder, jpayne@68: incrementaldecoder=IncrementalDecoder, jpayne@68: streamwriter=StreamWriter, jpayne@68: streamreader=StreamReader, jpayne@68: _is_text_encoding=False, jpayne@68: )