• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 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 APP_DOMAIN_VERIFY_APP_DETAILS_LRU_H
17 #define APP_DOMAIN_VERIFY_APP_DETAILS_LRU_H
18 
19 #include <string>
20 #include <unordered_map>
21 #include <list>
22 #include <mutex>
23 #include <memory>
24 
25 namespace OHOS {
26 namespace AppDomainVerify {
27 template <typename K, typename V>
28 class LruCacheUtil {
29 public:
30     LruCacheUtil<K, V>() = default;
maxCap_(maxCap)31     LruCacheUtil<K, V>(size_t maxCap):maxCap_(maxCap){};
32     bool SetMaxCap(size_t cap);
33     bool Get(const K& key, V& value);
34     void Put(const K& key, const V& value);
35     void Clear();
36     bool IsEmpty();
37 private:
38     std::atomic<size_t> maxCap_ = 10;
39     std::list<std::pair<K, V>> cache_;
40     std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> lruMap_;
41 };
42 
43 template<typename K, typename V>
SetMaxCap(size_t cap)44 bool LruCacheUtil<K, V>::SetMaxCap(size_t cap)
45 {
46     maxCap_ = cap;
47 };
48 
49 template<typename K, typename V>
Get(const K & key,V & value)50 bool LruCacheUtil<K, V>::Get(const K& key, V& value)
51 {
52     if (lruMap_.find(key) == lruMap_.end()) {
53         return false;
54     }
55     value = lruMap_[key]->second;
56     cache_.erase(lruMap_[key]);
57     cache_.push_front({key, value});
58     lruMap_[key] = cache_.begin();
59     return true;
60 };
61 
62 template<typename K, typename V>
Put(const K & key,const V & value)63 void LruCacheUtil<K, V>::Put(const K& key, const V& value)
64 {
65     auto iter = lruMap_.find(key);
66     if (iter != lruMap_.end()) {
67         V val = lruMap_[key]->second;
68         cache_.erase(iter->second);
69         cache_.push_front({key, val});
70         lruMap_[key] = cache_.begin();
71         return;
72     }
73     if (lruMap_.size() == maxCap_) {
74         lruMap_.erase(cache_.back().first);
75         cache_.pop_back();
76     }
77     cache_.push_front({key, value});
78     lruMap_[key] = cache_.begin();
79     return;
80 };
81 
82 template<typename K, typename V>
Clear()83 void LruCacheUtil<K, V>::Clear()
84 {
85     cache_.clear();
86     lruMap_.clear();
87 };
88 
89 template<typename K, typename V>
IsEmpty()90 bool LruCacheUtil<K, V>::IsEmpty()
91 {
92     return lruMap_.empty();
93 };
94 }
95 }
96 
97 #endif