图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

710 lines
23 KiB

  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. """Contains container classes to represent different protocol buffer types.
  31. This file defines container classes which represent categories of protocol
  32. buffer field types which need extra maintenance. Currently these categories
  33. are:
  34. - Repeated scalar fields - These are all repeated fields which aren't
  35. composite (e.g. they are of simple types like int32, string, etc).
  36. - Repeated composite fields - Repeated fields which are composite. This
  37. includes groups and nested messages.
  38. """
  39. import collections.abc
  40. import copy
  41. import pickle
  42. from typing import (
  43. Any,
  44. Iterable,
  45. Iterator,
  46. List,
  47. MutableMapping,
  48. MutableSequence,
  49. NoReturn,
  50. Optional,
  51. Sequence,
  52. TypeVar,
  53. Union,
  54. overload,
  55. )
  56. _T = TypeVar('_T')
  57. _K = TypeVar('_K')
  58. _V = TypeVar('_V')
  59. class BaseContainer(Sequence[_T]):
  60. """Base container class."""
  61. # Minimizes memory usage and disallows assignment to other attributes.
  62. __slots__ = ['_message_listener', '_values']
  63. def __init__(self, message_listener: Any) -> None:
  64. """
  65. Args:
  66. message_listener: A MessageListener implementation.
  67. The RepeatedScalarFieldContainer will call this object's
  68. Modified() method when it is modified.
  69. """
  70. self._message_listener = message_listener
  71. self._values = []
  72. @overload
  73. def __getitem__(self, key: int) -> _T:
  74. ...
  75. @overload
  76. def __getitem__(self, key: slice) -> List[_T]:
  77. ...
  78. def __getitem__(self, key):
  79. """Retrieves item by the specified key."""
  80. return self._values[key]
  81. def __len__(self) -> int:
  82. """Returns the number of elements in the container."""
  83. return len(self._values)
  84. def __ne__(self, other: Any) -> bool:
  85. """Checks if another instance isn't equal to this one."""
  86. # The concrete classes should define __eq__.
  87. return not self == other
  88. __hash__ = None
  89. def __repr__(self) -> str:
  90. return repr(self._values)
  91. def sort(self, *args, **kwargs) -> None:
  92. # Continue to support the old sort_function keyword argument.
  93. # This is expected to be a rare occurrence, so use LBYL to avoid
  94. # the overhead of actually catching KeyError.
  95. if 'sort_function' in kwargs:
  96. kwargs['cmp'] = kwargs.pop('sort_function')
  97. self._values.sort(*args, **kwargs)
  98. def reverse(self) -> None:
  99. self._values.reverse()
  100. # TODO(slebedev): Remove this. BaseContainer does *not* conform to
  101. # MutableSequence, only its subclasses do.
  102. collections.abc.MutableSequence.register(BaseContainer)
  103. class RepeatedScalarFieldContainer(BaseContainer[_T], MutableSequence[_T]):
  104. """Simple, type-checked, list-like container for holding repeated scalars."""
  105. # Disallows assignment to other attributes.
  106. __slots__ = ['_type_checker']
  107. def __init__(
  108. self,
  109. message_listener: Any,
  110. type_checker: Any,
  111. ) -> None:
  112. """Args:
  113. message_listener: A MessageListener implementation. The
  114. RepeatedScalarFieldContainer will call this object's Modified() method
  115. when it is modified.
  116. type_checker: A type_checkers.ValueChecker instance to run on elements
  117. inserted into this container.
  118. """
  119. super().__init__(message_listener)
  120. self._type_checker = type_checker
  121. def append(self, value: _T) -> None:
  122. """Appends an item to the list. Similar to list.append()."""
  123. self._values.append(self._type_checker.CheckValue(value))
  124. if not self._message_listener.dirty:
  125. self._message_listener.Modified()
  126. def insert(self, key: int, value: _T) -> None:
  127. """Inserts the item at the specified position. Similar to list.insert()."""
  128. self._values.insert(key, self._type_checker.CheckValue(value))
  129. if not self._message_listener.dirty:
  130. self._message_listener.Modified()
  131. def extend(self, elem_seq: Iterable[_T]) -> None:
  132. """Extends by appending the given iterable. Similar to list.extend()."""
  133. # TODO(b/286557203): Change OSS to raise error too
  134. if elem_seq is None:
  135. return
  136. try:
  137. elem_seq_iter = iter(elem_seq)
  138. except TypeError:
  139. if not elem_seq:
  140. warnings.warn('Value is not iterable. Please remove the wrong '
  141. 'usage. This will be changed to raise TypeError soon.')
  142. return
  143. raise
  144. new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter]
  145. if new_values:
  146. self._values.extend(new_values)
  147. self._message_listener.Modified()
  148. def MergeFrom(
  149. self,
  150. other: Union['RepeatedScalarFieldContainer[_T]', Iterable[_T]],
  151. ) -> None:
  152. """Appends the contents of another repeated field of the same type to this
  153. one. We do not check the types of the individual fields.
  154. """
  155. self._values.extend(other)
  156. self._message_listener.Modified()
  157. def remove(self, elem: _T):
  158. """Removes an item from the list. Similar to list.remove()."""
  159. self._values.remove(elem)
  160. self._message_listener.Modified()
  161. def pop(self, key: Optional[int] = -1) -> _T:
  162. """Removes and returns an item at a given index. Similar to list.pop()."""
  163. value = self._values[key]
  164. self.__delitem__(key)
  165. return value
  166. @overload
  167. def __setitem__(self, key: int, value: _T) -> None:
  168. ...
  169. @overload
  170. def __setitem__(self, key: slice, value: Iterable[_T]) -> None:
  171. ...
  172. def __setitem__(self, key, value) -> None:
  173. """Sets the item on the specified position."""
  174. if isinstance(key, slice):
  175. if key.step is not None:
  176. raise ValueError('Extended slices not supported')
  177. self._values[key] = map(self._type_checker.CheckValue, value)
  178. self._message_listener.Modified()
  179. else:
  180. self._values[key] = self._type_checker.CheckValue(value)
  181. self._message_listener.Modified()
  182. def __delitem__(self, key: Union[int, slice]) -> None:
  183. """Deletes the item at the specified position."""
  184. del self._values[key]
  185. self._message_listener.Modified()
  186. def __eq__(self, other: Any) -> bool:
  187. """Compares the current instance with another one."""
  188. if self is other:
  189. return True
  190. # Special case for the same type which should be common and fast.
  191. if isinstance(other, self.__class__):
  192. return other._values == self._values
  193. # We are presumably comparing against some other sequence type.
  194. return other == self._values
  195. def __deepcopy__(
  196. self,
  197. unused_memo: Any = None,
  198. ) -> 'RepeatedScalarFieldContainer[_T]':
  199. clone = RepeatedScalarFieldContainer(
  200. copy.deepcopy(self._message_listener), self._type_checker)
  201. clone.MergeFrom(self)
  202. return clone
  203. def __reduce__(self, **kwargs) -> NoReturn:
  204. raise pickle.PickleError(
  205. "Can't pickle repeated scalar fields, convert to list first")
  206. # TODO(slebedev): Constrain T to be a subtype of Message.
  207. class RepeatedCompositeFieldContainer(BaseContainer[_T], MutableSequence[_T]):
  208. """Simple, list-like container for holding repeated composite fields."""
  209. # Disallows assignment to other attributes.
  210. __slots__ = ['_message_descriptor']
  211. def __init__(self, message_listener: Any, message_descriptor: Any) -> None:
  212. """
  213. Note that we pass in a descriptor instead of the generated directly,
  214. since at the time we construct a _RepeatedCompositeFieldContainer we
  215. haven't yet necessarily initialized the type that will be contained in the
  216. container.
  217. Args:
  218. message_listener: A MessageListener implementation.
  219. The RepeatedCompositeFieldContainer will call this object's
  220. Modified() method when it is modified.
  221. message_descriptor: A Descriptor instance describing the protocol type
  222. that should be present in this container. We'll use the
  223. _concrete_class field of this descriptor when the client calls add().
  224. """
  225. super().__init__(message_listener)
  226. self._message_descriptor = message_descriptor
  227. def add(self, **kwargs: Any) -> _T:
  228. """Adds a new element at the end of the list and returns it. Keyword
  229. arguments may be used to initialize the element.
  230. """
  231. new_element = self._message_descriptor._concrete_class(**kwargs)
  232. new_element._SetListener(self._message_listener)
  233. self._values.append(new_element)
  234. if not self._message_listener.dirty:
  235. self._message_listener.Modified()
  236. return new_element
  237. def append(self, value: _T) -> None:
  238. """Appends one element by copying the message."""
  239. new_element = self._message_descriptor._concrete_class()
  240. new_element._SetListener(self._message_listener)
  241. new_element.CopyFrom(value)
  242. self._values.append(new_element)
  243. if not self._message_listener.dirty:
  244. self._message_listener.Modified()
  245. def insert(self, key: int, value: _T) -> None:
  246. """Inserts the item at the specified position by copying."""
  247. new_element = self._message_descriptor._concrete_class()
  248. new_element._SetListener(self._message_listener)
  249. new_element.CopyFrom(value)
  250. self._values.insert(key, new_element)
  251. if not self._message_listener.dirty:
  252. self._message_listener.Modified()
  253. def extend(self, elem_seq: Iterable[_T]) -> None:
  254. """Extends by appending the given sequence of elements of the same type
  255. as this one, copying each individual message.
  256. """
  257. message_class = self._message_descriptor._concrete_class
  258. listener = self._message_listener
  259. values = self._values
  260. for message in elem_seq:
  261. new_element = message_class()
  262. new_element._SetListener(listener)
  263. new_element.MergeFrom(message)
  264. values.append(new_element)
  265. listener.Modified()
  266. def MergeFrom(
  267. self,
  268. other: Union['RepeatedCompositeFieldContainer[_T]', Iterable[_T]],
  269. ) -> None:
  270. """Appends the contents of another repeated field of the same type to this
  271. one, copying each individual message.
  272. """
  273. self.extend(other)
  274. def remove(self, elem: _T) -> None:
  275. """Removes an item from the list. Similar to list.remove()."""
  276. self._values.remove(elem)
  277. self._message_listener.Modified()
  278. def pop(self, key: Optional[int] = -1) -> _T:
  279. """Removes and returns an item at a given index. Similar to list.pop()."""
  280. value = self._values[key]
  281. self.__delitem__(key)
  282. return value
  283. @overload
  284. def __setitem__(self, key: int, value: _T) -> None:
  285. ...
  286. @overload
  287. def __setitem__(self, key: slice, value: Iterable[_T]) -> None:
  288. ...
  289. def __setitem__(self, key, value):
  290. # This method is implemented to make RepeatedCompositeFieldContainer
  291. # structurally compatible with typing.MutableSequence. It is
  292. # otherwise unsupported and will always raise an error.
  293. raise TypeError(
  294. f'{self.__class__.__name__} object does not support item assignment')
  295. def __delitem__(self, key: Union[int, slice]) -> None:
  296. """Deletes the item at the specified position."""
  297. del self._values[key]
  298. self._message_listener.Modified()
  299. def __eq__(self, other: Any) -> bool:
  300. """Compares the current instance with another one."""
  301. if self is other:
  302. return True
  303. if not isinstance(other, self.__class__):
  304. raise TypeError('Can only compare repeated composite fields against '
  305. 'other repeated composite fields.')
  306. return self._values == other._values
  307. class ScalarMap(MutableMapping[_K, _V]):
  308. """Simple, type-checked, dict-like container for holding repeated scalars."""
  309. # Disallows assignment to other attributes.
  310. __slots__ = ['_key_checker', '_value_checker', '_values', '_message_listener',
  311. '_entry_descriptor']
  312. def __init__(
  313. self,
  314. message_listener: Any,
  315. key_checker: Any,
  316. value_checker: Any,
  317. entry_descriptor: Any,
  318. ) -> None:
  319. """
  320. Args:
  321. message_listener: A MessageListener implementation.
  322. The ScalarMap will call this object's Modified() method when it
  323. is modified.
  324. key_checker: A type_checkers.ValueChecker instance to run on keys
  325. inserted into this container.
  326. value_checker: A type_checkers.ValueChecker instance to run on values
  327. inserted into this container.
  328. entry_descriptor: The MessageDescriptor of a map entry: key and value.
  329. """
  330. self._message_listener = message_listener
  331. self._key_checker = key_checker
  332. self._value_checker = value_checker
  333. self._entry_descriptor = entry_descriptor
  334. self._values = {}
  335. def __getitem__(self, key: _K) -> _V:
  336. try:
  337. return self._values[key]
  338. except KeyError:
  339. key = self._key_checker.CheckValue(key)
  340. val = self._value_checker.DefaultValue()
  341. self._values[key] = val
  342. return val
  343. def __contains__(self, item: _K) -> bool:
  344. # We check the key's type to match the strong-typing flavor of the API.
  345. # Also this makes it easier to match the behavior of the C++ implementation.
  346. self._key_checker.CheckValue(item)
  347. return item in self._values
  348. @overload
  349. def get(self, key: _K) -> Optional[_V]:
  350. ...
  351. @overload
  352. def get(self, key: _K, default: _T) -> Union[_V, _T]:
  353. ...
  354. # We need to override this explicitly, because our defaultdict-like behavior
  355. # will make the default implementation (from our base class) always insert
  356. # the key.
  357. def get(self, key, default=None):
  358. if key in self:
  359. return self[key]
  360. else:
  361. return default
  362. def __setitem__(self, key: _K, value: _V) -> _T:
  363. checked_key = self._key_checker.CheckValue(key)
  364. checked_value = self._value_checker.CheckValue(value)
  365. self._values[checked_key] = checked_value
  366. self._message_listener.Modified()
  367. def __delitem__(self, key: _K) -> None:
  368. del self._values[key]
  369. self._message_listener.Modified()
  370. def __len__(self) -> int:
  371. return len(self._values)
  372. def __iter__(self) -> Iterator[_K]:
  373. return iter(self._values)
  374. def __repr__(self) -> str:
  375. return repr(self._values)
  376. def MergeFrom(self, other: 'ScalarMap[_K, _V]') -> None:
  377. self._values.update(other._values)
  378. self._message_listener.Modified()
  379. def InvalidateIterators(self) -> None:
  380. # It appears that the only way to reliably invalidate iterators to
  381. # self._values is to ensure that its size changes.
  382. original = self._values
  383. self._values = original.copy()
  384. original[None] = None
  385. # This is defined in the abstract base, but we can do it much more cheaply.
  386. def clear(self) -> None:
  387. self._values.clear()
  388. self._message_listener.Modified()
  389. def GetEntryClass(self) -> Any:
  390. return self._entry_descriptor._concrete_class
  391. class MessageMap(MutableMapping[_K, _V]):
  392. """Simple, type-checked, dict-like container for with submessage values."""
  393. # Disallows assignment to other attributes.
  394. __slots__ = ['_key_checker', '_values', '_message_listener',
  395. '_message_descriptor', '_entry_descriptor']
  396. def __init__(
  397. self,
  398. message_listener: Any,
  399. message_descriptor: Any,
  400. key_checker: Any,
  401. entry_descriptor: Any,
  402. ) -> None:
  403. """
  404. Args:
  405. message_listener: A MessageListener implementation.
  406. The ScalarMap will call this object's Modified() method when it
  407. is modified.
  408. key_checker: A type_checkers.ValueChecker instance to run on keys
  409. inserted into this container.
  410. value_checker: A type_checkers.ValueChecker instance to run on values
  411. inserted into this container.
  412. entry_descriptor: The MessageDescriptor of a map entry: key and value.
  413. """
  414. self._message_listener = message_listener
  415. self._message_descriptor = message_descriptor
  416. self._key_checker = key_checker
  417. self._entry_descriptor = entry_descriptor
  418. self._values = {}
  419. def __getitem__(self, key: _K) -> _V:
  420. key = self._key_checker.CheckValue(key)
  421. try:
  422. return self._values[key]
  423. except KeyError:
  424. new_element = self._message_descriptor._concrete_class()
  425. new_element._SetListener(self._message_listener)
  426. self._values[key] = new_element
  427. self._message_listener.Modified()
  428. return new_element
  429. def get_or_create(self, key: _K) -> _V:
  430. """get_or_create() is an alias for getitem (ie. map[key]).
  431. Args:
  432. key: The key to get or create in the map.
  433. This is useful in cases where you want to be explicit that the call is
  434. mutating the map. This can avoid lint errors for statements like this
  435. that otherwise would appear to be pointless statements:
  436. msg.my_map[key]
  437. """
  438. return self[key]
  439. @overload
  440. def get(self, key: _K) -> Optional[_V]:
  441. ...
  442. @overload
  443. def get(self, key: _K, default: _T) -> Union[_V, _T]:
  444. ...
  445. # We need to override this explicitly, because our defaultdict-like behavior
  446. # will make the default implementation (from our base class) always insert
  447. # the key.
  448. def get(self, key, default=None):
  449. if key in self:
  450. return self[key]
  451. else:
  452. return default
  453. def __contains__(self, item: _K) -> bool:
  454. item = self._key_checker.CheckValue(item)
  455. return item in self._values
  456. def __setitem__(self, key: _K, value: _V) -> NoReturn:
  457. raise ValueError('May not set values directly, call my_map[key].foo = 5')
  458. def __delitem__(self, key: _K) -> None:
  459. key = self._key_checker.CheckValue(key)
  460. del self._values[key]
  461. self._message_listener.Modified()
  462. def __len__(self) -> int:
  463. return len(self._values)
  464. def __iter__(self) -> Iterator[_K]:
  465. return iter(self._values)
  466. def __repr__(self) -> str:
  467. return repr(self._values)
  468. def MergeFrom(self, other: 'MessageMap[_K, _V]') -> None:
  469. # pylint: disable=protected-access
  470. for key in other._values:
  471. # According to documentation: "When parsing from the wire or when merging,
  472. # if there are duplicate map keys the last key seen is used".
  473. if key in self:
  474. del self[key]
  475. self[key].CopyFrom(other[key])
  476. # self._message_listener.Modified() not required here, because
  477. # mutations to submessages already propagate.
  478. def InvalidateIterators(self) -> None:
  479. # It appears that the only way to reliably invalidate iterators to
  480. # self._values is to ensure that its size changes.
  481. original = self._values
  482. self._values = original.copy()
  483. original[None] = None
  484. # This is defined in the abstract base, but we can do it much more cheaply.
  485. def clear(self) -> None:
  486. self._values.clear()
  487. self._message_listener.Modified()
  488. def GetEntryClass(self) -> Any:
  489. return self._entry_descriptor._concrete_class
  490. class _UnknownField:
  491. """A parsed unknown field."""
  492. # Disallows assignment to other attributes.
  493. __slots__ = ['_field_number', '_wire_type', '_data']
  494. def __init__(self, field_number, wire_type, data):
  495. self._field_number = field_number
  496. self._wire_type = wire_type
  497. self._data = data
  498. return
  499. def __lt__(self, other):
  500. # pylint: disable=protected-access
  501. return self._field_number < other._field_number
  502. def __eq__(self, other):
  503. if self is other:
  504. return True
  505. # pylint: disable=protected-access
  506. return (self._field_number == other._field_number and
  507. self._wire_type == other._wire_type and
  508. self._data == other._data)
  509. class UnknownFieldRef: # pylint: disable=missing-class-docstring
  510. def __init__(self, parent, index):
  511. self._parent = parent
  512. self._index = index
  513. def _check_valid(self):
  514. if not self._parent:
  515. raise ValueError('UnknownField does not exist. '
  516. 'The parent message might be cleared.')
  517. if self._index >= len(self._parent):
  518. raise ValueError('UnknownField does not exist. '
  519. 'The parent message might be cleared.')
  520. @property
  521. def field_number(self):
  522. self._check_valid()
  523. # pylint: disable=protected-access
  524. return self._parent._internal_get(self._index)._field_number
  525. @property
  526. def wire_type(self):
  527. self._check_valid()
  528. # pylint: disable=protected-access
  529. return self._parent._internal_get(self._index)._wire_type
  530. @property
  531. def data(self):
  532. self._check_valid()
  533. # pylint: disable=protected-access
  534. return self._parent._internal_get(self._index)._data
  535. class UnknownFieldSet:
  536. """UnknownField container"""
  537. # Disallows assignment to other attributes.
  538. __slots__ = ['_values']
  539. def __init__(self):
  540. self._values = []
  541. def __getitem__(self, index):
  542. if self._values is None:
  543. raise ValueError('UnknownFields does not exist. '
  544. 'The parent message might be cleared.')
  545. size = len(self._values)
  546. if index < 0:
  547. index += size
  548. if index < 0 or index >= size:
  549. raise IndexError('index %d out of range'.index)
  550. return UnknownFieldRef(self, index)
  551. def _internal_get(self, index):
  552. return self._values[index]
  553. def __len__(self):
  554. if self._values is None:
  555. raise ValueError('UnknownFields does not exist. '
  556. 'The parent message might be cleared.')
  557. return len(self._values)
  558. def _add(self, field_number, wire_type, data):
  559. unknown_field = _UnknownField(field_number, wire_type, data)
  560. self._values.append(unknown_field)
  561. return unknown_field
  562. def __iter__(self):
  563. for i in range(len(self)):
  564. yield UnknownFieldRef(self, i)
  565. def _extend(self, other):
  566. if other is None:
  567. return
  568. # pylint: disable=protected-access
  569. self._values.extend(other._values)
  570. def __eq__(self, other):
  571. if self is other:
  572. return True
  573. # Sort unknown fields because their order shouldn't
  574. # affect equality test.
  575. values = list(self._values)
  576. if other is None:
  577. return not values
  578. values.sort()
  579. # pylint: disable=protected-access
  580. other_values = sorted(other._values)
  581. return values == other_values
  582. def _clear(self):
  583. for value in self._values:
  584. # pylint: disable=protected-access
  585. if isinstance(value._data, UnknownFieldSet):
  586. value._data._clear() # pylint: disable=protected-access
  587. self._values = None