1 /* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 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 16 #ifndef SOC_PERF_COMMON_INCLUDE_LRU_CACHE_H 17 #define SOC_PERF_COMMON_INCLUDE_LRU_CACHE_H 18 19 #include <iostream> 20 #include <list> 21 #include <unordered_map> 22 #include <stdexcept> 23 24 namespace OHOS { 25 namespace SOCPERF { 26 template <typename K, typename V> 27 class SocPerfLRUCache { 28 private: 29 size_t capacity_; 30 std::list<std::pair<K, V>> lruList; 31 std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> relationMap; 32 public: capacity_(capacity)33 SocPerfLRUCache(size_t capacity = 32) : capacity_(capacity) {} get(const K & key,V & value)34 bool get(const K& key, V& value) 35 { 36 if (relationMap.find(key) == relationMap.end()) { 37 return false; 38 } 39 lruList.splice(lruList.begin(), lruList, relationMap[key]); 40 value = relationMap[key]->second; 41 return true; 42 } put(const K & key,const V & value)43 void put(const K& key, const V& value) 44 { 45 if (relationMap.find(key) != relationMap.end()) { 46 if (relationMap[key] != lruList.begin()) { 47 lruList.erase(relationMap[key]); 48 lruList.push_front(std::make_pair(key, value)); 49 relationMap[key] = lruList.begin(); 50 } else { 51 relationMap[key]->second = value; 52 } 53 } else { 54 if (lruList.size() >= capacity_) { 55 relationMap.erase(lruList.back().first); 56 lruList.pop_back(); 57 } 58 lruList.push_front(std::make_pair(key, value)); 59 relationMap[key] = lruList.begin(); 60 } 61 } 62 }; 63 } // namespace SOCPERF 64 } // namespace OHOS 65 #endif // SOC_PERF_COMMON_INCLUDE_LRU_CACHE_H