Behdad Esfahbod ba0a3b9abb Revamp name table Unicode handling some more
Part of https://github.com/behdad/fonttools/issues/236

Now we fallback to ASCII for unknown encodings.  Not sure if this might be a bad idea.
The main user-visible difference is that if there's an ASCII-only text in an unknown
encoding, we still "decode" it and use unicode="True" instead of unicode="False".

Or is assuming that any unsupported encoding is ASCII-compatible too intrusive?
2015-04-16 17:09:49 -07:00

82 lines
1.5 KiB
Python

"""Python 2/3 compat layer."""
from __future__ import print_function, division, absolute_import
try:
basestring
except NameError:
basestring = str
try:
unicode
except NameError:
unicode = str
try:
unichr
bytechr = chr
byteord = ord
except:
unichr = chr
def bytechr(n):
return bytes([n])
def byteord(c):
return c if isinstance(c, int) else ord(c)
try:
from StringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
def strjoin(iterable, joiner=''):
return tostr(joiner).join(iterable)
def tobytes(s, encoding='ascii', errors='strict'):
if not isinstance(s, bytes):
return s.encode(encoding, errors)
else:
return s
def tounicode(s, encoding='ascii', errors='strict'):
if not isinstance(s, unicode):
return s.decode(encoding, errors)
else:
return s
if str == bytes:
class Tag(str):
def tobytes(self):
if isinstance(self, bytes):
return self
else:
return self.encode('latin1')
tostr = tobytes
bytesjoin = strjoin
else:
class Tag(str):
@staticmethod
def transcode(blob):
if not isinstance(blob, str):
blob = blob.decode('latin-1')
return blob
def __new__(self, content):
return str.__new__(self, self.transcode(content))
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
return str.__eq__(self, self.transcode(other))
def __hash__(self):
return str.__hash__(self)
def tobytes(self):
return self.encode('latin-1')
tostr = tounicode
def bytesjoin(iterable, joiner=b''):
return tobytes(joiner).join(tobytes(item) for item in iterable)