Skip to content

Commit

Permalink
Add LRUCache::iter method
Browse files Browse the repository at this point in the history
  • Loading branch information
mbrubeck committed Jun 7, 2021
1 parent 862e50a commit ec1e22a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "uluru"
version = "2.0.0"
version = "2.1.0"
authors = ["The Servo Project Developers", "Matt Brubeck <mbrubeck@limpet.net>"]
license = "MPL-2.0"
description = "A simple, fast, LRU cache implementation"
Expand Down
38 changes: 30 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,14 +180,7 @@ impl<T, const N: usize> LRUCache<T, N> {

/// Returns the n-th entry in the list (most recently used).
pub fn get(&self, index: usize) -> Option<&T> {
if index >= self.len() {
return None;
}
let mut entry = self.entries.get(self.head as usize)?;
for _ in 0..index {
entry = self.entries.get(entry.next as usize)?;
}
Some(&entry.val)
self.iter().nth(index)
}

/// Touches the first item in the cache that matches the given predicate.
Expand All @@ -206,6 +199,14 @@ impl<T, const N: usize> LRUCache<T, N> {
false
}

/// Iterate mutably over the contents of this cache.
pub fn iter(&self) -> Iter<T, N> {
Iter {
pos: self.head,
cache: self,
}
}

/// Iterate mutably over the contents of this cache.
fn iter_mut(&mut self) -> IterMut<T, N> {
IterMut {
Expand Down Expand Up @@ -310,3 +311,24 @@ impl<'a, T, const N: usize> IterMut<'a, T, N> {
Some((index, &mut entry.val))
}
}

/// Iterator over values in an LRUCache, from most-recently-used to least-recently-used.
pub struct Iter<'a, T, const N: usize> {
cache: &'a LRUCache<T, N>,
pos: u16,
}

impl<'a, T, const N: usize> Iterator for Iter<'a, T, N> {
type Item = &'a T;

fn next(&mut self) -> Option<&'a T> {
let entry = self.cache.entries.get(self.pos as usize)?;

self.pos = if self.pos == self.cache.tail {
N as u16 // Point past the end of the array to signal we are done.
} else {
entry.next
};
Some(&entry.val)
}
}

0 comments on commit ec1e22a

Please sign in to comment.