gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.5KB

  1. import collections
  2. import threading
  3. import typing
  4. from collections.abc import Iterable, Iterator, MutableMapping
  5. from .func import locked
  6. __all__ = ['LRU']
  7. K = typing.TypeVar('K')
  8. V = typing.TypeVar('V')
  9. class LRU(MutableMapping[K, V], typing.Generic[K, V]):
  10. """
  11. Implementation of a length-limited O(1) LRU map.
  12. Original Copyright 2003 Josiah Carlson, later rebuilt on OrderedDict and added typing.
  13. """
  14. def __init__(self, count: int, pairs: Iterable[tuple[K, V]] = ()):
  15. self._lock = threading.RLock()
  16. self.count = max(count, 1)
  17. self.d: collections.OrderedDict[K, V] = collections.OrderedDict()
  18. for key, value in pairs:
  19. self[key] = value
  20. @locked
  21. def __contains__(self, obj: K) -> bool:
  22. return obj in self.d
  23. @locked
  24. def __getitem__(self, obj: K) -> V:
  25. a = self.d[obj]
  26. self.d.move_to_end(obj, last=False)
  27. return a
  28. @locked
  29. def __setitem__(self, obj: K, val: V):
  30. self.d[obj] = val
  31. self.d.move_to_end(obj, last=False)
  32. while len(self.d) > self.count:
  33. self.d.popitem(last=True)
  34. @locked
  35. def __delitem__(self, obj: K):
  36. del self.d[obj]
  37. @locked
  38. def __len__(self) -> int:
  39. return len(self.d)
  40. @locked
  41. def __iter__(self) -> Iterator[K]:
  42. return iter(self.d)
  43. @locked
  44. def pop(self, key: K) -> V:
  45. return self.d.pop(key)
  46. @locked
  47. def clear(self):
  48. self.d.clear()
上海开阖软件有限公司 沪ICP备12045867号-1