/thirdparty/breakpad/third_party/protobuf/protobuf/python/google/protobuf/text_format.py

http://github.com/tomahawk-player/tomahawk · Python · 691 lines · 498 code · 55 blank · 138 comment · 80 complexity · 00f8b4081552a97cca537d8ae0516e88 MD5 · raw file

  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # http://code.google.com/p/protobuf/
  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. """Contains routines for printing protocol messages in text format."""
  31. __author__ = 'kenton@google.com (Kenton Varda)'
  32. import cStringIO
  33. import re
  34. from collections import deque
  35. from google.protobuf.internal import type_checkers
  36. from google.protobuf import descriptor
  37. __all__ = [ 'MessageToString', 'PrintMessage', 'PrintField',
  38. 'PrintFieldValue', 'Merge' ]
  39. # Infinity and NaN are not explicitly supported by Python pre-2.6, and
  40. # float('inf') does not work on Windows (pre-2.6).
  41. _INFINITY = 1e10000 # overflows, thus will actually be infinity.
  42. _NAN = _INFINITY * 0
  43. class ParseError(Exception):
  44. """Thrown in case of ASCII parsing error."""
  45. def MessageToString(message, as_utf8=False, as_one_line=False):
  46. out = cStringIO.StringIO()
  47. PrintMessage(message, out, as_utf8=as_utf8, as_one_line=as_one_line)
  48. result = out.getvalue()
  49. out.close()
  50. if as_one_line:
  51. return result.rstrip()
  52. return result
  53. def PrintMessage(message, out, indent=0, as_utf8=False, as_one_line=False):
  54. for field, value in message.ListFields():
  55. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  56. for element in value:
  57. PrintField(field, element, out, indent, as_utf8, as_one_line)
  58. else:
  59. PrintField(field, value, out, indent, as_utf8, as_one_line)
  60. def PrintField(field, value, out, indent=0, as_utf8=False, as_one_line=False):
  61. """Print a single field name/value pair. For repeated fields, the value
  62. should be a single element."""
  63. out.write(' ' * indent);
  64. if field.is_extension:
  65. out.write('[')
  66. if (field.containing_type.GetOptions().message_set_wire_format and
  67. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  68. field.message_type == field.extension_scope and
  69. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):
  70. out.write(field.message_type.full_name)
  71. else:
  72. out.write(field.full_name)
  73. out.write(']')
  74. elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:
  75. # For groups, use the capitalized name.
  76. out.write(field.message_type.name)
  77. else:
  78. out.write(field.name)
  79. if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  80. # The colon is optional in this case, but our cross-language golden files
  81. # don't include it.
  82. out.write(': ')
  83. PrintFieldValue(field, value, out, indent, as_utf8, as_one_line)
  84. if as_one_line:
  85. out.write(' ')
  86. else:
  87. out.write('\n')
  88. def PrintFieldValue(field, value, out, indent=0,
  89. as_utf8=False, as_one_line=False):
  90. """Print a single field value (not including name). For repeated fields,
  91. the value should be a single element."""
  92. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  93. if as_one_line:
  94. out.write(' { ')
  95. PrintMessage(value, out, indent, as_utf8, as_one_line)
  96. out.write('}')
  97. else:
  98. out.write(' {\n')
  99. PrintMessage(value, out, indent + 2, as_utf8, as_one_line)
  100. out.write(' ' * indent + '}')
  101. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  102. out.write(field.enum_type.values_by_number[value].name)
  103. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  104. out.write('\"')
  105. if type(value) is unicode:
  106. out.write(_CEscape(value.encode('utf-8'), as_utf8))
  107. else:
  108. out.write(_CEscape(value, as_utf8))
  109. out.write('\"')
  110. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  111. if value:
  112. out.write("true")
  113. else:
  114. out.write("false")
  115. else:
  116. out.write(str(value))
  117. def Merge(text, message):
  118. """Merges an ASCII representation of a protocol message into a message.
  119. Args:
  120. text: Message ASCII representation.
  121. message: A protocol buffer message to merge into.
  122. Raises:
  123. ParseError: On ASCII parsing problems.
  124. """
  125. tokenizer = _Tokenizer(text)
  126. while not tokenizer.AtEnd():
  127. _MergeField(tokenizer, message)
  128. def _MergeField(tokenizer, message):
  129. """Merges a single protocol message field into a message.
  130. Args:
  131. tokenizer: A tokenizer to parse the field name and values.
  132. message: A protocol message to record the data.
  133. Raises:
  134. ParseError: In case of ASCII parsing problems.
  135. """
  136. message_descriptor = message.DESCRIPTOR
  137. if tokenizer.TryConsume('['):
  138. name = [tokenizer.ConsumeIdentifier()]
  139. while tokenizer.TryConsume('.'):
  140. name.append(tokenizer.ConsumeIdentifier())
  141. name = '.'.join(name)
  142. if not message_descriptor.is_extendable:
  143. raise tokenizer.ParseErrorPreviousToken(
  144. 'Message type "%s" does not have extensions.' %
  145. message_descriptor.full_name)
  146. field = message.Extensions._FindExtensionByName(name)
  147. if not field:
  148. raise tokenizer.ParseErrorPreviousToken(
  149. 'Extension "%s" not registered.' % name)
  150. elif message_descriptor != field.containing_type:
  151. raise tokenizer.ParseErrorPreviousToken(
  152. 'Extension "%s" does not extend message type "%s".' % (
  153. name, message_descriptor.full_name))
  154. tokenizer.Consume(']')
  155. else:
  156. name = tokenizer.ConsumeIdentifier()
  157. field = message_descriptor.fields_by_name.get(name, None)
  158. # Group names are expected to be capitalized as they appear in the
  159. # .proto file, which actually matches their type names, not their field
  160. # names.
  161. if not field:
  162. field = message_descriptor.fields_by_name.get(name.lower(), None)
  163. if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP:
  164. field = None
  165. if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and
  166. field.message_type.name != name):
  167. field = None
  168. if not field:
  169. raise tokenizer.ParseErrorPreviousToken(
  170. 'Message type "%s" has no field named "%s".' % (
  171. message_descriptor.full_name, name))
  172. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  173. tokenizer.TryConsume(':')
  174. if tokenizer.TryConsume('<'):
  175. end_token = '>'
  176. else:
  177. tokenizer.Consume('{')
  178. end_token = '}'
  179. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  180. if field.is_extension:
  181. sub_message = message.Extensions[field].add()
  182. else:
  183. sub_message = getattr(message, field.name).add()
  184. else:
  185. if field.is_extension:
  186. sub_message = message.Extensions[field]
  187. else:
  188. sub_message = getattr(message, field.name)
  189. sub_message.SetInParent()
  190. while not tokenizer.TryConsume(end_token):
  191. if tokenizer.AtEnd():
  192. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token))
  193. _MergeField(tokenizer, sub_message)
  194. else:
  195. _MergeScalarField(tokenizer, message, field)
  196. def _MergeScalarField(tokenizer, message, field):
  197. """Merges a single protocol message scalar field into a message.
  198. Args:
  199. tokenizer: A tokenizer to parse the field value.
  200. message: A protocol message to record the data.
  201. field: The descriptor of the field to be merged.
  202. Raises:
  203. ParseError: In case of ASCII parsing problems.
  204. RuntimeError: On runtime errors.
  205. """
  206. tokenizer.Consume(':')
  207. value = None
  208. if field.type in (descriptor.FieldDescriptor.TYPE_INT32,
  209. descriptor.FieldDescriptor.TYPE_SINT32,
  210. descriptor.FieldDescriptor.TYPE_SFIXED32):
  211. value = tokenizer.ConsumeInt32()
  212. elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,
  213. descriptor.FieldDescriptor.TYPE_SINT64,
  214. descriptor.FieldDescriptor.TYPE_SFIXED64):
  215. value = tokenizer.ConsumeInt64()
  216. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,
  217. descriptor.FieldDescriptor.TYPE_FIXED32):
  218. value = tokenizer.ConsumeUint32()
  219. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,
  220. descriptor.FieldDescriptor.TYPE_FIXED64):
  221. value = tokenizer.ConsumeUint64()
  222. elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,
  223. descriptor.FieldDescriptor.TYPE_DOUBLE):
  224. value = tokenizer.ConsumeFloat()
  225. elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:
  226. value = tokenizer.ConsumeBool()
  227. elif field.type == descriptor.FieldDescriptor.TYPE_STRING:
  228. value = tokenizer.ConsumeString()
  229. elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  230. value = tokenizer.ConsumeByteString()
  231. elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:
  232. # Enum can be specified by a number (the enum value), or by
  233. # a string literal (the enum name).
  234. enum_descriptor = field.enum_type
  235. if tokenizer.LookingAtInteger():
  236. number = tokenizer.ConsumeInt32()
  237. enum_value = enum_descriptor.values_by_number.get(number, None)
  238. if enum_value is None:
  239. raise tokenizer.ParseErrorPreviousToken(
  240. 'Enum type "%s" has no value with number %d.' % (
  241. enum_descriptor.full_name, number))
  242. else:
  243. identifier = tokenizer.ConsumeIdentifier()
  244. enum_value = enum_descriptor.values_by_name.get(identifier, None)
  245. if enum_value is None:
  246. raise tokenizer.ParseErrorPreviousToken(
  247. 'Enum type "%s" has no value named %s.' % (
  248. enum_descriptor.full_name, identifier))
  249. value = enum_value.number
  250. else:
  251. raise RuntimeError('Unknown field type %d' % field.type)
  252. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  253. if field.is_extension:
  254. message.Extensions[field].append(value)
  255. else:
  256. getattr(message, field.name).append(value)
  257. else:
  258. if field.is_extension:
  259. message.Extensions[field] = value
  260. else:
  261. setattr(message, field.name, value)
  262. class _Tokenizer(object):
  263. """Protocol buffer ASCII representation tokenizer.
  264. This class handles the lower level string parsing by splitting it into
  265. meaningful tokens.
  266. It was directly ported from the Java protocol buffer API.
  267. """
  268. _WHITESPACE = re.compile('(\\s|(#.*$))+', re.MULTILINE)
  269. _TOKEN = re.compile(
  270. '[a-zA-Z_][0-9a-zA-Z_+-]*|' # an identifier
  271. '[0-9+-][0-9a-zA-Z_.+-]*|' # a number
  272. '\"([^\"\n\\\\]|\\\\.)*(\"|\\\\?$)|' # a double-quoted string
  273. '\'([^\'\n\\\\]|\\\\.)*(\'|\\\\?$)') # a single-quoted string
  274. _IDENTIFIER = re.compile('\w+')
  275. _INTEGER_CHECKERS = [type_checkers.Uint32ValueChecker(),
  276. type_checkers.Int32ValueChecker(),
  277. type_checkers.Uint64ValueChecker(),
  278. type_checkers.Int64ValueChecker()]
  279. _FLOAT_INFINITY = re.compile('-?inf(inity)?f?', re.IGNORECASE)
  280. _FLOAT_NAN = re.compile("nanf?", re.IGNORECASE)
  281. def __init__(self, text_message):
  282. self._text_message = text_message
  283. self._position = 0
  284. self._line = -1
  285. self._column = 0
  286. self._token_start = None
  287. self.token = ''
  288. self._lines = deque(text_message.split('\n'))
  289. self._current_line = ''
  290. self._previous_line = 0
  291. self._previous_column = 0
  292. self._SkipWhitespace()
  293. self.NextToken()
  294. def AtEnd(self):
  295. """Checks the end of the text was reached.
  296. Returns:
  297. True iff the end was reached.
  298. """
  299. return self.token == ''
  300. def _PopLine(self):
  301. while len(self._current_line) <= self._column:
  302. if not self._lines:
  303. self._current_line = ''
  304. return
  305. self._line += 1
  306. self._column = 0
  307. self._current_line = self._lines.popleft()
  308. def _SkipWhitespace(self):
  309. while True:
  310. self._PopLine()
  311. match = self._WHITESPACE.match(self._current_line, self._column)
  312. if not match:
  313. break
  314. length = len(match.group(0))
  315. self._column += length
  316. def TryConsume(self, token):
  317. """Tries to consume a given piece of text.
  318. Args:
  319. token: Text to consume.
  320. Returns:
  321. True iff the text was consumed.
  322. """
  323. if self.token == token:
  324. self.NextToken()
  325. return True
  326. return False
  327. def Consume(self, token):
  328. """Consumes a piece of text.
  329. Args:
  330. token: Text to consume.
  331. Raises:
  332. ParseError: If the text couldn't be consumed.
  333. """
  334. if not self.TryConsume(token):
  335. raise self._ParseError('Expected "%s".' % token)
  336. def LookingAtInteger(self):
  337. """Checks if the current token is an integer.
  338. Returns:
  339. True iff the current token is an integer.
  340. """
  341. if not self.token:
  342. return False
  343. c = self.token[0]
  344. return (c >= '0' and c <= '9') or c == '-' or c == '+'
  345. def ConsumeIdentifier(self):
  346. """Consumes protocol message field identifier.
  347. Returns:
  348. Identifier string.
  349. Raises:
  350. ParseError: If an identifier couldn't be consumed.
  351. """
  352. result = self.token
  353. if not self._IDENTIFIER.match(result):
  354. raise self._ParseError('Expected identifier.')
  355. self.NextToken()
  356. return result
  357. def ConsumeInt32(self):
  358. """Consumes a signed 32bit integer number.
  359. Returns:
  360. The integer parsed.
  361. Raises:
  362. ParseError: If a signed 32bit integer couldn't be consumed.
  363. """
  364. try:
  365. result = self._ParseInteger(self.token, is_signed=True, is_long=False)
  366. except ValueError, e:
  367. raise self._IntegerParseError(e)
  368. self.NextToken()
  369. return result
  370. def ConsumeUint32(self):
  371. """Consumes an unsigned 32bit integer number.
  372. Returns:
  373. The integer parsed.
  374. Raises:
  375. ParseError: If an unsigned 32bit integer couldn't be consumed.
  376. """
  377. try:
  378. result = self._ParseInteger(self.token, is_signed=False, is_long=False)
  379. except ValueError, e:
  380. raise self._IntegerParseError(e)
  381. self.NextToken()
  382. return result
  383. def ConsumeInt64(self):
  384. """Consumes a signed 64bit integer number.
  385. Returns:
  386. The integer parsed.
  387. Raises:
  388. ParseError: If a signed 64bit integer couldn't be consumed.
  389. """
  390. try:
  391. result = self._ParseInteger(self.token, is_signed=True, is_long=True)
  392. except ValueError, e:
  393. raise self._IntegerParseError(e)
  394. self.NextToken()
  395. return result
  396. def ConsumeUint64(self):
  397. """Consumes an unsigned 64bit integer number.
  398. Returns:
  399. The integer parsed.
  400. Raises:
  401. ParseError: If an unsigned 64bit integer couldn't be consumed.
  402. """
  403. try:
  404. result = self._ParseInteger(self.token, is_signed=False, is_long=True)
  405. except ValueError, e:
  406. raise self._IntegerParseError(e)
  407. self.NextToken()
  408. return result
  409. def ConsumeFloat(self):
  410. """Consumes an floating point number.
  411. Returns:
  412. The number parsed.
  413. Raises:
  414. ParseError: If a floating point number couldn't be consumed.
  415. """
  416. text = self.token
  417. if self._FLOAT_INFINITY.match(text):
  418. self.NextToken()
  419. if text.startswith('-'):
  420. return -_INFINITY
  421. return _INFINITY
  422. if self._FLOAT_NAN.match(text):
  423. self.NextToken()
  424. return _NAN
  425. try:
  426. result = float(text)
  427. except ValueError, e:
  428. raise self._FloatParseError(e)
  429. self.NextToken()
  430. return result
  431. def ConsumeBool(self):
  432. """Consumes a boolean value.
  433. Returns:
  434. The bool parsed.
  435. Raises:
  436. ParseError: If a boolean value couldn't be consumed.
  437. """
  438. if self.token in ('true', 't', '1'):
  439. self.NextToken()
  440. return True
  441. elif self.token in ('false', 'f', '0'):
  442. self.NextToken()
  443. return False
  444. else:
  445. raise self._ParseError('Expected "true" or "false".')
  446. def ConsumeString(self):
  447. """Consumes a string value.
  448. Returns:
  449. The string parsed.
  450. Raises:
  451. ParseError: If a string value couldn't be consumed.
  452. """
  453. bytes = self.ConsumeByteString()
  454. try:
  455. return unicode(bytes, 'utf-8')
  456. except UnicodeDecodeError, e:
  457. raise self._StringParseError(e)
  458. def ConsumeByteString(self):
  459. """Consumes a byte array value.
  460. Returns:
  461. The array parsed (as a string).
  462. Raises:
  463. ParseError: If a byte array value couldn't be consumed.
  464. """
  465. list = [self._ConsumeSingleByteString()]
  466. while len(self.token) > 0 and self.token[0] in ('\'', '"'):
  467. list.append(self._ConsumeSingleByteString())
  468. return "".join(list)
  469. def _ConsumeSingleByteString(self):
  470. """Consume one token of a string literal.
  471. String literals (whether bytes or text) can come in multiple adjacent
  472. tokens which are automatically concatenated, like in C or Python. This
  473. method only consumes one token.
  474. """
  475. text = self.token
  476. if len(text) < 1 or text[0] not in ('\'', '"'):
  477. raise self._ParseError('Exptected string.')
  478. if len(text) < 2 or text[-1] != text[0]:
  479. raise self._ParseError('String missing ending quote.')
  480. try:
  481. result = _CUnescape(text[1:-1])
  482. except ValueError, e:
  483. raise self._ParseError(str(e))
  484. self.NextToken()
  485. return result
  486. def _ParseInteger(self, text, is_signed=False, is_long=False):
  487. """Parses an integer.
  488. Args:
  489. text: The text to parse.
  490. is_signed: True if a signed integer must be parsed.
  491. is_long: True if a long integer must be parsed.
  492. Returns:
  493. The integer value.
  494. Raises:
  495. ValueError: Thrown Iff the text is not a valid integer.
  496. """
  497. pos = 0
  498. if text.startswith('-'):
  499. pos += 1
  500. base = 10
  501. if text.startswith('0x', pos) or text.startswith('0X', pos):
  502. base = 16
  503. elif text.startswith('0', pos):
  504. base = 8
  505. # Do the actual parsing. Exception handling is propagated to caller.
  506. result = int(text, base)
  507. # Check if the integer is sane. Exceptions handled by callers.
  508. checker = self._INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
  509. checker.CheckValue(result)
  510. return result
  511. def ParseErrorPreviousToken(self, message):
  512. """Creates and *returns* a ParseError for the previously read token.
  513. Args:
  514. message: A message to set for the exception.
  515. Returns:
  516. A ParseError instance.
  517. """
  518. return ParseError('%d:%d : %s' % (
  519. self._previous_line + 1, self._previous_column + 1, message))
  520. def _ParseError(self, message):
  521. """Creates and *returns* a ParseError for the current token."""
  522. return ParseError('%d:%d : %s' % (
  523. self._line + 1, self._column - len(self.token) + 1, message))
  524. def _IntegerParseError(self, e):
  525. return self._ParseError('Couldn\'t parse integer: ' + str(e))
  526. def _FloatParseError(self, e):
  527. return self._ParseError('Couldn\'t parse number: ' + str(e))
  528. def _StringParseError(self, e):
  529. return self._ParseError('Couldn\'t parse string: ' + str(e))
  530. def NextToken(self):
  531. """Reads the next meaningful token."""
  532. self._previous_line = self._line
  533. self._previous_column = self._column
  534. self._column += len(self.token)
  535. self._SkipWhitespace()
  536. if not self._lines and len(self._current_line) <= self._column:
  537. self.token = ''
  538. return
  539. match = self._TOKEN.match(self._current_line, self._column)
  540. if match:
  541. token = match.group(0)
  542. self.token = token
  543. else:
  544. self.token = self._current_line[self._column]
  545. # text.encode('string_escape') does not seem to satisfy our needs as it
  546. # encodes unprintable characters using two-digit hex escapes whereas our
  547. # C++ unescaping function allows hex escapes to be any length. So,
  548. # "\0011".encode('string_escape') ends up being "\\x011", which will be
  549. # decoded in C++ as a single-character string with char code 0x11.
  550. def _CEscape(text, as_utf8):
  551. def escape(c):
  552. o = ord(c)
  553. if o == 10: return r"\n" # optional escape
  554. if o == 13: return r"\r" # optional escape
  555. if o == 9: return r"\t" # optional escape
  556. if o == 39: return r"\'" # optional escape
  557. if o == 34: return r'\"' # necessary escape
  558. if o == 92: return r"\\" # necessary escape
  559. # necessary escapes
  560. if not as_utf8 and (o >= 127 or o < 32): return "\\%03o" % o
  561. return c
  562. return "".join([escape(c) for c in text])
  563. _CUNESCAPE_HEX = re.compile('\\\\x([0-9a-fA-F]{2}|[0-9a-fA-F])')
  564. def _CUnescape(text):
  565. def ReplaceHex(m):
  566. return chr(int(m.group(0)[2:], 16))
  567. # This is required because the 'string_escape' encoding doesn't
  568. # allow single-digit hex escapes (like '\xf').
  569. result = _CUNESCAPE_HEX.sub(ReplaceHex, text)
  570. return result.decode('string_escape')