text_format.py 20 KB

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