1 // Copyright 2022 The Android Open Source Project 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 // http://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 #pragma once 16 17 #include <list> 18 #include <unordered_map> 19 20 namespace android { 21 namespace base { 22 23 template <typename Key, typename Value> 24 class LruCache { 25 public: LruCache(std::size_t maxSize)26 LruCache(std::size_t maxSize) : m_maxSize(maxSize) { 27 m_table.reserve(maxSize); 28 } 29 get(const Key & key)30 Value* get(const Key& key) { 31 auto tableIt = m_table.find(key); 32 if (tableIt == m_table.end()) { 33 return nullptr; 34 } 35 36 // Move to front. 37 auto elementsIt = tableIt->second; 38 m_elements.splice(elementsIt, m_elements, m_elements.begin()); 39 return &elementsIt->value; 40 } 41 set(const Key & key,Value && value)42 void set(const Key& key, Value&& value) { 43 auto tableIt = m_table.find(key); 44 if (tableIt == m_table.end()) { 45 if (m_table.size() >= m_maxSize) { 46 auto& kv = m_elements.back(); 47 m_table.erase(kv.key); 48 m_elements.pop_back(); 49 } 50 } else { 51 auto elementsIt = tableIt->second; 52 m_elements.erase(elementsIt); 53 } 54 m_elements.emplace_front(KeyValue{ 55 key, 56 std::forward<Value>(value), 57 }); 58 m_table[key] = m_elements.begin(); 59 } 60 remove(const Key & key)61 void remove(const Key& key) { 62 auto tableIt = m_table.find(key); 63 if (tableIt == m_table.end()) { 64 return; 65 } 66 auto elementsIt = tableIt->second; 67 m_elements.erase(elementsIt); 68 m_table.erase(tableIt); 69 } 70 71 private: 72 struct KeyValue { 73 Key key; 74 Value value; 75 }; 76 77 const std::size_t m_maxSize; 78 // Front is the most recently used and back is the least recently used. 79 std::list<KeyValue> m_elements; 80 std::unordered_map<Key, typename std::list<KeyValue>::iterator> m_table; 81 }; 82 83 } // namespace base 84 } // namespace android 85