micro_moka/unsync/
builder.rs1use super::Cache;
2
3use std::{
4 collections::hash_map::RandomState,
5 hash::{BuildHasher, Hash},
6 marker::PhantomData,
7};
8
9#[must_use]
29pub struct CacheBuilder<K, V, C> {
30 max_capacity: Option<u64>,
31 initial_capacity: Option<usize>,
32 cache_type: PhantomData<C>,
33 _marker: PhantomData<(K, V)>,
34}
35
36impl<K, V> Default for CacheBuilder<K, V, Cache<K, V, RandomState>>
37where
38 K: Eq + Hash,
39{
40 fn default() -> Self {
41 Self {
42 max_capacity: None,
43 initial_capacity: None,
44 cache_type: Default::default(),
45 _marker: Default::default(),
46 }
47 }
48}
49
50impl<K, V> CacheBuilder<K, V, Cache<K, V, RandomState>>
51where
52 K: Eq + Hash,
53{
54 pub fn new(max_capacity: u64) -> Self {
57 Self {
58 max_capacity: Some(max_capacity),
59 ..Default::default()
60 }
61 }
62
63 pub fn build(self) -> Cache<K, V, RandomState> {
65 let build_hasher = RandomState::default();
66 Cache::with_everything(self.max_capacity, self.initial_capacity, build_hasher)
67 }
68
69 pub fn build_with_hasher<S>(self, hasher: S) -> Cache<K, V, S>
71 where
72 S: BuildHasher + Clone,
73 {
74 Cache::with_everything(self.max_capacity, self.initial_capacity, hasher)
75 }
76}
77
78impl<K, V, C> CacheBuilder<K, V, C> {
79 pub fn max_capacity(self, max_capacity: u64) -> Self {
81 Self {
82 max_capacity: Some(max_capacity),
83 ..self
84 }
85 }
86
87 pub fn initial_capacity(self, number_of_entries: usize) -> Self {
89 Self {
90 initial_capacity: Some(number_of_entries),
91 ..self
92 }
93 }
94}
95
96#[cfg(test)]
97mod tests {
98 use super::CacheBuilder;
99
100 #[test]
101 fn build_cache() {
102 let mut cache = CacheBuilder::<char, String, _>::new(100).build();
104 let policy = cache.policy();
105
106 assert_eq!(policy.max_capacity(), Some(100));
107
108 cache.insert('a', "Alice".to_string());
109 assert_eq!(cache.get(&'a'), Some(&"Alice".to_string()));
110 }
111}