Files
StarPilot/openpilot/system/ui/lib/lru_cache.py
T
firestar5683 a82935f326 User interfaces and Android Auto
Integrate onroad views, configurable widgets, local settings, steering-profile contracts, Bluetooth and Android Auto with their device and runtime services.

Co-authored-by: Adeeb Shihadeh <adeebshihadeh@gmail.com>
Co-authored-by: Daniel Koepping <elkoled@gmail.com>
Co-authored-by: Danny <dannyirwin31@yahoo.com>
Co-authored-by: DimitriChrysafis <Dimitri.chrysafis@gmail.com>
Co-authored-by: Dom <168790843+firestar5683@users.noreply.github.com>
Co-authored-by: Harald Schäfer <harald.the.engineer@gmail.com>
Co-authored-by: Prabhaav Pillai <prabhaav@msu.edu>
Co-authored-by: Shane Smiskol <shane@smiskol.com>
Co-authored-by: dirwin31 <83434411+dirwin31@users.noreply.github.com>
Co-authored-by: firestarsdog <229254897+firestarsdog@users.noreply.github.com>
Co-authored-by: stef <19478336+stefpi@users.noreply.github.com>
Co-authored-by: whoisdomi <dcantu83@gmail.com>

Co-authored-by: Intelli <contact@intelli.software>
Co-authored-by: pharmacomaniac <blittle65@gmail.com>

Co-authored-by: prabhaavp <prabhaav@msu.edu>
2026-10-14 20:02:39 -05:00

47 lines
1.2 KiB
Python

from collections import OrderedDict
from typing import cast
_MISSING = object()
class LRUCache[K, V]:
"""Small bounded LRU cache.
Unlike an unbounded dict, this caps retained entries so callers that pass
per-frame-varying keys cannot grow memory without limit.
"""
def __init__(self, maxsize: int) -> None:
if maxsize <= 0:
raise ValueError("maxsize must be positive")
self.maxsize = maxsize
self._cache: OrderedDict[K, V] = OrderedDict()
def __contains__(self, key: K) -> bool:
return key in self._cache
def get(self, key: K, default: V | None = None) -> V | None:
value = self._cache.get(key, _MISSING)
if value is _MISSING:
return default
self._cache.move_to_end(key)
return cast(V, value)
def __getitem__(self, key: K) -> V:
value = self._cache[key]
self._cache.move_to_end(key)
return value
def __setitem__(self, key: K, value: V) -> None:
if key in self._cache:
self._cache.move_to_end(key)
self._cache[key] = value
if len(self._cache) > self.maxsize:
self._cache.popitem(last=False)
def __len__(self) -> int:
return len(self._cache)
def clear(self) -> None:
self._cache.clear()