blob: d8683fd56d325415a25116c129ab41ae45126016 [file] [log] [blame]
Guido van Rossumacfdf152001-05-15 15:34:07 +00001"""Codec for quoted-printable encoding.
2
3Like base64 and rot13, this returns Python strings, not Unicode.
4"""
5
6import codecs, quopri
7try:
8 from cStringIO import StringIO
9except ImportError:
10 from StringIO import StringIO
11
12def quopri_encode(input, errors='strict'):
13 """Encode the input, returning a tuple (output object, length consumed).
14
15 errors defines the error handling to apply. It defaults to
16 'strict' handling which is the only currently supported
17 error handling for this codec.
18
19 """
20 assert errors == 'strict'
Georg Brandl4cdceac2007-09-03 07:16:46 +000021 # using str() because of cStringIO's Unicode undesired Unicode behavior.
22 f = StringIO(str(input))
Guido van Rossumacfdf152001-05-15 15:34:07 +000023 g = StringIO()
24 quopri.encode(f, g, 1)
25 output = g.getvalue()
26 return (output, len(input))
27
28def quopri_decode(input, errors='strict'):
29 """Decode the input, returning a tuple (output object, length consumed).
30
31 errors defines the error handling to apply. It defaults to
32 'strict' handling which is the only currently supported
33 error handling for this codec.
34
35 """
36 assert errors == 'strict'
Georg Brandl4cdceac2007-09-03 07:16:46 +000037 f = StringIO(str(input))
Guido van Rossumacfdf152001-05-15 15:34:07 +000038 g = StringIO()
39 quopri.decode(f, g)
40 output = g.getvalue()
41 return (output, len(input))
42
43class Codec(codecs.Codec):
44
Marc-André Lemburg26e3b682001-09-20 10:33:38 +000045 def encode(self, input,errors='strict'):
46 return quopri_encode(input,errors)
47 def decode(self, input,errors='strict'):
48 return quopri_decode(input,errors)
Guido van Rossumacfdf152001-05-15 15:34:07 +000049
Walter Dörwaldabb02e52006-03-15 11:35:15 +000050class IncrementalEncoder(codecs.IncrementalEncoder):
51 def encode(self, input, final=False):
52 return quopri_encode(input, self.errors)[0]
53
54class IncrementalDecoder(codecs.IncrementalDecoder):
55 def decode(self, input, final=False):
56 return quopri_decode(input, self.errors)[0]
57
Guido van Rossumacfdf152001-05-15 15:34:07 +000058class StreamWriter(Codec, codecs.StreamWriter):
59 pass
60
61class StreamReader(Codec,codecs.StreamReader):
62 pass
63
64# encodings module API
65
66def getregentry():
Walter Dörwaldabb02e52006-03-15 11:35:15 +000067 return codecs.CodecInfo(
68 name='quopri',
69 encode=quopri_encode,
70 decode=quopri_decode,
71 incrementalencoder=IncrementalEncoder,
72 incrementaldecoder=IncrementalDecoder,
73 streamwriter=StreamWriter,
74 streamreader=StreamReader,
75 )