-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
358 lines (317 loc) · 12.9 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
use std::collections::HashMap;
use std::hash::Hash;
use std::rc::{Rc, Weak};
use std::cell::RefCell;
use std::fmt::Display;
pub mod nodes;
use nodes::{HasHead, Node};
// A single node in the cache
#[derive(Debug)]
pub struct CacheNode<K, V>
where K: Hash + Eq + Clone {
parent: Rc<RefCell<FrequencyList<K, V>>>,
key: K,
next: Option<Rc<RefCell<CacheNode<K, V>>>>,
prev: Option<Weak<RefCell<CacheNode<K, V>>>>
}
impl<K, V> CacheNode<K, V>
where K: Hash + Eq + Clone {
// Get the actual value associated with this cache node. This is
// used exclusively for testing and display purposes.
pub fn get_associated_data<'a>(&self, cache: &'a LFUCache<K, V>) -> &'a V {
&cache.cache.get(&self.key).unwrap().0
}
}
impl<K, V> nodes::Node for CacheNode<K, V>
where K: Hash + Eq + Clone {
fn get_next(&self) -> Option<Rc<RefCell<CacheNode<K, V>>>> {
match self.next {
None => {None}
Some(ref next) => {Some(Rc::clone(next))}
}
}
fn set_next(&mut self, new_next: Option<Rc<RefCell<CacheNode<K, V>>>>) {
self.next = new_next
}
fn get_prev(&self) -> Option<Weak<RefCell<CacheNode<K, V>>>> {
match self.prev {
None => {None}
Some(ref prev) => {Some(Rc::downgrade(&Rc::clone(&prev.upgrade().unwrap())))}
}
}
fn set_prev(&mut self, new_prev: Option<Weak<RefCell<CacheNode<K, V>>>>) {
self.prev = new_prev
}
}
// A linked list of CacheNode objects with the same frequency. This
// struct is also itself a node in a linked list of FrequencyList
// objects.
#[derive(Debug)]
pub struct FrequencyList<K, V>
where K: Hash + Eq + Clone {
head: Option<Rc<RefCell<CacheNode<K, V>>>>,
frequency: usize,
next: Option<Rc<RefCell<FrequencyList<K, V>>>>,
prev: Option<Weak<RefCell<FrequencyList<K, V>>>>,
}
impl<K, V> FrequencyList<K, V>
where K: Hash + Eq + Clone,
V: Display {
pub fn new(freq: usize) -> Self {
FrequencyList {
head: None,
frequency: freq,
next: None, prev: None
}
}
pub fn to_string(&self, cache: &LFUCache<K, V>) -> String
where K: Hash + Eq + Clone, V: Display {
self.reduce(|acc: String, node| {
let mut acc = acc.clone();
acc.push_str(&format!(" {}", node.borrow().get_associated_data(cache)));
acc
}, format!("Count {}:", self.frequency))
}
}
impl<K, V> nodes::Node for FrequencyList<K, V>
where K: Hash + Eq + Clone {
fn get_next(&self) -> Option<Rc<RefCell<FrequencyList<K, V>>>> {
match self.next {
None => {None}
Some(ref next) => {Some(Rc::clone(next))}
}
}
fn set_next(&mut self, new_next: Option<Rc<RefCell<FrequencyList<K, V>>>>) {
self.next = new_next
}
fn get_prev(&self) -> Option<Weak<RefCell<FrequencyList<K, V>>>> {
match self.prev {
None => {None}
Some(ref prev) => {Some(Rc::downgrade(&Rc::clone(&prev.upgrade().unwrap())))}
}
}
fn set_prev(&mut self, new_prev: Option<Weak<RefCell<FrequencyList<K, V>>>>) {
self.prev = new_prev
}
}
impl<K, V> nodes::HasHead for FrequencyList<K, V>
where K: Hash + Eq + Clone {
type Element = CacheNode<K, V>;
fn get_head(&self) -> Option<Rc<RefCell<CacheNode<K, V>>>> {
match self.head {
None => {None}
Some(ref head) => {Some(Rc::clone(head))}
}
}
fn set_head(&mut self, new_head: Option<Rc<RefCell<CacheNode<K, V>>>>) {
self.head = new_head
}
}
// This is the main struct and the entrypoint to the cache.
#[derive(Debug)]
pub struct LFUCache<K, V>
where K: Hash + Eq + Clone {
frequency_list_head: Option<Rc<RefCell<FrequencyList<K, V>>>>,
cache: HashMap<K, (V, Rc<RefCell<CacheNode<K, V>>>)>,
max_size: usize
}
impl<K, V> LFUCache<K, V>
where K: Hash + Eq + Clone, V: Display {
pub fn new(max_size: usize) -> Self {
LFUCache {
frequency_list_head: None,
cache: HashMap::new(),
max_size: max_size
}
}
pub fn len(&self) -> usize {
self.cache.len()
}
pub fn to_string(&self) -> String {
if self.frequency_list_head.is_none() {
"<empty>".to_string()
} else {
self.reduce(|acc: String, list| {
let mut acc = acc.clone();
acc.push_str(&format!("{}\n", list.borrow().to_string(&self)));
acc
}, "".to_string())
}
}
// Given a node in the cache that was recently used, increment
// this node's frequency by moving it ahead to the next frequency
// list.
fn increment_node_frequency(&mut self, node: Rc<RefCell<CacheNode<K, V>>>) {
// Create and initialize the new parent list. This might be an
// existing list, or we might need to create a new one.
let new_parent = {
let node = node.borrow();
let current_frequency = node.parent.borrow().frequency;
let there_is_a_gap = {
let next_list = &node.parent.borrow().next;
next_list.is_some() && next_list.as_ref().unwrap().borrow().frequency
!= current_frequency + 1
};
// if either the next frequency does doesn't exist (this is
// the last one) or the next frequency list's frequency is not
// the current frequency + 1 (there is a gap), we need to
// create a new frequency list and add this node to it.
let new_parent = if node.parent.borrow().next.is_none() || there_is_a_gap {
// create new parent list and connect it to the old parent
Rc::new(RefCell::new(FrequencyList::new(current_frequency + 1)))
} else {
Rc::clone(node.parent.borrow().next.as_ref().unwrap())
};
// if the next frequency list did exist, but there was a
// gap, we need to point it back to the new parent
if there_is_a_gap {
let next_list = &node.parent.borrow().next;
next_list.as_ref().unwrap()
.borrow_mut().prev = Some(Rc::downgrade(&new_parent));
new_parent.borrow_mut().next = Some(Rc::clone(
next_list.as_ref().unwrap()
));
}
// Point the new parent back to the old parent in case
// they are not connected.
new_parent.borrow_mut().prev = Some(Rc::downgrade(&node.parent));
node.parent.borrow_mut().next = Some(Rc::clone(&new_parent));
new_parent
};
// if this is the last node in it's current parent, we
// need to remove the current parent
if node.borrow().next.is_none() && node.borrow().prev.is_none() {
let node = node.borrow();
node.parent.borrow_mut().remove();
}
// if this node is the head, we need to advance the head of
// it's parent
if node.borrow().prev.is_none() {
let node_parent = Rc::clone(&node.borrow().parent);
node_parent.borrow_mut().pop_head();
}
// set the parent as the new parent
node.borrow_mut().parent = Rc::clone(&new_parent);
// if this is the frequency list head, we need to repoint the head to the next list.
if self.frequency_list_head.as_ref().unwrap().borrow().head.is_none() {
self.frequency_list_head = Some(Rc::clone(&new_parent));
}
// remove this node from it's list and add it to its new parent
node.borrow_mut().remove();
new_parent.borrow_mut().push(Rc::clone(&node));
}
// remove the given node from the internal cache structures
fn remove_node(&mut self, node: Rc<RefCell<CacheNode<K, V>>>) {
if node.borrow().is_head() {
let node_parent = {
Rc::clone(&node.borrow().parent)
};
if node.borrow().is_only_child() {
node_parent.borrow_mut().remove();
}
node_parent.borrow_mut().pop_head();
}
node.borrow_mut().remove();
}
// Get the value associated with the given key
pub fn get(&mut self, key: &K) -> Option<&V> {
let node = Rc::clone(&self.cache.get(key)?.1);
self.increment_node_frequency(Rc::clone(&node));
let (data, _) = self.cache.get(key)?;
Some(&data)
}
// Remove the value associated with the given key.
pub fn remove(&mut self, key: &K) -> Option<V> {
let node = Rc::clone(&self.cache.get(&key)?.1);
self.remove_node(Rc::clone(&node));
let (data, _) = self.cache.remove(&key)?;
Some(data)
}
// Insert the value associated with the given key. If this
// operations means that the cache size will be greater than the
// max size, evict the least frequently used key.
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
if !self.cache.contains_key(&key) {
// Get the first frequency list if it exists
match self.pop_head() {
None => {
// create a new list and a new node, connect them.
let mut new_frequency_list = Rc::new(RefCell::new(
FrequencyList::new(1)
));
let new_node = Rc::new(RefCell::new(CacheNode {
parent: Rc::clone(&new_frequency_list),
key: key.clone(), next: None, prev: None
}));
new_frequency_list.borrow_mut().push(Rc::clone(&new_node));
// set the new list as the freq list head, insert
// the new node and value into the hashmap
self.push(new_frequency_list);
self.cache.insert(key, (value, Rc::clone(&new_node)));
}
Some(list) => {
// remove LFU item if we are over the max size
if self.len() >= self.max_size {
let key = {
let node_to_remove = &list.borrow().head;
let node_to_remove = Rc::clone(
&node_to_remove.as_ref().unwrap()
);
let node_to_remove = node_to_remove.borrow();
node_to_remove.key.clone()
};
self.remove(&key);
}
// if the first list's frequency is 1, we can use it.
if list.borrow().frequency == 1 {
// create a new node and link it to the existing list
let new_node = Rc::new(RefCell::new(CacheNode {
parent: Rc::clone(&list),
key: key.clone(), next: None, prev: None
}));
list.borrow_mut().push(Rc::clone(&new_node));
// set the head back to the original list
self.push(Rc::clone(&list));
// insert the new data into the map
self.cache.insert(key, (value, Rc::clone(&new_node)));
} else {
// the existing list did not have a frequency
// of 1 - we can't use it.
let new_frequency_list = Rc::new(RefCell::new(
FrequencyList::new(1)
));
let new_node = Rc::new(RefCell::new(CacheNode {
parent: Rc::clone(&new_frequency_list),
key: key.clone(), next: None, prev: None
}));
// Push the new node onto the new list, push
// the new list onto the cache.
new_frequency_list.borrow_mut().push(Rc::clone(&new_node));
self.push(Rc::clone(&new_frequency_list));
// insert the new data into the map
self.cache.insert(key, (value, Rc::clone(&new_node)));
}
}
}
None
} else {
let (old_value, node) = self.cache.remove(&key).unwrap();
self.increment_node_frequency(Rc::clone(&node));
self.cache.insert(key, (value, Rc::clone(&node)));
Some(old_value)
}
}
}
impl<K, V> nodes::HasHead for LFUCache<K, V>
where K: Hash + Eq + Clone {
type Element = FrequencyList<K, V>;
fn get_head(&self) -> Option<Rc<RefCell<FrequencyList<K, V>>>> {
match self.frequency_list_head {
None => {None}
Some(ref head) => {Some(Rc::clone(head))}
}
}
fn set_head(&mut self, new_head: Option<Rc<RefCell<FrequencyList<K, V>>>>) {
self.frequency_list_head = new_head
}
}