Skip to content

Commit

Permalink
Add a const constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
mbrubeck committed Apr 8, 2024
1 parent 2e10902 commit 03d7eee
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
13 changes: 9 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,20 +78,25 @@ struct Entry<T> {

impl<T, const N: usize> Default for LRUCache<T, N> {
fn default() -> Self {
Self::new()
}
}

impl<T, const N: usize> LRUCache<T, N> {
/// Create an empty cache.
pub const fn new() -> Self {
let cache = LRUCache {
entries: ArrayVec::new(),
entries: ArrayVec::new_const(),
head: 0,
tail: 0,
};
assert!(
cache.entries.capacity() < u16::max_value() as usize,
N < u16::max_value() as usize,
"Capacity overflow"
);
cache
}
}

impl<T, const N: usize> LRUCache<T, N> {
/// Insert a given key in the cache.
///
/// This item becomes the front (most-recently-used) item in the cache. If the cache is full,
Expand Down
2 changes: 1 addition & 1 deletion src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ where

#[test]
fn empty() {
let mut cache = TestCache::default();
let mut cache = TestCache::new();
assert_eq!(cache.is_empty(), true);
assert_eq!(items(&mut cache), []);
cache.insert(1);
Expand Down

0 comments on commit 03d7eee

Please sign in to comment.