Adds a new key-value pair to cache, meaning LRU entries might be evicted if required. If the key is already in the cache, the previous metadata is returned. If the size of the metadata is greater than the `memory_limit`, the value is not inserted.
(
&mut self,
key: Path,
value: CachedFileMetadataEntry,
)
| 61 | /// If the key is already in the cache, the previous metadata is returned. |
| 62 | /// If the size of the metadata is greater than the `memory_limit`, the value is not inserted. |
| 63 | fn put( |
| 64 | &mut self, |
| 65 | key: Path, |
| 66 | value: CachedFileMetadataEntry, |
| 67 | ) -> Option<CachedFileMetadataEntry> { |
| 68 | let value_size = value.file_metadata.memory_size(); |
| 69 | |
| 70 | // no point in trying to add this value to the cache if it cannot fit entirely |
| 71 | if value_size > self.memory_limit { |
| 72 | return None; |
| 73 | } |
| 74 | |
| 75 | self.cache_hits.insert(key.clone(), 0); |
| 76 | // if the key is already in the cache, the old value is removed |
| 77 | let old_value = self.lru_queue.put(key, value); |
| 78 | self.memory_used += value_size; |
| 79 | if let Some(ref old_entry) = old_value { |
| 80 | self.memory_used -= old_entry.file_metadata.memory_size(); |
| 81 | } |
| 82 | |
| 83 | self.evict_entries(); |
| 84 | |
| 85 | old_value |
| 86 | } |
| 87 | |
| 88 | /// Evicts entries from the LRU cache until `memory_used` is lower than `memory_limit`. |
| 89 | fn evict_entries(&mut self) { |