text_encoding.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style
  5. # license that can be found in the LICENSE file or at
  6. # https://developers.google.com/open-source/licenses/bsd
  7. """Encoding related utilities."""
  8. import re
  9. def _AsciiIsPrint(i):
  10. return i >= 32 and i < 127
  11. def _MakeStrEscapes():
  12. ret = {}
  13. for i in range(0, 128):
  14. if not _AsciiIsPrint(i):
  15. ret[i] = r'\%03o' % i
  16. ret[ord('\t')] = r'\t' # optional escape
  17. ret[ord('\n')] = r'\n' # optional escape
  18. ret[ord('\r')] = r'\r' # optional escape
  19. ret[ord('"')] = r'\"' # necessary escape
  20. ret[ord('\'')] = r"\'" # optional escape
  21. ret[ord('\\')] = r'\\' # necessary escape
  22. return ret
  23. # Maps int -> char, performing string escapes.
  24. _str_escapes = _MakeStrEscapes()
  25. # Maps int -> char, performing byte escaping and string escapes
  26. _byte_escapes = {i: chr(i) for i in range(0, 256)}
  27. _byte_escapes.update(_str_escapes)
  28. _byte_escapes.update({i: r'\%03o' % i for i in range(128, 256)})
  29. def _DecodeUtf8EscapeErrors(text_bytes):
  30. ret = ''
  31. while text_bytes:
  32. try:
  33. ret += text_bytes.decode('utf-8').translate(_str_escapes)
  34. text_bytes = ''
  35. except UnicodeDecodeError as e:
  36. ret += text_bytes[:e.start].decode('utf-8').translate(_str_escapes)
  37. ret += _byte_escapes[text_bytes[e.start]]
  38. text_bytes = text_bytes[e.start+1:]
  39. return ret
  40. def CEscape(text, as_utf8) -> str:
  41. """Escape a bytes string for use in an text protocol buffer.
  42. Args:
  43. text: A byte string to be escaped.
  44. as_utf8: Specifies if result may contain non-ASCII characters.
  45. In Python 3 this allows unescaped non-ASCII Unicode characters.
  46. In Python 2 the return value will be valid UTF-8 rather than only ASCII.
  47. Returns:
  48. Escaped string (str).
  49. """
  50. # Python's text.encode() 'string_escape' or 'unicode_escape' codecs do not
  51. # satisfy our needs; they encodes unprintable characters using two-digit hex
  52. # escapes whereas our C++ unescaping function allows hex escapes to be any
  53. # length. So, "\0011".encode('string_escape') ends up being "\\x011", which
  54. # will be decoded in C++ as a single-character string with char code 0x11.
  55. text_is_unicode = isinstance(text, str)
  56. if as_utf8:
  57. if text_is_unicode:
  58. return text.translate(_str_escapes)
  59. else:
  60. return _DecodeUtf8EscapeErrors(text)
  61. else:
  62. if text_is_unicode:
  63. text = text.encode('utf-8')
  64. return ''.join([_byte_escapes[c] for c in text])
  65. _CUNESCAPE_HEX = re.compile(r'(\\+)x([0-9a-fA-F])(?![0-9a-fA-F])')
  66. def CUnescape(text: str) -> bytes:
  67. """Unescape a text string with C-style escape sequences to UTF-8 bytes.
  68. Args:
  69. text: The data to parse in a str.
  70. Returns:
  71. A byte string.
  72. """
  73. def ReplaceHex(m):
  74. # Only replace the match if the number of leading back slashes is odd. i.e.
  75. # the slash itself is not escaped.
  76. if len(m.group(1)) & 1:
  77. return m.group(1) + 'x0' + m.group(2)
  78. return m.group(0)
  79. # This is required because the 'string_escape' encoding doesn't
  80. # allow single-digit hex escapes (like '\xf').
  81. result = _CUNESCAPE_HEX.sub(ReplaceHex, text)
  82. # Replaces Unicode escape sequences with their character equivalents.
  83. result = result.encode('raw_unicode_escape').decode('raw_unicode_escape')
  84. # Encode Unicode characters as UTF-8, then decode to Latin-1 escaping
  85. # unprintable characters.
  86. result = result.encode('utf-8').decode('unicode_escape')
  87. # Convert Latin-1 text back to a byte string (latin-1 codec also works here).
  88. return result.encode('latin-1')