blob: f2ed0a7658e23eb68f53bcd4440d785651a05d74 [file] [log] [blame]
Georg Brandl02524622010-12-02 18:06:51 +00001"""Python 'hex_codec' Codec - 2-digit hex content transfer encoding.
2
3This codec de/encodes from bytes to bytes and is therefore usable with
4bytes.transform() and bytes.untransform().
5
6Written by Marc-Andre Lemburg (mal@lemburg.com).
7"""
8
9import codecs
10import binascii
11
12### Codec APIs
13
14def hex_encode(input, errors='strict'):
15 assert errors == 'strict'
16 return (binascii.b2a_hex(input), len(input))
17
18def hex_decode(input, errors='strict'):
19 assert errors == 'strict'
20 return (binascii.a2b_hex(input), len(input))
21
22class 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
28class IncrementalEncoder(codecs.IncrementalEncoder):
29 def encode(self, input, final=False):
30 assert self.errors == 'strict'
31 return binascii.b2a_hex(input)
32
33class IncrementalDecoder(codecs.IncrementalDecoder):
34 def decode(self, input, final=False):
35 assert self.errors == 'strict'
36 return binascii.a2b_hex(input)
37
38class StreamWriter(Codec, codecs.StreamWriter):
39 charbuffertype = bytes
40
41class StreamReader(Codec, codecs.StreamReader):
42 charbuffertype = bytes
43
44### encodings module API
45
46def 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,
Serhiy Storchaka94ee3892014-02-24 14:43:03 +020055 _is_text_encoding=False,
Georg Brandl02524622010-12-02 18:06:51 +000056 )