Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add get_many #6

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,26 @@ impl<K: Hash + Eq, V, S: BuildHasher, A: Clone + Allocator> LruCache<K, V, S, A>
}
}

pub fn get_many<'a, 'b, Q>(&mut self, ks: impl Iterator<Item = &'b Q>) -> Vec<Option<&'a V>>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
pub fn get_many<'a, 'b, Q>(&mut self, ks: impl Iterator<Item = &'b Q>) -> Vec<Option<&'a V>>
pub fn get_many<'a, 'b, Q>(&'a mut self, ks: impl Iterator<Item = &'b Q>) -> Vec<Option<&'a V>>

Otherwise the returned lifetime can be arbitrary long and there could be potentially use-after-free if we insert after that, IIUC.

where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized + 'b,
{
ks.map(|k| {
if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
let node_ptr: *mut LruEntry<K, V> = &mut **node;

self.detach(node_ptr);
self.attach(node_ptr);
// SAFETY: Both `attach` and `dettach` will not modify the val field.
Some(unsafe { &(*(*node_ptr).val.as_ptr()) as &V })
} else {
None
}
})
.collect()
}

/// Returns a mutable reference to the value of the key in the cache or `None` if it
/// is not present in the cache. Moves the key to the head of the LRU list if it exists.
///
Expand Down Expand Up @@ -1932,6 +1952,17 @@ mod tests {
assert_opt_eq(cache.get("apple"), "red");
}

#[test]
fn test_get_many() {
let mut cache = LruCache::new(2);

cache.put("apple", "red");
cache.put("pear", "yellow");

let res = cache.get_many(["pear", "watermelon", "apple"].iter());
assert_eq!(res, vec![Some(&"yellow"), None, Some(&"red")]);
}

#[test]
fn test_get_mut_with_borrow() {
use alloc::string::String;
Expand Down