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 #include "screen_cache.h"
17 
18 namespace OHOS::Rosen {
ScreenCache(size_t capacity,int32_t errorCode)19 ScreenCache::ScreenCache(size_t capacity, int32_t errorCode)
20     : capacity_(capacity), errorCode_(errorCode)
21 {
22 }
23 
Set(int32_t key,int32_t value)24 void ScreenCache::Set(int32_t key, int32_t value)
25 {
26     std::lock_guard<std::mutex> guard(mtx_);
27     auto it = Map_.find(key);
28     if (it != Map_.end()) {
29         accessOrder_.erase(std::find(accessOrder_.begin(), accessOrder_.end(), key));
30     } else {
31         if (Map_.size() >= capacity_) {
32             int32_t lastKey = accessOrder_.back();
33             accessOrder_.pop_back();
34             Map_.erase(lastKey);
35         }
36     }
37     Map_[key] = value;
38     accessOrder_.push_front(key);
39 }
40 
Get(int32_t key)41 int32_t ScreenCache::Get(int32_t key)
42 {
43     std::lock_guard<std::mutex> guard(mtx_);
44     auto it = Map_.find(key);
45     if (it != Map_.end()) {
46         accessOrder_.erase(std::find(accessOrder_.begin(), accessOrder_.end(), key));
47         accessOrder_.push_front(key);
48         return it->second;
49     }
50     return errorCode_;
51 }
52 } // namespace OHOS::Rosen