compat.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import sys
  2. if sys.version_info < (3,):
  3. def isbasestring(s):
  4. return isinstance(s, basestring)
  5. def open_utf8(filename, mode):
  6. return open(filename, mode)
  7. def byte_to_str(x):
  8. return str(ord(x))
  9. import cStringIO
  10. def StringIO():
  11. return cStringIO.StringIO()
  12. def encode_utf8(x):
  13. return x
  14. def decode_utf8(x):
  15. return x
  16. def iteritems(d):
  17. return d.iteritems()
  18. def escape_string(s):
  19. if isinstance(s, unicode):
  20. s = s.encode('ascii')
  21. result = ''
  22. for c in s:
  23. if not (32 <= ord(c) < 127) or c in ('\\', '"'):
  24. result += '\\%03o' % ord(c)
  25. else:
  26. result += c
  27. return result
  28. else:
  29. def isbasestring(s):
  30. return isinstance(s, (str, bytes))
  31. def open_utf8(filename, mode):
  32. return open(filename, mode, encoding="utf-8")
  33. def byte_to_str(x):
  34. return str(x)
  35. import io
  36. def StringIO():
  37. return io.StringIO()
  38. import codecs
  39. def encode_utf8(x):
  40. return codecs.utf_8_encode(x)[0]
  41. def decode_utf8(x):
  42. return codecs.utf_8_decode(x)[0]
  43. def iteritems(d):
  44. return iter(d.items())
  45. def charcode_to_c_escapes(c):
  46. rev_result = []
  47. while c >= 256:
  48. c, low = (c // 256, c % 256)
  49. rev_result.append('\\%03o' % low)
  50. rev_result.append('\\%03o' % c)
  51. return ''.join(reversed(rev_result))
  52. def escape_string(s):
  53. result = ''
  54. if isinstance(s, str):
  55. s = s.encode('utf-8')
  56. for c in s:
  57. if not(32 <= c < 127) or c in (ord('\\'), ord('"')):
  58. result += charcode_to_c_escapes(c)
  59. else:
  60. result += chr(c)
  61. return result