1"""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'
21    # using str() because of cStringIO's Unicode undesired Unicode behavior.
22    f = StringIO(str(input))
23    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'
37    f = StringIO(str(input))
38    g = StringIO()
39    quopri.decode(f, g)
40    output = g.getvalue()
41    return (output, len(input))
42
43class Codec(codecs.Codec):
44
45    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)
49
50class 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
58class StreamWriter(Codec, codecs.StreamWriter):
59    pass
60
61class StreamReader(Codec,codecs.StreamReader):
62    pass
63
64# encodings module API
65
66def getregentry():
67    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    )
76