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