The Pedigree Project  0.1
LruCache.h
1 /*
2  * Copyright (c) 2008-2014, Pedigree Developers
3  *
4  * Please see the CONTRIB file in the root of the source tree for a full
5  * list of contributors.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #ifndef KERNEL_UTILITIES_LRUCACHE_H
21 #define KERNEL_UTILITIES_LRUCACHE_H
22 
26 #include "pedigree/kernel/processor/types.h"
27 #include "pedigree/kernel/utilities/utility.h"
28 
37 template <class K, class T, size_t Slots = 32>
38 class LruCache
39 {
40  static_assert(Slots >= 4, "At least four slots are needed for LruCache.");
41 
42  private:
43  struct Slot
44  {
45  K key;
46  T object;
47  bool set = false;
48  };
49 
50  public:
51  LruCache() = default;
52  virtual ~LruCache() = default;
53 
55  bool get(const K &key, T &object)
56  {
57  for (size_t i = 0; i < Slots; ++i)
58  {
59  if (!m_Slots[i].set)
60  {
61  continue;
62  }
63  else if (m_Slots[i].key != key)
64  {
65  continue;
66  }
67 
68  object = m_Slots[i].object;
69  ++m_Hits;
70  return true;
71  }
72 
73  ++m_Misses;
74  return false;
75  }
76 
78  void store(const K &key, const T &object)
79  {
80  // Already the most recently used item.
81  if (m_Slots[0].set && m_Slots[0].key == key)
82  {
83  return;
84  }
85 
86  pedigree_std::copy(&m_Slots[1], &m_Slots[0], Slots - 1);
87  m_Slots[0].key = key;
88  m_Slots[0].object = object;
89  m_Slots[0].set = true;
90  }
91 
92  size_t hits() const
93  {
94  return m_Hits;
95  }
96 
97  size_t misses() const
98  {
99  return m_Misses;
100  }
101 
102  private:
103  Slot m_Slots[Slots];
104 
105  size_t m_Hits = 0;
106  size_t m_Misses = 0;
107 };
108 
111 #endif // KERNEL_UTILITIES_LRUCACHE_H
void store(const K &key, const T &object)
Definition: LruCache.h:78
LruCache provides a least-recently-used cache abstraction.
Definition: LruCache.h:38