intervaltree-0.2.7/.cargo_vcs_info.json0000644000000001120000000000100135400ustar { "git": { "sha1": "b45ad6723fe23eaeeae585398e3681de988b0b07" } } intervaltree-0.2.7/.gitignore000064400000000000000000000000420072674642500143520ustar 00000000000000/target/ **/*.rs.bk *~ Cargo.lock intervaltree-0.2.7/Cargo.toml0000644000000017620000000000100115520ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "intervaltree" version = "0.2.7" authors = ["main() "] description = "A simple and generic implementation of an immutable interval tree." documentation = "https://docs.rs/intervaltree" categories = ["data-structures", "no-std"] license = "MIT" repository = "https://github.com/main--/rust-intervaltree" [dependencies.serde] version = "1.0" features = ["alloc", "derive"] optional = true default-features = false [dependencies.smallvec] version = "1.0.0" [features] default = ["std"] std = [] intervaltree-0.2.7/Cargo.toml.orig000064400000000000000000000010370072674642500152560ustar 00000000000000[package] name = "intervaltree" documentation = "https://docs.rs/intervaltree" repository = "https://github.com/main--/rust-intervaltree" version = "0.2.7" authors = ["main() "] license = "MIT" description = "A simple and generic implementation of an immutable interval tree." categories = ["data-structures", "no-std"] edition = "2018" [dependencies] smallvec = { version = "1.0.0" } serde = { version = "1.0", default-features = false, features = ["alloc", "derive"], optional = true } [features] std = [] default = ["std"] intervaltree-0.2.7/LICENSE000064400000000000000000000020470072674642500133760ustar 00000000000000MIT License Copyright (c) 2018 main() Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. intervaltree-0.2.7/src/lib.rs000064400000000000000000000214030072674642500142710ustar 00000000000000#![no_std] #![warn(missing_docs)] //! A simple and generic implementation of an immutable interval tree. #[cfg(not(feature = "std"))] extern crate alloc; #[cfg(feature = "serde")] extern crate serde; #[cfg(feature = "std")] extern crate std; #[cfg(not(feature = "std"))] use alloc::vec::{IntoIter, Vec}; use core::cmp; use core::fmt::{Debug, Formatter, Result as FmtResult}; use core::iter::FromIterator; use core::ops::Range; use core::slice::Iter; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use smallvec::SmallVec; #[cfg(feature = "std")] use std::vec::{IntoIter, Vec}; /// An element of an interval tree. #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Element { /// The range associated with this element. pub range: Range, /// The value associated with this element. pub value: V, } impl From<(Range, V)> for Element { fn from(tup: (Range, V)) -> Element { let (range, value) = tup; Element { range, value } } } #[derive(Clone, Debug, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] struct Node { element: Element, max: K, } /// A simple and generic implementation of an immutable interval tree. /// /// To build it, always use `FromIterator`. This is not very optimized /// as it takes `O(log n)` stack (it uses recursion) but runs in `O(n log n)`. #[derive(Clone, Debug, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct IntervalTree { data: Vec>, } impl>> FromIterator for IntervalTree { fn from_iter>(iter: T) -> Self { let mut nodes: Vec<_> = iter.into_iter().map(|i| i.into()) .map(|element| Node { max: element.range.end.clone(), element }).collect(); nodes.sort_unstable_by(|a, b| a.element.range.start.cmp(&b.element.range.start)); if !nodes.is_empty() { Self::update_max(&mut nodes); } IntervalTree { data: nodes } } } /// An iterator over all the elements in the tree (in no particular order). pub struct TreeIter<'a, K: 'a, V: 'a>(Iter<'a, Node>); impl<'a, K: 'a, V: 'a> Iterator for TreeIter<'a, K, V> { type Item = &'a Element; fn next(&mut self) -> Option { self.0.next().map(|x| &x.element) } } impl<'a, K: 'a + Ord, V: 'a> IntoIterator for &'a IntervalTree { type Item = &'a Element; type IntoIter = TreeIter<'a, K, V>; fn into_iter(self) -> TreeIter<'a, K, V> { self.iter() } } /// An iterator that moves out of an interval tree. pub struct TreeIntoIter(IntoIter>); impl IntoIterator for IntervalTree { type Item = Element; type IntoIter = TreeIntoIter; fn into_iter(self) -> TreeIntoIter { TreeIntoIter(self.data.into_iter()) } } impl Iterator for TreeIntoIter { type Item = Element; fn next(&mut self) -> Option> { self.0.next().map(|x| x.element) } } impl IntervalTree { fn update_max(nodes: &mut [Node]) -> K { assert!(!nodes.is_empty()); let i = nodes.len() / 2; if nodes.len() > 1 { { let (left, rest) = nodes.split_at_mut(i); if !left.is_empty() { rest[0].max = cmp::max(rest[0].max.clone(), Self::update_max(left)); } } { let (rest, right) = nodes.split_at_mut(i + 1); if !right.is_empty() { rest[i].max = cmp::max(rest[i].max.clone(), Self::update_max(right)); } } } nodes[i].max.clone() } } impl IntervalTree { fn todo(&self) -> TodoVec { let mut todo = SmallVec::new(); if !self.data.is_empty() { todo.push((0, self.data.len())); } todo } /// Queries the interval tree for all elements overlapping a given interval. /// /// This runs in `O(log n + m)`. pub fn query(&self, range: Range) -> QueryIter { QueryIter { todo: self.todo(), tree: self, query: Query::Range(range), } } /// Queries the interval tree for all elements containing a given point. /// /// This runs in `O(log n + m)`. pub fn query_point(&self, point: K) -> QueryIter { QueryIter { todo: self.todo(), tree: self, query: Query::Point(point), } } /// Returns an iterator over all elements in the tree (in no particular order). pub fn iter(&self) -> TreeIter { TreeIter(self.data.iter()) } /// Returns an iterator over all elements in the tree, sorted by `Element.range.start`. /// /// This is currently identical to `IntervalTree::iter` because the internal structure /// is already sorted this way, but may not be in the future. pub fn iter_sorted(&self) -> impl Iterator> { TreeIter(self.data.iter()) } } #[derive(Clone)] enum Query { Point(K), Range(Range), } impl Query { fn point(&self) -> &K { match *self { Query::Point(ref k) => k, Query::Range(ref r) => &r.start, } } fn go_right(&self, start: &K) -> bool { match *self { Query::Point(ref k) => k >= start, Query::Range(ref r) => &r.end > start, } } fn intersect(&self, range: &Range) -> bool { match *self { Query::Point(ref k) => k < &range.end, Query::Range(ref r) => r.end > range.start && r.start < range.end, } } } type TodoVec = SmallVec<[(usize, usize); 16]>; /// Iterator for query results. pub struct QueryIter<'a, K: 'a, V: 'a> { tree: &'a IntervalTree, todo: TodoVec, query: Query, } impl<'a, K: Ord + Clone, V> Clone for QueryIter<'a, K, V> { fn clone(&self) -> Self { QueryIter { tree: self.tree, todo: self.todo.clone(), query: self.query.clone(), } } } impl<'a, K: Ord + Clone + Debug, V: Debug> Debug for QueryIter<'a, K, V> { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { let v: Vec<_> = (*self).clone().collect(); write!(fmt, "{:?}", v) } } impl<'a, K: Ord, V> Iterator for QueryIter<'a, K, V> { type Item = &'a Element; fn next(&mut self) -> Option<&'a Element> { while let Some((s, l)) = self.todo.pop() { let i = s + l/2; let node = &self.tree.data[i]; if self.query.point() < &node.max { // push left { let leftsz = i - s; if leftsz > 0 { self.todo.push((s, leftsz)); } } if self.query.go_right(&node.element.range.start) { // push right { let rightsz = l + s - i - 1; if rightsz > 0 { self.todo.push((i + 1, rightsz)); } } // finally, search this if self.query.intersect(&node.element.range) { return Some(&node.element); } } } } None } } #[cfg(test)] mod tests { use core::iter; use super::*; fn verify(tree: &IntervalTree, i: u32, expected: &[u32]) { let mut v1: Vec<_> = tree.query_point(i).map(|x| x.value).collect(); v1.sort(); let mut v2: Vec<_> = tree.query(i..(i+1)).map(|x| x.value).collect(); v2.sort(); assert_eq!(v1, expected); assert_eq!(v2, expected); } #[test] fn it_works() { let tree: IntervalTree = [ (0..3, 1), (1..4, 2), (2..5, 3), (3..6, 4), (4..7, 5), (5..8, 6), (4..5, 7), (2..7, 8), ].iter().cloned().collect(); verify(&tree, 0, &[1]); verify(&tree, 1, &[1, 2]); verify(&tree, 2, &[1, 2, 3, 8]); verify(&tree, 3, &[2, 3, 4, 8]); verify(&tree, 4, &[3, 4, 5, 7, 8]); verify(&tree, 5, &[4, 5, 6, 8]); verify(&tree, 6, &[5, 6, 8]); verify(&tree, 7, &[6]); verify(&tree, 8, &[]); verify(&tree, 9, &[]); } #[test] fn empty() { let tree: IntervalTree = iter::empty::>().collect(); verify(&tree, 42, &[]); } }