2 * Copyright (c) 2017 Cisco and/or its affiliates.
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:
7 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 #ifndef __VOM_INST_DB_H__
17 #define __VOM_INST_DB_H__
24 * A Database to store the unique 'singular' instances of a single object
26 * The instances are stored as weak pointers. So the DB does not own these
27 * objects, they are owned by object in the client_db.
29 template <typename KEY, typename OBJ>
42 typename std::map<KEY, std::weak_ptr<OBJ>>::const_iterator const_iterator;
45 * Get iterator to the beginning of the DB
47 const_iterator cbegin() { return m_map.cbegin(); }
50 * Get iterator to the beginning of the DB
52 const_iterator cend() { return m_map.cend(); }
55 * Find or add the object to the store.
56 * The object passed is deisred state. A new instance will be copy
57 * constructed from it. This function is templatised on the object type
58 * passed, which may be drrived from, the object type stored. this
59 * prevents slicing during the make_shared construction.
61 template <typename DERIVED>
62 std::shared_ptr<OBJ> find_or_add(const KEY& key, const DERIVED& obj)
64 auto search = m_map.find(key);
66 if (search == m_map.end()) {
67 std::shared_ptr<OBJ> sp = std::make_shared<DERIVED>(obj);
71 VOM_LOG(log_level_t::DEBUG) << *sp;
75 return (search->second.lock());
79 * Find the object to the store.
81 std::shared_ptr<OBJ> find(const KEY& key)
83 auto search = m_map.find(key);
85 if (search == m_map.end()) {
86 std::shared_ptr<OBJ> sp(NULL);
91 return (search->second.lock());
95 * Release the object from the DB store, if it's the one we have stored
97 void release(const KEY& key, const OBJ* obj)
99 auto search = m_map.find(key);
101 if (search != m_map.end()) {
102 if (search->second.expired()) {
105 std::shared_ptr<OBJ> sp = m_map[key].lock();
107 if (sp.get() == obj) {
115 * Find the object to the store.
117 void add(const KEY& key, std::shared_ptr<OBJ> sp) { m_map[key] = sp; }
120 * Print each of the object in the DB into the stream provided
122 void dump(std::ostream& os)
124 for (auto entry : m_map) {
125 os << "key: " << entry.first << std::endl;
126 os << " " << entry.second.lock()->to_string() << std::endl;
131 * Populate VPP from current state, on VPP restart
135 for (auto entry : m_map) {
136 entry.second.lock()->replay();
142 * the map of objects against their key
144 std::map<KEY, std::weak_ptr<OBJ>> m_map;
149 * fd.io coding-style-patch-verification: ON
152 * eval: (c-set-style "mozilla")