protobuf/python/google/protobuf/text_encoding.py
Go to the documentation of this file.
1 # Protocol Buffers - Google's data interchange format
2 # Copyright 2008 Google Inc. All rights reserved.
3 # https://developers.google.com/protocol-buffers/
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are
7 # met:
8 #
9 # * Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # * Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following disclaimer
13 # in the documentation and/or other materials provided with the
14 # distribution.
15 # * Neither the name of Google Inc. nor the names of its
16 # contributors may be used to endorse or promote products derived from
17 # this software without specific prior written permission.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 """Encoding related utilities."""
32 import re
33 
34 _cescape_chr_to_symbol_map = {}
35 _cescape_chr_to_symbol_map[9] = r'\t' # optional escape
36 _cescape_chr_to_symbol_map[10] = r'\n' # optional escape
37 _cescape_chr_to_symbol_map[13] = r'\r' # optional escape
38 _cescape_chr_to_symbol_map[34] = r'\"' # necessary escape
39 _cescape_chr_to_symbol_map[39] = r"\'" # optional escape
40 _cescape_chr_to_symbol_map[92] = r'\\' # necessary escape
41 
42 # Lookup table for unicode
43 _cescape_unicode_to_str = [chr(i) for i in range(0, 256)]
44 for byte, string in _cescape_chr_to_symbol_map.items():
45  _cescape_unicode_to_str[byte] = string
46 
47 # Lookup table for non-utf8, with necessary escapes at (o >= 127 or o < 32)
48 _cescape_byte_to_str = ([r'\%03o' % i for i in range(0, 32)] +
49  [chr(i) for i in range(32, 127)] +
50  [r'\%03o' % i for i in range(127, 256)])
51 for byte, string in _cescape_chr_to_symbol_map.items():
52  _cescape_byte_to_str[byte] = string
53 del byte, string
54 
55 
56 def CEscape(text, as_utf8):
57  # type: (...) -> str
58  """Escape a bytes string for use in an text protocol buffer.
59 
60  Args:
61  text: A byte string to be escaped.
62  as_utf8: Specifies if result may contain non-ASCII characters.
63  In Python 3 this allows unescaped non-ASCII Unicode characters.
64  In Python 2 the return value will be valid UTF-8 rather than only ASCII.
65  Returns:
66  Escaped string (str).
67  """
68  # Python's text.encode() 'string_escape' or 'unicode_escape' codecs do not
69  # satisfy our needs; they encodes unprintable characters using two-digit hex
70  # escapes whereas our C++ unescaping function allows hex escapes to be any
71  # length. So, "\0011".encode('string_escape') ends up being "\\x011", which
72  # will be decoded in C++ as a single-character string with char code 0x11.
73  text_is_unicode = isinstance(text, str)
74  if as_utf8 and text_is_unicode:
75  # We're already unicode, no processing beyond control char escapes.
76  return text.translate(_cescape_chr_to_symbol_map)
77  ord_ = ord if text_is_unicode else lambda x: x # bytes iterate as ints.
78  if as_utf8:
79  return ''.join(_cescape_unicode_to_str[ord_(c)] for c in text)
80  return ''.join(_cescape_byte_to_str[ord_(c)] for c in text)
81 
82 
83 _CUNESCAPE_HEX = re.compile(r'(\\+)x([0-9a-fA-F])(?![0-9a-fA-F])')
84 
85 
86 def CUnescape(text):
87  # type: (str) -> bytes
88  """Unescape a text string with C-style escape sequences to UTF-8 bytes.
89 
90  Args:
91  text: The data to parse in a str.
92  Returns:
93  A byte string.
94  """
95 
96  def ReplaceHex(m):
97  # Only replace the match if the number of leading back slashes is odd. i.e.
98  # the slash itself is not escaped.
99  if len(m.group(1)) & 1:
100  return m.group(1) + 'x0' + m.group(2)
101  return m.group(0)
102 
103  # This is required because the 'string_escape' encoding doesn't
104  # allow single-digit hex escapes (like '\xf').
105  result = _CUNESCAPE_HEX.sub(ReplaceHex, text)
106 
107  return (result.encode('utf-8') # Make it bytes to allow decode.
108  .decode('unicode_escape')
109  # Make it bytes again to return the proper type.
110  .encode('raw_unicode_escape'))
capstone.range
range
Definition: third_party/bloaty/third_party/capstone/bindings/python/capstone/__init__.py:6
grpc._common.encode
def encode(s)
Definition: grpc/_common.py:68
google::protobuf.text_encoding.CEscape
def CEscape(text, as_utf8)
Definition: bloaty/third_party/protobuf/python/google/protobuf/text_encoding.py:58
google::protobuf.text_encoding.CUnescape
def CUnescape(text)
Definition: bloaty/third_party/protobuf/python/google/protobuf/text_encoding.py:91
grpc._common.decode
def decode(b)
Definition: grpc/_common.py:75
len
int len
Definition: abseil-cpp/absl/base/internal/low_level_alloc_test.cc:46


grpc
Author(s):
autogenerated on Thu Mar 13 2025 03:01:35