blob: 881d1ba0beeb5983f64f54d26ac60ab1dc0fc5f8 [file] [log] [blame]
Georg Brandl02524622010-12-02 18:06:51 +00001"""Python 'base64_codec' Codec - base64 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 base64
11
12### Codec APIs
13
14def base64_encode(input, errors='strict'):
15 assert errors == 'strict'
Georg Brandl7c23ea22010-12-06 22:25:25 +000016 return (base64.encodebytes(input), len(input))
Georg Brandl02524622010-12-02 18:06:51 +000017
18def base64_decode(input, errors='strict'):
19 assert errors == 'strict'
Georg Brandl7c23ea22010-12-06 22:25:25 +000020 return (base64.decodebytes(input), len(input))
Georg Brandl02524622010-12-02 18:06:51 +000021
22class Codec(codecs.Codec):
23 def encode(self, input, errors='strict'):
24 return base64_encode(input, errors)
25 def decode(self, input, errors='strict'):
26 return base64_decode(input, errors)
27
28class IncrementalEncoder(codecs.IncrementalEncoder):
29 def encode(self, input, final=False):
30 assert self.errors == 'strict'
Georg Brandl7c23ea22010-12-06 22:25:25 +000031 return base64.encodebytes(input)
Georg Brandl02524622010-12-02 18:06:51 +000032
33class IncrementalDecoder(codecs.IncrementalDecoder):
34 def decode(self, input, final=False):
35 assert self.errors == 'strict'
Georg Brandl7c23ea22010-12-06 22:25:25 +000036 return base64.decodebytes(input)
Georg Brandl02524622010-12-02 18:06:51 +000037
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='base64',
49 encode=base64_encode,
50 decode=base64_decode,
51 incrementalencoder=IncrementalEncoder,
52 incrementaldecoder=IncrementalDecoder,
53 streamwriter=StreamWriter,
54 streamreader=StreamReader,
Nick Coghlanc72e4e62013-11-22 22:39:36 +100055 _is_text_encoding=False,
Georg Brandl02524622010-12-02 18:06:51 +000056 )