containers.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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 setdefault(self, key: _K, value: Optional[_V] = None) -> _V:
  344. if value == None:
  345. raise ValueError('The value for scalar map setdefault must be set.')
  346. if key not in self._values:
  347. self.__setitem__(key, value)
  348. return self[key]
  349. def MergeFrom(self, other: 'ScalarMap[_K, _V]') -> None:
  350. self._values.update(other._values)
  351. self._message_listener.Modified()
  352. def InvalidateIterators(self) -> None:
  353. # It appears that the only way to reliably invalidate iterators to
  354. # self._values is to ensure that its size changes.
  355. original = self._values
  356. self._values = original.copy()
  357. original[None] = None
  358. # This is defined in the abstract base, but we can do it much more cheaply.
  359. def clear(self) -> None:
  360. self._values.clear()
  361. self._message_listener.Modified()
  362. def GetEntryClass(self) -> Any:
  363. return self._entry_descriptor._concrete_class
  364. class MessageMap(MutableMapping[_K, _V]):
  365. """Simple, type-checked, dict-like container for with submessage values."""
  366. # Disallows assignment to other attributes.
  367. __slots__ = ['_key_checker', '_values', '_message_listener',
  368. '_message_descriptor', '_entry_descriptor']
  369. def __init__(
  370. self,
  371. message_listener: Any,
  372. message_descriptor: Any,
  373. key_checker: Any,
  374. entry_descriptor: Any,
  375. ) -> None:
  376. """
  377. Args:
  378. message_listener: A MessageListener implementation.
  379. The ScalarMap will call this object's Modified() method when it
  380. is modified.
  381. key_checker: A type_checkers.ValueChecker instance to run on keys
  382. inserted into this container.
  383. value_checker: A type_checkers.ValueChecker instance to run on values
  384. inserted into this container.
  385. entry_descriptor: The MessageDescriptor of a map entry: key and value.
  386. """
  387. self._message_listener = message_listener
  388. self._message_descriptor = message_descriptor
  389. self._key_checker = key_checker
  390. self._entry_descriptor = entry_descriptor
  391. self._values = {}
  392. def __getitem__(self, key: _K) -> _V:
  393. key = self._key_checker.CheckValue(key)
  394. try:
  395. return self._values[key]
  396. except KeyError:
  397. new_element = self._message_descriptor._concrete_class()
  398. new_element._SetListener(self._message_listener)
  399. self._values[key] = new_element
  400. self._message_listener.Modified()
  401. return new_element
  402. def get_or_create(self, key: _K) -> _V:
  403. """get_or_create() is an alias for getitem (ie. map[key]).
  404. Args:
  405. key: The key to get or create in the map.
  406. This is useful in cases where you want to be explicit that the call is
  407. mutating the map. This can avoid lint errors for statements like this
  408. that otherwise would appear to be pointless statements:
  409. msg.my_map[key]
  410. """
  411. return self[key]
  412. @overload
  413. def get(self, key: _K) -> Optional[_V]:
  414. ...
  415. @overload
  416. def get(self, key: _K, default: _T) -> Union[_V, _T]:
  417. ...
  418. # We need to override this explicitly, because our defaultdict-like behavior
  419. # will make the default implementation (from our base class) always insert
  420. # the key.
  421. def get(self, key, default=None):
  422. if key in self:
  423. return self[key]
  424. else:
  425. return default
  426. def __contains__(self, item: _K) -> bool:
  427. item = self._key_checker.CheckValue(item)
  428. return item in self._values
  429. def __setitem__(self, key: _K, value: _V) -> NoReturn:
  430. raise ValueError('May not set values directly, call my_map[key].foo = 5')
  431. def __delitem__(self, key: _K) -> None:
  432. key = self._key_checker.CheckValue(key)
  433. del self._values[key]
  434. self._message_listener.Modified()
  435. def __len__(self) -> int:
  436. return len(self._values)
  437. def __iter__(self) -> Iterator[_K]:
  438. return iter(self._values)
  439. def __repr__(self) -> str:
  440. return repr(self._values)
  441. def setdefault(self, key: _K, value: Optional[_V] = None) -> _V:
  442. raise NotImplementedError(
  443. 'Set message map value directly is not supported, call'
  444. ' my_map[key].foo = 5'
  445. )
  446. def MergeFrom(self, other: 'MessageMap[_K, _V]') -> None:
  447. # pylint: disable=protected-access
  448. for key in other._values:
  449. # According to documentation: "When parsing from the wire or when merging,
  450. # if there are duplicate map keys the last key seen is used".
  451. if key in self:
  452. del self[key]
  453. self[key].CopyFrom(other[key])
  454. # self._message_listener.Modified() not required here, because
  455. # mutations to submessages already propagate.
  456. def InvalidateIterators(self) -> None:
  457. # It appears that the only way to reliably invalidate iterators to
  458. # self._values is to ensure that its size changes.
  459. original = self._values
  460. self._values = original.copy()
  461. original[None] = None
  462. # This is defined in the abstract base, but we can do it much more cheaply.
  463. def clear(self) -> None:
  464. self._values.clear()
  465. self._message_listener.Modified()
  466. def GetEntryClass(self) -> Any:
  467. return self._entry_descriptor._concrete_class
  468. class _UnknownField:
  469. """A parsed unknown field."""
  470. # Disallows assignment to other attributes.
  471. __slots__ = ['_field_number', '_wire_type', '_data']
  472. def __init__(self, field_number, wire_type, data):
  473. self._field_number = field_number
  474. self._wire_type = wire_type
  475. self._data = data
  476. return
  477. def __lt__(self, other):
  478. # pylint: disable=protected-access
  479. return self._field_number < other._field_number
  480. def __eq__(self, other):
  481. if self is other:
  482. return True
  483. # pylint: disable=protected-access
  484. return (self._field_number == other._field_number and
  485. self._wire_type == other._wire_type and
  486. self._data == other._data)
  487. class UnknownFieldRef: # pylint: disable=missing-class-docstring
  488. def __init__(self, parent, index):
  489. self._parent = parent
  490. self._index = index
  491. def _check_valid(self):
  492. if not self._parent:
  493. raise ValueError('UnknownField does not exist. '
  494. 'The parent message might be cleared.')
  495. if self._index >= len(self._parent):
  496. raise ValueError('UnknownField does not exist. '
  497. 'The parent message might be cleared.')
  498. @property
  499. def field_number(self):
  500. self._check_valid()
  501. # pylint: disable=protected-access
  502. return self._parent._internal_get(self._index)._field_number
  503. @property
  504. def wire_type(self):
  505. self._check_valid()
  506. # pylint: disable=protected-access
  507. return self._parent._internal_get(self._index)._wire_type
  508. @property
  509. def data(self):
  510. self._check_valid()
  511. # pylint: disable=protected-access
  512. return self._parent._internal_get(self._index)._data
  513. class UnknownFieldSet:
  514. """UnknownField container"""
  515. # Disallows assignment to other attributes.
  516. __slots__ = ['_values']
  517. def __init__(self):
  518. self._values = []
  519. def __getitem__(self, index):
  520. if self._values is None:
  521. raise ValueError('UnknownFields does not exist. '
  522. 'The parent message might be cleared.')
  523. size = len(self._values)
  524. if index < 0:
  525. index += size
  526. if index < 0 or index >= size:
  527. raise IndexError('index %d out of range'.index)
  528. return UnknownFieldRef(self, index)
  529. def _internal_get(self, index):
  530. return self._values[index]
  531. def __len__(self):
  532. if self._values is None:
  533. raise ValueError('UnknownFields does not exist. '
  534. 'The parent message might be cleared.')
  535. return len(self._values)
  536. def _add(self, field_number, wire_type, data):
  537. unknown_field = _UnknownField(field_number, wire_type, data)
  538. self._values.append(unknown_field)
  539. return unknown_field
  540. def __iter__(self):
  541. for i in range(len(self)):
  542. yield UnknownFieldRef(self, i)
  543. def _extend(self, other):
  544. if other is None:
  545. return
  546. # pylint: disable=protected-access
  547. self._values.extend(other._values)
  548. def __eq__(self, other):
  549. if self is other:
  550. return True
  551. # Sort unknown fields because their order shouldn't
  552. # affect equality test.
  553. values = list(self._values)
  554. if other is None:
  555. return not values
  556. values.sort()
  557. # pylint: disable=protected-access
  558. other_values = sorted(other._values)
  559. return values == other_values
  560. def _clear(self):
  561. for value in self._values:
  562. # pylint: disable=protected-access
  563. if isinstance(value._data, UnknownFieldSet):
  564. value._data._clear() # pylint: disable=protected-access
  565. self._values = None