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