quopri_codec.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Codec for quoted-printable encoding.
  2. This codec de/encodes from bytes to bytes.
  3. """
  4. import codecs
  5. import quopri
  6. from io import BytesIO
  7. def quopri_encode(input, errors='strict'):
  8. assert errors == 'strict'
  9. f = BytesIO(input)
  10. g = BytesIO()
  11. quopri.encode(f, g, quotetabs=True)
  12. return (g.getvalue(), len(input))
  13. def quopri_decode(input, errors='strict'):
  14. assert errors == 'strict'
  15. f = BytesIO(input)
  16. g = BytesIO()
  17. quopri.decode(f, g)
  18. return (g.getvalue(), len(input))
  19. class Codec(codecs.Codec):
  20. def encode(self, input, errors='strict'):
  21. return quopri_encode(input, errors)
  22. def decode(self, input, errors='strict'):
  23. return quopri_decode(input, errors)
  24. class IncrementalEncoder(codecs.IncrementalEncoder):
  25. def encode(self, input, final=False):
  26. return quopri_encode(input, self.errors)[0]
  27. class IncrementalDecoder(codecs.IncrementalDecoder):
  28. def decode(self, input, final=False):
  29. return quopri_decode(input, self.errors)[0]
  30. class StreamWriter(Codec, codecs.StreamWriter):
  31. charbuffertype = bytes
  32. class StreamReader(Codec, codecs.StreamReader):
  33. charbuffertype = bytes
  34. # encodings module API
  35. def getregentry():
  36. return codecs.CodecInfo(
  37. name='quopri',
  38. encode=quopri_encode,
  39. decode=quopri_decode,
  40. incrementalencoder=IncrementalEncoder,
  41. incrementaldecoder=IncrementalDecoder,
  42. streamwriter=StreamWriter,
  43. streamreader=StreamReader,
  44. _is_text_encoding=False,
  45. )