set.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. import itertools
  17. import sys
  18. if sys.version_info >= (3, 7):
  19. odict = dict
  20. else:
  21. from collections import OrderedDict as odict # pragma: no cover
  22. class Set:
  23. """A simple set class.
  24. This class was originally used to deal with sets being missing in
  25. ancient versions of python, but dnspython will continue to use it
  26. as these sets are based on lists and are thus indexable, and this
  27. ability is widely used in dnspython applications.
  28. """
  29. __slots__ = ['items']
  30. def __init__(self, items=None):
  31. """Initialize the set.
  32. *items*, an iterable or ``None``, the initial set of items.
  33. """
  34. self.items = odict()
  35. if items is not None:
  36. for item in items:
  37. self.add(item)
  38. def __repr__(self):
  39. return "dns.set.Set(%s)" % repr(list(self.items.keys()))
  40. def add(self, item):
  41. """Add an item to the set.
  42. """
  43. if item not in self.items:
  44. self.items[item] = None
  45. def remove(self, item):
  46. """Remove an item from the set.
  47. """
  48. try:
  49. del self.items[item]
  50. except KeyError:
  51. raise ValueError
  52. def discard(self, item):
  53. """Remove an item from the set if present.
  54. """
  55. self.items.pop(item, None)
  56. def _clone(self):
  57. """Make a (shallow) copy of the set.
  58. There is a 'clone protocol' that subclasses of this class
  59. should use. To make a copy, first call your super's _clone()
  60. method, and use the object returned as the new instance. Then
  61. make shallow copies of the attributes defined in the subclass.
  62. This protocol allows us to write the set algorithms that
  63. return new instances (e.g. union) once, and keep using them in
  64. subclasses.
  65. """
  66. if hasattr(self, '_clone_class'):
  67. cls = self._clone_class
  68. else:
  69. cls = self.__class__
  70. obj = cls.__new__(cls)
  71. obj.items = odict()
  72. obj.items.update(self.items)
  73. return obj
  74. def __copy__(self):
  75. """Make a (shallow) copy of the set.
  76. """
  77. return self._clone()
  78. def copy(self):
  79. """Make a (shallow) copy of the set.
  80. """
  81. return self._clone()
  82. def union_update(self, other):
  83. """Update the set, adding any elements from other which are not
  84. already in the set.
  85. """
  86. if not isinstance(other, Set):
  87. raise ValueError('other must be a Set instance')
  88. if self is other:
  89. return
  90. for item in other.items:
  91. self.add(item)
  92. def intersection_update(self, other):
  93. """Update the set, removing any elements from other which are not
  94. in both sets.
  95. """
  96. if not isinstance(other, Set):
  97. raise ValueError('other must be a Set instance')
  98. if self is other:
  99. return
  100. # we make a copy of the list so that we can remove items from
  101. # the list without breaking the iterator.
  102. for item in list(self.items):
  103. if item not in other.items:
  104. del self.items[item]
  105. def difference_update(self, other):
  106. """Update the set, removing any elements from other which are in
  107. the set.
  108. """
  109. if not isinstance(other, Set):
  110. raise ValueError('other must be a Set instance')
  111. if self is other:
  112. self.items.clear()
  113. else:
  114. for item in other.items:
  115. self.discard(item)
  116. def union(self, other):
  117. """Return a new set which is the union of ``self`` and ``other``.
  118. Returns the same Set type as this set.
  119. """
  120. obj = self._clone()
  121. obj.union_update(other)
  122. return obj
  123. def intersection(self, other):
  124. """Return a new set which is the intersection of ``self`` and
  125. ``other``.
  126. Returns the same Set type as this set.
  127. """
  128. obj = self._clone()
  129. obj.intersection_update(other)
  130. return obj
  131. def difference(self, other):
  132. """Return a new set which ``self`` - ``other``, i.e. the items
  133. in ``self`` which are not also in ``other``.
  134. Returns the same Set type as this set.
  135. """
  136. obj = self._clone()
  137. obj.difference_update(other)
  138. return obj
  139. def __or__(self, other):
  140. return self.union(other)
  141. def __and__(self, other):
  142. return self.intersection(other)
  143. def __add__(self, other):
  144. return self.union(other)
  145. def __sub__(self, other):
  146. return self.difference(other)
  147. def __ior__(self, other):
  148. self.union_update(other)
  149. return self
  150. def __iand__(self, other):
  151. self.intersection_update(other)
  152. return self
  153. def __iadd__(self, other):
  154. self.union_update(other)
  155. return self
  156. def __isub__(self, other):
  157. self.difference_update(other)
  158. return self
  159. def update(self, other):
  160. """Update the set, adding any elements from other which are not
  161. already in the set.
  162. *other*, the collection of items with which to update the set, which
  163. may be any iterable type.
  164. """
  165. for item in other:
  166. self.add(item)
  167. def clear(self):
  168. """Make the set empty."""
  169. self.items.clear()
  170. def __eq__(self, other):
  171. if odict == dict:
  172. return self.items == other.items
  173. else:
  174. # We don't want an ordered comparison.
  175. if len(self.items) != len(other.items):
  176. return False
  177. return all(elt in other.items for elt in self.items)
  178. def __ne__(self, other):
  179. return not self.__eq__(other)
  180. def __len__(self):
  181. return len(self.items)
  182. def __iter__(self):
  183. return iter(self.items)
  184. def __getitem__(self, i):
  185. if isinstance(i, slice):
  186. return list(itertools.islice(self.items, i.start, i.stop, i.step))
  187. else:
  188. return next(itertools.islice(self.items, i, i + 1))
  189. def __delitem__(self, i):
  190. if isinstance(i, slice):
  191. for elt in list(self[i]):
  192. del self.items[elt]
  193. else:
  194. del self.items[self[i]]
  195. def issubset(self, other):
  196. """Is this set a subset of *other*?
  197. Returns a ``bool``.
  198. """
  199. if not isinstance(other, Set):
  200. raise ValueError('other must be a Set instance')
  201. for item in self.items:
  202. if item not in other.items:
  203. return False
  204. return True
  205. def issuperset(self, other):
  206. """Is this set a superset of *other*?
  207. Returns a ``bool``.
  208. """
  209. if not isinstance(other, Set):
  210. raise ValueError('other must be a Set instance')
  211. for item in other.items:
  212. if item not in self.items:
  213. return False
  214. return True