containers.py 25 KB

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