2 use std::marker::PhantomData;
4 use std::ops::RangeBounds;
7 use crate::vec::IndexVec;
8 use smallvec::SmallVec;
13 /// Stores a set of intervals on the indices.
14 #[derive(Debug, Clone)]
15 pub struct IntervalSet<I> {
17 map: SmallVec<[(u32, u32); 4]>,
19 _data: PhantomData<I>,
23 fn inclusive_start<T: Idx>(range: impl RangeBounds<T>) -> u32 {
24 match range.start_bound() {
25 Bound::Included(start) => start.index() as u32,
26 Bound::Excluded(start) => start.index() as u32 + 1,
27 Bound::Unbounded => 0,
32 fn inclusive_end<T: Idx>(domain: usize, range: impl RangeBounds<T>) -> Option<u32> {
33 let end = match range.end_bound() {
34 Bound::Included(end) => end.index() as u32,
35 Bound::Excluded(end) => end.index().checked_sub(1)? as u32,
36 Bound::Unbounded => domain.checked_sub(1)? as u32,
41 impl<I: Idx> IntervalSet<I> {
42 pub fn new(domain: usize) -> IntervalSet<I> {
43 IntervalSet { map: SmallVec::new(), domain, _data: PhantomData }
46 pub fn clear(&mut self) {
50 pub fn iter(&self) -> impl Iterator<Item = I> + '_
54 self.iter_intervals().flatten()
57 /// Iterates through intervals stored in the set, in order.
58 pub fn iter_intervals(&self) -> impl Iterator<Item = std::ops::Range<I>> + '_
62 self.map.iter().map(|&(start, end)| I::new(start as usize)..I::new(end as usize + 1))
65 /// Returns true if we increased the number of elements present.
66 pub fn insert(&mut self, point: I) -> bool {
67 self.insert_range(point..=point)
70 /// Returns true if we increased the number of elements present.
71 pub fn insert_range(&mut self, range: impl RangeBounds<I> + Clone) -> bool {
72 let start = inclusive_start(range.clone());
73 let Some(mut end) = inclusive_end(self.domain, range) else {
82 // This condition looks a bit weird, but actually makes sense.
84 // if r.0 == end + 1, then we're actually adjacent, so we want to
85 // continue to the next range. We're looking here for the first
86 // range which starts *non-adjacently* to our end.
87 let next = self.map.partition_point(|r| r.0 <= end + 1);
88 if let Some(last) = next.checked_sub(1) {
89 let (prev_start, prev_end) = &mut self.map[last];
90 if *prev_end + 1 >= start {
91 // If the start for the inserted range is adjacent to the
92 // end of the previous, we can extend the previous range.
93 if start < *prev_start {
94 // Our range starts before the one we found. We'll need
95 // to *remove* it, and then try again.
97 // FIXME: This is not so efficient; we may need to
98 // recurse a bunch of times here. Instead, it's probably
99 // better to do something like drain_filter(...) on the
100 // map to be able to delete or modify all the ranges in
101 // start..=end and then potentially re-insert a new
103 end = std::cmp::max(end, *prev_end);
104 self.map.remove(last);
106 // We overlap with the previous range, increase it to
109 // Make sure we're actually going to *increase* it though --
110 // it may be that end is just inside the previously existing
112 return if end > *prev_end {
120 // Otherwise, we don't overlap, so just insert
121 self.map.insert(last + 1, (start, end));
125 if self.map.is_empty() {
126 // Quite common in practice, and expensive to call memcpy
128 self.map.push((start, end));
130 self.map.insert(next, (start, end));
137 pub fn contains(&self, needle: I) -> bool {
138 let needle = needle.index() as u32;
139 let Some(last) = self.map.partition_point(|r| r.0 <= needle).checked_sub(1) else {
140 // All ranges in the map start after the new range's end
143 let (_, prev_end) = &self.map[last];
147 pub fn superset(&self, other: &IntervalSet<I>) -> bool
151 // FIXME: Performance here is probably not great. We will be doing a lot
152 // of pointless tree traversals.
153 other.iter().all(|elem| self.contains(elem))
156 pub fn is_empty(&self) -> bool {
160 /// Returns the maximum (last) element present in the set from `range`.
161 pub fn last_set_in(&self, range: impl RangeBounds<I> + Clone) -> Option<I> {
162 let start = inclusive_start(range.clone());
163 let Some(end) = inclusive_end(self.domain, range) else {
170 let Some(last) = self.map.partition_point(|r| r.0 <= end).checked_sub(1) else {
171 // All ranges in the map start after the new range's end
174 let (_, prev_end) = &self.map[last];
175 if start <= *prev_end { Some(I::new(std::cmp::min(*prev_end, end) as usize)) } else { None }
178 pub fn insert_all(&mut self) {
180 self.map.push((0, self.domain.try_into().unwrap()));
183 pub fn union(&mut self, other: &IntervalSet<I>) -> bool
187 assert_eq!(self.domain, other.domain);
188 let mut did_insert = false;
189 for range in other.iter_intervals() {
190 did_insert |= self.insert_range(range);
196 /// This data structure optimizes for cases where the stored bits in each row
197 /// are expected to be highly contiguous (long ranges of 1s or 0s), in contrast
198 /// to BitMatrix and SparseBitMatrix which are optimized for
199 /// "random"/non-contiguous bits and cheap(er) point queries at the expense of
202 pub struct SparseIntervalMatrix<R, C>
207 rows: IndexVec<R, IntervalSet<C>>,
211 impl<R: Idx, C: Step + Idx> SparseIntervalMatrix<R, C> {
212 pub fn new(column_size: usize) -> SparseIntervalMatrix<R, C> {
213 SparseIntervalMatrix { rows: IndexVec::new(), column_size }
216 pub fn rows(&self) -> impl Iterator<Item = R> {
220 pub fn row(&self, row: R) -> Option<&IntervalSet<C>> {
224 fn ensure_row(&mut self, row: R) -> &mut IntervalSet<C> {
225 self.rows.ensure_contains_elem(row, || IntervalSet::new(self.column_size));
229 pub fn union_row(&mut self, row: R, from: &IntervalSet<C>) -> bool
233 self.ensure_row(row).union(from)
236 pub fn union_rows(&mut self, read: R, write: R) -> bool
240 if read == write || self.rows.get(read).is_none() {
243 self.ensure_row(write);
244 let (read_row, write_row) = self.rows.pick2_mut(read, write);
245 write_row.union(read_row)
248 pub fn insert_all_into_row(&mut self, row: R) {
249 self.ensure_row(row).insert_all();
252 pub fn insert_range(&mut self, row: R, range: impl RangeBounds<C> + Clone) {
253 self.ensure_row(row).insert_range(range);
256 pub fn insert(&mut self, row: R, point: C) -> bool {
257 self.ensure_row(row).insert(point)
260 pub fn contains(&self, row: R, point: C) -> bool {
261 self.row(row).map_or(false, |r| r.contains(point))