| 1 |
#!/usr/bin/env python |
| 2 |
# vim:fileencoding=utf-8 |
| 3 |
# License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> |
| 4 |
|
| 5 |
|
| 6 |
from io import BytesIO, StringIO |
| 7 |
|
| 8 |
|
| 9 |
class PolyglotStringIO(StringIO): |
| 10 |
|
| 11 |
def __init__(self, initial_data=None, encoding='utf-8', errors='strict'): |
| 12 |
StringIO.__init__(self) |
| 13 |
self._encoding_for_bytes = encoding |
| 14 |
self._errors = errors |
| 15 |
if initial_data is not None: |
| 16 |
self.write(initial_data) |
| 17 |
|
| 18 |
def write(self, x): |
| 19 |
if isinstance(x, bytes): |
| 20 |
x = x.decode(self._encoding_for_bytes, errors=self._errors) |
| 21 |
StringIO.write(self, x) |
| 22 |
|
| 23 |
|
| 24 |
class PolyglotBytesIO(BytesIO): |
| 25 |
|
| 26 |
def __init__(self, initial_data=None, encoding='utf-8', errors='strict'): |
| 27 |
BytesIO.__init__(self) |
| 28 |
self._encoding_for_bytes = encoding |
| 29 |
self._errors = errors |
| 30 |
if initial_data is not None: |
| 31 |
self.write(initial_data) |
| 32 |
|
| 33 |
def write(self, x): |
| 34 |
if not isinstance(x, bytes): |
| 35 |
x = x.encode(self._encoding_for_bytes, errors=self._errors) |
| 36 |
BytesIO.write(self, x) |