Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame^] | 1 | """Codec for quoted-printable encoding. |
| 2 | |
| 3 | This codec de/encodes from bytes to bytes and is therefore usable with |
| 4 | bytes.transform() and bytes.untransform(). |
| 5 | """ |
| 6 | |
| 7 | import codecs |
| 8 | import quopri |
| 9 | from io import BytesIO |
| 10 | |
| 11 | def quopri_encode(input, errors='strict'): |
| 12 | assert errors == 'strict' |
| 13 | f = BytesIO(input) |
| 14 | g = BytesIO() |
| 15 | quopri.encode(f, g, 1) |
| 16 | return (g.getvalue(), len(input)) |
| 17 | |
| 18 | def quopri_decode(input, errors='strict'): |
| 19 | assert errors == 'strict' |
| 20 | f = BytesIO(input) |
| 21 | g = BytesIO() |
| 22 | quopri.decode(f, g) |
| 23 | return (g.getvalue(), len(input)) |
| 24 | |
| 25 | class Codec(codecs.Codec): |
| 26 | def encode(self, input, errors='strict'): |
| 27 | return quopri_encode(input, errors) |
| 28 | def decode(self, input, errors='strict'): |
| 29 | return quopri_decode(input, errors) |
| 30 | |
| 31 | class IncrementalEncoder(codecs.IncrementalEncoder): |
| 32 | def encode(self, input, final=False): |
| 33 | return quopri_encode(input, self.errors)[0] |
| 34 | |
| 35 | class IncrementalDecoder(codecs.IncrementalDecoder): |
| 36 | def decode(self, input, final=False): |
| 37 | return quopri_decode(input, self.errors)[0] |
| 38 | |
| 39 | class StreamWriter(Codec, codecs.StreamWriter): |
| 40 | charbuffertype = bytes |
| 41 | |
| 42 | class StreamReader(Codec, codecs.StreamReader): |
| 43 | charbuffertype = bytes |
| 44 | |
| 45 | # encodings module API |
| 46 | |
| 47 | def getregentry(): |
| 48 | return codecs.CodecInfo( |
| 49 | name='quopri', |
| 50 | encode=quopri_encode, |
| 51 | decode=quopri_decode, |
| 52 | incrementalencoder=IncrementalEncoder, |
| 53 | incrementaldecoder=IncrementalDecoder, |
| 54 | streamwriter=StreamWriter, |
| 55 | streamreader=StreamReader, |
| 56 | ) |