1/*
2 * Copyright (c) 2023 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 "core/common/lru/count_limit_lru.h"
17
18namespace OHOS::Ace {
19template<typename T>
20void CountLimitLRU::CacheWithCountLimitLRU(const std::string& key, const T& cacheObj,
21    std::list<CacheNode<T>>& cacheList,
22    std::unordered_map<std::string, typename std::list<CacheNode<T>>::iterator>& cache,
23    const std::atomic<size_t>& capacity)
24{
25    auto iter = cache.find(key);
26    if (iter == cache.end()) {
27        if (cache.size() == capacity) {
28            cache.erase(cacheList.back().cacheKey);
29            cacheList.pop_back();
30        }
31        cacheList.emplace_front(key, cacheObj);
32        cache.emplace(key, cacheList.begin());
33    } else {
34        iter->second->cacheObj = cacheObj;
35        cacheList.splice(cacheList.begin(), cacheList, iter->second);
36        iter->second = cacheList.begin();
37    }
38}
39
40template<typename T>
41T CountLimitLRU::GetCacheObjWithCountLimitLRU(const std::string& key, std::list<CacheNode<T>>& cacheList,
42    std::unordered_map<std::string, typename std::list<CacheNode<T>>::iterator>& cache)
43{
44    auto iter = cache.find(key);
45    if (iter != cache.end()) {
46        cacheList.splice(cacheList.begin(), cacheList, iter->second);
47        iter->second = cacheList.begin();
48        return iter->second->cacheObj;
49    }
50    return nullptr;
51}
52
53template<typename T>
54void CountLimitLRU::RemoveCacheObjFromCountLimitLRU(const std::string& key, std::list<CacheNode<T>>& cacheList,
55    std::unordered_map<std::string, typename std::list<CacheNode<T>>::iterator>& cache)
56{
57    auto iter = cache.find(key);
58    if (iter != cache.end()) {
59        cacheList.erase(iter->second);
60        cache.erase(key);
61    }
62}
63} // namespace OHOS::Ace
64