encoding.py 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. # Purpose: low level DXF data encoding/decoding module
  2. # Created: 26.03.2016
  3. # Copyright (c) 2016-2018, Manfred Moitzi
  4. # License: MIT License
  5. from .const import DXFEncodingError
  6. def dxf_backslash_replace(exc: Exception):
  7. if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)):
  8. s = ""
  9. for c in exc.object[exc.start:exc.end]:
  10. if ord(c) <= 0xff:
  11. s += "\\x%02x" % ord(c)
  12. elif ord(c) <= 0xffff:
  13. s += "\\U+%04x" % ord(c)
  14. else:
  15. s += "\\U+%08x" % ord(c)
  16. return s, exc.end
  17. else:
  18. raise TypeError("can't handle %s" % exc.__name__)
  19. def encode(unicode: str, encoding: str = 'cp1252', ignore_error: bool = False):
  20. try:
  21. return bytes(unicode, encoding)
  22. except UnicodeEncodeError: # can not use the given encoding
  23. if ignore_error: # encode string with the default unicode encoding
  24. return bytes(unicode, 'utf-8')
  25. else:
  26. raise DXFEncodingError("Can not encode string '{}' with given encoding '{}'".format(unicode, encoding))