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
37template <class K, class T, size_t Slots = 32>
38class LruCache {
39 static_assert(Slots >= 4, "At least four slots are needed for LruCache.");
40
41 private:
42 struct Slot {
43 K key;
44 T object;
45 bool set = false;
46 };
47
48 public:
49 LruCache() = default;
50 virtual ~LruCache() = default;
51
53 bool get(const K& key, T& object) {
54 for (size_t i = 0; i < Slots; ++i) {
55 if (!m_Slots[i].set) {
56 continue;
57 } else if (m_Slots[i].key != key) {
58 continue;
59 }
60
61 object = m_Slots[i].object;
62 ++m_Hits;
63 return true;
64 }
65
66 ++m_Misses;
67 return false;
68 }
69
71 void store(const K& key, const T& object) {
72 for (size_t i = 0; i < Slots; ++i) {
73 if (m_Slots[i].set && m_Slots[i].key == key) {
74 pedigree_std::copy(&m_Slots[1], &m_Slots[0], i);
75 m_Slots[0].key = key;
76 m_Slots[0].object = object;
77 return;
78 }
79 }
80
81 pedigree_std::copy(&m_Slots[1], &m_Slots[0], Slots - 1);
82 m_Slots[0].key = key;
83 m_Slots[0].object = object;
84 m_Slots[0].set = true;
85 }
86
87 size_t hits() const {
88 return m_Hits;
89 }
90
91 size_t misses() const {
92 return m_Misses;
93 }
94
95 private:
96 Slot m_Slots[Slots];
97
98 size_t m_Hits = 0;
99 size_t m_Misses = 0;
100};
101
104#endif // KERNEL_UTILITIES_LRUCACHE_H
LruCache provides a least-recently-used cache abstraction.
Definition LruCache.h:38
void store(const K &key, const T &object)
Definition LruCache.h:71
bool get(const K &key, T &object)
Definition LruCache.h:53