summaryrefslogtreecommitdiffstats
path: root/third_party/rust/uniffi_bindgen/src/bindings/python/templates/HandleMap.py
blob: f7c13cf745537f5f57eed32c9cb6def52c9e5db9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class _UniffiHandleMap:
    """
    A map where inserting, getting and removing data is synchronized with a lock.
    """

    def __init__(self):
        # type Handle = int
        self._map = {}  # type: Dict[Handle, Any]
        self._lock = threading.Lock()
        self._counter = itertools.count()

    def insert(self, obj):
        with self._lock:
            handle = next(self._counter)
            self._map[handle] = obj
            return handle

    def get(self, handle):
        try:
            with self._lock:
                return self._map[handle]
        except KeyError:
            raise InternalError("UniffiHandleMap.get: Invalid handle")

    def remove(self, handle):
        try:
            with self._lock:
                return self._map.pop(handle)
        except KeyError:
            raise InternalError("UniffiHandleMap.remove: Invalid handle")

    def __len__(self):
        return len(self._map)