fn_cache/
container.rs

1/// A generic trait for anything that would like to be used in a [`GenericCache`], allowing easy
2/// extensibility using a container not covered by this library.
3///
4/// [`HashCache`] and [`BTreeCache`] are both just using `GenericCache` under the hood, by
5/// implementing this trait on `HashMap` and `BTreeMap`.
6///
7/// If this trait doesn't quite fit with your container, you can also implement fully your own
8/// [`FnCache`], which requires a bit more work than using this trait, but gives you full
9/// generality. This is how [`VecCache`] is implemented, because it is not sparse, and must fill
10/// all earlier indices.
11pub trait SparseContainer: Sized {
12	type Input;
13	type Output;
14
15	/// Returns true if the container is holding an output associated with `input`.
16	fn has(&self, input: &Self::Input) -> bool {
17		self.get(input).is_some()
18	}
19
20	/// Returns the output associated with `input`, if it exists.
21	fn get(&self, input: &Self::Input) -> Option<&Self::Output>;
22
23	/// Associate a new `output` with the key `input`, which can later be retrieved using
24	/// [`Self::get`]
25	fn put(&mut self, input: Self::Input, output: Self::Output) -> &Self::Output;
26}
27
28/// A trait to clear the container, for cases when caching may need to be temporary during some
29/// calcuations, but may grow unbounded over the course of the program otherwise.
30pub trait ContainerClear {
31	/// Clears the cache, removing all key-value pairs.
32	/// Keeps the allocated memory for reuse.
33	fn clear(&mut self);
34}
35
36/// A trait to let you see how many values the container is holding.
37pub trait ContainerLen {
38	/// Returns the number of elements in the container.
39	fn len(&self) -> usize;
40}
41
42/// A trait to reserve space in a container, in case you know how many values are about to enter
43/// and can avoid reallocations by reserving more space at once.
44pub trait ContainerReserve {
45	/// Reserves capacity for at least `additional` more elements
46	/// to be inserted in the cache. The collection may
47	/// reserve more space to avoid frequent reallocations.
48	fn reserve(&mut self, additional: usize);
49}
50
51/// A trait to remove items from a container, to prevent growth without bound.
52pub trait ContainerRemove: SparseContainer {
53	/// Removes the input from the cache, returning any value
54	/// if the input was previously in the cache.
55	fn remove(&mut self, input: &Self::Input) -> Option<Self::Output>;
56}