| 1 | use crate::weight::{WeightScale, ZeroWeightScale}; |
| 2 | use std::collections::hash_map::RandomState; |
| 3 | use std::hash::BuildHasher; |
| 4 | use std::marker::PhantomData; |
| 5 | use std::num::NonZeroUsize; |
| 6 | |
| 7 | /// A configuration structure used to create an LRU cache. |
| 8 | pub struct CLruCacheConfig<K, V, S = RandomState, W = ZeroWeightScale> { |
| 9 | pub(crate) capacity: NonZeroUsize, |
| 10 | pub(crate) hash_builder: S, |
| 11 | pub(crate) reserve: Option<usize>, |
| 12 | pub(crate) scale: W, |
| 13 | _marker: PhantomData<(K, V)>, |
| 14 | } |
| 15 | |
| 16 | impl<K, V> CLruCacheConfig<K, V> { |
| 17 | /// Creates a new configuration that will create an LRU cache |
| 18 | /// that will hold at most `capacity` elements and default parameters. |
| 19 | pub fn new(capacity: NonZeroUsize) -> Self { |
| 20 | Self { |
| 21 | capacity, |
| 22 | hash_builder: RandomState::default(), |
| 23 | reserve: None, |
| 24 | scale: ZeroWeightScale, |
| 25 | _marker: PhantomData, |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | impl<K, V, S: BuildHasher, W: WeightScale<K, V>> CLruCacheConfig<K, V, S, W> { |
| 31 | /// Configure the provided hash builder. |
| 32 | pub fn with_hasher<O: BuildHasher>(self, hash_builder: O) -> CLruCacheConfig<K, V, O, W> { |
| 33 | let Self { |
| 34 | capacity, |
| 35 | reserve, |
| 36 | scale, |
| 37 | _marker, |
| 38 | .. |
| 39 | } = self; |
| 40 | CLruCacheConfig { |
| 41 | capacity, |
| 42 | hash_builder, |
| 43 | reserve, |
| 44 | scale, |
| 45 | _marker, |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// Configure the amount of pre-allocated memory in order to hold at least `reserve` elements |
| 50 | /// without reallocating. |
| 51 | pub fn with_memory(mut self, reserve: usize) -> Self { |
| 52 | self.reserve = Some(reserve); |
| 53 | self |
| 54 | } |
| 55 | |
| 56 | /// Configure the provided scale. |
| 57 | pub fn with_scale<O: WeightScale<K, V>>(self, scale: O) -> CLruCacheConfig<K, V, S, O> { |
| 58 | let Self { |
| 59 | capacity, |
| 60 | hash_builder, |
| 61 | reserve, |
| 62 | .. |
| 63 | } = self; |
| 64 | CLruCacheConfig { |
| 65 | capacity, |
| 66 | hash_builder, |
| 67 | reserve, |
| 68 | scale, |
| 69 | _marker: PhantomData, |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |