containers.py 21 KB

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