fn_cache/
btree_cache.rs

1use std::collections::BTreeMap;
2
3use core::cmp::Ord;
4
5use crate::{
6	container::{ContainerClear, ContainerLen, ContainerRemove, SparseContainer},
7	GenericCache,
8};
9
10/// A cache for a function which uses a [`BTreeMap`].
11///
12/// The cache takes ownership of all inputs, but
13/// only passes a reference to the function,
14/// allowing it to store the input in the cache
15/// without any copies or clones.
16///
17/// The requirements for a [`BTreeMap`] must be met,
18/// specifically the keys must implement [`Ord`]
19pub type BTreeCache<'f, I, O> = GenericCache<'f, BTreeMap<I, O>>;
20
21impl<I, O> SparseContainer for BTreeMap<I, O>
22where
23	I: Ord,
24{
25	type Input = I;
26	type Output = O;
27
28	fn has(&self, input: &Self::Input) -> bool {
29		self.contains_key(input)
30	}
31
32	fn get(&self, input: &Self::Input) -> Option<&Self::Output> {
33		self.get(input)
34	}
35
36	fn put(&mut self, input: Self::Input, output: Self::Output) -> &Self::Output {
37		self.entry(input).or_insert(output)
38	}
39}
40
41impl<I, O> ContainerLen for BTreeMap<I, O>
42where
43	I: Ord,
44{
45	fn len(&self) -> usize {
46		self.len()
47	}
48}
49
50impl<I, O> ContainerClear for BTreeMap<I, O>
51where
52	I: Ord,
53{
54	fn clear(&mut self) {
55		self.clear()
56	}
57}
58
59impl<I, O> ContainerRemove for BTreeMap<I, O>
60where
61	I: Ord,
62{
63	fn remove(&mut self, input: &Self::Input) -> Option<Self::Output> {
64		self.remove(input)
65	}
66}