MCPcopy Create free account
hub / github.com/nodejs/node / LRUCache

Class LRUCache

deps/v8/third_party/jinja2/utils.py:421–567  ·  view source on GitHub ↗

A simple LRU Cache implementation.

Source from the content-addressed store, hash-verified

419
420@abc.MutableMapping.register
421class LRUCache:
422 """A simple LRU Cache implementation."""
423
424 # this is fast for small capacities (something below 1000) but doesn't
425 # scale. But as long as it's only used as storage for templates this
426 # won't do any harm.
427
428 def __init__(self, capacity: int) -> None:
429 self.capacity = capacity
430 self._mapping: t.Dict[t.Any, t.Any] = {}
431 self._queue: "te.Deque[t.Any]" = deque()
432 self._postinit()
433
434 def _postinit(self) -> None:
435 # alias all queue methods for faster lookup
436 self._popleft = self._queue.popleft
437 self._pop = self._queue.pop
438 self._remove = self._queue.remove
439 self._wlock = Lock()
440 self._append = self._queue.append
441
442 def __getstate__(self) -> t.Mapping[str, t.Any]:
443 return {
444 "capacity": self.capacity,
445 "_mapping": self._mapping,
446 "_queue": self._queue,
447 }
448
449 def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:
450 self.__dict__.update(d)
451 self._postinit()
452
453 def __getnewargs__(self) -> t.Tuple:
454 return (self.capacity,)
455
456 def copy(self) -> "LRUCache":
457 """Return a shallow copy of the instance."""
458 rv = self.__class__(self.capacity)
459 rv._mapping.update(self._mapping)
460 rv._queue.extend(self._queue)
461 return rv
462
463 def get(self, key: t.Any, default: t.Any = None) -> t.Any:
464 """Return an item from the cache dict or `default`"""
465 try:
466 return self[key]
467 except KeyError:
468 return default
469
470 def setdefault(self, key: t.Any, default: t.Any = None) -> t.Any:
471 """Set `default` if the key is not in the cache otherwise
472 leave unchanged. Return the value of this key.
473 """
474 try:
475 return self[key]
476 except KeyError:
477 self[key] = default
478 return default

Callers 3

create_cacheFunction · 0.70
copy_cacheFunction · 0.70
lexer.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected