fn_cache/fn_cache.rs
1/// The generic trait for all caches.
2///
3/// This trait is implemented on all caches. This allows
4/// someone to write a function like
5/// `fn f(cache: &mut impl FnCache<u32,u32>, x: &u32) -> u32`
6/// and have it work for all the caches written in this crate.
7pub trait FnCache<I, O> {
8 /// Retrieve a value stored in the cache. If the
9 /// value does not yet exist in the cache, the
10 /// function is called, and the result is added
11 /// to the cache before returning it.
12 fn get(&mut self, input: I) -> &O;
13}
14
15/// The generic trait for caches which support getting multiple
16/// values.
17///
18/// This trait may have additional restrictions such as I is
19/// [`Clone`]. This allows someone to write a function like
20/// `fn f(cache: &mut impl FnCacheMany<u32,u32>, x: &u32) -> u32` and
21/// have it work in most cases when the key is cloneable with caches
22/// in this crate.
23pub trait FnCacheMany<I, O>: FnCache<I, O> {
24 /// Retrieve multiple values stored in the cache.
25 /// If any of the values do not yet exist, the
26 /// function is called, and the result is added
27 /// to the cache before returning them.
28 ///
29 /// This is helpful for cases which may require a
30 /// recursive definition that uses multiple values
31 /// at once.
32 fn get_many<const N: usize>(&mut self, inputs: [I; N]) -> [&O; N];
33}