intervaltree-0.2.4/.gitignore010064400017500000144000000000421320144273200144200ustar0000000000000000/target/ **/*.rs.bk *~ Cargo.lock intervaltree-0.2.4/Cargo.toml.orig010064400017500000144000000007151333003454300153260ustar0000000000000000[package] name = "intervaltree" documentation = "https://docs.rs/intervaltree" repository = "https://github.com/main--/rust-intervaltree" version = "0.2.4" authors = ["main() "] license = "MIT" description = "A simple and generic implementation of an immutable interval tree." categories = ["data-structures", "no-std"] [dependencies] smallvec = { version = "0.6", default-features = false } [features] std = ["smallvec/std"] default = ["std"] intervaltree-0.2.4/Cargo.toml0000644000000017210000000000000116010ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "intervaltree" version = "0.2.4" 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.smallvec] version = "0.6" default-features = false [features] default = ["std"] std = ["smallvec/std"] intervaltree-0.2.4/LICENSE010064400017500000144000000020471333003453100134410ustar0000000000000000MIT 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.4/src/lib.rs010064400017500000144000000202621333003453100143360ustar0000000000000000#![no_std] #![cfg_attr(not(feature = "std"), feature(alloc))] #![warn(missing_docs)] //! A simple and generic implementation of an immutable interval tree. #[cfg(feature = "std")] extern crate std; #[cfg(not(feature = "std"))] extern crate alloc; extern crate smallvec; use core::ops::Range; use core::iter::FromIterator; use core::fmt::{Debug, Formatter, Result as FmtResult}; use core::slice::Iter; use core::cmp; #[cfg(feature = "std")] use std::vec::{Vec, IntoIter}; #[cfg(not(feature = "std"))] use alloc::vec::{Vec, IntoIter}; use smallvec::SmallVec; /// An element of an interval tree. #[derive(Debug, Clone, PartialEq, Eq, Hash)] 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)] 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)] 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()) } } #[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, &[]); } }