Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 1 | """Python 'hex_codec' Codec - 2-digit hex content transfer encoding. |
| 2 | |
| 3 | This codec de/encodes from bytes to bytes and is therefore usable with |
| 4 | bytes.transform() and bytes.untransform(). |
| 5 | |
| 6 | Written by Marc-Andre Lemburg (mal@lemburg.com). |
| 7 | """ |
| 8 | |
| 9 | import codecs |
| 10 | import binascii |
| 11 | |
| 12 | ### Codec APIs |
| 13 | |
| 14 | def hex_encode(input, errors='strict'): |
| 15 | assert errors == 'strict' |
| 16 | return (binascii.b2a_hex(input), len(input)) |
| 17 | |
| 18 | def hex_decode(input, errors='strict'): |
| 19 | assert errors == 'strict' |
| 20 | return (binascii.a2b_hex(input), len(input)) |
| 21 | |
| 22 | class Codec(codecs.Codec): |
| 23 | def encode(self, input, errors='strict'): |
| 24 | return hex_encode(input, errors) |
| 25 | def decode(self, input, errors='strict'): |
| 26 | return hex_decode(input, errors) |
| 27 | |
| 28 | class IncrementalEncoder(codecs.IncrementalEncoder): |
| 29 | def encode(self, input, final=False): |
| 30 | assert self.errors == 'strict' |
| 31 | return binascii.b2a_hex(input) |
| 32 | |
| 33 | class IncrementalDecoder(codecs.IncrementalDecoder): |
| 34 | def decode(self, input, final=False): |
| 35 | assert self.errors == 'strict' |
| 36 | return binascii.a2b_hex(input) |
| 37 | |
| 38 | class StreamWriter(Codec, codecs.StreamWriter): |
| 39 | charbuffertype = bytes |
| 40 | |
| 41 | class StreamReader(Codec, codecs.StreamReader): |
| 42 | charbuffertype = bytes |
| 43 | |
| 44 | ### encodings module API |
| 45 | |
| 46 | def getregentry(): |
| 47 | return codecs.CodecInfo( |
| 48 | name='hex', |
| 49 | encode=hex_encode, |
| 50 | decode=hex_decode, |
| 51 | incrementalencoder=IncrementalEncoder, |
| 52 | incrementaldecoder=IncrementalDecoder, |
| 53 | streamwriter=StreamWriter, |
| 54 | streamreader=StreamReader, |
| 55 | ) |