blob: 588dfaac7946d23075ec636c375e054f20c92cf0 [file] [log] [blame]
alexander3c798932021-03-26 21:42:19 +00001/*
2 * Copyright (c) 2021 Arm Limited. All rights reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17#ifndef APP_CTX_HPP
18#define APP_CTX_HPP
19
20#include <string>
21#include <map>
22
23namespace arm {
24namespace app {
25
26 class IAttribute
27 {
28 public:
29 virtual ~IAttribute() = default;
30 };
31
32 template<typename T>
33 class Attribute : public IAttribute
34 {
35 public:
36 ~Attribute() override = default;
37
38 explicit Attribute(const T value): _m_value(value){}
39
40 T Get()
41 {
42 return _m_value;
43 }
44 private:
45 T _m_value;
46 };
47
48 /* Application context class */
49 class ApplicationContext {
50 public:
51
52 /**
53 * @brief Saves given value as a named attribute in the context.
54 * @tparam T value type.
55 * @param[in] name Context attribute name.
56 * @param[in] object Value to save in the context.
57 */
58 template<typename T>
59 void Set(const std::string &name, T object)
60 {
61 this->_m_attributes[name] = new Attribute<T>(object);
62 }
63
64 /**
65 * @brief Gets the saved attribute from the context by the given name.
66 * @tparam T value type.
67 * @param[in] name Context attribute name.
68 * @return Value saved in the context.
69 */
70 template<typename T>
71 T Get(const std::string &name)
72 {
73 auto a = (Attribute<T>*)_m_attributes[name];
74 return a->Get();
75 }
76
77 /**
78 * @brief Checks if an attribute for a given name exists in the context.
79 * @param[in] name Attribute name.
80 * @return true if attribute exists, false otherwise
81 */
82 bool Has(const std::string& name)
83 {
84 return _m_attributes.find(name) != _m_attributes.end();
85 }
86
87 ApplicationContext() = default;
88
89 ~ApplicationContext() {
90 for (auto& attribute : _m_attributes)
91 delete attribute.second;
92
93 this->_m_attributes.clear();
94 }
95 private:
96 std::map<std::string, IAttribute*> _m_attributes;
97 };
98
99} /* namespace app */
100} /* namespace arm */
101
102#endif /* APP_CTX_HPP */