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  * Description: API of param bundle
16  */
17 
18 #ifndef PARAM_BUNDLE_H
19 #define PARAM_BUNDLE_H
20 
21 #include <string>
22 #include <unordered_map>
23 #include <any>
24 #include <memory>
25 #include <mutex>
26 
27 class ParamBundle;
28 using ParamSP = std::shared_ptr<ParamBundle>;
29 
30 class ParamBundle {
31 public:
32     ParamBundle() = default;
33     ~ParamBundle() = default;
34     template<typename T>
SetValue(const std::string & key,const T & value)35     void SetValue(const std::string &key, const T &value)
36     {
37         std::lock_guard<std::mutex> lock(m_mtx);
38         m_items[key] = value;
39     }
40 
41     template<typename T>
GetValue(const std::string & key,T & value)42     bool GetValue(const std::string &key, T &value) const
43     {
44         std::lock_guard<std::mutex> lock(m_mtx);
45         const auto it = m_items.find(key);
46         if (it == m_items.end()) {
47             return false;
48         }
49         try {
50             value = std::any_cast<T>(it->second);
51             return true;
52         } catch (const std::bad_any_cast&) {
53             return false;
54         }
55     }
56 
57     ParamBundle(const ParamBundle &) = delete;
58     ParamBundle &operator=(const ParamBundle &) = delete;
59     ParamBundle(ParamBundle &&) = delete;
60     ParamBundle &operator=(ParamBundle &&) = delete;
61 
62 private:
63     mutable std::mutex m_mtx;
64     std::unordered_map<std::string, std::any> m_items;
65 };
66 
67 #endif
68