Dunno what this is
This commit is contained in:
parent
9983278598
commit
d86bd596ca
1 changed files with 31 additions and 27 deletions
56
src/lib.rs
56
src/lib.rs
|
@ -3,9 +3,8 @@ use std::collections::BTreeMap;
|
|||
#[derive(Debug)]
|
||||
pub struct LRUCache {
|
||||
keys: BTreeMap<i32, i32>,
|
||||
keys_used: BTreeMap<i32, u64>,
|
||||
counter: u64,
|
||||
capacity: i32,
|
||||
counter_entries: Vec<i32>,
|
||||
counter: i32,
|
||||
}
|
||||
|
||||
impl LRUCache {
|
||||
|
@ -13,39 +12,44 @@ impl LRUCache {
|
|||
println!("new {capacity}");
|
||||
Self {
|
||||
keys: BTreeMap::new(),
|
||||
keys_used: BTreeMap::new(),
|
||||
counter_entries: vec![0; capacity as usize],
|
||||
counter: 0,
|
||||
capacity,
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&mut self, key: i32) -> i32 {
|
||||
println!("getting {key}");
|
||||
let result = self.keys.get(&key).unwrap_or(&-1);
|
||||
if result != &-1 {
|
||||
*self.keys_used.get_mut(&key).unwrap() = self.counter;
|
||||
// println!("getting {key}");
|
||||
// let result = self.keys.get(&key).unwrap_or(&-1);
|
||||
// if result != &-1 {
|
||||
// *self.keys_used.get_mut(&key).unwrap() = self.counter;
|
||||
// self.counter += 1;
|
||||
// }
|
||||
// *result
|
||||
self.counter += 1;
|
||||
}
|
||||
*result
|
||||
let result = *self.keys.get(&key).unwrap_or(&-1);
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn put(&mut self, key: i32, value: i32) {
|
||||
println!("inserting {key} {value}");
|
||||
// println!("inserting {key} {value}");
|
||||
// self.keys.insert(key, value);
|
||||
// self.keys_used.insert(key, self.counter);
|
||||
// if self.keys_used.len() > self.capacity.try_into().unwrap() {
|
||||
// let mut lowest = u64::MAX;
|
||||
// let mut lowest_key = -1;
|
||||
// for (k, v) in self.keys_used.iter() {
|
||||
// if v < &lowest {
|
||||
// lowest = *v;
|
||||
// lowest_key = *k;
|
||||
// }
|
||||
// }
|
||||
// println!("evicting {lowest_key}");
|
||||
// self.keys.remove(&lowest_key);
|
||||
// self.keys_used.remove(&lowest_key);
|
||||
// }
|
||||
// self.counter += 1;
|
||||
self.keys.insert(key, value);
|
||||
self.keys_used.insert(key, self.counter);
|
||||
if self.keys_used.len() >= self.capacity.try_into().unwrap() {
|
||||
let mut lowest = u64::MAX;
|
||||
let mut lowest_key = -1;
|
||||
for (k, v) in self.keys_used.iter() {
|
||||
if v < &lowest {
|
||||
lowest = *v;
|
||||
lowest_key = *k;
|
||||
}
|
||||
}
|
||||
println!("evicting {lowest_key}");
|
||||
self.keys.remove(&lowest_key);
|
||||
self.keys_used.remove(&lowest_key);
|
||||
}
|
||||
self.counter += 1;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue