1 /*
2  * Copyright (c) 2024-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 OHOS_CAMERA_LRU_MAP_H
17 #define OHOS_CAMERA_LRU_MAP_H
18 
19 #include <map>
20 #include <mutex>
21 #include <queue>
22 #include <list>
23 
24 namespace OHOS {
25 namespace CameraStandard {
26 template<typename K, typename V>
27 class LruMap final {
28 public:
29     LruMap() = default;
30     ~LruMap() = default;
31 
32     LruMap(const LruMap &) = delete;
33     LruMap(LruMap &&) = delete;
34     LruMap& operator=(const LruMap &) = delete;
35     LruMap& operator=(LruMap &&) = delete;
36 
Get(const K & key,V & value)37     bool Get(const K &key, V &value)
38     {
39         std::lock_guard<std::mutex> lock(lruLock_);
40         if (cache_.find(key) == cache_.end()) {
41             return false;
42         }
43         value = cache_[key];
44         return MoveNodeToLast(key, value);
45     }
46 
Put(const K & key,const V & inValue)47     bool Put(const K &key, const V &inValue)
48     {
49         std::lock_guard<std::mutex> lock(lruLock_);
50         cache_[key] = inValue;
51         return MoveNodeToLast(key, inValue);
52     }
53 
Clear()54     void Clear()
55     {
56         std::lock_guard<std::mutex> lock(lruLock_);
57         cache_.clear();
58         queue_.clear();
59     }
60 
61 private:
MoveNodeToLast(const K & key,const V & val)62     bool MoveNodeToLast(const K &key, const V &val)
63     {
64         auto it = std::find_if(queue_.begin(), queue_.end(), [&key](const std::pair<K, V>& pair) {
65             return pair.first == key;
66         });
67         if (it != queue_.end()) {
68             queue_.erase(it);
69         }
70         std::pair<K, V> entry = {key, val};
71         queue_.push_back(entry);
72         while (queue_.size() > MAX_CACHE_ITEMS) {
73             std::pair<K, V> &pair = queue_.front();
74             cache_.erase(pair.first);
75             queue_.pop_front();
76         }
77         return true;
78     }
79 
80     std::mutex lruLock_;
81     std::map<K, V> cache_;
82     std::deque<std::pair<K, V>> queue_;
83 
84     static const int MAX_CACHE_ITEMS = 10;
85 };
86 } // namespace CameraStandard
87 } // namespace OHOS
88 #endif // OHOS_CAMERA_LRU_MAP_H