containers.py 19 KB

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