containers.py 20 KB

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