Skip to main content

btree_range_map/generic/
multimap.rs

1use crate::{
2	AnyRange, AsRange,
3	generic::{
4		RangeMap,
5		map::{IntoIter, Iter},
6	},
7};
8use cc_traits::SetMut;
9use range_traits::{Measure, PartialEnum};
10use raw_btree::{Item, Storage};
11
12/// Multi map.
13///
14/// In a multi map, each key is associated to a set of values.
15/// The type parameter `S` is the set type. It can be replaced by anything
16/// implementing the [`cc_traits::SetMut`] trait, such as the standard
17/// [`BTreeSet`](std::collections::BTreeSet) and [`HashSet`](std::collections::HashSet).
18pub struct RangeMultiMap<K, S, C: Storage<Item<AnyRange<K>, S>>> {
19	map: RangeMap<K, S, C>,
20}
21
22impl<K: Clone, S: Clone, C: Storage<Item<AnyRange<K>, S>>> Clone for RangeMultiMap<K, S, C> {
23	fn clone(&self) -> Self {
24		RangeMultiMap {
25			map: self.map.clone(),
26		}
27	}
28}
29
30impl<K, S, C: Storage<Item<AnyRange<K>, S>>> RangeMultiMap<K, S, C> {
31	pub fn new() -> RangeMultiMap<K, S, C> {
32		RangeMultiMap {
33			map: RangeMap::new(),
34		}
35	}
36}
37
38impl<K, S, C: Storage<Item<AnyRange<K>, S>>> Default for RangeMultiMap<K, S, C> {
39	fn default() -> Self {
40		Self::new()
41	}
42}
43
44impl<K, S, C: Storage<Item<AnyRange<K>, S>>> RangeMultiMap<K, S, C> {
45	pub fn iter(&self) -> Iter<'_, K, S, C> {
46		self.map.iter()
47	}
48}
49
50impl<'a, K: Clone + PartialOrd + Measure, S, C: Storage<Item<AnyRange<K>, S>>> IntoIterator
51	for &'a RangeMultiMap<K, S, C>
52{
53	type Item = (&'a AnyRange<K>, &'a S);
54	type IntoIter = Iter<'a, K, S, C>;
55
56	fn into_iter(self) -> Self::IntoIter {
57		self.iter()
58	}
59}
60
61impl<K, S, C: Storage<Item<AnyRange<K>, S>>> RangeMultiMap<K, S, C> {
62	pub fn insert<R: AsRange<Item = K>, V>(&mut self, key: R, value: V)
63	where
64		K: Clone + PartialEnum + Measure,
65		V: PartialEq + Clone,
66		S: SetMut<V> + PartialEq + Clone + Default,
67	{
68		self.map.update(key, |set_opt| {
69			let mut result = match set_opt {
70				Some(set) => set.clone(),
71				None => S::default(),
72			};
73
74			result.insert(value.clone());
75			Some(result)
76		})
77	}
78
79	pub fn remove<R: AsRange<Item = K>, V>(&mut self, key: R, value: &V)
80	where
81		K: Clone + PartialEnum + Measure,
82		V: PartialEq + Clone,
83		S: SetMut<V> + PartialEq + Clone + Default,
84	{
85		self.map.update(key, |set_opt| match set_opt {
86			Some(set) => {
87				let mut result = set.clone();
88				result.remove(value);
89				if result.is_empty() {
90					None
91				} else {
92					Some(result)
93				}
94			}
95			None => None,
96		})
97	}
98}
99
100impl<K: Clone + PartialOrd + Measure, S, C: Storage<Item<AnyRange<K>, S>>> IntoIterator
101	for RangeMultiMap<K, S, C>
102{
103	type Item = (AnyRange<K>, S);
104	type IntoIter = IntoIter<K, S, C>;
105
106	fn into_iter(self) -> Self::IntoIter {
107		self.map.into_iter()
108	}
109}