Skip to main content

txmap/
tx_map_builder.rs

1use crate::{
2    custodian::Custodian,
3    hasher::DefaultBuildHasher,
4    indexer::Indexer,
5    lock_policies::{lock_policy::LockPolicy, mutex_policy::MutexPolicy},
6    new_types::ShardCount,
7    shards::Shards,
8    tx_map::TxMap,
9};
10use std::{
11    hash::{BuildHasher, Hash},
12    marker::PhantomData,
13};
14
15/// Builder for configuring and constructing a [`TxMap`].
16///
17/// Use [`TxMapBuilder::default`] to get a builder with sensible defaults
18/// (32 shards, `MutexPolicy`, default hasher), then customise as needed.
19pub struct TxMapBuilder<L = MutexPolicy, S = DefaultBuildHasher>
20where
21    L: LockPolicy,
22    S: BuildHasher,
23{
24    shards: Shards,
25    capacity: usize,
26    hasher_builder: S,
27    _phantom_l: PhantomData<L>,
28}
29
30impl<L, S> TxMapBuilder<L, S>
31where
32    L: LockPolicy,
33    S: BuildHasher,
34{
35    #[must_use]
36    /// Sets the initial capacity hint (total across all shards).
37    pub fn with_capacity(mut self, capacity: usize) -> Self {
38        self.capacity = capacity;
39        self
40    }
41
42    #[must_use]
43    /// Sets the number of shards.
44    pub fn with_shards(mut self, shards: Shards) -> Self {
45        self.shards = shards;
46        self
47    }
48
49    #[must_use]
50    /// Replaces the hasher builder.
51    pub fn with_hasher<BH>(self, hasher_builder: BH) -> TxMapBuilder<L, BH>
52    where
53        BH: BuildHasher,
54    {
55        let Self {
56            capacity,
57            shards,
58            _phantom_l,
59            ..
60        } = self;
61        TxMapBuilder::<L, BH> {
62            capacity,
63            shards,
64            hasher_builder,
65            _phantom_l,
66        }
67    }
68
69    #[must_use]
70    /// Replaces the lock policy.
71    pub fn with_lock_policy<LP>(self) -> TxMapBuilder<LP, S>
72    where
73        LP: LockPolicy,
74    {
75        let Self {
76            capacity,
77            shards,
78            hasher_builder,
79            ..
80        } = self;
81        TxMapBuilder::<LP, S> {
82            capacity,
83            shards,
84            hasher_builder,
85            _phantom_l: PhantomData,
86        }
87    }
88
89    #[must_use]
90    /// Consumes the builder and returns a [`TxMap`].
91    pub fn build<K, V>(self) -> TxMap<K, V, L, S>
92    where
93        K: Clone + Hash + Eq,
94    {
95        let shard_count: ShardCount = self.shards.into();
96        TxMap {
97            shard_count,
98            custodian: Custodian::new(shard_count, self.capacity),
99            indexer: Indexer::new(self.hasher_builder),
100        }
101    }
102}
103
104impl Default for TxMapBuilder<MutexPolicy, DefaultBuildHasher> {
105    fn default() -> Self {
106        Self {
107            capacity: 0,
108            shards: Shards::_32,
109            _phantom_l: PhantomData,
110            hasher_builder: DefaultBuildHasher::default(),
111        }
112    }
113}