diff --git a/src/lib.rs b/src/lib.rs index 2cfca93..01d6859 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,9 +3,8 @@ use std::collections::BTreeMap; #[derive(Debug)] pub struct LRUCache { keys: BTreeMap, - keys_used: BTreeMap, - counter: u64, - capacity: i32, + counter_entries: Vec, + 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; - self.counter += 1; - } - *result + // 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; + 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; } }