multi_containers/
multimap_builder.rs

1use crate::maps::Map;
2use crate::sets::Set;
3use crate::MultiMap;
4use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
5use std::hash::Hash;
6
7/// A builder for a multi-map. This struct does nothing by itself, but it is used to chain method calls to
8/// configure the multi-map before building it.
9pub struct MultiMapBuilder {}
10
11impl MultiMapBuilder {
12    /// Configures the multi-map to use a hashmap.
13    pub fn hash_keys<K, S>() -> MultiMapBuilderWithKeys<HashMap<K, S>>
14    where
15        K: Hash + Eq,
16    {
17        Self::with_map_type()
18    }
19
20    /// Configures the multi-map to use a sorted map.
21    pub fn sorted_keys<K, S>() -> MultiMapBuilderWithKeys<BTreeMap<K, S>>
22    where
23        K: Ord,
24    {
25        Self::with_map_type()
26    }
27
28    /// An advanced method that allows you to specify the type of map to use for keys.
29    pub fn with_map_type<M>() -> MultiMapBuilderWithKeys<M>
30    where
31        M: Map,
32    {
33        MultiMapBuilderWithKeys {
34            _m: std::marker::PhantomData,
35        }
36    }
37}
38
39/// A builder for a multi-map that has a known type for the map.
40pub struct MultiMapBuilderWithKeys<M>
41where
42    M: Map,
43{
44    _m: std::marker::PhantomData<M>,
45}
46
47impl<M> MultiMapBuilderWithKeys<M>
48where
49    M: Map,
50{
51    /// Configures the multi-map to use a hash set for values.
52    pub fn hash_values<V>(self) -> MultiMapBuilderWithKeysAndVals<M>
53    where
54        M: Map<Val = HashSet<V>>,
55        V: Hash + Eq,
56    {
57        self.with_set_type()
58    }
59
60    /// Configures the multi-map to use a sorted set for values.
61    pub fn sorted_values<V>(self) -> MultiMapBuilderWithKeysAndVals<M>
62    where
63        M: Map<Val = BTreeSet<V>>,
64        V: Ord,
65    {
66        self.with_set_type()
67    }
68
69    /// An advanced method that allows you to specify the type of set to use for values.
70    pub fn with_set_type(self) -> MultiMapBuilderWithKeysAndVals<M>
71    where
72        M: Map,
73        M::Val: Set,
74    {
75        MultiMapBuilderWithKeysAndVals {
76            _m: std::marker::PhantomData,
77        }
78    }
79}
80
81/// A builder for a multi-map that has a known type for keys and values.
82pub struct MultiMapBuilderWithKeysAndVals<M> {
83    _m: std::marker::PhantomData<M>,
84}
85
86impl<M> MultiMapBuilderWithKeysAndVals<M>
87where
88    M: Default,
89{
90    /// Builds a multi-map.
91    pub fn build(self) -> MultiMap<M> {
92        Default::default()
93    }
94}