Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 1 | """Python 'base64_codec' Codec - base64 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 base64 |
| 11 | |
| 12 | ### Codec APIs |
| 13 | |
| 14 | def base64_encode(input, errors='strict'): |
| 15 | assert errors == 'strict' |
Georg Brandl | 7c23ea2 | 2010-12-06 22:25:25 +0000 | [diff] [blame] | 16 | return (base64.encodebytes(input), len(input)) |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 17 | |
| 18 | def base64_decode(input, errors='strict'): |
| 19 | assert errors == 'strict' |
Georg Brandl | 7c23ea2 | 2010-12-06 22:25:25 +0000 | [diff] [blame] | 20 | return (base64.decodebytes(input), len(input)) |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 21 | |
| 22 | class 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 | |
| 28 | class IncrementalEncoder(codecs.IncrementalEncoder): |
| 29 | def encode(self, input, final=False): |
| 30 | assert self.errors == 'strict' |
Georg Brandl | 7c23ea2 | 2010-12-06 22:25:25 +0000 | [diff] [blame] | 31 | return base64.encodebytes(input) |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 32 | |
| 33 | class IncrementalDecoder(codecs.IncrementalDecoder): |
| 34 | def decode(self, input, final=False): |
| 35 | assert self.errors == 'strict' |
Georg Brandl | 7c23ea2 | 2010-12-06 22:25:25 +0000 | [diff] [blame] | 36 | return base64.decodebytes(input) |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 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='base64', |
| 49 | encode=base64_encode, |
| 50 | decode=base64_decode, |
| 51 | incrementalencoder=IncrementalEncoder, |
| 52 | incrementaldecoder=IncrementalDecoder, |
| 53 | streamwriter=StreamWriter, |
| 54 | streamreader=StreamReader, |
Serhiy Storchaka | 94ee389 | 2014-02-24 14:43:03 +0200 | [diff] [blame] | 55 | _is_text_encoding=False, |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 56 | ) |