• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2023-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 PANDA_PLUGINS_ETS_RUNTIME_INTEROP_JS_ETS_PROXY_WRAPPERS_CACHE_H_
17 #define PANDA_PLUGINS_ETS_RUNTIME_INTEROP_JS_ETS_PROXY_WRAPPERS_CACHE_H_
18 
19 #include "libpandabase/macros.h"
20 
21 #include <memory>
22 #include <unordered_map>
23 
24 namespace ark::ets::interop::js::ets_proxy {
25 
26 template <typename Key, typename Wrapper>
27 class WrappersCache {
28 public:
29     WrappersCache() = default;
30     ~WrappersCache() = default;
31     NO_COPY_SEMANTIC(WrappersCache);
32     NO_MOVE_SEMANTIC(WrappersCache);
33 
Lookup(Key key)34     Wrapper *Lookup(Key key)
35     {
36         auto it = cache_.find(key);
37         if (UNLIKELY(it == cache_.end())) {
38             return nullptr;
39         }
40         return it->second.get();
41     }
42 
Insert(Key key,std::unique_ptr<Wrapper> && wrapper)43     Wrapper *Insert(Key key, std::unique_ptr<Wrapper> &&wrapper)
44     {
45         auto [it, inserted] = cache_.insert_or_assign(key, std::move(wrapper));
46         ASSERT(inserted);
47         return it->second.get();
48     }
49 
Steal(Key key)50     std::unique_ptr<Wrapper> Steal(Key key)
51     {
52         auto nh = cache_.extract(key);
53         return nh ? std::move(nh.mapped()) : nullptr;
54     }
55 
56 private:
57     std::unordered_map<Key, std::unique_ptr<Wrapper>> cache_;
58 };
59 
60 }  // namespace ark::ets::interop::js::ets_proxy
61 
62 #endif  // !PANDA_PLUGINS_ETS_RUNTIME_INTEROP_JS_ETS_PROXY_WRAPPERS_CACHE_H_
63