diff --git a/src/entry.rs b/src/entry.rs index c1c90c2..04898ae 100644 --- a/src/entry.rs +++ b/src/entry.rs @@ -1,11 +1,8 @@ -use core::{ - fmt, - ops::Range, -}; use super::{ - IntervalMap, Interval, - ix::{IndexType, DefaultIx}, + ix::{DefaultIx, IndexType}, + Interval, IntervalMap, }; +use core::{fmt, ops::RangeInclusive}; /// A view into a vacant entry in an `IntervalMap`. It is part of the [Entry](enum.Entry.html) enum. pub struct VacantEntry<'a, T, V, Ix: IndexType = DefaultIx> { @@ -16,29 +13,43 @@ pub struct VacantEntry<'a, T, V, Ix: IndexType = DefaultIx> { } impl<'a, T, V, Ix: IndexType> VacantEntry<'a, T, V, Ix> -where T: Copy, +where + T: Copy, { - pub(super) fn new(tree: &'a mut IntervalMap, parent: Ix, left_side: bool, interval: Interval) -> Self { - Self { tree, parent, left_side, interval } + pub(super) fn new( + tree: &'a mut IntervalMap, + parent: Ix, + left_side: bool, + interval: Interval, + ) -> Self { + Self { + tree, + parent, + left_side, + interval, + } } /// Returns the interval that was used for the search. - pub fn interval(&self) -> Range { + pub fn interval(&self) -> RangeInclusive { self.interval.to_range() } } impl<'a, T, V, Ix: IndexType> VacantEntry<'a, T, V, Ix> -where T: Copy + PartialOrd, +where + T: Copy + PartialOrd, { /// Inserts a new value in the IntervalMap, and returns a mutable reference to it. pub fn insert(self, value: V) -> &'a mut V { - self.tree.insert_at(self.parent, self.left_side, self.interval, value) + self.tree + .insert_at(self.parent, self.left_side, self.interval, value) } } impl<'a, T, V, Ix: IndexType> fmt::Debug for VacantEntry<'a, T, V, Ix> -where T: PartialOrd + Copy + fmt::Debug, +where + T: PartialOrd + Copy + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "VacantEntry({:?})", self.interval.to_range()) @@ -52,14 +63,15 @@ pub struct OccupiedEntry<'a, T, V, Ix: IndexType = DefaultIx> { } impl<'a, T, V, Ix: IndexType> OccupiedEntry<'a, T, V, Ix> -where T: Copy, +where + T: Copy, { pub(super) fn new(tree: &'a mut IntervalMap, index: Ix) -> Self { Self { tree, index } } /// Returns the interval that was used for the search. - pub fn interval(&self) -> Range { + pub fn interval(&self) -> RangeInclusive { self.tree.nodes[self.index.get()].interval.to_range() } @@ -88,17 +100,24 @@ where T: Copy, } impl<'a, T, V, Ix: IndexType> fmt::Debug for OccupiedEntry<'a, T, V, Ix> -where T: PartialOrd + Copy + fmt::Debug, - V: fmt::Debug, +where + T: PartialOrd + Copy + fmt::Debug, + V: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let node = &self.tree.nodes[self.index.get()]; - write!(f, "OccupiedEntry({:?} => {:?})", node.interval.to_range(), node.value) + write!( + f, + "OccupiedEntry({:?} => {:?})", + node.interval.to_range(), + node.value + ) } } impl<'a, T, V, Ix: IndexType> OccupiedEntry<'a, T, V, Ix> -where T: Copy + PartialOrd, +where + T: Copy + PartialOrd, { /// Removes the entry from the map, and returns the removed value. pub fn remove(self) -> V { @@ -110,14 +129,15 @@ where T: Copy + PartialOrd, /// This enum is constructed from the [entry](../struct.IntervalMap.html#method.entry). pub enum Entry<'a, T, V, Ix: IndexType = DefaultIx> { Vacant(VacantEntry<'a, T, V, Ix>), - Occupied(OccupiedEntry<'a, T, V, Ix>) + Occupied(OccupiedEntry<'a, T, V, Ix>), } impl<'a, T, V, Ix: IndexType> Entry<'a, T, V, Ix> -where T: Copy, +where + T: Copy, { /// Returns the interval that was used for the search. - pub fn interval(&self) -> Range { + pub fn interval(&self) -> RangeInclusive { match self { Entry::Occupied(entry) => entry.interval(), Entry::Vacant(entry) => entry.interval(), @@ -126,7 +146,8 @@ where T: Copy, } impl<'a, T, V, Ix: IndexType> Entry<'a, T, V, Ix> -where T: Copy + PartialOrd, +where + T: Copy + PartialOrd, { /// If value is missing, initializes it with the `default` value. /// In any case, returns a mutable reference to the value. @@ -149,7 +170,8 @@ where T: Copy + PartialOrd, /// If value is missing, initializes it with a `default(interval)`. /// In any case, returns a mutable reference to the value. pub fn or_insert_with_interval(self, default: F) -> &'a mut V - where F: FnOnce(Range) -> V, + where + F: FnOnce(RangeInclusive) -> V, { match self { Entry::Occupied(entry) => entry.into_mut(), @@ -163,7 +185,8 @@ where T: Copy + PartialOrd, /// If the entry is occupied, modifies the value with `f` function, and returns a new entry. /// Does nothing if the value was vacant. pub fn and_modify(self, f: F) -> Self - where F: FnOnce(&mut V), + where + F: FnOnce(&mut V), { match self { Entry::Occupied(mut entry) => { @@ -176,8 +199,9 @@ where T: Copy + PartialOrd, } impl<'a, T, V, Ix: IndexType> Entry<'a, T, V, Ix> -where T: Copy + PartialOrd, - V: Default, +where + T: Copy + PartialOrd, + V: Default, { /// If value is missing, initializes it with `V::default()`. /// In any case, returns a mutable reference to the value. @@ -190,8 +214,9 @@ where T: Copy + PartialOrd, } impl<'a, T, V, Ix: IndexType> fmt::Debug for Entry<'a, T, V, Ix> -where T: PartialOrd + Copy + fmt::Debug, - V: fmt::Debug, +where + T: PartialOrd + Copy + fmt::Debug, + V: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { diff --git a/src/iter.rs b/src/iter.rs index 1f04e3a..7c30569 100644 --- a/src/iter.rs +++ b/src/iter.rs @@ -1,15 +1,16 @@ //! Module with various iterators over `IntervalMap` and `IntervalSet`. use alloc::vec::Vec; -use core::ops::{Range, RangeBounds, Bound}; use core::iter::FusedIterator; use core::mem; +use core::ops::{Bound, RangeBounds, RangeInclusive}; -use super::{Interval, IntervalMap, Node, IndexType, check_ordered, BitVec}; +use super::{check_ordered, BitVec, IndexType, Interval, IntervalMap, Node}; fn should_go_left(nodes: &[Node], index: Ix, start_bound: Bound<&T>) -> bool -where T: PartialOrd + Copy, - Ix: IndexType, +where + T: PartialOrd + Copy, + Ix: IndexType, { if !nodes[index.get()].left.defined() { return false; @@ -22,8 +23,9 @@ where T: PartialOrd + Copy, } fn should_go_right(nodes: &[Node], index: Ix, end_bound: Bound<&T>) -> bool -where T: PartialOrd + Copy, - Ix: IndexType, +where + T: PartialOrd + Copy, + Ix: IndexType, { if !nodes[index.get()].right.defined() { return false; @@ -45,7 +47,7 @@ impl ActionStack { } #[inline] - fn push(& mut self) { + fn push(&mut self) { self.0.push(false); self.0.push(false); } @@ -99,10 +101,16 @@ impl ActionStack { } } -fn move_to_next(nodes: &[Node], mut index: Ix, range: &R, stack: &mut ActionStack) -> Ix -where T: PartialOrd + Copy, - R: RangeBounds, - Ix: IndexType, +fn move_to_next( + nodes: &[Node], + mut index: Ix, + range: &R, + stack: &mut ActionStack, +) -> Ix +where + T: PartialOrd + Copy, + R: RangeBounds, + Ix: IndexType, { while index.defined() { if stack.can_go_left() { @@ -190,28 +198,67 @@ macro_rules! iterator { iterator! { #[doc="Iterator over pairs `(x..y, &value)`."] #[derive(Clone, Debug)] - struct Iter -> (Range, &'a V), + struct Iter -> (RangeInclusive, &'a V), node -> (node.interval.to_range(), &node.value), { /* no mut */ } } iterator! { #[doc="Iterator over intervals `x..y`."] #[derive(Clone, Debug)] - struct Intervals -> Range, + struct Intervals -> RangeInclusive, node -> node.interval.to_range(), { /* no mut */ } } -iterator! { - #[doc="Iterator over values."] - #[derive(Clone, Debug)] - struct Values -> &'a V, - node -> &node.value, { /* no mut */ } +#[doc = "Iterator over values."] +#[derive(Clone, Debug)] +pub struct Values<'a, T, V, R, Ix> +where + T: PartialOrd + Copy, + R: RangeBounds, + Ix: IndexType, +{ + pub(crate) index: Ix, + range: R, + nodes: &'a [Node], + stack: ActionStack, +} +impl<'a, T: PartialOrd + Copy, V, R: RangeBounds, Ix: IndexType> Values<'a, T, V, R, Ix> { + pub(crate) fn new(tree: &'a IntervalMap, range: R) -> Self { + check_ordered(&range); + Self { + index: tree.root, + range, + nodes: &tree.nodes, + stack: ActionStack::new(), + } + } +} +impl<'a, T: PartialOrd + Copy, V, R: RangeBounds, Ix: IndexType> Iterator + for Values<'a, T, V, R, Ix> +{ + type Item = &'a V; + fn next(&mut self) -> Option { + self.index = move_to_next(self.nodes, self.index, &self.range, &mut self.stack); + if self.index.defined() { + let node = &self.nodes[self.index.get()]; + Some((&node.value)) + } else { + None + } + } + fn size_hint(&self) -> (usize, Option) { + (0, Some(self.nodes.len())) + } +} +impl<'a, T: PartialOrd + Copy, V, R: RangeBounds, Ix: IndexType> FusedIterator + for Values<'a, T, V, R, Ix> +{ } iterator! { #[doc="Iterator over pairs `(x..y, &mut value)`."] #[derive(Debug)] - struct IterMut -> (Range, &'a mut V), + struct IterMut -> (RangeInclusive, &'a mut V), node -> (node.interval.to_range(), unsafe { &mut *(&mut node.value as *mut V) }), { mut } } @@ -279,14 +326,14 @@ macro_rules! into_iterator { into_iterator! { #[doc="Iterator over pairs `(x..y, value)`. Takes ownership of the interval map/set."] #[derive(Debug)] - struct IntoIter -> (Range, V), + struct IntoIter -> (RangeInclusive, V), node -> (node.interval.to_range(), mem::replace(&mut node.value, unsafe { mem::zeroed() })) } into_iterator! { #[doc="Iterator over intervals `x..y`. Takes ownership of the interval map/set."] #[derive(Debug)] - struct IntoIntervals -> Range, + struct IntoIntervals -> RangeInclusive, node -> node.interval.to_range() } @@ -355,7 +402,7 @@ macro_rules! unsorted_iterator { unsorted_iterator! { #[doc="Unsorted iterator over pairs `(x..y, &value)`."] #[derive(Clone, Debug)] - struct UnsIter -> (Range, &'a V), + struct UnsIter -> (RangeInclusive, &'a V), (iter -> alloc::slice::Iter<'a, Node>), node -> (node.interval.to_range(), &node.value), { /* no mut */ } } @@ -363,7 +410,7 @@ unsorted_iterator! { unsorted_iterator! { #[doc="Unsorted iterator over intervals `x..y`."] #[derive(Clone, Debug)] - struct UnsIntervals -> Range, + struct UnsIntervals -> RangeInclusive, (iter -> alloc::slice::Iter<'a, Node>), node -> node.interval.to_range(), { /* no mut */ } } @@ -379,7 +426,7 @@ unsorted_iterator! { unsorted_iterator! { #[doc="Unsorted iterator over pairs `(x..y, &mut V)`."] #[derive(Debug)] - struct UnsIterMut -> (Range, &'a mut V), + struct UnsIterMut -> (RangeInclusive, &'a mut V), (iter_mut -> alloc::slice::IterMut<'a, Node>), node -> (node.interval.to_range(), &mut node.value), { mut } } @@ -440,14 +487,14 @@ macro_rules! unsorted_into_iterator { unsorted_into_iterator! { #[doc="Unsorted IntoIterator over pairs `(x..y, V)`. Takes ownership of the interval map/set."] #[derive(Debug)] - struct UnsIntoIter -> (Range, V), + struct UnsIntoIter -> (RangeInclusive, V), node -> (node.interval.to_range(), node.value) } unsorted_into_iterator! { #[doc="Unsorted IntoIterator over intervals `x..y`. Takes ownership of the interval map/set."] #[derive(Debug)] - struct UnsIntoIntervals -> Range, + struct UnsIntoIntervals -> RangeInclusive, node -> node.interval.to_range() } @@ -459,31 +506,38 @@ unsorted_into_iterator! { } fn should_go_left_exact(nodes: &[Node], index: Ix, query: &Interval) -> bool -where T: PartialOrd + Copy, - Ix: IndexType, +where + T: PartialOrd + Copy, + Ix: IndexType, { let node = &nodes[index.get()]; let left_index = nodes[index.get()].left; - left_index.defined() && query <= &node.interval && nodes[left_index.get()].subtree_interval.contains(query) + left_index.defined() + && query <= &node.interval + && nodes[left_index.get()].subtree_interval.contains(query) } fn should_go_right_exact(nodes: &[Node], index: Ix, query: &Interval) -> bool -where T: PartialOrd + Copy, - Ix: IndexType, +where + T: PartialOrd + Copy, + Ix: IndexType, { let node = &nodes[index.get()]; let right_index = nodes[index.get()].right; - right_index.defined() && query >= &node.interval && nodes[right_index.get()].subtree_interval.contains(query) + right_index.defined() + && query >= &node.interval + && nodes[right_index.get()].subtree_interval.contains(query) } fn move_to_next_exact( nodes: &[Node], mut index: Ix, query: &Interval, - stack: &mut ActionStack + stack: &mut ActionStack, ) -> Ix -where T: PartialOrd + Copy, - Ix: IndexType, +where + T: PartialOrd + Copy, + Ix: IndexType, { while !stack.is_empty() && index.defined() { if stack.can_go_left() { diff --git a/src/lib.rs b/src/lib.rs index 4f9039b..cbd8aea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -//! This crates implements map and set with interval keys (ranges `x..y`). +//! This crates implements map and set with interval keys (ranges `x..=y`). //! //! [IntervalMap](struct.IntervalMap.html) is implemented using red-black binary tree, where each node contains //! information about the smallest start and largest end in its subtree. @@ -17,44 +17,44 @@ #![no_std] +extern crate alloc; #[cfg(feature = "std")] extern crate std; -extern crate alloc; -pub mod ix; +mod bitvec; +pub mod entry; pub mod iter; +pub mod ix; pub mod set; -pub mod entry; mod tree_rm; -mod bitvec; #[cfg(all(test, feature = "std"))] mod tests; use alloc::vec::Vec; use core::{ - ops::{Range, RangeFull, RangeInclusive, RangeBounds, Bound, AddAssign, Sub, Index}, - fmt::{self, Debug, Display, Formatter}, cmp::Ordering, + fmt::{self, Debug, Display, Formatter}, iter::FromIterator, + ops::{AddAssign, Bound, Index, RangeBounds, RangeFull, RangeInclusive, Sub}, }; #[cfg(feature = "dot")] use std::io::{self, Write}; #[cfg(feature = "serde")] use { core::marker::PhantomData, - serde::{Serialize, Serializer, Deserialize, Deserializer}, - serde::ser::{SerializeTuple, SerializeSeq}, - serde::de::{Visitor, SeqAccess}, + serde::de::{SeqAccess, Visitor}, + serde::ser::{SerializeSeq, SerializeTuple}, + serde::{Deserialize, Deserializer, Serialize, Serializer}, }; -use ix::IndexType; -use iter::*; use bitvec::BitVec; +use iter::*; +use ix::IndexType; +pub use entry::Entry; pub use ix::DefaultIx; pub use set::IntervalSet; -pub use entry::Entry; #[derive(Clone, Debug, PartialEq, PartialOrd)] struct Interval { @@ -63,11 +63,11 @@ struct Interval { } impl Interval { - fn new(range: &Range) -> Self { - check_interval(range.start, range.end); + fn new(range: &RangeInclusive) -> Self { + check_interval(range.start(), range.end()); Interval { - start: range.start, - end: range.end, + start: *range.start(), + end: *range.end(), } } @@ -77,10 +77,8 @@ impl Interval { Bound::Included(&value) => self.start <= value, Bound::Excluded(&value) => self.start < value, Bound::Unbounded => true, - }) - && - (match range.start_bound() { - Bound::Included(&value) | Bound::Excluded(&value) => self.end > value, + }) && (match range.start_bound() { + Bound::Included(&value) | Bound::Excluded(&value) => self.end >= value, Bound::Unbounded => true, }) } @@ -101,17 +99,18 @@ impl Interval { impl Interval { #[inline] - fn to_range(&self) -> Range { - self.start..self.end + fn to_range(&self) -> RangeInclusive { + self.start..=self.end } } impl Display for Interval { fn fmt(&self, f: &mut Formatter) -> fmt::Result { - write!(f, "{}..{}", self.start, self.end) + write!(f, "{}..={}", self.start, self.end) } } +#[allow(clippy::derive_ord_xor_partial_ord)] impl Ord for Interval { fn cmp(&self, other: &Self) -> Ordering { // Implement cmp by ourselves because T can be PartialOrd. @@ -131,7 +130,7 @@ impl Ord for Interval { } } -impl Eq for Interval { } +impl Eq for Interval {} #[cfg(feature = "serde")] impl Serialize for Interval { @@ -184,8 +183,16 @@ impl Node { #[cfg(feature = "dot")] impl Node { fn write_dot(&self, index: usize, is_red: bool, mut writer: W) -> io::Result<()> { - writeln!(writer, " {} [label=\"i={}\\n{}: {}\\nsubtree: {}\", fillcolor={}, style=filled]", - index, index, self.interval, self.value, self.subtree_interval, if is_red { "salmon" } else { "grey65" })?; + writeln!( + writer, + " {} [label=\"i={}\\n{}: {}\\nsubtree: {}\", fillcolor={}, style=filled]", + index, + index, + self.interval, + self.value, + self.subtree_interval, + if is_red { "salmon" } else { "grey65" } + )?; if self.left.defined() { writeln!(writer, " {} -> {} [label=\"L\"]", index, self.left)?; } @@ -198,9 +205,21 @@ impl Node { #[cfg(feature = "dot")] impl Node { - fn write_dot_without_values(&self, index: usize, is_red: bool, mut writer: W) -> io::Result<()> { - writeln!(writer, " {} [label=\"i={}: {}\\nsubtree: {}\", fillcolor={}, style=filled]", - index, index, self.interval, self.subtree_interval, if is_red { "salmon" } else { "grey65" })?; + fn write_dot_without_values( + &self, + index: usize, + is_red: bool, + mut writer: W, + ) -> io::Result<()> { + writeln!( + writer, + " {} [label=\"i={}: {}\\nsubtree: {}\", fillcolor={}, style=filled]", + index, + index, + self.interval, + self.subtree_interval, + if is_red { "salmon" } else { "grey65" } + )?; if self.left.defined() { writeln!(writer, " {} -> {} [label=\"L\"]", index, self.left)?; } @@ -212,18 +231,24 @@ impl Node { } fn check_interval(start: T, end: T) { - if start < end { - assert!(end > start, "Interval cannot be ordered (`start < end` but not `end > start`)"); + if start <= end { + assert!( + end >= start, + "Interval cannot be ordered (`start <= end` but not `end >= start`)" + ); } else if end <= start { panic!("Interval is empty (`start >= end`)"); } else { - panic!("Interval cannot be ordered (not `start < end` and not `end <= start`)"); + // panic!("Interval cannot be ordered (not `start <= end` and not `end <= start`)"); } } fn check_interval_incl(start: T, end: T) { if start <= end { - assert!(end >= start, "Interval cannot be ordered (`start < end` but not `end > start`)"); + assert!( + end >= start, + "Interval cannot be ordered (`start < end` but not `end > start`)" + ); } else if end < start { panic!("Interval is empty (`start > end`)"); } else { @@ -233,7 +258,7 @@ fn check_interval_incl(start: T, end: T) { fn check_ordered>(range: &R) { match (range.start_bound(), range.end_bound()) { - (_, Bound::Unbounded) | (Bound::Unbounded, _) => {}, + (_, Bound::Unbounded) | (Bound::Unbounded, _) => {} (Bound::Included(a), Bound::Included(b)) => check_interval_incl(a, b), (Bound::Included(a), Bound::Excluded(b)) | (Bound::Excluded(a), Bound::Included(b)) @@ -241,7 +266,7 @@ fn check_ordered>(range: &R) { } } -/// Map with interval keys (`x..y`). +/// Map with interval keys (`x..=y`). /// /// Range bounds should implement `PartialOrd` and `Copy`, for example any /// integer or float types. However, you cannot use values that cannot be used in comparison (such as `NAN`), @@ -250,28 +275,28 @@ fn check_ordered>(range: &R) { /// /// # Example ///```rust -/// let mut map = iset::interval_map!{ 20..30 => 'a', 15..25 => 'b', 10..20 => 'c' }; -/// assert_eq!(map.insert(10..20, 'd'), Some('c')); -/// assert_eq!(map.insert(5..15, 'e'), None); +/// let mut map = iset::interval_map!{ 20..=30 => 'a', 15..=25 => 'b', 10..=19 => 'c' }; +/// assert_eq!(map.insert(10..=19, 'd'), Some('c')); +/// assert_eq!(map.insert(5..=15, 'e'), None); /// /// // Iterator over all pairs (range, value). Output is sorted. /// let a: Vec<_> = map.iter(..).collect(); -/// assert_eq!(a, &[(5..15, &'e'), (10..20, &'d'), (15..25, &'b'), (20..30, &'a')]); +/// assert_eq!(a, &[(5..=15, &'e'), (10..=19, &'d'), (15..=25, &'b'), (20..=30, &'a')]); /// -/// // Iterate over intervals that overlap query (..20 here). Output is sorted. -/// let b: Vec<_> = map.intervals(..20).collect(); -/// assert_eq!(b, &[5..15, 10..20, 15..25]); +/// // Iterate over intervals that overlap query (..=20 here). Output is sorted. +/// let b: Vec<_> = map.intervals(..=20).collect(); +/// assert_eq!(b, &[5..=15, 10..=19, 15..=25, 20..=30]); /// -/// assert_eq!(map[15..25], 'b'); -/// // Replace 15..25 => 'b' into 'z'. -/// *map.get_mut(15..25).unwrap() = 'z'; +/// assert_eq!(map[15..=25], 'b'); +/// // Replace 15..=25 => 'b' into 'z'. +/// *map.get_mut(15..=25).unwrap() = 'z'; /// -/// // Iterate over values that overlap query (20.. here). Output is sorted by intervals. +/// // Iterate over values that overlap query (20..= here). Output is sorted by intervals. /// let c: Vec<_> = map.values(20..).collect(); /// assert_eq!(c, &[&'z', &'a']); /// -/// // Remove 10..20 => 'd'. -/// assert_eq!(map.remove(10..20), Some('d')); +/// // Remove 10..=20 => 'd'. +/// assert_eq!(map.remove(10..=19), Some('d')); /// ``` /// /// # Insertion, search and removal @@ -311,8 +336,8 @@ fn check_ordered>(range: &R) { /// the size of the output. All iterators traverse entries in a sorted order /// (sorted lexicographically by intervals). /// Iteration methods include: -/// - [iter](#method.iter): iterate over pairs `(x..y, &value)`, -/// - [intervals](#method.intervals): iterate over interval keys `x..y`, +/// - [iter](#method.iter): iterate over pairs `(x..=y, &value)`, +/// - [intervals](#method.intervals): iterate over interval keys `x..=y`, /// - [values](#method.values): iterate over values `&value`, /// - Mutable iterators [iter_mut](#method.iter_mut) and [values_mut](#method.values_mut), /// - Into iterators [into_iter](#method.into_iter), [into_intervals](#method.into_intervals) and @@ -327,7 +352,7 @@ fn check_ordered>(range: &R) { /// unsorted iterator is slightly faster as it reads the memory consecutively instead of traversing the tree. /// /// Methods `iter`, `intervals`, `values`, `iter_mut` and `values_mut` have alternatives [overlap](#method.overlap), -/// [overlap_intervals](#method.overlap_intervals), ..., that allow to iterate over all entries that +/// [overlap_intervals](#method.overlap_intervals), ..=., that allow to iterate over all entries that /// cover a single point `x` (same as `x..=x`). /// /// # Index types @@ -349,29 +374,29 @@ fn check_ordered>(range: &R) { /// /// // Creates an empty interval map with the default index type (u32): /// let mut map = IntervalMap::new(); -/// map.insert(10..20, 'a'); +/// map.insert(10..=20, 'a'); /// /// // Creates an empty interval map and specifies index type (u16 here): /// let mut map = IntervalMap::<_, _, u16>::default(); -/// map.insert(10..20, 'a'); +/// map.insert(10..=20, 'a'); /// /// let mut map = IntervalMap::<_, _, u16>::with_capacity(10); -/// map.insert(10..20, 'a'); +/// map.insert(10..=20, 'a'); /// /// // Creates an interval map with the default index type: -/// let map = interval_map!{ 0..10 => 'a', 5..15 => 'b' }; +/// let map = interval_map!{ 0..=10 => 'a', 5..=15 => 'b' }; /// /// // Creates an interval map and specifies index type: -/// let map = interval_map!{ [u16] 0..10 => 'a', 5..15 => 'b' }; +/// let map = interval_map!{ [u16] 0..=10 => 'a', 5..=15 => 'b' }; /// /// // Creates an interval map from a sorted iterator, takes O(N): -/// let vec = vec![(0..10, 'b'), (5..15, 'a')]; +/// let vec = vec![(0..=10, 'b'), (5..=15, 'a')]; /// let map = IntervalMap::<_, _, u32>::from_sorted(vec.into_iter()); /// /// // Alternatively, you can use `.collect()` method that creates an interval map /// // with the default index size. `Collect` does not require sorted intervals, /// // but takes O(N log N). -/// let vec = vec![(5..15, 'a'), (0..10, 'b')]; +/// let vec = vec![(5..=15, 'a'), (0..=10, 'b')]; /// let map: IntervalMap<_, _> = vec.into_iter().collect(); /// ``` /// @@ -380,15 +405,15 @@ fn check_ordered>(range: &R) { /// directly after search was made. /// ``` /// let mut map = iset::IntervalMap::new(); -/// map.entry(0..100).or_insert("abc".to_string()); -/// map.entry(100..200).or_insert_with(|| "def".to_string()); -/// let val = map.entry(200..300).or_insert(String::new()); +/// map.entry(0..=100).or_insert("abc".to_string()); +/// map.entry(101..=200).or_insert_with(|| "def".to_string()); +/// let val = map.entry(201..=300).or_insert(String::new()); /// *val += "ghi"; -/// map.entry(200..300).and_modify(|s| *s += "jkl").or_insert("xyz".to_string()); +/// map.entry(201..=300).and_modify(|s| *s += "jkl").or_insert("xyz".to_string()); /// -/// assert_eq!(map[0..100], "abc"); -/// assert_eq!(map[100..200], "def"); -/// assert_eq!(map[200..300], "ghijkl"); +/// assert_eq!(map[0..=100], "abc"); +/// assert_eq!(map[101..=200], "def"); +/// assert_eq!(map[201..=300], "ghijkl"); /// ``` /// /// # Implementation, merge and split @@ -475,9 +500,12 @@ impl IntervalMap { /// /// Panics if the intervals are not sorted or if there are equal intervals. pub fn from_sorted(iter: I) -> Self - where I: Iterator, V)>, + where + I: Iterator, V)>, { - let nodes: Vec<_> = iter.map(|(range, value)| Node::new(Interval::new(&range), value)).collect(); + let nodes: Vec<_> = iter + .map(|(range, value)| Node::new(Interval::new(&range), value)) + .collect(); let n = nodes.len(); let mut map = Self { nodes, @@ -656,10 +684,14 @@ impl IntervalMap { continue; } - if index == self.nodes[parent.get()].right && parent == self.nodes[grandparent.get()].left { + if index == self.nodes[parent.get()].right + && parent == self.nodes[grandparent.get()].left + { self.rotate_left(parent); index = self.nodes[index.get()].left; - } else if index == self.nodes[parent.get()].left && parent == self.nodes[grandparent.get()].right { + } else if index == self.nodes[parent.get()].left + && parent == self.nodes[grandparent.get()].right + { self.rotate_right(parent); index = self.nodes[index.get()].right; } @@ -686,7 +718,13 @@ impl IntervalMap { /// Inserts pair `(interval, value)` as a child of `parent`. Left child if `left_child`, right child otherwise. /// Returns mutable reference to the added value. - fn insert_at(&mut self, parent: Ix, left_child: bool, interval: Interval, value: V) -> &mut V { + fn insert_at( + &mut self, + parent: Ix, + left_child: bool, + interval: Interval, + value: V, + ) -> &mut V { let mut new_node = Node::new(interval, value); let new_index = Ix::new(self.nodes.len()).unwrap(); @@ -715,7 +753,7 @@ impl IntervalMap { /// Insert pair `(interval, value)`. /// If both `replace` and `interval` was already in the map, replacing the value and returns the old value. /// Otherwise, inserts a new node and returns None. - fn insert_inner(&mut self, interval: Range, value: V, replace: bool) -> Option { + fn insert_inner(&mut self, interval: RangeInclusive, value: V, replace: bool) -> Option { let interval = Interval::new(&interval); let mut current = self.root; @@ -727,7 +765,9 @@ impl IntervalMap { let node = &mut self.nodes[current.get()]; let (child, left_side) = match interval.cmp(&node.interval) { Ordering::Less => (node.left, true), - Ordering::Equal if replace => return Some(core::mem::replace(&mut node.value, value)), + Ordering::Equal if replace => { + return Some(core::mem::replace(&mut node.value, value)) + } Ordering::Equal | Ordering::Greater => (node.right, false), }; if child.defined() { @@ -742,14 +782,14 @@ impl IntervalMap { /// Gets the given key's corresponding entry in the map for in-place manipulation. /// ``` /// let mut counts = iset::IntervalMap::new(); - /// for x in [0..5, 3..9, 2..6, 0..5, 2..6, 2..6] { + /// for x in [0..=5, 3..=9, 2..=6, 0..=5, 2..=6, 2..=6] { /// counts.entry(x).and_modify(|curr| *curr += 1).or_insert(1); /// } - /// assert_eq!(counts[0..5], 2); - /// assert_eq!(counts[3..9], 1); - /// assert_eq!(counts[2..6], 3); + /// assert_eq!(counts[0..=5], 2); + /// assert_eq!(counts[3..=9], 1); + /// assert_eq!(counts[2..=6], 3); /// ``` - pub fn entry<'a>(&'a mut self, interval: Range) -> Entry<'a, T, V, Ix> { + pub fn entry(&mut self, interval: RangeInclusive) -> Entry<'_, T, V, Ix> { let interval = Interval::new(&interval); let mut current = self.root; if !current.defined() { @@ -760,7 +800,9 @@ impl IntervalMap { let (child, left_side) = match interval.cmp(&node.interval) { Ordering::Less => (node.left, true), Ordering::Greater => (node.right, false), - Ordering::Equal => return Entry::Occupied(entry::OccupiedEntry::new(self, current)), + Ordering::Equal => { + return Entry::Occupied(entry::OccupiedEntry::new(self, current)) + } }; if child.defined() { current = child; @@ -770,16 +812,16 @@ impl IntervalMap { } } - /// Inserts an interval `x..y` and its value into the map. Takes *O(log N)*. + /// Inserts an interval `x..=y` and its value into the map. Takes *O(log N)*. /// /// If the map did not contain the interval, returns `None`. Otherwise returns the old value. /// /// Panics if `interval` is empty (`start >= end`) or contains a value that cannot be compared (such as `NAN`). - pub fn insert(&mut self, interval: Range, value: V) -> Option { + pub fn insert(&mut self, interval: RangeInclusive, value: V) -> Option { self.insert_inner(interval, value, true) } - /// Inserts an interval `x..y` and its value into the map even if there was an entry with matching interval. + /// Inserts an interval `x..=y` and its value into the map even if there was an entry with matching interval. /// Takes *O(log N)*. /// /// Panics if `interval` is empty (`start >= end`) or contains a value that cannot be compared (such as `NAN`). @@ -797,22 +839,25 @@ impl IntervalMap { /// /// ```rust /// let mut map = iset::interval_map!{}; - /// map.force_insert(10..20, 1); - /// map.force_insert(15..25, 2); - /// map.force_insert(20..30, 3); - /// map.force_insert(15..25, 4); + /// map.force_insert(10..=20, 1); + /// map.force_insert(15..=25, 2); + /// map.force_insert(20..=30, 3); + /// map.force_insert(15..=25, 4); /// /// // Returns either 2 or 4. - /// assert!(map.get(15..25).unwrap() % 2 == 0); - /// // Removes either 15..25 => 2 or 15..25 => 4. - /// assert!(map.remove(15..25).unwrap() % 2 == 0); + /// assert!(map.get(15..=25).unwrap() % 2 == 0); + /// // Removes either 15..=25 => 2 or 15..=25 => 4. + /// assert!(map.remove(15..=25).unwrap() % 2 == 0); /// println!("{:?}", map); - /// // {10..20 => 1, 15..25 => 4, 20..30 => 3} OR - /// // {10..20 => 1, 15..25 => 2, 20..30 => 3} + /// // {10..=20 => 1, 15..=25 => 4, 20..=30 => 3} OR + /// // {10..=20 => 1, 15..=25 => 2, 20..=30 => 3} /// ``` - pub fn force_insert(&mut self, interval: Range, value: V) { + pub fn force_insert(&mut self, interval: RangeInclusive, value: V) { // Cannot be replaced with debug_assert. - assert!(self.insert_inner(interval, value, false).is_none(), "Force insert should always return None"); + assert!( + self.insert_inner(interval, value, false).is_none(), + "Force insert should always return None" + ); } fn find_index(&self, interval: &Interval) -> Ix { @@ -831,7 +876,7 @@ impl IntervalMap { /// Check if the interval map contains `interval` (exact match). /// /// Panics if `interval` is empty (`start >= end`) or contains a value that cannot be compared (such as `NAN`). - pub fn contains(&self, interval: Range) -> bool { + pub fn contains(&self, interval: RangeInclusive) -> bool { self.find_index(&Interval::new(&interval)).defined() } @@ -839,7 +884,7 @@ impl IntervalMap { /// If there is no such interval, returns `None`. /// /// Panics if `interval` is empty (`start >= end`) or contains a value that cannot be compared (such as `NAN`). - pub fn get(&self, interval: Range) -> Option<&V> { + pub fn get(&self, interval: RangeInclusive) -> Option<&V> { let index = self.find_index(&Interval::new(&interval)); if index.defined() { Some(&self.nodes[index.get()].value) @@ -852,7 +897,7 @@ impl IntervalMap { /// If there is no such interval, returns `None`. /// /// Panics if `interval` is empty (`start >= end`) or contains a value that cannot be compared (such as `NAN`). - pub fn get_mut(&mut self, interval: Range) -> Option<&mut V> { + pub fn get_mut(&mut self, interval: RangeInclusive) -> Option<&mut V> { let index = self.find_index(&Interval::new(&interval)); if index.defined() { Some(&mut self.nodes[index.get()].value) @@ -865,7 +910,7 @@ impl IntervalMap { /// Returns value if the interval was present in the map, and None otherwise. /// /// Panics if `interval` is empty (`start >= end`) or contains a value that cannot be compared (such as `NAN`). - pub fn remove(&mut self, interval: Range) -> Option { + pub fn remove(&mut self, interval: RangeInclusive) -> Option { self.remove_at(self.find_index(&Interval::new(&interval))) } @@ -881,25 +926,29 @@ impl IntervalMap { /// # Examples /// ```rust /// let mut map = iset::IntervalMap::new(); - /// map.force_insert(5..15, 0); - /// map.force_insert(10..20, 1); - /// map.force_insert(10..20, 2); - /// map.force_insert(10..20, 3); - /// map.force_insert(10..20, 4); - /// map.force_insert(15..25, 5); + /// map.force_insert(5..=15, 0); + /// map.force_insert(10..=20, 1); + /// map.force_insert(10..=20, 2); + /// map.force_insert(10..=20, 3); + /// map.force_insert(10..=20, 4); + /// map.force_insert(15..=25, 5); /// /// // Remove an entry with an even value - /// let removed = map.remove_where(10..20, |&x| x % 2 == 0); + /// let removed = map.remove_where(10..=20, |&x| x % 2 == 0); /// assert!(removed == Some(2) || removed == Some(4)); /// /// // Remove the entry with the minimum value - /// let minimum = map.values_at(10..20).cloned().min().unwrap(); + /// let minimum = map.values_at(10..=20).cloned().min().unwrap(); /// assert_eq!(minimum, 1); - /// let removed = map.remove_where(10..20, |&x| x == minimum); + /// let removed = map.remove_where(10..=20, |&x| x == minimum); /// assert_eq!(removed, Some(1)); /// assert_eq!(map.len(), 4); /// ``` - pub fn remove_where(&mut self, interval: Range, mut predicate: impl FnMut(&V) -> bool) -> Option { + pub fn remove_where( + &mut self, + interval: RangeInclusive, + mut predicate: impl FnMut(&V) -> bool, + ) -> Option { let mut values_it = self.values_at(interval); while let Some(val) = values_it.next() { if predicate(val) { @@ -912,7 +961,7 @@ impl IntervalMap { /// Returns a range of interval keys in the map, takes *O(1)*. Returns `None` if the map is empty. /// `out.start` is the minimal start of all intervals in the map, /// and `out.end` is the maximal end of all intervals in the map. - pub fn range(&self) -> Option> { + pub fn range(&self) -> Option> { if self.root.defined() { Some(self.nodes[self.root.get()].subtree_interval.to_range()) } else { @@ -936,9 +985,9 @@ impl IntervalMap { index } - /// Returns the pair `(x..y, &value)` with the smallest interval `x..y` (in lexicographical order). + /// Returns the pair `(x..=y, &value)` with the smallest interval `x..=y` (in lexicographical order). /// Takes *O(log N)*. Returns `None` if the map is empty. - pub fn smallest(&self) -> Option<(Range, &V)> { + pub fn smallest(&self) -> Option<(RangeInclusive, &V)> { if !self.root.defined() { None } else { @@ -947,9 +996,9 @@ impl IntervalMap { } } - /// Returns the pair `(x..y, &mut value)` with the smallest interval `x..y` (in lexicographical order). + /// Returns the pair `(x..=y, &mut value)` with the smallest interval `x..=y` (in lexicographical order). /// Takes *O(log N)*. Returns `None` if the map is empty. - pub fn smallest_mut(&mut self) -> Option<(Range, &mut V)> { + pub fn smallest_mut(&mut self) -> Option<(RangeInclusive, &mut V)> { if !self.root.defined() { None } else { @@ -959,9 +1008,9 @@ impl IntervalMap { } } - /// Removes the smallest interval `x..y` (in lexicographical order) from the map and returns pair `(x..y, value)`. + /// Removes the smallest interval `x..=y` (in lexicographical order) from the map and returns pair `(x..=y, value)`. /// Takes *O(log N)*. Returns `None` if the map is empty. - pub fn remove_smallest(&mut self) -> Option<(Range, V)> { + pub fn remove_smallest(&mut self) -> Option<(RangeInclusive, V)> { if !self.root.defined() { None } else { @@ -971,9 +1020,9 @@ impl IntervalMap { } } - /// Returns the pair `(x..y, &value)` with the largest interval `x..y` (in lexicographical order). + /// Returns the pair `(x..=y, &value)` with the largest interval `x..=y` (in lexicographical order). /// Takes *O(log N)*. Returns `None` if the map is empty. - pub fn largest(&self) -> Option<(Range, &V)> { + pub fn largest(&self) -> Option<(RangeInclusive, &V)> { if !self.root.defined() { None } else { @@ -982,9 +1031,9 @@ impl IntervalMap { } } - /// Returns the pair `(x..y, &mut value)` with the largest interval `x..y` (in lexicographical order). + /// Returns the pair `(x..=y, &mut value)` with the largest interval `x..=y` (in lexicographical order). /// Takes *O(log N)*. Returns `None` if the map is empty. - pub fn largest_mut(&mut self) -> Option<(Range, &mut V)> { + pub fn largest_mut(&mut self) -> Option<(RangeInclusive, &mut V)> { if !self.root.defined() { None } else { @@ -994,9 +1043,9 @@ impl IntervalMap { } } - /// Removes the largest interval `x..y` (in lexicographical order) from the map and returns pair `(x..y, value)`. + /// Removes the largest interval `x..=y` (in lexicographical order) from the map and returns pair `(x..=y, value)`. /// Takes *O(log N)*. Returns `None` if the map is empty. - pub fn remove_largest(&mut self) -> Option<(Range, V)> { + pub fn remove_largest(&mut self) -> Option<(RangeInclusive, V)> { if !self.root.defined() { None } else { @@ -1010,12 +1059,13 @@ impl IntervalMap { /// Equivalent to `map.iter(query).next().is_some()`, but much faster. /// /// ```rust - /// let map = iset::interval_map!{ 5..8 => 'a', 10..15 => 'b' }; - /// assert!(!map.has_overlap(8..10)); + /// let map = iset::interval_map!{ 5..=8 => 'a', 10..=15 => 'b' }; + /// assert!(!map.has_overlap(9..=9)); /// assert!(map.has_overlap(8..=10)); /// ``` pub fn has_overlap(&self, query: R) -> bool - where R: RangeBounds, + where + R: RangeBounds, { check_ordered(&query); if !self.root.defined() { @@ -1044,7 +1094,7 @@ impl IntervalMap { // The whole subtree lies to the left of the query. continue; } - }, + } Bound::Excluded(&q_start) => { if q_start <= subtree_start { true @@ -1054,7 +1104,7 @@ impl IntervalMap { // The whole subtree lies to the left of the query. continue; } - }, + } }; // Query end is greater than the subtree interval end. @@ -1069,14 +1119,14 @@ impl IntervalMap { } else { q_end > subtree_end } - }, + } Bound::Excluded(&q_end) => { if q_end <= subtree_start { continue; } else { q_end > subtree_end } - }, + } }; if q_start_lt_start || q_end_gt_end || node.interval.intersects_range(&query) { return true; @@ -1091,63 +1141,70 @@ impl IntervalMap { false } - /// Iterates over pairs `(x..y, &value)` that overlap the `query`. + /// Iterates over pairs `(x..=y, &value)` that overlap the `query`. /// Takes *O(log N + K)* where *K* is the size of the output. /// Output is sorted by intervals, but not by values. /// /// Panics if `interval` is empty or contains a value that cannot be compared (such as `NAN`). - pub fn iter<'a, R>(&'a self, query: R) -> Iter<'a, T, V, R, Ix> - where R: RangeBounds, + pub fn iter(&self, query: R) -> Iter<'_, T, V, R, Ix> + where + R: RangeBounds, { Iter::new(self, query) } - /// Iterates over intervals `x..y` that overlap the `query`. + /// Iterates over intervals `x..=y` that overlap the `query`. /// See [iter](#method.iter) for more details. - pub fn intervals<'a, R>(&'a self, query: R) -> Intervals<'a, T, V, R, Ix> - where R: RangeBounds, + pub fn intervals(&self, query: R) -> Intervals<'_, T, V, R, Ix> + where + R: RangeBounds, { Intervals::new(self, query) } /// Iterates over values that overlap the `query`. /// See [iter](#method.iter) for more details. - pub fn values<'a, R>(&'a self, query: R) -> Values<'a, T, V, R, Ix> - where R: RangeBounds, + pub fn values(&self, query: R) -> Values<'_, T, V, R, Ix> + where + R: RangeBounds, { Values::new(self, query) } - /// Iterator over pairs `(x..y, &mut value)` that overlap the `query`. + /// Iterator over pairs `(x..=y, &mut value)` that overlap the `query`. /// See [iter](#method.iter) for more details. - pub fn iter_mut<'a, R>(&'a mut self, query: R) -> IterMut<'a, T, V, R, Ix> - where R: RangeBounds, + pub fn iter_mut(&mut self, query: R) -> IterMut<'_, T, V, R, Ix> + where + R: RangeBounds, { IterMut::new(self, query) } /// Iterator over *mutable* values that overlap the `query`. /// See [iter](#method.iter) for more details. - pub fn values_mut<'a, R>(&'a mut self, query: R) -> ValuesMut<'a, T, V, R, Ix> - where R: RangeBounds, + pub fn values_mut(&mut self, query: R) -> ValuesMut<'_, T, V, R, Ix> + where + R: RangeBounds, { ValuesMut::new(self, query) } /// Consumes [IntervalMap](struct.IntervalMap.html) and - /// iterates over pairs `(x..y, value)` that overlap the `query`. + /// iterates over pairs `(x..=y, value)` that overlap the `query`. /// See [iter](#method.iter) for more details. pub fn into_iter(self, query: R) -> IntoIter - where R: RangeBounds, + where + R: RangeBounds, { IntoIter::new(self, query) } /// Consumes [IntervalMap](struct.IntervalMap.html) and - /// iterates over pairs `(x..y, value)` that overlap the `query`. + /// iterates over pairs `(x..=y, value)` that overlap the `query`. /// See [iter](#method.iter) for more details. pub fn into_intervals(self, query: R) -> IntoIntervals - where R: RangeBounds, + where + R: RangeBounds, { IntoIntervals::new(self, query) } @@ -1156,89 +1213,90 @@ impl IntervalMap { /// iterates over values, for which intervals that overlap the `query`. /// See [iter](#method.iter) for more details. pub fn into_values(self, query: R) -> IntoValues - where R: RangeBounds, + where + R: RangeBounds, { IntoValues::new(self, query) } - /// Iterates over pairs `(x..y, &value)` that overlap the `point`. + /// Iterates over pairs `(x..=y, &value)` that overlap the `point`. /// See [iter](#method.iter) for more details. #[inline] - pub fn overlap<'a>(&'a self, point: T) -> Iter<'a, T, V, RangeInclusive, Ix> { + pub fn overlap(&self, point: T) -> Iter<'_, T, V, RangeInclusive, Ix> { Iter::new(self, point..=point) } - /// Iterates over intervals `x..y` that overlap the `point`. + /// Iterates over intervals `x..=y` that overlap the `point`. /// See [iter](#method.iter) for more details. #[inline] - pub fn intervals_overlap<'a>(&'a self, point: T) -> Intervals<'a, T, V, RangeInclusive, Ix> { + pub fn intervals_overlap(&self, point: T) -> Intervals<'_, T, V, RangeInclusive, Ix> { Intervals::new(self, point..=point) } /// Iterates over values that overlap the `point`. /// See [iter](#method.iter) for more details. #[inline] - pub fn values_overlap<'a>(&'a self, point: T) -> Values<'a, T, V, RangeInclusive, Ix> { + pub fn values_overlap(&self, point: T) -> Values<'_, T, V, RangeInclusive, Ix> { Values::new(self, point..=point) } - /// Iterator over pairs `(x..y, &mut value)` that overlap the `point`. + /// Iterator over pairs `(x..=y, &mut value)` that overlap the `point`. /// See [iter](#method.iter) for more details. #[inline] - pub fn overlap_mut<'a>(&'a mut self, point: T) -> IterMut<'a, T, V, RangeInclusive, Ix> { + pub fn overlap_mut(&mut self, point: T) -> IterMut<'_, T, V, RangeInclusive, Ix> { IterMut::new(self, point..=point) } /// Iterates over *mutable* values that overlap the `point`. /// See [iter](#method.iter) for more details. #[inline] - pub fn values_overlap_mut<'a>(&'a mut self, point: T) -> ValuesMut<'a, T, V, RangeInclusive, Ix> { + pub fn values_overlap_mut(&mut self, point: T) -> ValuesMut<'_, T, V, RangeInclusive, Ix> { ValuesMut::new(self, point..=point) } /// Iterates over all values (`&V`) with intervals that match `query` exactly. /// Takes *O(log N + K)* where *K* is the size of the output. - pub fn values_at<'a>(&'a self, query: Range) -> ValuesExact<'a, T, V, Ix> { + pub fn values_at(&self, query: RangeInclusive) -> ValuesExact<'_, T, V, Ix> { ValuesExact::new(self, Interval::new(&query)) } /// Iterates over all mutable values (`&mut V`) with intervals that match `query` exactly. - pub fn values_mut_at<'a>(&'a mut self, query: Range) -> ValuesExactMut<'a, T, V, Ix> { + pub fn values_mut_at(&mut self, query: RangeInclusive) -> ValuesExactMut<'_, T, V, Ix> { ValuesExactMut::new(self, Interval::new(&query)) } - /// Creates an unsorted iterator over all pairs `(x..y, &value)`. + /// Creates an unsorted iterator over all pairs `(x..=y, &value)`. /// Slightly faster than the sorted iterator, although both take *O(N)*. - pub fn unsorted_iter<'a>(&'a self) -> UnsIter<'a, T, V, Ix> { + pub fn unsorted_iter(&self) -> UnsIter<'_, T, V, Ix> { UnsIter::new(self) } - /// Creates an unsorted iterator over all intervals `x..y`. - pub fn unsorted_intervals<'a>(&'a self) -> UnsIntervals<'a, T, V, Ix> { + /// Creates an unsorted iterator over all intervals `x..=y`. + pub fn unsorted_intervals(&self) -> UnsIntervals<'_, T, V, Ix> { UnsIntervals::new(self) } /// Creates an unsorted iterator over all values `&value`. - pub fn unsorted_values<'a>(&'a self) -> UnsValues<'a, T, V, Ix> { + pub fn unsorted_values(&self) -> UnsValues<'_, T, V, Ix> { UnsValues::new(self) } - /// Creates an unsorted iterator over all pairs `(x..y, &mut value)`. - pub fn unsorted_iter_mut<'a>(&'a mut self) -> UnsIterMut<'a, T, V, Ix> { + /// Creates an unsorted iterator over all pairs `(x..=y, &mut value)`. + pub fn unsorted_iter_mut(&mut self) -> UnsIterMut<'_, T, V, Ix> { UnsIterMut::new(self) } /// Creates an unsorted iterator over all mutable values `&mut value`. - pub fn unsorted_values_mut<'a>(&'a mut self) -> UnsValuesMut<'a, T, V, Ix> { + pub fn unsorted_values_mut(&mut self) -> UnsValuesMut<'_, T, V, Ix> { UnsValuesMut::new(self) } - /// Consumes `IntervalMap` and creates an unsorted iterator over all pairs `(x..y, value)`. + /// Consumes `IntervalMap` and creates an unsorted iterator over all pairs `(x..=y, value)`. pub fn unsorted_into_iter(self) -> UnsIntoIter { UnsIntoIter::new(self) } - /// Consumes `IntervalMap` and creates an unsorted iterator over all intervals `x..y`. + /// Consumes `IntervalMap` and creates an unsorted iterator over all intervals `x..=y`. pub fn unsorted_into_intervals(self) -> UnsIntoIntervals { UnsIntoIntervals::new(self) } @@ -1251,39 +1309,44 @@ impl IntervalMap { impl IntoIterator for IntervalMap { type IntoIter = IntoIter; - type Item = (Range, V); + type Item = (RangeInclusive, V); fn into_iter(self) -> Self::IntoIter { IntoIter::new(self, ..) } } -/// Construct [IntervalMap](struct.IntervalMap.html) from pairs `(x..y, value)`. +/// Construct [IntervalMap](struct.IntervalMap.html) from pairs `(x..=y, value)`. /// /// Panics, if the iterator contains duplicate intervals. -impl FromIterator<(Range, V)> for IntervalMap { +impl FromIterator<(RangeInclusive, V)> for IntervalMap { fn from_iter(iter: I) -> Self - where I: IntoIterator, V)> + where + I: IntoIterator, V)>, { let mut map = IntervalMap::new(); for (range, value) in iter { - assert!(map.insert(range, value).is_none(), "Cannot collect IntervalMap with duplicate intervals!"); + assert!( + map.insert(range, value).is_none(), + "Cannot collect IntervalMap with duplicate intervals!" + ); } map } } -impl Index> for IntervalMap { +impl Index> for IntervalMap { type Output = V; - fn index(&self, range: Range) -> &Self::Output { + fn index(&self, range: RangeInclusive) -> &Self::Output { self.get(range).expect("No entry found for range") } } impl IntervalMap -where T: PartialOrd + Copy + Default + AddAssign + Sub, - Ix: IndexType, +where + T: PartialOrd + Copy + Default + AddAssign + Sub, + Ix: IndexType, { /// Calculates the total length of the `query` that is covered by intervals in the map. /// Takes *O(log N + K)* where *K* is the number of intervals that overlap `query`. @@ -1294,12 +1357,13 @@ where T: PartialOrd + Copy + Default + AddAssign + Sub, /// This also means that the size of the interval *(0, 1)* will be 1 even for integer types. /// /// ```rust - /// let map = iset::interval_map!{ 0..10 => 'a', 4..8 => 'b', 12..15 => 'c' }; - /// assert_eq!(map.covered_len(2..14), 10); + /// let map = iset::interval_map!{ 0..=10 => 'a', 4..=8 => 'b', 12..=15 => 'c' }; + /// assert_eq!(map.covered_len(2..=14), 10); /// assert_eq!(map.covered_len(..), 13); /// ``` pub fn covered_len(&self, query: R) -> T - where R: RangeBounds, + where + R: RangeBounds, { let mut res = T::default(); let start_bound = query.start_bound().cloned(); @@ -1310,12 +1374,12 @@ where T: PartialOrd + Copy + Default + AddAssign + Sub, let mut curr_end = res; for interval in self.intervals(query) { let start = match start_bound { - Bound::Included(a) | Bound::Excluded(a) if a >= interval.start => a, - _ => interval.start, + Bound::Included(a) | Bound::Excluded(a) if a >= *interval.start() => a, + _ => *interval.start(), }; let end = match end_bound { - Bound::Included(b) | Bound::Excluded(b) if b <= interval.end => b, - _ => interval.end, + Bound::Included(b) | Bound::Excluded(b) if b <= *interval.end() => b, + _ => *interval.end(), }; debug_assert!(end >= start); @@ -1345,7 +1409,7 @@ impl IntervalMap(&self, mut writer: W) -> io::Result<()> { writeln!(writer, "digraph {{")?; - for i in 0..self.nodes.len() { + for i in 0..=self.nodes.len() { self.nodes[i].write_dot(i, self.colors.get(i), &mut writer)?; } writeln!(writer, "}}") @@ -1357,7 +1421,7 @@ impl IntervalMap { /// Writes dot file to `writer` without values. `T` should implement `Display`. pub fn write_dot_without_values(&self, mut writer: W) -> io::Result<()> { writeln!(writer, "digraph {{")?; - for i in 0..self.nodes.len() { + for i in 0..=self.nodes.len() { self.nodes[i].write_dot_without_values(i, self.colors.get(i), &mut writer)?; } writeln!(writer, "}}") @@ -1382,24 +1446,24 @@ impl Debug for IntervalMa #[cfg(feature = "serde")] impl Serialize for IntervalMap - where - T: PartialOrd + Copy + Serialize, - V: Serialize, - Ix: IndexType + Serialize, +where + T: PartialOrd + Copy + Serialize, + V: Serialize, + Ix: IndexType + Serialize, { fn serialize(&self, serializer: S) -> Result { // For some reason, Vec does not support serialization. Because of that we create a newtype. struct NodeVecSer<'a, T, V, Ix>(&'a Vec>) - where - T: PartialOrd + Copy + Serialize, - V: Serialize, - Ix: IndexType + Serialize; + where + T: PartialOrd + Copy + Serialize, + V: Serialize, + Ix: IndexType + Serialize; impl<'a, T, V, Ix> Serialize for NodeVecSer<'a, T, V, Ix> - where - T: PartialOrd + Copy + Serialize, - V: Serialize, - Ix: IndexType + Serialize, + where + T: PartialOrd + Copy + Serialize, + V: Serialize, + Ix: IndexType + Serialize, { fn serialize(&self, serializer: S) -> Result { let mut seq = serializer.serialize_seq(Some(self.0.len()))?; @@ -1424,10 +1488,10 @@ struct NodeVecDe(Vec>); #[cfg(feature = "serde")] impl<'de, T, V, Ix> Deserialize<'de> for NodeVecDe - where - T: PartialOrd + Copy + Deserialize<'de>, - V: Deserialize<'de>, - Ix: IndexType + Deserialize<'de>, +where + T: PartialOrd + Copy + Deserialize<'de>, + V: Deserialize<'de>, + Ix: IndexType + Deserialize<'de>, { fn deserialize>(deserializer: D) -> Result { struct NodeVecVisitor { @@ -1470,7 +1534,8 @@ where Ix: IndexType + Deserialize<'de>, { fn deserialize>(deserializer: D) -> Result { - let (node_vec, colors, root) = <(NodeVecDe, BitVec, Ix)>::deserialize(deserializer)?; + let (node_vec, colors, root) = + <(NodeVecDe, BitVec, Ix)>::deserialize(deserializer)?; Ok(IntervalMap { nodes: node_vec.0, colors, @@ -1483,12 +1548,12 @@ where /// ```rust /// use iset::interval_map; /// -/// let map = interval_map!{ 0..10 => "a", 5..15 => "b", -5..20 => "c" }; +/// let map = interval_map!{ 0..=10 => "a", 5..=15 => "b", -5..=20 => "c" }; /// let a: Vec<_> = map.iter(..).collect(); -/// assert_eq!(a, &[(-5..20, &"c"), (0..10, &"a"), (5..15, &"b")]); +/// assert_eq!(a, &[(-5..=20, &"c"), (0..=10, &"a"), (5..=15, &"b")]); /// /// // Creates an interval map with `u8` index type (up to 255 values in the map). -/// let set = interval_map!{ [u8] 0..10 => "a", 5..15 => "b", -5..20 => "c" }; +/// let set = interval_map!{ [u8] 0..=10 => "a", 5..=15 => "b", -5..=20 => "c" }; /// ``` /// /// Panics if there are duplicate intervals. @@ -1506,7 +1571,7 @@ macro_rules! interval_map { let mut _temp_map = $crate::IntervalMap::<_, _, $ix>::default(); $( assert!(_temp_map.insert($k, $v).is_none(), - "Cannot use interval_map!{{ ... }} with duplicate intervals"); + "Cannot use interval_map!{{ ..=. }} with duplicate intervals"); )* _temp_map } @@ -1518,7 +1583,7 @@ macro_rules! interval_map { let mut _temp_map = $crate::IntervalMap::new(); $( assert!(_temp_map.insert($k, $v).is_none(), - "Cannot use interval_map!{{ ... }} with duplicate intervals"); + "Cannot use interval_map!{{ ..=. }} with duplicate intervals"); )* _temp_map } @@ -1529,12 +1594,12 @@ macro_rules! interval_map { /// ```rust /// use iset::interval_set; /// -/// let set = interval_set!{ 100..210, 50..150 }; +/// let set = interval_set!{ 100..=210, 50..=150 }; /// let a: Vec<_> = set.iter(..).collect(); -/// assert_eq!(a, &[50..150, 100..210]); +/// assert_eq!(a, &[50..=150, 100..=210]); /// /// // Creates an interval set with `u8` index type (up to 255 values in the set). -/// let set = interval_set!{ [u8] 100..210, 50..150 }; +/// let set = interval_set!{ [u8] 100..=210, 50..=150 }; /// ``` #[macro_export] macro_rules! interval_set { diff --git a/src/set.rs b/src/set.rs index 4255700..08b6a8c 100644 --- a/src/set.rs +++ b/src/set.rs @@ -1,61 +1,61 @@ //! `IntervalSet` implementation. use core::{ - ops::{Range, RangeInclusive, RangeBounds, RangeFull, AddAssign, Sub}, fmt::{self, Debug, Formatter}, iter::{FromIterator, IntoIterator}, + ops::{AddAssign, RangeBounds, RangeFull, RangeInclusive, Sub}, }; +#[cfg(feature = "serde")] +use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "dot")] use std::io::{self, Write}; -#[cfg(feature = "serde")] -use serde::{Serialize, Serializer, Deserialize, Deserializer}; -use super::IntervalMap; -use super::ix::{IndexType, DefaultIx}; use super::iter::*; +use super::ix::{DefaultIx, IndexType}; +use super::IntervalMap; -/// Set with interval keys (ranges `x..y`). Newtype over `IntervalMap`. -/// See [IntervalMap](../struct.IntervalMap.html) for more information. +/// Set with interval keys (ranges `x..=y`). Newtype over `IntervalMap`. +/// See [IntervalMap](..=/struct.IntervalMap.html) for more information. /// /// ```rust /// use iset::interval_set; -/// let mut set = interval_set!{ 0.4..1.5, 0.1..0.5, 5.0..7.0 }; -/// assert!(set.insert(-1.0..0.2)); +/// let mut set = interval_set!{ 0.4..=1.5, 0.1..=0.5, 5.0..=7.0 }; +/// assert!(set.insert(-1.0..=0.2)); /// // false because the interval is already in the set. -/// assert!(!set.insert(0.1..0.5)); +/// assert!(!set.insert(0.1..=0.5)); /// -/// assert!(set.contains(5.0..7.0)); -/// assert!(set.remove(5.0..7.0)); +/// assert!(set.contains(5.0..=7.0)); +/// assert!(set.remove(5.0..=7.0)); /// -/// // Iterate over intervals that overlap `0.2..0.8`. -/// let a: Vec<_> = set.iter(0.2..0.8).collect(); -/// assert_eq!(a, &[0.1..0.5, 0.4..1.5]); +/// // Iterate over intervals that overlap `0.2..=0.8`. +/// let a: Vec<_> = set.iter(0.2..=0.8).collect(); +/// assert_eq!(a, &[0.1..=0.5, 0.4..=1.5]); /// /// // Iterate over intervals that overlap a point 0.5. /// let b: Vec<_> = set.overlap(0.5).collect(); -/// assert_eq!(b, &[0.4..1.5]); +/// assert_eq!(b, &[0.4..=1.5]); /// /// // Will panic: -/// // set.insert(0.0..core::f64::NAN); +/// // set.insert(0.0..=core::f64::NAN); /// // set.overlap(core::f64::NAN); /// /// // It is still possible to use infinity. /// const INF: f64 = core::f64::INFINITY; -/// set.insert(0.0..INF); +/// set.insert(0.0..=INF); /// let c: Vec<_> = set.overlap(0.5).collect(); -/// assert_eq!(c, &[0.0..INF, 0.4..1.5]); +/// assert_eq!(c, &[0.0..=INF, 0.4..=1.5]); /// /// println!("{:?}", set); -/// // {-1.0..0.2, 0.0..inf, 0.1..0.5, 0.4..1.5} -/// assert_eq!(set.range().unwrap(), -1.0..INF); -/// assert_eq!(set.smallest().unwrap(), -1.0..0.2); -/// assert_eq!(set.largest().unwrap(), 0.4..1.5); +/// // {-1.0..=0.2, 0.0..=inf, 0.1..=0.5, 0.4..=1.5} +/// assert_eq!(set.range().unwrap(), -1.0..=INF); +/// assert_eq!(set.smallest().unwrap(), -1.0..=0.2); +/// assert_eq!(set.largest().unwrap(), 0.4..=1.5); /// ``` /// /// There are no mutable iterators over [IntervalSet](struct.IntervalSet.html) as keys should be immutable. /// -/// In contrast to the [IntervalMap](../struct.IntervalMap.html), `IntervalSet` does not have a -/// [force_insert](../struct.IntervalMap.html#method.force_insert), and completely forbids duplicate intervals. +/// In contrast to the [IntervalMap](..=/struct.IntervalMap.html), `IntervalSet` does not have a +/// [force_insert](..=/struct.IntervalMap.html#method.force_insert), and completely forbids duplicate intervals. #[derive(Clone)] pub struct IntervalSet { inner: IntervalMap, @@ -63,7 +63,7 @@ pub struct IntervalSet { impl IntervalSet { /// Creates an empty [IntervalSet](struct.IntervalSet.html) - /// with default index type [DefaultIx](../ix/type.DefaultIx.html). + /// with default index type [DefaultIx](..=/ix/type.DefaultIx.html). pub fn new() -> Self { Self::default() } @@ -89,7 +89,8 @@ impl IntervalSet { /// /// Panics if the intervals are not sorted or if there are equal intervals. pub fn from_sorted(iter: I) -> Self - where I: Iterator>, + where + I: Iterator>, { Self { inner: IntervalMap::from_sorted(iter.map(|range| (range, ()))), @@ -120,25 +121,25 @@ impl IntervalSet { self.inner.shrink_to_fit() } - /// Inserts an interval `x..y` to the set. If the set did not have this interval present, true is returned. + /// Inserts an interval `x..=y` to the set. If the set did not have this interval present, true is returned. /// Takes *O(log N)*. /// /// Panics if `interval` is empty (`start >= end`) or contains a value that cannot be compared (such as `NAN`). - pub fn insert(&mut self, interval: Range) -> bool { + pub fn insert(&mut self, interval: RangeInclusive) -> bool { self.inner.insert(interval, ()).is_none() } /// Check if the interval set contains `interval` (exact match). Takes *O(log N)*. /// /// Panics if `interval` is empty (`start >= end`) or contains a value that cannot be compared (such as `NAN`). - pub fn contains(&self, interval: Range) -> bool { + pub fn contains(&self, interval: RangeInclusive) -> bool { self.inner.contains(interval) } /// Removes the interval from the set. Returns true if the interval was present in the set. Takes *O(log N)*. /// /// Panics if `interval` is empty (`start >= end`) or contains a value that cannot be compared (such as `NAN`). - pub fn remove(&mut self, interval: Range) -> bool { + pub fn remove(&mut self, interval: RangeInclusive) -> bool { self.inner.remove(interval).is_some() } @@ -146,31 +147,31 @@ impl IntervalSet { /// `out.start` is the minimal start of all intervals in the set, /// and `out.end` is the maximal end of all intervals in the set. #[inline] - pub fn range(&self) -> Option> { + pub fn range(&self) -> Option> { self.inner.range() } /// Returns the smallest interval in the set (in lexicographical order). /// Takes *O(log N)*. Returns `None` if the set is empty. - pub fn smallest(&self) -> Option> { + pub fn smallest(&self) -> Option> { self.inner.smallest().map(|(interval, _)| interval) } /// Removes and returns the smallest interval in the set (in lexicographical order). /// Takes *O(log N)*. Returns `None` if the set is empty. - pub fn remove_smallest(&mut self) -> Option> { + pub fn remove_smallest(&mut self) -> Option> { self.inner.remove_smallest().map(|(interval, _)| interval) } /// Returns the largest interval in the set (in lexicographical order). /// Takes *O(log N)*. Returns `None` if the set is empty. - pub fn largest(&self) -> Option> { + pub fn largest(&self) -> Option> { self.inner.largest().map(|(interval, _)| interval) } /// Removes and returns the largest interval in the set (in lexicographical order). /// Takes *O(log N)*. Returns `None` if the set is empty. - pub fn remove_largest(&mut self) -> Option> { + pub fn remove_largest(&mut self) -> Option> { self.inner.remove_largest().map(|(interval, _)| interval) } @@ -178,42 +179,46 @@ impl IntervalSet { /// Equivalent to `set.iter(query).next().is_some()`, but much faster. #[inline] pub fn has_overlap(&self, query: R) -> bool - where R: RangeBounds, { + where + R: RangeBounds, + { self.inner.has_overlap(query) } - /// Iterates over intervals `x..y` that overlap the `query`. + /// Iterates over intervals `x..=y` that overlap the `query`. /// Takes *O(log N + K)* where *K* is the size of the output. /// Output is sorted by intervals. /// /// Panics if `interval` is empty or contains a value that cannot be compared (such as `NAN`). - pub fn iter<'a, R>(&'a self, query: R) -> Intervals<'a, T, (), R, Ix> - where R: RangeBounds, + pub fn iter(&self, query: R) -> Intervals<'_, T, (), R, Ix> + where + R: RangeBounds, { self.inner.intervals(query) } - /// Iterates over intervals `x..y` that overlap the `point`. Same as `iter(point..=point)`. + /// Iterates over intervals `x..=y` that overlap the `point`. Same as `iter(point..==point)`. /// See [iter](#method.iter) for more details. - pub fn overlap<'a>(&'a self, point: T) -> Intervals<'a, T, (), RangeInclusive, Ix> { + pub fn overlap(&self, point: T) -> Intervals<'_, T, (), RangeInclusive, Ix> { self.inner.intervals(point..=point) } - /// Consumes [IntervalSet](struct.IntervalSet.html) and iterates over intervals `x..y` that overlap the `query`. + /// Consumes [IntervalSet](struct.IntervalSet.html) and iterates over intervals `x..=y` that overlap the `query`. /// See [iter](#method.iter) for more details. pub fn into_iter(self, query: R) -> IntoIntervals - where R: RangeBounds, + where + R: RangeBounds, { IntoIntervals::new(self.inner, query) } - /// Creates an unsorted iterator over all intervals `x..y`. + /// Creates an unsorted iterator over all intervals `x..=y`. /// Slightly faster than the sorted iterator, although both take *O(N)*. - pub fn unsorted_iter<'a>(&'a self) -> UnsIntervals<'a, T, (), Ix> { + pub fn unsorted_iter(&self) -> UnsIntervals<'_, T, (), Ix> { UnsIntervals::new(&self.inner) } - /// Consumes `IntervalSet` and creates an unsorted iterator over all intervals `x..y`. + /// Consumes `IntervalSet` and creates an unsorted iterator over all intervals `x..=y`. pub fn unsorted_into_iter(self) -> UnsIntoIntervals { UnsIntoIntervals::new(self.inner) } @@ -221,16 +226,16 @@ impl IntervalSet { impl IntoIterator for IntervalSet { type IntoIter = IntoIntervals; - type Item = Range; + type Item = RangeInclusive; fn into_iter(self) -> Self::IntoIter { IntoIntervals::new(self.inner, ..) } } -/// Construct [IntervalSet](struct.IntervalSet.html) from ranges `x..y`. -impl FromIterator> for IntervalSet { - fn from_iter>>(iter: I) -> Self { +/// Construct [IntervalSet](struct.IntervalSet.html) from ranges `x..=y`. +impl FromIterator> for IntervalSet { + fn from_iter>>(iter: I) -> Self { let mut set = IntervalSet::new(); for range in iter { set.insert(range); @@ -240,16 +245,18 @@ impl FromIterator> for IntervalSet { } impl IntervalSet -where T: PartialOrd + Copy + Default + AddAssign + Sub, - Ix: IndexType, +where + T: PartialOrd + Copy + Default + AddAssign + Sub, + Ix: IndexType, { /// Calculates the total length of the `query` that is covered by intervals in the map. /// Takes *O(log N + K)* where *K* is the number of intervals that overlap `query`. /// - /// See [IntervalMap::covered_len](../struct.IntervalMap.html#method.covered_len) for more details. + /// See [IntervalMap::covered_len](..=/struct.IntervalMap.html#method.covered_len) for more details. #[inline] pub fn covered_len(&self, query: R) -> T - where R: RangeBounds + where + R: RangeBounds, { self.inner.covered_len(query) } @@ -300,4 +307,4 @@ where let inner = >::deserialize(deserializer)?; Ok(IntervalSet { inner }) } -} \ No newline at end of file +} diff --git a/src/tests.rs b/src/tests.rs index 938216f..2e2dac0 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -1,25 +1,31 @@ +use rand::prelude::*; use std::{ + fmt::{Debug, Write}, + ops::{self, Bound, Range, RangeBounds}, println, string::String, - ops::{self, Range, RangeBounds, Bound}, - fmt::{Debug, Write}, }; -use rand::prelude::*; #[cfg(feature = "serde")] -use std::{ - path::Path, - fs::File, -}; +use std::{fs::File, path::Path}; use super::*; /// Returns distance to leaves (only black nodes). -fn validate_tree_recursive(tree: &IntervalMap, index: Ix, upper_interval: &mut Interval, - visited: &mut BitVec) -> u32 -where T: PartialOrd + Copy, - Ix: IndexType, +fn validate_tree_recursive( + tree: &IntervalMap, + index: Ix, + upper_interval: &mut Interval, + visited: &mut BitVec, +) -> u32 +where + T: PartialOrd + Copy, + Ix: IndexType, { - assert!(!visited.get(index.get()), "The tree contains a cycle: node {} was visited twice", index); + assert!( + !visited.get(index.get()), + "The tree contains a cycle: node {} was visited twice", + index + ); visited.set(index.get(), true); let node = &tree.nodes[index.get()]; @@ -29,26 +35,56 @@ where T: PartialOrd + Copy, let left_depth = if left.defined() { if tree.is_red(index) { - assert!(tree.is_black(left), "Red node {} has a red child {}", index, left); + assert!( + tree.is_black(left), + "Red node {} has a red child {}", + index, + left + ); } - Some(validate_tree_recursive(tree, left, &mut down_interval, visited)) + Some(validate_tree_recursive( + tree, + left, + &mut down_interval, + visited, + )) } else { None }; let right_depth = if right.defined() { if tree.is_red(index) { - assert!(tree.is_black(right), "Red node {} has a red child {}", index, right); + assert!( + tree.is_black(right), + "Red node {} has a red child {}", + index, + right + ); } - Some(validate_tree_recursive(tree, right, &mut down_interval, visited)) + Some(validate_tree_recursive( + tree, + right, + &mut down_interval, + visited, + )) } else { None }; - assert!(down_interval == node.subtree_interval, "Interval != subtree interval for node {}", index); + assert!( + down_interval == node.subtree_interval, + "Interval != subtree interval for node {}", + index + ); upper_interval.extend(&down_interval); match (left_depth, right_depth) { - (Some(x), Some(y)) => assert!(x == y, "Node {} has different depths to leaves: {} != {}", index, x, y), - _ => {}, + (Some(x), Some(y)) => assert!( + x == y, + "Node {} has different depths to leaves: {} != {}", + index, + x, + y + ), + _ => {} } let depth = left_depth.or(right_depth).unwrap_or(0); if tree.is_black(index) { @@ -61,7 +97,11 @@ where T: PartialOrd + Copy, fn validate(tree: &IntervalMap, size: usize) { assert_eq!(size, tree.len(), "Tree sizes do not match"); assert_eq!(size > 0, tree.root.defined(), "Tree root != size"); - assert_eq!(tree.len(), tree.colors.len(), "Number of nodes != number of colors"); + assert_eq!( + tree.len(), + tree.colors.len(), + "Number of nodes != number of colors" + ); if !tree.root.defined() { assert!(tree.nodes.is_empty(), "Non empty nodes with an empty root"); @@ -69,9 +109,19 @@ fn validate(tree: &IntervalMap } for i in 0..tree.nodes.len() { if i == tree.root.get() { - assert!(!tree.nodes[i].parent.defined(), "Root {} has a parent {}", i, tree.nodes[i].parent); + assert!( + !tree.nodes[i].parent.defined(), + "Root {} has a parent {}", + i, + tree.nodes[i].parent + ); } else { - assert!(tree.nodes[i].parent.defined(), "Non-root {} has an empty parent (root is {})", i, tree.root); + assert!( + tree.nodes[i].parent.defined(), + "Non-root {} has an empty parent (root is {})", + i, + tree.root + ); } } @@ -79,39 +129,43 @@ fn validate(tree: &IntervalMap let mut interval = node.interval.clone(); let mut visited = BitVec::from_elem(tree.nodes.len(), false); validate_tree_recursive(tree, tree.root, &mut interval, &mut visited); - assert!(interval == node.subtree_interval, "Interval != subtree interval for node {}", tree.root); + assert!( + interval == node.subtree_interval, + "Interval != subtree interval for node {}", + tree.root + ); for i in 0..tree.len() { - assert!(visited.get(i), "The tree is disjoint: node {} has no connection to the root", i); + assert!( + visited.get(i), + "The tree is disjoint: node {} has no connection to the root", + i + ); } } -fn intersects>(range: &Range, query: &R) -> bool { +fn intersects>(range: &RangeInclusive, query: &R) -> bool { (match query.end_bound() { Bound::Included(value) => value >= &range.start, Bound::Excluded(value) => value > &range.start, Bound::Unbounded => true, - }) - && - (match query.start_bound() { + }) && (match query.start_bound() { Bound::Included(value) | Bound::Excluded(value) => value < &range.end, Bound::Unbounded => true, }) } -fn range_eq(a: &Range, b: &Range) -> bool { +fn range_eq(a: &RangeInclusive, b: &RangeInclusive) -> bool { a.start_bound() == b.start_bound() && a.end_bound() == b.end_bound() } struct NaiveIntervalMap { - nodes: Vec<(Range, V)>, + nodes: Vec<(RangeInclusive, V)>, } impl NaiveIntervalMap { fn new() -> Self { - Self { - nodes: Vec::new(), - } + Self { nodes: Vec::new() } } fn len(&self) -> usize { @@ -122,20 +176,28 @@ impl NaiveIntervalMap { self.nodes.is_empty() } - fn insert(&mut self, range: Range, value: V) { + fn insert(&mut self, range: RangeInclusive, value: V) { self.nodes.push((range, value)); } - fn iter<'a, R: 'a + RangeBounds>(&'a self, query: R) -> impl Iterator, &V)> + 'a { - self.nodes.iter().filter(move |(range, _value)| intersects(range, &query)) + fn iter<'a, R: 'a + RangeBounds>( + &'a self, + query: R, + ) -> impl Iterator, &V)> + 'a { + self.nodes + .iter() + .filter(move |(range, _value)| intersects(range, &query)) .map(|(range, value)| (range.clone(), value)) } - fn all_matching<'a>(&'a self, query: Range) -> impl Iterator + 'a { - self.nodes.iter().filter(move |(range, _value)| range_eq(&range, &query)).map(|(_range, value)| value) + fn all_matching<'a>(&'a self, query: RangeInclusive) -> impl Iterator + 'a { + self.nodes + .iter() + .filter(move |(range, _value)| range_eq(&range, &query)) + .map(|(_range, value)| value) } - fn remove_random(&mut self, rng: &mut impl Rng) -> (Range, V) { + fn remove_random(&mut self, rng: &mut impl Rng) -> (RangeInclusive, V) { self.nodes.swap_remove(rng.gen_range(0..self.nodes.len())) } } @@ -181,7 +243,10 @@ impl NaiveIntervalMap { } } -fn generate_ordered_pair T>(generator: &mut F, forbid_eq: bool) -> (T, T) { +fn generate_ordered_pair T>( + generator: &mut F, + forbid_eq: bool, +) -> (T, T) { let a = generator(); let mut b = generator(); while forbid_eq && a == b { @@ -200,8 +265,9 @@ fn random_inserts( n_inserts: u32, mut generator: F, ) -> String -where T: PartialOrd + Copy + Debug, - F: FnMut() -> Range, +where + T: PartialOrd + Copy + Debug, + F: FnMut() -> RangeInclusive, { let mut history = String::new(); for i in 0..n_inserts { @@ -209,7 +275,11 @@ where T: PartialOrd + Copy + Debug, writeln!(history, "insert({:?})", range).unwrap(); naive.insert(range.clone(), i); if let Some(value) = tree.insert(range.clone(), i) { - let i = naive.nodes.iter().position(|(range2, _value2)| range == *range2).unwrap(); + let i = naive + .nodes + .iter() + .position(|(range2, _value2)| range == *range2) + .unwrap(); assert_eq!(naive.nodes[i].1, value); naive.nodes.swap_remove(i); } @@ -223,8 +293,9 @@ fn random_force_inserts( n_inserts: u32, mut generator: F, ) -> String -where T: PartialOrd + Copy + Debug, - F: FnMut() -> Range, +where + T: PartialOrd + Copy + Debug, + F: FnMut() -> RangeInclusive, { let mut history = String::new(); for i in 0..n_inserts { @@ -236,12 +307,17 @@ where T: PartialOrd + Copy + Debug, history } -fn save_iter<'a, T, I>(iter: I) -> Vec<(Range, u32)> -where T: PartialOrd + Copy, - I: Iterator, &'a u32)>, +fn save_iter<'a, T, I>(iter: I) -> Vec<(RangeInclusive, u32)> +where + T: PartialOrd + Copy, + I: Iterator, &'a u32)>, { let mut res: Vec<_> = iter.map(|(range, value)| (range, *value)).collect(); - res.sort_by(|a, b| (a.0.start, a.0.end, a.1).partial_cmp(&(b.0.start, b.0.end, b.1)).unwrap()); + res.sort_by(|a, b| { + (a.0.start, a.0.end, a.1) + .partial_cmp(&(b.0.start, b.0.end, b.1)) + .unwrap() + }); res } @@ -261,16 +337,18 @@ fn generate_float_rounding() -> impl (FnMut() -> f64) { move || (rng.gen::() * MULT).round() / MULT } -fn generate_range T>(mut generator: F) - -> impl (FnMut() -> Range) { +fn generate_range T>( + mut generator: F, +) -> impl (FnMut() -> RangeInclusive) { move || { let (a, b) = generate_ordered_pair(&mut generator, true); a..b } } -fn generate_range_from T>(mut generator: F) - -> impl (FnMut() -> ops::RangeFrom) { +fn generate_range_from T>( + mut generator: F, +) -> impl (FnMut() -> ops::RangeFrom) { move || generator().. } @@ -278,29 +356,37 @@ fn generate_range_full() -> ops::RangeFull { .. } -fn generate_range_incl T>(mut generator: F) - -> impl (FnMut() -> ops::RangeInclusive) { +fn generate_range_incl T>( + mut generator: F, +) -> impl (FnMut() -> ops::RangeInclusive) { move || { let (a, b) = generate_ordered_pair(&mut generator, false); a..=b } } -fn generate_range_to T>(mut generator: F) - -> impl (FnMut() -> ops::RangeTo) { +fn generate_range_to T>( + mut generator: F, +) -> impl (FnMut() -> ops::RangeTo) { move || ..generator() } -fn generate_range_to_incl T>(mut generator: F) - -> impl (FnMut() -> ops::RangeToInclusive) { +fn generate_range_to_incl T>( + mut generator: F, +) -> impl (FnMut() -> ops::RangeToInclusive) { move || ..=generator() } -fn search_rand(naive: &mut NaiveIntervalMap, tree: &mut IntervalMap, n_searches: u32, - mut range_generator: F, history: &str) -where T: PartialOrd + Copy + Debug, - R: RangeBounds + Debug + Clone, - F: FnMut() -> R, +fn search_rand( + naive: &mut NaiveIntervalMap, + tree: &mut IntervalMap, + n_searches: u32, + mut range_generator: F, + history: &str, +) where + T: PartialOrd + Copy + Debug, + R: RangeBounds + Debug + Clone, + F: FnMut() -> R, { for _ in 0..n_searches { let range = range_generator(); @@ -322,10 +408,17 @@ where T: PartialOrd + Copy + Debug, } fn compare_extremums(naive: &NaiveIntervalMap, tree: &IntervalMap, history: &str) -where T: PartialOrd + Copy + Debug +where + T: PartialOrd + Copy + Debug, { - let smallest_a = naive.nodes.iter() - .min_by(|a, b| (a.0.start, a.0.end, a.1).partial_cmp(&(b.0.start, b.0.end, b.1)).unwrap()) + let smallest_a = naive + .nodes + .iter() + .min_by(|a, b| { + (a.0.start, a.0.end, a.1) + .partial_cmp(&(b.0.start, b.0.end, b.1)) + .unwrap() + }) .map(|(interval, _)| interval.clone()); let smallest_b = tree.smallest().map(|(interval, _)| interval); if smallest_a != smallest_b { @@ -334,8 +427,14 @@ where T: PartialOrd + Copy + Debug assert_eq!(smallest_a, smallest_b); } - let largest_a = naive.nodes.iter() - .max_by(|a, b| (a.0.start, a.0.end, a.1).partial_cmp(&(b.0.start, b.0.end, b.1)).unwrap()) + let largest_a = naive + .nodes + .iter() + .max_by(|a, b| { + (a.0.start, a.0.end, a.1) + .partial_cmp(&(b.0.start, b.0.end, b.1)) + .unwrap() + }) .map(|(interval, _)| interval.clone()); let largest_b = tree.largest().map(|(interval, _)| interval); if largest_a != largest_b { @@ -349,11 +448,11 @@ fn compare_match_results( naive: &NaiveIntervalMap, tree: &IntervalMap, history: &str, - range: Range, + range: RangeInclusive, getter: &mut G, -) -where T: PartialOrd + Copy + Clone + Debug, - G: FnMut(&IntervalMap, Range) -> Vec, +) where + T: PartialOrd + Copy + Clone + Debug, + G: FnMut(&IntervalMap, RangeInclusive) -> Vec, { let mut naive_vals: Vec<_> = naive.all_matching(range.clone()).map(|v| *v).collect(); let mut tree_vals = getter(tree, range.clone()); @@ -361,7 +460,10 @@ where T: PartialOrd + Copy + Clone + Debug, tree_vals.sort_unstable(); if naive_vals != tree_vals { - println!("Range: {:?}, naive: {:?}, tree: {:?}", range, naive_vals, tree_vals); + println!( + "Range: {:?}, naive: {:?}, tree: {:?}", + range, naive_vals, tree_vals + ); println!("{}", history); println!(); panic!(); @@ -374,10 +476,10 @@ fn compare_exact_matching( history: &str, mut generator: F, mut getter: G, -) -where T: PartialOrd + Copy + Debug, - F: FnMut() -> Range, - G: FnMut(&IntervalMap, Range) -> Vec, +) where + T: PartialOrd + Copy + Debug, + F: FnMut() -> RangeInclusive, + G: FnMut(&IntervalMap, RangeInclusive) -> Vec, { for (range, _value) in &naive.nodes { compare_match_results(naive, tree, history, range.clone(), &mut getter); @@ -388,10 +490,15 @@ where T: PartialOrd + Copy + Debug, } } -fn check_covered_len(naive: &NaiveIntervalMap, tree: &IntervalMap, - count: u32, mut generator: F, history: &str) -where R: RangeBounds + Clone + Debug, - F: FnMut() -> R, +fn check_covered_len( + naive: &NaiveIntervalMap, + tree: &IntervalMap, + count: u32, + mut generator: F, + history: &str, +) where + R: RangeBounds + Clone + Debug, + F: FnMut() -> R, { for _ in 0..count { let query = generator(); @@ -400,7 +507,10 @@ where R: RangeBounds + Clone + Debug, if len1 != len2 { println!("{}", history); println!(); - println!("Query = {:?}, naive len = {}, map len = {}", query, len1, len2); + println!( + "Query = {:?}, naive len = {}, map len = {}", + query, len1, len2 + ); panic!(); } assert_eq!(len1, len2); @@ -417,11 +527,13 @@ where loop { match (iter1.next(), iter2.next()) { (None, None) => break, - (x, y) => if x != y { - println!("{}", history); - println!(); - assert_eq!(x, y); - }, + (x, y) => { + if x != y { + println!("{}", history); + println!(); + assert_eq!(x, y); + } + } } } } @@ -431,20 +543,60 @@ fn test_int_inserts() { const COUNT: u32 = 1000; let mut naive = NaiveIntervalMap::new(); let mut tree = IntervalMap::new(); - let history = random_inserts(&mut naive, &mut tree, COUNT, generate_range(generate_int(20, 120))); + let history = random_inserts( + &mut naive, + &mut tree, + COUNT, + generate_range(generate_int(20, 120)), + ); validate(&tree, naive.len()); compare_extremums(&naive, &tree, &history); let mut generator = generate_int(0, 140); - compare_exact_matching(&naive, &tree, &history, - generate_range(&mut generator), |tree, range| tree.get(range).into_iter().cloned().collect()); - search_rand(&mut naive, &mut tree, COUNT, generate_range(&mut generator), &history); - search_rand(&mut naive, &mut tree, COUNT, generate_range_from(&mut generator), &history); + compare_exact_matching( + &naive, + &tree, + &history, + generate_range(&mut generator), + |tree, range| tree.get(range).into_iter().cloned().collect(), + ); + search_rand( + &mut naive, + &mut tree, + COUNT, + generate_range(&mut generator), + &history, + ); + search_rand( + &mut naive, + &mut tree, + COUNT, + generate_range_from(&mut generator), + &history, + ); search_rand(&mut naive, &mut tree, 1, generate_range_full, &history); - search_rand(&mut naive, &mut tree, COUNT, generate_range_incl(&mut generator), &history); - search_rand(&mut naive, &mut tree, COUNT, generate_range_to(&mut generator), &history); - search_rand(&mut naive, &mut tree, COUNT, generate_range_to_incl(&mut generator), &history); + search_rand( + &mut naive, + &mut tree, + COUNT, + generate_range_incl(&mut generator), + &history, + ); + search_rand( + &mut naive, + &mut tree, + COUNT, + generate_range_to(&mut generator), + &history, + ); + search_rand( + &mut naive, + &mut tree, + COUNT, + generate_range_to_incl(&mut generator), + &history, + ); } #[test] @@ -452,16 +604,51 @@ fn test_covered_len() { const COUNT: u32 = 1000; let mut naive = NaiveIntervalMap::new(); let mut tree = IntervalMap::new(); - let history = random_inserts(&mut naive, &mut tree, COUNT, generate_range(generate_int(-500, 500))); + let history = random_inserts( + &mut naive, + &mut tree, + COUNT, + generate_range(generate_int(-500, 500)), + ); validate(&tree, naive.len()); let mut generator = generate_int(-510, 510); - check_covered_len(&mut naive, &mut tree, COUNT, generate_range(&mut generator), &history); - check_covered_len(&mut naive, &mut tree, COUNT, generate_range_from(&mut generator), &history); + check_covered_len( + &mut naive, + &mut tree, + COUNT, + generate_range(&mut generator), + &history, + ); + check_covered_len( + &mut naive, + &mut tree, + COUNT, + generate_range_from(&mut generator), + &history, + ); check_covered_len(&mut naive, &mut tree, 1, generate_range_full, &history); - check_covered_len(&mut naive, &mut tree, COUNT, generate_range_incl(&mut generator), &history); - check_covered_len(&mut naive, &mut tree, COUNT, generate_range_to(&mut generator), &history); - check_covered_len(&mut naive, &mut tree, COUNT, generate_range_to_incl(&mut generator), &history); + check_covered_len( + &mut naive, + &mut tree, + COUNT, + generate_range_incl(&mut generator), + &history, + ); + check_covered_len( + &mut naive, + &mut tree, + COUNT, + generate_range_to(&mut generator), + &history, + ); + check_covered_len( + &mut naive, + &mut tree, + COUNT, + generate_range_to_incl(&mut generator), + &history, + ); } #[test] @@ -469,18 +656,53 @@ fn test_float_inserts() { const COUNT: u32 = 1000; let mut naive = NaiveIntervalMap::new(); let mut tree = IntervalMap::new(); - let history = random_inserts(&mut naive, &mut tree, COUNT, generate_range(generate_float(0.0, 1000.0))); + let history = random_inserts( + &mut naive, + &mut tree, + COUNT, + generate_range(generate_float(0.0, 1000.0)), + ); validate(&tree, naive.len()); compare_extremums(&naive, &tree, &history); let mut generator = generate_float(-50.0, 1050.0); - search_rand(&mut naive, &mut tree, COUNT, generate_range(&mut generator), &history); - search_rand(&mut naive, &mut tree, COUNT, generate_range_from(&mut generator), &history); + search_rand( + &mut naive, + &mut tree, + COUNT, + generate_range(&mut generator), + &history, + ); + search_rand( + &mut naive, + &mut tree, + COUNT, + generate_range_from(&mut generator), + &history, + ); search_rand(&mut naive, &mut tree, 1, generate_range_full, &history); - search_rand(&mut naive, &mut tree, COUNT, generate_range_incl(&mut generator), &history); - search_rand(&mut naive, &mut tree, COUNT, generate_range_to(&mut generator), &history); - search_rand(&mut naive, &mut tree, COUNT, generate_range_to_incl(&mut generator), &history); + search_rand( + &mut naive, + &mut tree, + COUNT, + generate_range_incl(&mut generator), + &history, + ); + search_rand( + &mut naive, + &mut tree, + COUNT, + generate_range_to(&mut generator), + &history, + ); + search_rand( + &mut naive, + &mut tree, + COUNT, + generate_range_to_incl(&mut generator), + &history, + ); } #[test] @@ -491,7 +713,7 @@ fn test_from_sorted() { let mut vec = Vec::new(); for i in 0..COUNT { - vec.push((i..i+1, i)); + vec.push((i..i + 1, i)); map = IntervalMap::from_sorted(vec.clone().into_iter()); validate(&map, vec.len()); } @@ -505,12 +727,21 @@ fn test_exact_iterators() { const COUNT: u32 = 5000; let mut naive = NaiveIntervalMap::new(); let mut tree = IntervalMap::new(); - let history = random_force_inserts(&mut naive, &mut tree, COUNT, generate_range(generate_int(10, 25))); + let history = random_force_inserts( + &mut naive, + &mut tree, + COUNT, + generate_range(generate_int(10, 25)), + ); validate(&tree, COUNT as usize); - compare_exact_matching(&naive, &tree, &history, + compare_exact_matching( + &naive, + &tree, + &history, generate_range(generate_int(5, 30)), - |tree, range| tree.values_at(range).cloned().collect()); + |tree, range| tree.values_at(range).cloned().collect(), + ); } #[cfg(feature = "serde")] @@ -519,7 +750,12 @@ fn test_serde() { const COUNT: u32 = 1000; let mut naive = NaiveIntervalMap::new(); let mut tree: IntervalMap = IntervalMap::new(); - let history = random_inserts(&mut naive, &mut tree, COUNT, generate_range(generate_int(0, 10000))); + let history = random_inserts( + &mut naive, + &mut tree, + COUNT, + generate_range(generate_int(0, 10000)), + ); let json_path = Path::new("tests/data/serde.json"); let folders = json_path.parent().unwrap(); diff --git a/src/tree_rm.rs b/src/tree_rm.rs index 66d8b92..efd9f57 100644 --- a/src/tree_rm.rs +++ b/src/tree_rm.rs @@ -1,4 +1,3 @@ - use super::*; impl IntervalMap { @@ -103,10 +102,18 @@ impl IntervalMap { let parent = &self.nodes[parent_ix.get()]; let parent_black = self.is_black(parent_ix); let node_is_left = parent.left == ix; - let sibling_ix = if node_is_left { parent.right } else { parent.left }; + let sibling_ix = if node_is_left { + parent.right + } else { + parent.left + }; let (close_nephew_ix, distant_nephew_ix) = if sibling_ix.defined() { let sibling = &self.nodes[sibling_ix.get()]; - if node_is_left { (sibling.left, sibling.right) } else { (sibling.right, sibling.left) } + if node_is_left { + (sibling.left, sibling.right) + } else { + (sibling.right, sibling.left) + } } else { (Ix::MAX, Ix::MAX) }; @@ -155,7 +162,8 @@ impl IntervalMap { else { debug_assert!(sibling_black && !distant_nephew_black); // parent's color -> sibling's color. - self.colors.set(sibling_ix.get(), self.colors.get(parent_ix.get())); + self.colors + .set(sibling_ix.get(), self.colors.get(parent_ix.get())); self.set_black(parent_ix); self.set_black(distant_nephew_ix); self.replace_children(parent_ix, sibling_ix); @@ -200,7 +208,9 @@ impl IntervalMap { } }; if rm_ix != ix { - unsafe { self.swap_nodes(ix, rm_ix); } + unsafe { + self.swap_nodes(ix, rm_ix); + } } let rm_node = &self.nodes[rm_ix.get()]; @@ -209,7 +219,9 @@ impl IntervalMap { if child_ix.defined() { // Removed node has a child, replace the node with the child and remove the child. - unsafe { self.swap_nodes(rm_ix, child_ix); } + unsafe { + self.swap_nodes(rm_ix, child_ix); + } self.remove_child(rm_ix, child_ix); self.fix_intervals_up(rm_ix); Some(self.swap_remove(child_ix))