containers.py 23 KB

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