diff sat/tools/common/utils.py @ 3292:84f77f04aa08

tools (common/utils): new OrderedSet class
author Goffi <goffi@goffi.org>
date Mon, 08 Jun 2020 08:54:53 +0200
parents 1649bbe8d07e
children be6d91572633
line wrap: on
line diff
--- a/sat/tools/common/utils.py	Mon Jun 01 11:15:16 2020 +0200
+++ b/sat/tools/common/utils.py	Mon Jun 08 08:54:53 2020 +0200
@@ -44,3 +44,32 @@
             ori[k] = v
     return ori
 
+class OrderedSet(collections.abc.MutableSet):
+    """A mutable sequence which doesn't keep duplicates"""
+    # TODO: complete missing set methods
+
+    def __init__(self, values=None):
+        self._dict = {}
+        if values is not None:
+            self.update(values)
+
+    def __len__(self):
+        return len(self._dict)
+
+    def __iter__(self):
+        return iter(self._dict.keys())
+
+    def __contains__(self, item):
+        return item in self._dict
+
+    def add(self, item):
+        self._dict[item] = None
+
+    def discard(self, item):
+        try:
+            del self._dict[item]
+        except KeyError:
+            pass
+
+    def update(self, items):
+        self._dict.update({i: None for i in items})