blob: 431e63576b0ae22273aae0ecdea017f92b5feb15 [file] [log] [blame]
Yingdi Yu77627ab2015-07-21 16:13:49 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * Copyright (c) 2013-2014 Regents of the University of California.
4 *
5 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
6 *
7 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
8 * terms of the GNU Lesser General Public License as published by the Free Software
9 * Foundation, either version 3 of the License, or (at your option) any later version.
10 *
11 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
12 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
14 *
15 * You should have received copies of the GNU General Public License and GNU Lesser
16 * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
17 * <http://www.gnu.org/licenses/>.
18 *
19 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
20 */
21
22#include "key-cache.hpp"
23
24namespace ndn {
25namespace pib {
26
27KeyCacheEntry::KeyCacheEntry(const Name& name, shared_ptr<PublicKey> key)
28 : name(name)
29 , key(key)
30{
31 BOOST_ASSERT(static_cast<bool>(key));
32}
33
34KeyCache::KeyCache(size_t capacity)
35 : m_capacity(capacity)
36{
37}
38
39void
40KeyCache::insert(const Name& name, shared_ptr<PublicKey> key)
41{
42 // check if key exist
43 KeyContainer::index<byName>::type::iterator it = m_keys.get<byName>().find(name);
44 if (it != m_keys.get<byName>().end()) {
45 adjustLru(it);
46 return;
47 }
48
49 // evict key when capacity is reached
50 if (size() >= m_capacity)
51 evictKey();
52
53 // insert entry
54 m_keys.insert(KeyCacheEntry(name, key));
55}
56
57shared_ptr<PublicKey>
58KeyCache::find(const Name& name) const
59{
60 // check if key exist
61 KeyContainer::index<byName>::type::iterator it = m_keys.get<byName>().find(name);
62 if (it == m_keys.get<byName>().end())
63 return shared_ptr<PublicKey>();
64 else {
65 // adjust lru
66 shared_ptr<PublicKey> key = it->key;
67 adjustLru(it);
68 return key;
69 }
70}
71
72void
73KeyCache::erase(const Name& name)
74{
75 // check if key exist
76 KeyContainer::index<byName>::type::iterator it = m_keys.get<byName>().find(name);
77 if (it != m_keys.get<byName>().end()) {
78 m_keys.erase(it);
79 }
80}
81
82size_t
83KeyCache::size() const
84{
85 return m_keys.size();
86}
87
88void
89KeyCache::evictKey()
90{
91 if (!m_keys.get<byUsedTime>().empty()) {
92 KeyContainer::index<byUsedTime>::type::iterator it = m_keys.get<byUsedTime>().begin();
93 m_keys.erase(m_keys.project<0>(it));
94 }
95}
96
97void
98KeyCache::adjustLru(KeyContainer::iterator it) const
99{
100 KeyCacheEntry entry = std::move(*it);
101 m_keys.erase(it);
102 m_keys.insert(entry);
103}
104
105} // namespace pib
106} // namespace ndn