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 WINDOW_WINDOW_MANAGER_SCREEN_CACHE_H
17 #define WINDOW_WINDOW_MANAGER_SCREEN_CACHE_H
18
19 #include <unordered_map>
20 #include <list>
21 #include <mutex>
22 #include <algorithm>
23
24 namespace OHOS::Rosen {
25
26 template <typename KeyType, typename ValueType>
27 class ScreenCache {
28 public:
29 ScreenCache(size_t capacity, ValueType errorCode);
30 void Set(const KeyType& key, const ValueType& value);
31 ValueType Get(const KeyType& key);
32
33 private:
34 std::unordered_map<KeyType, ValueType> Map_;
35 std::list<KeyType> accessOrder_;
36 const size_t capacity_;
37 const ValueType errorCode_;
38 std::mutex mtx_;
39 };
40
41 template <typename KeyType, typename ValueType>
ScreenCache(size_t capacity,ValueType errorCode)42 ScreenCache<KeyType, ValueType>::ScreenCache(size_t capacity, ValueType errorCode)
43 : capacity_(capacity), errorCode_(errorCode)
44 {
45 }
46
47 template <typename KeyType, typename ValueType>
Set(const KeyType & key,const ValueType & value)48 void ScreenCache<KeyType, ValueType>::Set(const KeyType& key, const ValueType& value)
49 {
50 std::lock_guard<std::mutex> guard(mtx_);
51 auto it = Map_.find(key);
52 if (it != Map_.end()) {
53 accessOrder_.erase(std::find(accessOrder_.begin(), accessOrder_.end(), key));
54 } else {
55 if (Map_.size() >= capacity_) {
56 KeyType lastKey = accessOrder_.back();
57 accessOrder_.pop_back();
58 Map_.erase(lastKey);
59 }
60 }
61 Map_[key] = value;
62 accessOrder_.push_front(key);
63 }
64
65 template <typename KeyType, typename ValueType>
Get(const KeyType & key)66 ValueType ScreenCache<KeyType, ValueType>::Get(const KeyType& key)
67 {
68 std::lock_guard<std::mutex> guard(mtx_);
69 auto it = Map_.find(key);
70 if (it != Map_.end()) {
71 accessOrder_.erase(std::find(accessOrder_.begin(), accessOrder_.end(), key));
72 accessOrder_.push_front(key);
73 return it->second;
74 }
75 return errorCode_;
76 }
77 } // namespace OHOS::Rosen
78 #endif // WINDOW_WINDOW_MANAGER_SCREEN_CACHE_H