cuckoo_cache/builder.rs
1//! Builder for configuring a [`CuckooCache`] instance.
2
3use crate::{CuckooCache, Policy};
4
5/// A builder used to configure and construct a [`CuckooCache`].
6pub struct Builder {
7 pub(crate) item_size: usize,
8 pub(crate) nitem: usize,
9 pub(crate) max_displace: usize,
10 pub(crate) policy: Policy,
11 pub(crate) max_ttl: u32,
12}
13
14impl Default for Builder {
15 fn default() -> Self {
16 Self {
17 item_size: 64,
18 nitem: 1024,
19 max_displace: 2,
20 policy: Policy::Random,
21 max_ttl: 2_592_000, // 30 days in seconds
22 }
23 }
24}
25
26impl Builder {
27 /// Set the fixed size in bytes for each item slot. Key, value, and
28 /// per-item overhead must fit within this size.
29 ///
30 /// ```
31 /// use cuckoo_cache::CuckooCache;
32 ///
33 /// let cache = CuckooCache::builder().item_size(128).build();
34 /// ```
35 pub fn item_size(mut self, bytes: usize) -> Self {
36 self.item_size = bytes;
37 self
38 }
39
40 /// Set the maximum number of items the cache can hold.
41 ///
42 /// ```
43 /// use cuckoo_cache::CuckooCache;
44 ///
45 /// let cache = CuckooCache::builder().nitem(4096).build();
46 /// ```
47 pub fn nitem(mut self, nitem: usize) -> Self {
48 self.nitem = nitem;
49 self
50 }
51
52 /// Set the maximum displacement depth during insertion. Higher values
53 /// reduce evictions at the cost of longer worst-case insertion times.
54 ///
55 /// ```
56 /// use cuckoo_cache::CuckooCache;
57 ///
58 /// let cache = CuckooCache::builder().max_displace(4).build();
59 /// ```
60 pub fn max_displace(mut self, depth: usize) -> Self {
61 self.max_displace = depth;
62 self
63 }
64
65 /// Set the eviction policy.
66 ///
67 /// ```
68 /// use cuckoo_cache::{CuckooCache, Policy};
69 ///
70 /// let cache = CuckooCache::builder().policy(Policy::Expire).build();
71 /// ```
72 pub fn policy(mut self, policy: Policy) -> Self {
73 self.policy = policy;
74 self
75 }
76
77 /// Set the maximum TTL in seconds. Items with a TTL exceeding this value
78 /// will have their TTL clamped.
79 ///
80 /// ```
81 /// use cuckoo_cache::CuckooCache;
82 ///
83 /// let cache = CuckooCache::builder().max_ttl(86400).build();
84 /// ```
85 pub fn max_ttl(mut self, seconds: u32) -> Self {
86 self.max_ttl = seconds;
87 self
88 }
89
90 /// Consume the builder and allocate a [`CuckooCache`].
91 ///
92 /// ```
93 /// use cuckoo_cache::{CuckooCache, Policy};
94 ///
95 /// let cache = CuckooCache::builder()
96 /// .nitem(4096)
97 /// .item_size(64)
98 /// .policy(Policy::Random)
99 /// .build();
100 /// ```
101 pub fn build(self) -> CuckooCache {
102 CuckooCache::from_builder(self)
103 }
104}