contain-rs / lru-cache

A cache that holds a limited number of key-value pairs
https://contain-rs.github.io/lru-cache/lru_cache/
Apache License 2.0
83 stars 36 forks source link

Adds convenience method for seamless caching by providing access with… #19

Closed regexident closed 8 years ago

regexident commented 8 years ago

Adds convenience method for seamless caching by providing access with fallback value via computation closure.

Example:

let borrowed = cache.get_or_insert(42, |key| {
    let mut value = ...;
    // ... <- expensive computation
    value
});

Currently returns reference to existing/inserted value (&V). Could be changed to also return replaced value (Option<V>, &V). Would introduce lots of syntax noise (let (_, value) = …) for the most common case though.

FlashCat commented 8 years ago

Thanks for the pull request, and welcome! The contain-rs team is excited to review your changes, and you should hear from @apasel422 (or someone else) soon.

If any changes to this PR are deemed necessary, please add them as extra commits. This ensures that the reviewer can see what has changed since they last reviewed the code. The way Github handles out-of-date commits, this should also make it reasonably obvious what issues have or haven't been addressed. Large or tricky changes may require several passes of review and changes.

apasel422 commented 8 years ago

I'd like to hold off on this until contain-rs/linked-hash-map#36 is merged, and instead provide the entry API for LruCache.

regexident commented 8 years ago

Interesting. I'm wondering, how would an equivalent cache access look like with that?

Like this?

let value = cache.entry(42).or_insert_with(|| {
    let mut value = ...;
    // ... <- expensive computation
    value
}).get();

A little more convoluted but covering a wider area for sure.

I'm fine with either way. :+1:

apasel422 commented 8 years ago

or_insert_with returns &mut V:

let value: &mut V = cache.entry(42).or_insert_with(|| ...);

See the reference for more details: https://doc.rust-lang.org/std/collections/#entries

regexident commented 8 years ago

Ah, that looks pretty good actually. Didn't know the entries API was an official stdlib pattern.

Guess I'll exercise myself in patience then. :innocent: