| 1 |
""" Python 'hex_codec' Codec - 2-digit hex content transfer encoding |
| 2 |
|
| 3 |
Unlike most of the other codecs which target Unicode, this codec |
| 4 |
will return Python string objects for both encode and decode. |
| 5 |
|
| 6 |
Written by Marc-Andre Lemburg ([email protected]). |
| 7 |
|
| 8 |
""" |
| 9 |
import codecs, binascii |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
def hex_encode(input,errors='strict'): |
| 14 |
|
| 15 |
""" Encodes the object input and returns a tuple (output |
| 16 |
object, length consumed). |
| 17 |
|
| 18 |
errors defines the error handling to apply. It defaults to |
| 19 |
'strict' handling which is the only currently supported |
| 20 |
error handling for this codec. |
| 21 |
|
| 22 |
""" |
| 23 |
assert errors == 'strict' |
| 24 |
output = binascii.b2a_hex(input) |
| 25 |
return (output, len(input)) |
| 26 |
|
| 27 |
def hex_decode(input,errors='strict'): |
| 28 |
|
| 29 |
""" Decodes the object input and returns a tuple (output |
| 30 |
object, length consumed). |
| 31 |
|
| 32 |
input must be an object which provides the bf_getreadbuf |
| 33 |
buffer slot. Python strings, buffer objects and memory |
| 34 |
mapped files are examples of objects providing this slot. |
| 35 |
|
| 36 |
errors defines the error handling to apply. It defaults to |
| 37 |
'strict' handling which is the only currently supported |
| 38 |
error handling for this codec. |
| 39 |
|
| 40 |
""" |
| 41 |
assert errors == 'strict' |
| 42 |
output = binascii.a2b_hex(input) |
| 43 |
return (output, len(input)) |
| 44 |
|
| 45 |
class Codec(codecs.Codec): |
| 46 |
|
| 47 |
def encode(self, input,errors='strict'): |
| 48 |
return hex_encode(input,errors) |
| 49 |
def decode(self, input,errors='strict'): |
| 50 |
return hex_decode(input,errors) |
| 51 |
|
| 52 |
class IncrementalEncoder(codecs.IncrementalEncoder): |
| 53 |
def encode(self, input, final=False): |
| 54 |
assert self.errors == 'strict' |
| 55 |
return binascii.b2a_hex(input) |
| 56 |
|
| 57 |
class IncrementalDecoder(codecs.IncrementalDecoder): |
| 58 |
def decode(self, input, final=False): |
| 59 |
assert self.errors == 'strict' |
| 60 |
return binascii.a2b_hex(input) |
| 61 |
|
| 62 |
class StreamWriter(Codec,codecs.StreamWriter): |
| 63 |
pass |
| 64 |
|
| 65 |
class StreamReader(Codec,codecs.StreamReader): |
| 66 |
pass |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
def getregentry(): |
| 71 |
return codecs.CodecInfo( |
| 72 |
name='hex', |
| 73 |
encode=hex_encode, |
| 74 |
decode=hex_decode, |
| 75 |
incrementalencoder=IncrementalEncoder, |
| 76 |
incrementaldecoder=IncrementalDecoder, |
| 77 |
streamwriter=StreamWriter, |
| 78 |
streamreader=StreamReader, |
| 79 |
_is_text_encoding=False, |
| 80 |
) |