aboutsummaryrefslogtreecommitdiff
path: root/services/manager/list.py
blob: 216a561ec9b6be22e84d4192c1bb4394a6999cbc (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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
from __future__ import annotations

from collections.abc import Callable, Iterator
from typing import Any, Generic, Iterable, TypeAlias, TypeVar, overload

from ._error import CruInternalError
from ._iter import CruIterator
from ._const import CruNotFound

_T = TypeVar("_T")
_O = TypeVar("_O")


class CruListEdit(CruIterator[_T]):
    def __init__(self, iterable: Iterable[_T], _list: CruList[Any]) -> None:
        super().__init__(iterable)
        self._list = _list

    def create_me(self, iterable: Iterable[_O]) -> CruListEdit[_O]:
        return CruListEdit(iterable, self._list)

    @property
    def list(self) -> CruList[Any]:
        return self._list

    def done(self) -> CruList[Any]:
        self._list.reset(self)
        return self._list


class CruList(list[_T]):
    def reset(self, new_values: Iterable[_T]):
        if self is new_values:
            new_values = list(new_values)
        self.clear()
        self.extend(new_values)
        return self

    def as_cru_iterator(self) -> CruIterator[_T]:
        return CruIterator(self)

    @staticmethod
    def make(maybe_list: Iterable[_T] | _T | None) -> CruList[_T]:
        if maybe_list is None:
            return CruList()
        if isinstance(maybe_list, Iterable):
            return CruList(maybe_list)
        return CruList([maybe_list])


_K = TypeVar("_K")

_KeyGetter: TypeAlias = Callable[[_T], _K]


class CruUniqueKeyList(Generic[_T, _K]):
    def __init__(
        self,
        key_getter: _KeyGetter[_T, _K],
        *,
        before_add: Callable[[_T], _T] | None = None,
    ):
        super().__init__()
        self._key_getter = key_getter
        self._before_add = before_add
        self._list: CruList[_T] = CruList()

    @property
    def key_getter(self) -> _KeyGetter[_T, _K]:
        return self._key_getter

    @property
    def internal_list(self) -> CruList[_T]:
        return self._list

    def validate_self(self):
        keys = self._list.transform(self._key_getter)
        if len(keys) != len(set(keys)):
            raise CruInternalError("Duplicate keys!")

    @overload
    def get_or(
        self, key: _K, fallback: CruNotFound = CruNotFound.VALUE
    ) -> _T | CruNotFound: ...

    @overload
    def get_or(self, key: _K, fallback: _O) -> _T | _O: ...

    def get_or(
        self, key: _K, fallback: _O | CruNotFound = CruNotFound.VALUE
    ) -> _T | _O | CruNotFound:
        return (
            self._list.as_cru_iterator()
            .filter(lambda v: key == self._key_getter(v))
            .first_or(fallback)
        )

    def get(self, key: _K) -> _T:
        value = self.get_or(key)
        if value is CruNotFound.VALUE:
            raise KeyError(f"Key {key} not found!")
        return value  # type: ignore

    @property
    def keys(self) -> Iterable[_K]:
        return self._list.as_cru_iterator().map(self._key_getter)

    def has_key(self, key: _K) -> bool:
        return self.get_or(key) != CruNotFound.VALUE

    def try_remove(self, key: _K) -> bool:
        value = self.get_or(key)
        if value is CruNotFound.VALUE:
            return False
        self._list.remove(value)
        return True

    def remove(self, key: _K, allow_absence: bool = False) -> None:
        if not self.try_remove(key) and not allow_absence:
            raise KeyError(f"Key {key} not found!")

    def add(self, value: _T, /, replace: bool = False) -> None:
        v = self.get_or(self._key_getter(value))
        if v is not CruNotFound.VALUE:
            if not replace:
                raise KeyError(f"Key {self._key_getter(v)} already exists!")
            self._list.remove(v)
        if self._before_add is not None:
            value = self._before_add(value)
        self._list.append(value)

    def set(self, value: _T) -> None:
        self.add(value, True)

    def extend(self, iterable: Iterable[_T], /, replace: bool = False) -> None:
        values = list(iterable)
        to_remove = []
        for value in values:
            v = self.get_or(self._key_getter(value))
            if v is not CruNotFound.VALUE:
                if not replace:
                    raise KeyError(f"Key {self._key_getter(v)} already exists!")
                to_remove.append(v)
        for value in to_remove:
            self._list.remove(value)
        if self._before_add is not None:
            values = [self._before_add(value) for value in values]
        self._list.extend(values)

    def clear(self) -> None:
        self._list.reset([])

    def __iter__(self) -> Iterator[_T]:
        return iter(self._list)

    def __len__(self) -> int:
        return len(self._list)

    def cru_iter(self) -> CruIterator[_T]:
        return CruIterator(self._list)