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__
23 #include "vom/logger.hpp"
27 * A Database to store the unique 'singular' instances of a single object
29 * The instances are stored as weak pointers. So the DB does not own these
30 * objects, they are owned by object in the client_db.
32 template <typename KEY, typename OBJ>
45 typename std::map<KEY, std::weak_ptr<OBJ>>::const_iterator const_iterator;
48 * Get iterator to the beginning of the DB
50 const_iterator begin() const { return m_map.cbegin(); }
53 * Get iterator to the beginning of the DB
55 const_iterator end() const { return m_map.cend(); }
58 * Find or add the object to the store.
59 * The object passed is deisred state. A new instance will be copy
60 * constructed from it. This function is templatised on the object type
61 * passed, which may be drrived from, the object type stored. this
62 * prevents slicing during the make_shared construction.
64 template <typename DERIVED>
65 std::shared_ptr<OBJ> find_or_add(const KEY& key, const DERIVED& obj)
67 auto search = m_map.find(key);
69 if (search == m_map.end()) {
70 std::shared_ptr<OBJ> sp = std::make_shared<DERIVED>(obj);
74 VOM_LOG(log_level_t::DEBUG) << *sp;
78 return (search->second.lock());
82 * Find the object to the store.
84 std::shared_ptr<OBJ> find(const KEY& key)
86 auto search = m_map.find(key);
88 if (search == m_map.end()) {
89 std::shared_ptr<OBJ> sp(NULL);
94 return (search->second.lock());
98 * Release the object from the DB store, if it's the one we have stored
100 void release(const KEY& key, const OBJ* obj)
102 auto search = m_map.find(key);
104 if (search != m_map.end()) {
105 if (search->second.expired()) {
108 std::shared_ptr<OBJ> sp = m_map[key].lock();
110 if (sp.get() == obj) {
118 * Find the object to the store.
120 void add(const KEY& key, std::shared_ptr<OBJ> sp) { m_map[key] = sp; }
123 * Populate VPP from current state, on VPP restart
127 for (auto entry : m_map) {
128 entry.second.lock()->replay();
134 * the map of objects against their key
136 std::map<const KEY, std::weak_ptr<OBJ>> m_map;
141 * fd.io coding-style-patch-verification: ON
144 * eval: (c-set-style "mozilla")