Skip to main content

mid_tools/
range_set.rs

1use std::{borrow::Borrow, fmt, ops};
2
3use crate::partition_map::{IntoPartitions, Partition, PartitionBounds, PartitionMap, Partitions};
4
5#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
6#[repr(transparent)]
7pub struct RangeSet<T>(PartitionMap<T, bool>);
8
9impl<T: fmt::Debug> fmt::Debug for RangeSet<T> {
10    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11        self.0
12            .partitions()
13            .filter_map(|(k, &v)| v.then_some(k))
14            .fold(&mut f.debug_set(), |d, k| d.entry(&k))
15            .finish()
16    }
17}
18
19impl<T> RangeSet<T> {
20    pub const EMPTY: Self = Self::empty();
21    pub const FULL: Self = Self::full();
22
23    #[must_use]
24    #[inline]
25    pub const fn new(init: bool) -> Self { Self(PartitionMap::new(init)) }
26
27    #[must_use]
28    #[inline]
29    pub const fn empty() -> Self { Self::new(false) }
30
31    #[must_use]
32    #[inline]
33    pub const fn full() -> Self { Self::new(true) }
34
35    #[must_use]
36    pub fn all_ranges(&self) -> AllRanges<'_, T> { AllRanges(self.0.partitions()) }
37
38    #[must_use]
39    pub fn ranges(&self) -> Ranges<'_, T> { Ranges(self.0.partitions(), true) }
40
41    #[must_use]
42    pub fn empty_ranges(&self) -> Ranges<'_, T> { Ranges(self.0.partitions(), false) }
43
44    #[must_use]
45    pub fn into_ranges(self) -> IntoRanges<T> { IntoRanges(self.0.into_partitions(), true) }
46
47    #[must_use]
48    pub fn into_empty_ranges(self) -> IntoRanges<T> { IntoRanges(self.0.into_partitions(), false) }
49}
50
51impl<T: Ord> RangeSet<T> {
52    #[inline]
53    pub fn contains<Q: ?Sized + Ord>(&self, at: &Q) -> bool
54    where T: Borrow<Q> {
55        *self.0.sample(at)
56    }
57}
58
59impl<T: Clone + Ord> RangeSet<T> {
60    #[inline]
61    pub fn insert<B: PartitionBounds<T>>(&mut self, range: B) { self.0.set(range, true); }
62
63    #[inline]
64    pub fn remove<B: PartitionBounds<T>>(&mut self, range: B) { self.0.set(range, false); }
65
66    pub fn union(&mut self, other: &Self) { self.0.fold(other, |(_, &v), &s| v || s); }
67
68    #[must_use]
69    #[inline]
70    pub fn unioned(mut self, other: &Self) -> Self {
71        self.union(other);
72        self
73    }
74
75    pub fn intersect(&mut self, other: &Self) { self.0.fold(other, |(_, &v), &s| v && s); }
76
77    #[must_use]
78    #[inline]
79    pub fn intersected(mut self, other: &Self) -> Self {
80        self.intersect(other);
81        self
82    }
83
84    pub fn invert(&mut self) { self.0.update(.., |_, &v| !v); }
85
86    #[must_use]
87    #[inline]
88    pub fn inverted(mut self) -> Self {
89        self.invert();
90        self
91    }
92}
93
94impl<T> ops::Deref for RangeSet<T> {
95    type Target = PartitionMap<T, bool>;
96
97    #[inline]
98    fn deref(&self) -> &Self::Target { &self.0 }
99}
100
101impl<T> ops::DerefMut for RangeSet<T> {
102    #[inline]
103    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
104}
105
106impl<T: Clone + Ord, B: PartitionBounds<T>> Extend<B> for RangeSet<T> {
107    #[inline]
108    fn extend<I: IntoIterator<Item = B>>(&mut self, it: I) {
109        self.0.extend(it.into_iter().map(|r| (r, true)));
110    }
111}
112
113impl<T: Clone + Ord, B: PartitionBounds<T>> FromIterator<B> for RangeSet<T> {
114    #[inline]
115    fn from_iter<I: IntoIterator<Item = B>>(it: I) -> Self {
116        Self(it.into_iter().map(|r| (r, true)).collect())
117    }
118}
119
120#[derive(Debug, Clone)]
121pub struct Ranges<'a, T>(Partitions<'a, T, bool>, bool);
122
123impl<'a, T> Iterator for Ranges<'a, T> {
124    type Item = Partition<&'a T>;
125
126    fn next(&mut self) -> Option<Self::Item> {
127        loop {
128            let (part, &value) = self.0.next()?;
129
130            if value == self.1 {
131                return Some(part);
132            }
133        }
134    }
135}
136
137#[derive(Debug)]
138pub struct IntoRanges<T>(IntoPartitions<T, bool>, bool);
139
140impl<T: Clone> Iterator for IntoRanges<T> {
141    type Item = Partition<T>;
142
143    fn next(&mut self) -> Option<Self::Item> {
144        loop {
145            let (part, value) = self.0.next()?;
146
147            if value == self.1 {
148                return Some(part);
149            }
150        }
151    }
152}
153
154#[derive(Debug, Clone)]
155#[repr(transparent)]
156pub struct AllRanges<'a, T>(Partitions<'a, T, bool>);
157
158impl<'a, T> Iterator for AllRanges<'a, T> {
159    type Item = (Partition<&'a T>, bool);
160
161    fn next(&mut self) -> Option<Self::Item> {
162        let (part, &value) = self.0.next()?;
163        Some((part, value))
164    }
165}
166
167#[cfg(test)]
168mod test {
169    use proptest::prelude::*;
170
171    use super::*;
172
173    const MAX: usize = 1024;
174    type Part = (Partition<usize>, bool);
175
176    fn check_part((Partition { start, end }, _): &Part) -> bool {
177        start.zip(*end).is_none_or(|(s, e)| e >= s)
178    }
179
180    fn prop_idx() -> impl Strategy<Value = usize> { 0..MAX }
181
182    fn to_open<T>(opt: Option<T>) -> ops::Bound<T> {
183        opt.map_or(ops::Bound::Unbounded, ops::Bound::Excluded)
184    }
185
186    fn to_closed<T>(opt: Option<T>) -> ops::Bound<T> {
187        opt.map_or(ops::Bound::Unbounded, ops::Bound::Included)
188    }
189
190    fn prop_part() -> impl Strategy<Value = Part> {
191        (
192            prop::option::of(prop_idx()),
193            prop::option::of(prop_idx()),
194            any::<bool>(),
195        )
196            .prop_map(|(start, end, value)| {
197                let (start, end) = if start.zip(end).is_some_and(|(s, e)| e < s) {
198                    (end, start)
199                } else {
200                    (start, end)
201                };
202
203                (Partition { start, end }, value)
204            })
205            .prop_filter("Partitions must be valid", check_part)
206    }
207
208    fn dense_map(start: bool, parts: &[Part]) -> [bool; MAX] {
209        let mut arr = [start; MAX];
210
211        for (Partition { start, end }, value) in parts {
212            arr[(to_closed(*start), to_open(*end))]
213                .iter_mut()
214                .for_each(|v| *v = *value);
215        }
216
217        arr
218    }
219
220    fn test_unop<F: FnOnce(&mut RangeSet<usize>), G: Fn(bool) -> bool>(
221        s: bool,
222        v: Vec<Part>,
223        op: F,
224        dense_op: G,
225    ) {
226        let dense = dense_map(s, &v);
227
228        let mut set = RangeSet::new(s);
229        (*set).extend(v);
230        op(&mut set);
231
232        for (i, el) in dense.into_iter().enumerate() {
233            assert_eq!(*set.sample(&i), dense_op(el), "i = {i:?}, set = {set:?}");
234        }
235    }
236
237    fn test_binop<F: FnOnce(&mut RangeSet<usize>, &RangeSet<usize>), G: Fn(bool, bool) -> bool>(
238        ls: bool,
239        lv: Vec<Part>,
240        rs: bool,
241        rv: Vec<Part>,
242        op: F,
243        dense_op: G,
244    ) {
245        let ld = dense_map(ls, &lv);
246        let rd = dense_map(rs, &rv);
247
248        let mut lhs = RangeSet::new(ls);
249        let mut rhs = RangeSet::new(rs);
250        (*lhs).extend(lv);
251        (*rhs).extend(rv);
252        let mut out = lhs.clone();
253        op(&mut out, &rhs);
254
255        for i in 0..MAX {
256            assert_eq!(
257                *out.sample(&i),
258                dense_op(ld[i], rd[i]),
259                "i = {i:?}, lhs = {lhs:?}, rhs = {rhs:?}, out = {out:?}"
260            );
261        }
262    }
263
264    fn part<B: super::PartitionBounds<K>, K, V>(b: B, v: V) -> (Partition<K>, V) { (b.into(), v) }
265
266    #[test]
267    fn inter_sanity() {
268        test_binop(
269            false,
270            vec![part(1.., true)],
271            false,
272            vec![part(..1, true)],
273            RangeSet::intersect,
274            |l, r| l && r,
275        );
276        test_binop(
277            false,
278            vec![part(..1, true)],
279            false,
280            vec![part(1.., true)],
281            RangeSet::intersect,
282            |l, r| l && r,
283        );
284    }
285
286    proptest! {
287        #[test]
288        fn test_union(
289            ls in any::<bool>(),
290            lv in prop::collection::vec(prop_part(), 0..512),
291            rs in any::<bool>(),
292            rv in prop::collection::vec(prop_part(), 0..512),
293        ) {
294            test_binop(ls, lv, rs, rv, RangeSet::union, |l, r| l || r);
295        }
296
297        #[test]
298        fn test_intersect(
299            ls in any::<bool>(),
300            lv in prop::collection::vec(prop_part(), 0..512),
301            rs in any::<bool>(),
302            rv in prop::collection::vec(prop_part(), 0..512),
303        ) {
304            test_binop(ls, lv, rs, rv, RangeSet::intersect, |l, r| l && r);
305        }
306
307        #[test]
308        fn test_invert(
309            s in any::<bool>(),
310            v in prop::collection::vec(prop_part(), 0..512),
311        ) {
312            test_unop(s, v, RangeSet::invert, |b| !b);
313        }
314    }
315}