|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from collections import OrderedDict |
| 16 | + |
| 17 | + |
| 18 | +class LRUCache(dict): |
| 19 | + def __init__(self, maxsize): |
| 20 | + super().__init__() |
| 21 | + self._order = OrderedDict() |
| 22 | + self.maxsize = maxsize |
| 23 | + |
| 24 | + def clear(self): |
| 25 | + super().clear() |
| 26 | + self._order.clear() |
| 27 | + |
| 28 | + def get(self, key, default=None): |
| 29 | + try: |
| 30 | + value = super().__getitem__(key) |
| 31 | + self._update(key) |
| 32 | + return value |
| 33 | + except KeyError: |
| 34 | + return default |
| 35 | + |
| 36 | + def __getitem__(self, key): |
| 37 | + value = super().__getitem__(key) |
| 38 | + self._update(key) |
| 39 | + return value |
| 40 | + |
| 41 | + def __setitem__(self, key, value): |
| 42 | + maxsize = self.maxsize |
| 43 | + if maxsize <= 0: |
| 44 | + return |
| 45 | + if key not in self: |
| 46 | + while len(self) >= maxsize: |
| 47 | + self.popitem() |
| 48 | + super().__setitem__(key, value) |
| 49 | + self._update(key) |
| 50 | + |
| 51 | + def __delitem__(self, key): |
| 52 | + super().__delitem__(key) |
| 53 | + del self._order[key] |
| 54 | + |
| 55 | + def popitem(self): |
| 56 | + """Remove and return the least recently used key-value pair.""" |
| 57 | + key, _ = self._order.popitem(last=False) |
| 58 | + return key, super().pop(key) |
| 59 | + |
| 60 | + def _update(self, key): |
| 61 | + try: |
| 62 | + self._order.move_to_end(key) |
| 63 | + except KeyError: |
| 64 | + self._order[key] = None |
0 commit comments