diff --git a/src/doc/reference.md b/src/doc/reference.md index 084309e9978f6d70a63550179a60abc77482a134..704311b37d97ec29dc97d66f91f5c94916895ef1 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -944,10 +944,10 @@ An example of `use` declarations: ``` use std::iter::range_step; use std::option::{Some, None}; -use std::collections::hashmap::{mod, HashMap}; +use std::collections::hash_map::{mod, HashMap}; -# fn foo(_: T){} -# fn bar(map: HashMap, set: hashmap::HashSet){} +fn foo(_: T){} +fn bar(map1: HashMap, map2: hash_map::HashMap){} fn main() { // Equivalent to 'std::iter::range_step(0u, 10u, 2u);' @@ -957,10 +957,10 @@ fn main() { // std::option::None]);' foo(vec![Some(1.0f64), None]); - // Both `hash` and `HashMap` are in scope. - let map = HashMap::new(); - let set = hashmap::HashSet::new(); - bar(map, set); + // Both `hash_map` and `HashMap` are in scope. + let map1 = HashMap::new(); + let map2 = hash_map::HashMap::new(); + bar(map1, map2); } ``` @@ -4096,7 +4096,7 @@ cause transitions between the states. The lifecycle states of a task are: * running * blocked -* panicked +* panicked * dead A task begins its lifecycle — once it has been spawned — in the diff --git a/src/libcollections/priority_queue.rs b/src/libcollections/binary_heap.rs similarity index 82% rename from src/libcollections/priority_queue.rs rename to src/libcollections/binary_heap.rs index 885b5c99c450108ba28173c70f7199bf05440840..8481111ae91a3cecdbf95801a482e23a3dccf05e 100644 --- a/src/libcollections/priority_queue.rs +++ b/src/libcollections/binary_heap.rs @@ -19,14 +19,14 @@ //! //! This is a larger example which implements [Dijkstra's algorithm][dijkstra] //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph]. -//! It showcases how to use the `PriorityQueue` with custom types. +//! It showcases how to use the `BinaryHeap` with custom types. //! //! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm //! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph //! //! ``` -//! use std::collections::PriorityQueue; +//! use std::collections::BinaryHeap; //! use std::uint; //! //! #[deriving(Eq, PartialEq)] @@ -68,7 +68,7 @@ //! // dist[node] = current shortest distance from `start` to `node` //! let mut dist = Vec::from_elem(adj_list.len(), uint::MAX); //! -//! let mut pq = PriorityQueue::new(); +//! let mut pq = BinaryHeap::new(); //! //! // We're at `start`, with a zero cost //! dist[start] = 0u; @@ -166,52 +166,52 @@ /// /// This will be a max-heap. #[deriving(Clone)] -pub struct PriorityQueue { +pub struct BinaryHeap { data: Vec, } -impl Default for PriorityQueue { +impl Default for BinaryHeap { #[inline] - fn default() -> PriorityQueue { PriorityQueue::new() } + fn default() -> BinaryHeap { BinaryHeap::new() } } -impl PriorityQueue { - /// Creates an empty `PriorityQueue` as a max-heap. +impl BinaryHeap { + /// Creates an empty `BinaryHeap` as a max-heap. /// /// # Example /// /// ``` - /// use std::collections::PriorityQueue; - /// let pq: PriorityQueue = PriorityQueue::new(); + /// use std::collections::BinaryHeap; + /// let pq: BinaryHeap = BinaryHeap::new(); /// ``` - pub fn new() -> PriorityQueue { PriorityQueue{data: vec!(),} } + pub fn new() -> BinaryHeap { BinaryHeap{data: vec!(),} } - /// Creates an empty `PriorityQueue` with a specific capacity. + /// Creates an empty `BinaryHeap` with a specific capacity. /// This preallocates enough memory for `capacity` elements, - /// so that the `PriorityQueue` does not have to be reallocated + /// so that the `BinaryHeap` does not have to be reallocated /// until it contains at least that many values. /// /// # Example /// /// ``` - /// use std::collections::PriorityQueue; - /// let pq: PriorityQueue = PriorityQueue::with_capacity(10u); + /// use std::collections::BinaryHeap; + /// let pq: BinaryHeap = BinaryHeap::with_capacity(10u); /// ``` - pub fn with_capacity(capacity: uint) -> PriorityQueue { - PriorityQueue { data: Vec::with_capacity(capacity) } + pub fn with_capacity(capacity: uint) -> BinaryHeap { + BinaryHeap { data: Vec::with_capacity(capacity) } } - /// Creates a `PriorityQueue` from a vector. This is sometimes called + /// Creates a `BinaryHeap` from a vector. This is sometimes called /// `heapifying` the vector. /// /// # Example /// /// ``` - /// use std::collections::PriorityQueue; - /// let pq = PriorityQueue::from_vec(vec![9i, 1, 2, 7, 3, 2]); + /// use std::collections::BinaryHeap; + /// let pq = BinaryHeap::from_vec(vec![9i, 1, 2, 7, 3, 2]); /// ``` - pub fn from_vec(xs: Vec) -> PriorityQueue { - let mut q = PriorityQueue{data: xs,}; + pub fn from_vec(xs: Vec) -> BinaryHeap { + let mut q = BinaryHeap{data: xs,}; let mut n = q.len() / 2; while n > 0 { n -= 1; @@ -226,8 +226,8 @@ pub fn from_vec(xs: Vec) -> PriorityQueue { /// # Example /// /// ``` - /// use std::collections::PriorityQueue; - /// let pq = PriorityQueue::from_vec(vec![1i, 2, 3, 4]); + /// use std::collections::BinaryHeap; + /// let pq = BinaryHeap::from_vec(vec![1i, 2, 3, 4]); /// /// // Print 1, 2, 3, 4 in arbitrary order /// for x in pq.iter() { @@ -243,9 +243,9 @@ pub fn iter<'a>(&'a self) -> Items<'a, T> { /// # Example /// /// ``` - /// use std::collections::PriorityQueue; + /// use std::collections::BinaryHeap; /// - /// let mut pq = PriorityQueue::new(); + /// let mut pq = BinaryHeap::new(); /// assert_eq!(pq.top(), None); /// /// pq.push(1i); @@ -263,36 +263,36 @@ pub fn top<'a>(&'a self) -> Option<&'a T> { /// # Example /// /// ``` - /// use std::collections::PriorityQueue; + /// use std::collections::BinaryHeap; /// - /// let pq: PriorityQueue = PriorityQueue::with_capacity(100u); + /// let pq: BinaryHeap = BinaryHeap::with_capacity(100u); /// assert!(pq.capacity() >= 100u); /// ``` pub fn capacity(&self) -> uint { self.data.capacity() } - /// Reserves capacity for exactly `n` elements in the `PriorityQueue`. + /// Reserves capacity for exactly `n` elements in the `BinaryHeap`. /// Do nothing if the capacity is already sufficient. /// /// # Example /// /// ``` - /// use std::collections::PriorityQueue; + /// use std::collections::BinaryHeap; /// - /// let mut pq: PriorityQueue = PriorityQueue::new(); + /// let mut pq: BinaryHeap = BinaryHeap::new(); /// pq.reserve_exact(100u); /// assert!(pq.capacity() == 100u); /// ``` pub fn reserve_exact(&mut self, n: uint) { self.data.reserve_exact(n) } - /// Reserves capacity for at least `n` elements in the `PriorityQueue`. + /// Reserves capacity for at least `n` elements in the `BinaryHeap`. /// Do nothing if the capacity is already sufficient. /// /// # Example /// /// ``` - /// use std::collections::PriorityQueue; + /// use std::collections::BinaryHeap; /// - /// let mut pq: PriorityQueue = PriorityQueue::new(); + /// let mut pq: BinaryHeap = BinaryHeap::new(); /// pq.reserve(100u); /// assert!(pq.capacity() >= 100u); /// ``` @@ -306,9 +306,9 @@ pub fn reserve(&mut self, n: uint) { /// # Example /// /// ``` - /// use std::collections::PriorityQueue; + /// use std::collections::BinaryHeap; /// - /// let mut pq = PriorityQueue::from_vec(vec![1i, 3]); + /// let mut pq = BinaryHeap::from_vec(vec![1i, 3]); /// /// assert_eq!(pq.pop(), Some(3i)); /// assert_eq!(pq.pop(), Some(1i)); @@ -332,9 +332,9 @@ pub fn pop(&mut self) -> Option { /// # Example /// /// ``` - /// use std::collections::PriorityQueue; + /// use std::collections::BinaryHeap; /// - /// let mut pq = PriorityQueue::new(); + /// let mut pq = BinaryHeap::new(); /// pq.push(3i); /// pq.push(5i); /// pq.push(1i); @@ -354,9 +354,9 @@ pub fn push(&mut self, item: T) { /// # Example /// /// ``` - /// use std::collections::PriorityQueue; + /// use std::collections::BinaryHeap; /// - /// let mut pq = PriorityQueue::new(); + /// let mut pq = BinaryHeap::new(); /// pq.push(1i); /// pq.push(5i); /// @@ -380,9 +380,9 @@ pub fn push_pop(&mut self, mut item: T) -> T { /// # Example /// /// ``` - /// use std::collections::PriorityQueue; + /// use std::collections::BinaryHeap; /// - /// let mut pq = PriorityQueue::new(); + /// let mut pq = BinaryHeap::new(); /// /// assert_eq!(pq.replace(1i), None); /// assert_eq!(pq.replace(3i), Some(1i)); @@ -400,15 +400,15 @@ pub fn replace(&mut self, mut item: T) -> Option { } } - /// Consumes the `PriorityQueue` and returns the underlying vector + /// Consumes the `BinaryHeap` and returns the underlying vector /// in arbitrary order. /// /// # Example /// /// ``` - /// use std::collections::PriorityQueue; + /// use std::collections::BinaryHeap; /// - /// let pq = PriorityQueue::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]); + /// let pq = BinaryHeap::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]); /// let vec = pq.into_vec(); /// /// // Will print in some order @@ -416,17 +416,17 @@ pub fn replace(&mut self, mut item: T) -> Option { /// println!("{}", x); /// } /// ``` - pub fn into_vec(self) -> Vec { let PriorityQueue{data: v} = self; v } + pub fn into_vec(self) -> Vec { let BinaryHeap{data: v} = self; v } - /// Consumes the `PriorityQueue` and returns a vector in sorted + /// Consumes the `BinaryHeap` and returns a vector in sorted /// (ascending) order. /// /// # Example /// /// ``` - /// use std::collections::PriorityQueue; + /// use std::collections::BinaryHeap; /// - /// let mut pq = PriorityQueue::from_vec(vec![1i, 2, 4, 5, 7]); + /// let mut pq = BinaryHeap::from_vec(vec![1i, 2, 4, 5, 7]); /// pq.push(6); /// pq.push(3); /// @@ -504,7 +504,7 @@ pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn clear(&mut self) { self.data.truncate(0) } } -/// `PriorityQueue` iterator. +/// `BinaryHeap` iterator. pub struct Items <'a, T:'a> { iter: slice::Items<'a, T>, } @@ -517,14 +517,14 @@ fn next(&mut self) -> Option<(&'a T)> { self.iter.next() } fn size_hint(&self) -> (uint, Option) { self.iter.size_hint() } } -impl FromIterator for PriorityQueue { - fn from_iter>(mut iter: Iter) -> PriorityQueue { +impl FromIterator for BinaryHeap { + fn from_iter>(mut iter: Iter) -> BinaryHeap { let vec: Vec = iter.collect(); - PriorityQueue::from_vec(vec) + BinaryHeap::from_vec(vec) } } -impl Extendable for PriorityQueue { +impl Extendable for BinaryHeap { fn extend>(&mut self, mut iter: Iter) { let (lower, _) = iter.size_hint(); @@ -541,14 +541,14 @@ fn extend>(&mut self, mut iter: Iter) { mod tests { use std::prelude::*; - use priority_queue::PriorityQueue; + use super::BinaryHeap; use vec::Vec; #[test] fn test_iterator() { let data = vec!(5i, 9, 3); let iterout = [9i, 5, 3]; - let pq = PriorityQueue::from_vec(data); + let pq = BinaryHeap::from_vec(data); let mut i = 0; for el in pq.iter() { assert_eq!(*el, iterout[i]); @@ -561,7 +561,7 @@ fn test_top_and_pop() { let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1); let mut sorted = data.clone(); sorted.sort(); - let mut heap = PriorityQueue::from_vec(data); + let mut heap = BinaryHeap::from_vec(data); while !heap.is_empty() { assert_eq!(heap.top().unwrap(), sorted.last().unwrap()); assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap()); @@ -570,7 +570,7 @@ fn test_top_and_pop() { #[test] fn test_push() { - let mut heap = PriorityQueue::from_vec(vec!(2i, 4, 9)); + let mut heap = BinaryHeap::from_vec(vec!(2i, 4, 9)); assert_eq!(heap.len(), 3); assert!(*heap.top().unwrap() == 9); heap.push(11); @@ -592,7 +592,7 @@ fn test_push() { #[test] fn test_push_unique() { - let mut heap = PriorityQueue::from_vec(vec!(box 2i, box 4, box 9)); + let mut heap = BinaryHeap::from_vec(vec!(box 2i, box 4, box 9)); assert_eq!(heap.len(), 3); assert!(*heap.top().unwrap() == box 9); heap.push(box 11); @@ -614,7 +614,7 @@ fn test_push_unique() { #[test] fn test_push_pop() { - let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3)); + let mut heap = BinaryHeap::from_vec(vec!(5i, 5, 2, 1, 3)); assert_eq!(heap.len(), 5); assert_eq!(heap.push_pop(6), 6); assert_eq!(heap.len(), 5); @@ -628,7 +628,7 @@ fn test_push_pop() { #[test] fn test_replace() { - let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3)); + let mut heap = BinaryHeap::from_vec(vec!(5i, 5, 2, 1, 3)); assert_eq!(heap.len(), 5); assert_eq!(heap.replace(6).unwrap(), 5); assert_eq!(heap.len(), 5); @@ -641,7 +641,7 @@ fn test_replace() { } fn check_to_vec(mut data: Vec) { - let heap = PriorityQueue::from_vec(data.clone()); + let heap = BinaryHeap::from_vec(data.clone()); let mut v = heap.clone().into_vec(); v.sort(); data.sort(); @@ -669,19 +669,19 @@ fn test_to_vec() { #[test] fn test_empty_pop() { - let mut heap: PriorityQueue = PriorityQueue::new(); + let mut heap: BinaryHeap = BinaryHeap::new(); assert!(heap.pop().is_none()); } #[test] fn test_empty_top() { - let empty: PriorityQueue = PriorityQueue::new(); + let empty: BinaryHeap = BinaryHeap::new(); assert!(empty.top().is_none()); } #[test] fn test_empty_replace() { - let mut heap: PriorityQueue = PriorityQueue::new(); + let mut heap: BinaryHeap = BinaryHeap::new(); heap.replace(5).is_none(); } @@ -689,7 +689,7 @@ fn test_empty_replace() { fn test_from_iter() { let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1); - let mut q: PriorityQueue = xs.as_slice().iter().rev().map(|&x| x).collect(); + let mut q: BinaryHeap = xs.as_slice().iter().rev().map(|&x| x).collect(); for &x in xs.iter() { assert_eq!(q.pop().unwrap(), x); diff --git a/src/libcollections/bitv.rs b/src/libcollections/bit.rs similarity index 99% rename from src/libcollections/bitv.rs rename to src/libcollections/bit.rs index 26e0c73724c6aa461f1128d4cf63d16bd093a610..b7085c96aed154f276abf9a1b7817b7d548c7621 100644 --- a/src/libcollections/bitv.rs +++ b/src/libcollections/bit.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +// FIXME(Gankro): Bitv and BitvSet are very tightly coupled. Ideally (for maintenance), +// they should be in separate files/modules, with BitvSet only using Bitv's public API. + //! Collections implemented with bit vectors. //! //! # Example @@ -1654,7 +1657,7 @@ mod tests { use std::rand::Rng; use test::Bencher; - use bitv::{Bitv, BitvSet, from_fn, from_bytes}; + use super::{Bitv, BitvSet, from_fn, from_bytes}; use bitv; use vec::Vec; diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index 4570d49ba0ace81482d402acb88ed10f282293f1..e3dfabfa29549d53499e678f7d5aaf133ef590e1 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -23,7 +23,7 @@ use core::{iter, fmt, mem}; use core::fmt::Show; -use ringbuf::RingBuf; +use ring_buf::RingBuf; /// A map based on a B-Tree. /// diff --git a/src/libcollections/btree/mod.rs b/src/libcollections/btree/mod.rs index 653de91c0ffd48a8bc6c6edbb15a320d446c96ac..282128099da0a3d2021140f43839bcbb17356fd4 100644 --- a/src/libcollections/btree/mod.rs +++ b/src/libcollections/btree/mod.rs @@ -8,27 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub use self::map::BTreeMap; -pub use self::map::Entries; -pub use self::map::MutEntries; -pub use self::map::MoveEntries; -pub use self::map::Keys; -pub use self::map::Values; -pub use self::map::Entry; -pub use self::map::Occupied; -pub use self::map::Vacant; -pub use self::map::OccupiedEntry; -pub use self::map::VacantEntry; - -pub use self::set::BTreeSet; -pub use self::set::Items; -pub use self::set::MoveItems; -pub use self::set::DifferenceItems; -pub use self::set::UnionItems; -pub use self::set::SymDifferenceItems; -pub use self::set::IntersectionItems; - - mod node; -mod map; -mod set; +pub mod map; +pub mod set; diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index eac74098758ae2b0f924dbac53e913543e1fe193..27752207b9797d93ce92e15498c6a93f40a128cb 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -13,7 +13,7 @@ use core::prelude::*; -use super::{BTreeMap, Keys, MoveEntries}; +use btree_map::{BTreeMap, Keys, MoveEntries}; use std::hash::Hash; use core::default::Default; use core::{iter, fmt}; diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index b78c1897b065939bccc66aa11b05fc3bbcf72198..bcae4fe68c9b87bd3ee514e72ed06fbbf71392b7 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -155,7 +155,7 @@ mod test { use std::prelude::*; use std::mem; - use enum_set::{EnumSet, CLike}; + use super::{EnumSet, CLike}; #[deriving(PartialEq, Show)] #[repr(uint)] diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index e28bc766480153d992f4b03ebd48ed96d9c81bfc..5ec8a85fb0fb771e227e5a8249859bb986aa5120 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -37,34 +37,72 @@ #[cfg(test)] #[phase(plugin, link)] extern crate std; #[cfg(test)] #[phase(plugin, link)] extern crate log; -pub use bitv::{Bitv, BitvSet}; -pub use btree::{BTreeMap, BTreeSet}; + +pub use binary_heap::BinaryHeap; +pub use bitv::Bitv; +pub use bitv_set::BitvSet; +pub use btree_map::BTreeMap; +pub use btree_set::BTreeSet; pub use dlist::DList; pub use enum_set::EnumSet; -pub use priority_queue::PriorityQueue; -pub use ringbuf::RingBuf; -pub use smallintmap::SmallIntMap; +pub use ring_buf::RingBuf; pub use string::String; -pub use treemap::{TreeMap, TreeSet}; -pub use trie::{TrieMap, TrieSet}; +pub use tree_map::TreeMap; +pub use tree_set::TreeSet; +pub use trie_map::TrieMap; +pub use trie_set::TrieSet; pub use vec::Vec; +pub use vec_map::VecMap; mod macros; -pub mod bitv; -pub mod btree; +pub mod binary_heap; +mod bit; +mod btree; pub mod dlist; pub mod enum_set; -pub mod priority_queue; -pub mod ringbuf; -pub mod smallintmap; -pub mod treemap; -pub mod trie; +pub mod ring_buf; +mod tree; +mod trie; pub mod slice; pub mod str; pub mod string; pub mod vec; pub mod hash; +pub mod vec_map; + +pub mod bitv { + pub use bit::{Bitv, Bits, from_fn, from_bytes}; +} + +pub mod bitv_set { + pub use bit::{BitvSet, BitPositions, TwoBitPositions}; +} + +pub mod tree_map { + pub use tree::map::*; +} + +pub mod tree_set { + pub use tree::set::*; +} + +pub mod trie_map { + pub use trie::map::*; +} + +pub mod trie_set { + pub use trie::set::*; +} + +pub mod btree_map { + pub use btree::map::*; +} + +pub mod btree_set { + pub use btree::set::*; +} + #[cfg(test)] mod bench; diff --git a/src/libcollections/ringbuf.rs b/src/libcollections/ring_buf.rs similarity index 100% rename from src/libcollections/ringbuf.rs rename to src/libcollections/ring_buf.rs diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index 297ba71d252d7cf1c99769a21da6639b20d004bd..2d6cf865878e3c40997f42fb9c451d6dc46898f1 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -65,7 +65,7 @@ use core::prelude::{range}; use hash; -use ringbuf::RingBuf; +use ring_buf::RingBuf; use string::String; use unicode; use vec::Vec; diff --git a/src/libcollections/treemap.rs b/src/libcollections/tree/map.rs similarity index 67% rename from src/libcollections/treemap.rs rename to src/libcollections/tree/map.rs index 7e6efcb3d1266485c205686786f227244e9a3f31..9742bddb1f6594f0c971dbe22c2d1049d5778d25 100644 --- a/src/libcollections/treemap.rs +++ b/src/libcollections/tree/map.rs @@ -8,37 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Maps are collections of unique keys with corresponding values, and sets are -//! just unique keys without a corresponding value. The `Map` and `Set` traits in -//! `std::container` define the basic interface. -//! -//! This crate defines the `TreeMap` and `TreeSet` types. Their keys must implement `Ord`. -//! -//! `TreeMap`s are ordered. -//! -//! ## Example -//! -//! ```{rust} -//! use std::collections::TreeSet; -//! -//! let mut tree_set = TreeSet::new(); -//! -//! tree_set.insert(2i); -//! tree_set.insert(1i); -//! tree_set.insert(3i); -//! -//! for i in tree_set.iter() { -//! println!("{}", i) // prints 1, then 2, then 3 -//! } -//! ``` - use core::prelude::*; use alloc::boxed::Box; use core::default::Default; use core::fmt; use core::fmt::Show; -use core::iter::Peekable; use core::iter; use core::mem::{replace, swap}; use core::ptr; @@ -378,7 +353,7 @@ pub fn rev_iter_mut<'a>(&'a mut self) -> RevMutEntries<'a, K, V> { RevMutEntries{iter: self.iter_mut()} } - /// Gets a lazy iterator that consumes the treemap. + /// Gets a lazy iterator that consumes the TreeMap. /// /// # Example /// @@ -592,7 +567,7 @@ impl TreeMap { /// # Example /// /// ``` - /// use collections::treemap::TreeMap; + /// use std::collections::TreeMap; /// /// fn get_headers() -> TreeMap { /// let mut result = TreeMap::new(); @@ -621,7 +596,9 @@ pub fn find_with<'a>(&'a self, f:|&K| -> Ordering) -> Option<&'a V> { /// # Example /// /// ``` - /// let mut t = collections::treemap::TreeMap::new(); + /// use std::collections::TreeMap; + /// + /// let mut t = TreeMap::new(); /// t.insert("Content-Type", "application/xml"); /// t.insert("User-Agent", "Curl-Rust/0.1"); /// @@ -1075,616 +1052,6 @@ fn size_hint(&self) -> (uint, Option) { } -impl<'a, T> Iterator<&'a T> for SetItems<'a, T> { - #[inline] - fn next(&mut self) -> Option<&'a T> { - self.iter.next().map(|(value, _)| value) - } -} - -impl<'a, T> Iterator<&'a T> for RevSetItems<'a, T> { - #[inline] - fn next(&mut self) -> Option<&'a T> { - self.iter.next().map(|(value, _)| value) - } -} - -/// An implementation of the `Set` trait on top of the `TreeMap` container. The -/// only requirement is that the type of the elements contained ascribes to the -/// `Ord` trait. -/// -/// ## Example -/// -/// ```{rust} -/// use std::collections::TreeSet; -/// -/// let mut set = TreeSet::new(); -/// -/// set.insert(2i); -/// set.insert(1i); -/// set.insert(3i); -/// -/// for i in set.iter() { -/// println!("{}", i) // prints 1, then 2, then 3 -/// } -/// -/// set.remove(&3); -/// -/// if !set.contains(&3) { -/// println!("set does not contain a 3 anymore"); -/// } -/// ``` -/// -/// The easiest way to use `TreeSet` with a custom type is to implement `Ord`. -/// We must also implement `PartialEq`, `Eq` and `PartialOrd`. -/// -/// ``` -/// use std::collections::TreeSet; -/// -/// // We need `Eq` and `PartialEq`, these can be derived. -/// #[deriving(Eq, PartialEq)] -/// struct Troll<'a> { -/// name: &'a str, -/// level: uint, -/// } -/// -/// // Implement `Ord` and sort trolls by level. -/// impl<'a> Ord for Troll<'a> { -/// fn cmp(&self, other: &Troll) -> Ordering { -/// // If we swap `self` and `other`, we get descending ordering. -/// self.level.cmp(&other.level) -/// } -/// } -/// -/// // `PartialOrd` needs to be implemented as well. -/// impl<'a> PartialOrd for Troll<'a> { -/// fn partial_cmp(&self, other: &Troll) -> Option { -/// Some(self.cmp(other)) -/// } -/// } -/// -/// let mut trolls = TreeSet::new(); -/// -/// trolls.insert(Troll { name: "Orgarr", level: 2 }); -/// trolls.insert(Troll { name: "Blargarr", level: 3 }); -/// trolls.insert(Troll { name: "Kron the Smelly One", level: 4 }); -/// trolls.insert(Troll { name: "Wartilda", level: 1 }); -/// -/// println!("You are facing {} trolls!", trolls.len()); -/// -/// // Print the trolls, ordered by level with smallest level first -/// for x in trolls.iter() { -/// println!("level {}: {}!", x.level, x.name); -/// } -/// -/// // Kill all trolls -/// trolls.clear(); -/// assert_eq!(trolls.len(), 0); -/// ``` -#[deriving(Clone)] -pub struct TreeSet { - map: TreeMap -} - -impl PartialEq for TreeSet { - #[inline] - fn eq(&self, other: &TreeSet) -> bool { self.map == other.map } -} - -impl Eq for TreeSet {} - -impl PartialOrd for TreeSet { - #[inline] - fn partial_cmp(&self, other: &TreeSet) -> Option { - self.map.partial_cmp(&other.map) - } -} - -impl Ord for TreeSet { - #[inline] - fn cmp(&self, other: &TreeSet) -> Ordering { - iter::order::cmp(self.iter(), other.iter()) - } -} - -impl Show for TreeSet { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{{")); - - for (i, x) in self.iter().enumerate() { - if i != 0 { try!(write!(f, ", ")); } - try!(write!(f, "{}", *x)); - } - - write!(f, "}}") - } -} - -impl Default for TreeSet { - #[inline] - fn default() -> TreeSet { TreeSet::new() } -} - -impl TreeSet { - /// Creates an empty `TreeSet`. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// let mut set: TreeSet = TreeSet::new(); - /// ``` - #[inline] - pub fn new() -> TreeSet { TreeSet{map: TreeMap::new()} } - - /// Gets a lazy iterator over the values in the set, in ascending order. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// let set: TreeSet = [1i, 4, 3, 5, 2].iter().map(|&x| x).collect(); - /// - /// // Will print in ascending order. - /// for x in set.iter() { - /// println!("{}", x); - /// } - /// ``` - #[inline] - pub fn iter<'a>(&'a self) -> SetItems<'a, T> { - SetItems{iter: self.map.iter()} - } - - /// Gets a lazy iterator over the values in the set, in descending order. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// let set: TreeSet = [1i, 4, 3, 5, 2].iter().map(|&x| x).collect(); - /// - /// // Will print in descending order. - /// for x in set.rev_iter() { - /// println!("{}", x); - /// } - /// ``` - #[inline] - pub fn rev_iter<'a>(&'a self) -> RevSetItems<'a, T> { - RevSetItems{iter: self.map.rev_iter()} - } - - /// Creates a consuming iterator, that is, one that moves each value out of the - /// set in ascending order. The set cannot be used after calling this. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// let set: TreeSet = [1i, 4, 3, 5, 2].iter().map(|&x| x).collect(); - /// - /// // Not possible with a regular `.iter()` - /// let v: Vec = set.into_iter().collect(); - /// assert_eq!(v, vec![1, 2, 3, 4, 5]); - /// ``` - #[inline] - pub fn into_iter(self) -> MoveSetItems { - self.map.into_iter().map(|(value, _)| value) - } - - /// Gets a lazy iterator pointing to the first value not less than `v` (greater or equal). - /// If all elements in the set are less than `v` empty iterator is returned. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// let set: TreeSet = [2, 4, 6, 8].iter().map(|&x| x).collect(); - /// - /// assert_eq!(set.lower_bound(&4).next(), Some(&4)); - /// assert_eq!(set.lower_bound(&5).next(), Some(&6)); - /// assert_eq!(set.lower_bound(&10).next(), None); - /// ``` - #[inline] - pub fn lower_bound<'a>(&'a self, v: &T) -> SetItems<'a, T> { - SetItems{iter: self.map.lower_bound(v)} - } - - /// Gets a lazy iterator pointing to the first value greater than `v`. - /// If all elements in the set are less than or equal to `v` an - /// empty iterator is returned. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// let set: TreeSet = [2, 4, 6, 8].iter().map(|&x| x).collect(); - /// - /// assert_eq!(set.upper_bound(&4).next(), Some(&6)); - /// assert_eq!(set.upper_bound(&5).next(), Some(&6)); - /// assert_eq!(set.upper_bound(&10).next(), None); - /// ``` - #[inline] - pub fn upper_bound<'a>(&'a self, v: &T) -> SetItems<'a, T> { - SetItems{iter: self.map.upper_bound(v)} - } - - /// Visits the values representing the difference, in ascending order. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let a: TreeSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// let b: TreeSet = [3, 4, 5].iter().map(|&x| x).collect(); - /// - /// // Can be seen as `a - b`. - /// for x in a.difference(&b) { - /// println!("{}", x); // Print 1 then 2 - /// } - /// - /// let diff: TreeSet = a.difference(&b).map(|&x| x).collect(); - /// assert_eq!(diff, [1, 2].iter().map(|&x| x).collect()); - /// - /// // Note that difference is not symmetric, - /// // and `b - a` means something else: - /// let diff: TreeSet = b.difference(&a).map(|&x| x).collect(); - /// assert_eq!(diff, [4, 5].iter().map(|&x| x).collect()); - /// ``` - pub fn difference<'a>(&'a self, other: &'a TreeSet) -> DifferenceItems<'a, T> { - DifferenceItems{a: self.iter().peekable(), b: other.iter().peekable()} - } - - /// Visits the values representing the symmetric difference, in ascending order. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let a: TreeSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// let b: TreeSet = [3, 4, 5].iter().map(|&x| x).collect(); - /// - /// // Print 1, 2, 4, 5 in ascending order. - /// for x in a.symmetric_difference(&b) { - /// println!("{}", x); - /// } - /// - /// let diff1: TreeSet = a.symmetric_difference(&b).map(|&x| x).collect(); - /// let diff2: TreeSet = b.symmetric_difference(&a).map(|&x| x).collect(); - /// - /// assert_eq!(diff1, diff2); - /// assert_eq!(diff1, [1, 2, 4, 5].iter().map(|&x| x).collect()); - /// ``` - pub fn symmetric_difference<'a>(&'a self, other: &'a TreeSet) - -> SymDifferenceItems<'a, T> { - SymDifferenceItems{a: self.iter().peekable(), b: other.iter().peekable()} - } - - /// Visits the values representing the intersection, in ascending order. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let a: TreeSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// let b: TreeSet = [2, 3, 4].iter().map(|&x| x).collect(); - /// - /// // Print 2, 3 in ascending order. - /// for x in a.intersection(&b) { - /// println!("{}", x); - /// } - /// - /// let diff: TreeSet = a.intersection(&b).map(|&x| x).collect(); - /// assert_eq!(diff, [2, 3].iter().map(|&x| x).collect()); - /// ``` - pub fn intersection<'a>(&'a self, other: &'a TreeSet) - -> IntersectionItems<'a, T> { - IntersectionItems{a: self.iter().peekable(), b: other.iter().peekable()} - } - - /// Visits the values representing the union, in ascending order. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let a: TreeSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// let b: TreeSet = [3, 4, 5].iter().map(|&x| x).collect(); - /// - /// // Print 1, 2, 3, 4, 5 in ascending order. - /// for x in a.union(&b) { - /// println!("{}", x); - /// } - /// - /// let diff: TreeSet = a.union(&b).map(|&x| x).collect(); - /// assert_eq!(diff, [1, 2, 3, 4, 5].iter().map(|&x| x).collect()); - /// ``` - pub fn union<'a>(&'a self, other: &'a TreeSet) -> UnionItems<'a, T> { - UnionItems{a: self.iter().peekable(), b: other.iter().peekable()} - } - - /// Return the number of elements in the set - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let mut v = TreeSet::new(); - /// assert_eq!(v.len(), 0); - /// v.insert(1i); - /// assert_eq!(v.len(), 1); - /// ``` - #[inline] - pub fn len(&self) -> uint { self.map.len() } - - /// Returns true if the set contains no elements - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let mut v = TreeSet::new(); - /// assert!(v.is_empty()); - /// v.insert(1i); - /// assert!(!v.is_empty()); - /// ``` - pub fn is_empty(&self) -> bool { self.len() == 0 } - - /// Clears the set, removing all values. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let mut v = TreeSet::new(); - /// v.insert(1i); - /// v.clear(); - /// assert!(v.is_empty()); - /// ``` - #[inline] - pub fn clear(&mut self) { self.map.clear() } - - /// Returns `true` if the set contains a value. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let set: TreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); - /// assert_eq!(set.contains(&1), true); - /// assert_eq!(set.contains(&4), false); - /// ``` - #[inline] - pub fn contains(&self, value: &T) -> bool { - self.map.contains_key(value) - } - - /// Returns `true` if the set has no elements in common with `other`. - /// This is equivalent to checking for an empty intersection. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let a: TreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); - /// let mut b: TreeSet = TreeSet::new(); - /// - /// assert_eq!(a.is_disjoint(&b), true); - /// b.insert(4); - /// assert_eq!(a.is_disjoint(&b), true); - /// b.insert(1); - /// assert_eq!(a.is_disjoint(&b), false); - /// ``` - pub fn is_disjoint(&self, other: &TreeSet) -> bool { - self.intersection(other).next().is_none() - } - - /// Returns `true` if the set is a subset of another. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let sup: TreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); - /// let mut set: TreeSet = TreeSet::new(); - /// - /// assert_eq!(set.is_subset(&sup), true); - /// set.insert(2); - /// assert_eq!(set.is_subset(&sup), true); - /// set.insert(4); - /// assert_eq!(set.is_subset(&sup), false); - /// ``` - pub fn is_subset(&self, other: &TreeSet) -> bool { - let mut x = self.iter(); - let mut y = other.iter(); - let mut a = x.next(); - let mut b = y.next(); - while a.is_some() { - if b.is_none() { - return false; - } - - let a1 = a.unwrap(); - let b1 = b.unwrap(); - - match b1.cmp(a1) { - Less => (), - Greater => return false, - Equal => a = x.next(), - } - - b = y.next(); - } - true - } - - /// Returns `true` if the set is a superset of another. - /// - /// # Example - /// - /// ``` - /// use std::collections::TreeSet; - /// - /// let sub: TreeSet = [1i, 2].iter().map(|&x| x).collect(); - /// let mut set: TreeSet = TreeSet::new(); - /// - /// assert_eq!(set.is_superset(&sub), false); - /// - /// set.insert(0); - /// set.insert(1); - /// assert_eq!(set.is_superset(&sub), false); - /// - /// set.insert(2); - /// assert_eq!(set.is_superset(&sub), true); - /// ``` - pub fn is_superset(&self, other: &TreeSet) -> bool { - other.is_subset(self) - } - - /// Adds a value to the set. Returns `true` if the value was not already - /// present in the set. - /// - /// # Example - /// - /// ``` - /// use std::collections::BTreeSet; - /// - /// let mut set = BTreeSet::new(); - /// - /// assert_eq!(set.insert(2i), true); - /// assert_eq!(set.insert(2i), false); - /// assert_eq!(set.len(), 1); - /// ``` - #[inline] - pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) } - - /// Removes a value from the set. Returns `true` if the value was - /// present in the set. - /// - /// # Example - /// - /// ``` - /// use std::collections::BTreeSet; - /// - /// let mut set = BTreeSet::new(); - /// - /// set.insert(2i); - /// assert_eq!(set.remove(&2), true); - /// assert_eq!(set.remove(&2), false); - /// ``` - #[inline] - pub fn remove(&mut self, value: &T) -> bool { self.map.remove(value) } -} - -/// A lazy forward iterator over a set. -pub struct SetItems<'a, T:'a> { - iter: Entries<'a, T, ()> -} - -/// A lazy backward iterator over a set. -pub struct RevSetItems<'a, T:'a> { - iter: RevEntries<'a, T, ()> -} - -/// A lazy forward iterator over a set that consumes the set while iterating. -pub type MoveSetItems = iter::Map<'static, (T, ()), T, MoveEntries>; - -/// A lazy iterator producing elements in the set difference (in-order). -pub struct DifferenceItems<'a, T:'a> { - a: Peekable<&'a T, SetItems<'a, T>>, - b: Peekable<&'a T, SetItems<'a, T>>, -} - -/// A lazy iterator producing elements in the set symmetric difference (in-order). -pub struct SymDifferenceItems<'a, T:'a> { - a: Peekable<&'a T, SetItems<'a, T>>, - b: Peekable<&'a T, SetItems<'a, T>>, -} - -/// A lazy iterator producing elements in the set intersection (in-order). -pub struct IntersectionItems<'a, T:'a> { - a: Peekable<&'a T, SetItems<'a, T>>, - b: Peekable<&'a T, SetItems<'a, T>>, -} - -/// A lazy iterator producing elements in the set union (in-order). -pub struct UnionItems<'a, T:'a> { - a: Peekable<&'a T, SetItems<'a, T>>, - b: Peekable<&'a T, SetItems<'a, T>>, -} - -/// Compare `x` and `y`, but return `short` if x is None and `long` if y is None -fn cmp_opt(x: Option<&T>, y: Option<&T>, - short: Ordering, long: Ordering) -> Ordering { - match (x, y) { - (None , _ ) => short, - (_ , None ) => long, - (Some(x1), Some(y1)) => x1.cmp(y1), - } -} - -impl<'a, T: Ord> Iterator<&'a T> for DifferenceItems<'a, T> { - fn next(&mut self) -> Option<&'a T> { - loop { - match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) { - Less => return self.a.next(), - Equal => { self.a.next(); self.b.next(); } - Greater => { self.b.next(); } - } - } - } -} - -impl<'a, T: Ord> Iterator<&'a T> for SymDifferenceItems<'a, T> { - fn next(&mut self) -> Option<&'a T> { - loop { - match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) { - Less => return self.a.next(), - Equal => { self.a.next(); self.b.next(); } - Greater => return self.b.next(), - } - } - } -} - -impl<'a, T: Ord> Iterator<&'a T> for IntersectionItems<'a, T> { - fn next(&mut self) -> Option<&'a T> { - loop { - let o_cmp = match (self.a.peek(), self.b.peek()) { - (None , _ ) => None, - (_ , None ) => None, - (Some(a1), Some(b1)) => Some(a1.cmp(b1)), - }; - match o_cmp { - None => return None, - Some(Less) => { self.a.next(); } - Some(Equal) => { self.b.next(); return self.a.next() } - Some(Greater) => { self.b.next(); } - } - } - } -} - -impl<'a, T: Ord> Iterator<&'a T> for UnionItems<'a, T> { - fn next(&mut self) -> Option<&'a T> { - loop { - match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) { - Less => return self.a.next(), - Equal => { self.b.next(); return self.a.next() } - Greater => return self.b.next(), - } - } - } -} // Nodes keep track of their level in the tree, starting at 1 in the @@ -1908,30 +1275,6 @@ fn hash(&self, state: &mut S) { } } -impl FromIterator for TreeSet { - fn from_iter>(iter: Iter) -> TreeSet { - let mut set = TreeSet::new(); - set.extend(iter); - set - } -} - -impl Extendable for TreeSet { - #[inline] - fn extend>(&mut self, mut iter: Iter) { - for elem in iter { - self.insert(elem); - } - } -} - -impl> Hash for TreeSet { - fn hash(&self, state: &mut S) { - for elt in self.iter() { - elt.hash(state); - } - } -} #[cfg(test)] mod test_treemap { @@ -2448,6 +1791,22 @@ fn test_index_nonexistent() { map[4]; } + + #[test] + fn test_swap() { + let mut m = TreeMap::new(); + assert_eq!(m.swap(1u, 2i), None); + assert_eq!(m.swap(1u, 3i), Some(2)); + assert_eq!(m.swap(1u, 4i), Some(3)); + } + + #[test] + fn test_pop() { + let mut m = TreeMap::new(); + m.insert(1u, 2i); + assert_eq!(m.pop(&1), Some(2)); + assert_eq!(m.pop(&1), None); + } } #[cfg(test)] @@ -2557,311 +1916,3 @@ pub fn iter_100000(b: &mut Bencher) { } } -#[cfg(test)] -mod test_set { - use std::prelude::*; - use std::hash; - - use super::{TreeMap, TreeSet}; - - #[test] - fn test_clear() { - let mut s = TreeSet::new(); - s.clear(); - assert!(s.insert(5i)); - assert!(s.insert(12)); - assert!(s.insert(19)); - s.clear(); - assert!(!s.contains(&5)); - assert!(!s.contains(&12)); - assert!(!s.contains(&19)); - assert!(s.is_empty()); - } - - #[test] - fn test_disjoint() { - let mut xs = TreeSet::new(); - let mut ys = TreeSet::new(); - assert!(xs.is_disjoint(&ys)); - assert!(ys.is_disjoint(&xs)); - assert!(xs.insert(5i)); - assert!(ys.insert(11i)); - assert!(xs.is_disjoint(&ys)); - assert!(ys.is_disjoint(&xs)); - assert!(xs.insert(7)); - assert!(xs.insert(19)); - assert!(xs.insert(4)); - assert!(ys.insert(2)); - assert!(ys.insert(-11)); - assert!(xs.is_disjoint(&ys)); - assert!(ys.is_disjoint(&xs)); - assert!(ys.insert(7)); - assert!(!xs.is_disjoint(&ys)); - assert!(!ys.is_disjoint(&xs)); - } - - #[test] - fn test_subset_and_superset() { - let mut a = TreeSet::new(); - assert!(a.insert(0i)); - assert!(a.insert(5)); - assert!(a.insert(11)); - assert!(a.insert(7)); - - let mut b = TreeSet::new(); - assert!(b.insert(0i)); - assert!(b.insert(7)); - assert!(b.insert(19)); - assert!(b.insert(250)); - assert!(b.insert(11)); - assert!(b.insert(200)); - - assert!(!a.is_subset(&b)); - assert!(!a.is_superset(&b)); - assert!(!b.is_subset(&a)); - assert!(!b.is_superset(&a)); - - assert!(b.insert(5)); - - assert!(a.is_subset(&b)); - assert!(!a.is_superset(&b)); - assert!(!b.is_subset(&a)); - assert!(b.is_superset(&a)); - } - - #[test] - fn test_iterator() { - let mut m = TreeSet::new(); - - assert!(m.insert(3i)); - assert!(m.insert(0)); - assert!(m.insert(4)); - assert!(m.insert(2)); - assert!(m.insert(1)); - - let mut n = 0; - for x in m.iter() { - assert_eq!(*x, n); - n += 1 - } - } - - #[test] - fn test_rev_iter() { - let mut m = TreeSet::new(); - - assert!(m.insert(3i)); - assert!(m.insert(0)); - assert!(m.insert(4)); - assert!(m.insert(2)); - assert!(m.insert(1)); - - let mut n = 4; - for x in m.rev_iter() { - assert_eq!(*x, n); - n -= 1; - } - } - - #[test] - fn test_move_iter() { - let s: TreeSet = range(0i, 5).collect(); - - let mut n = 0; - for x in s.into_iter() { - assert_eq!(x, n); - n += 1; - } - } - - #[test] - fn test_move_iter_size_hint() { - let s: TreeSet = vec!(0i, 1).into_iter().collect(); - - let mut it = s.into_iter(); - - assert_eq!(it.size_hint(), (2, Some(2))); - assert!(it.next() != None); - - assert_eq!(it.size_hint(), (1, Some(1))); - assert!(it.next() != None); - - assert_eq!(it.size_hint(), (0, Some(0))); - assert_eq!(it.next(), None); - } - - #[test] - fn test_clone_eq() { - let mut m = TreeSet::new(); - - m.insert(1i); - m.insert(2); - - assert!(m.clone() == m); - } - - #[test] - fn test_hash() { - let mut x = TreeSet::new(); - let mut y = TreeSet::new(); - - x.insert(1i); - x.insert(2); - x.insert(3); - - y.insert(3i); - y.insert(2); - y.insert(1); - - assert!(hash::hash(&x) == hash::hash(&y)); - } - - fn check(a: &[int], - b: &[int], - expected: &[int], - f: |&TreeSet, &TreeSet, f: |&int| -> bool| -> bool) { - let mut set_a = TreeSet::new(); - let mut set_b = TreeSet::new(); - - for x in a.iter() { assert!(set_a.insert(*x)) } - for y in b.iter() { assert!(set_b.insert(*y)) } - - let mut i = 0; - f(&set_a, &set_b, |x| { - assert_eq!(*x, expected[i]); - i += 1; - true - }); - assert_eq!(i, expected.len()); - } - - #[test] - fn test_intersection() { - fn check_intersection(a: &[int], b: &[int], expected: &[int]) { - check(a, b, expected, |x, y, f| x.intersection(y).all(f)) - } - - check_intersection([], [], []); - check_intersection([1, 2, 3], [], []); - check_intersection([], [1, 2, 3], []); - check_intersection([2], [1, 2, 3], [2]); - check_intersection([1, 2, 3], [2], [2]); - check_intersection([11, 1, 3, 77, 103, 5, -5], - [2, 11, 77, -9, -42, 5, 3], - [3, 5, 11, 77]); - } - - #[test] - fn test_difference() { - fn check_difference(a: &[int], b: &[int], expected: &[int]) { - check(a, b, expected, |x, y, f| x.difference(y).all(f)) - } - - check_difference([], [], []); - check_difference([1, 12], [], [1, 12]); - check_difference([], [1, 2, 3, 9], []); - check_difference([1, 3, 5, 9, 11], - [3, 9], - [1, 5, 11]); - check_difference([-5, 11, 22, 33, 40, 42], - [-12, -5, 14, 23, 34, 38, 39, 50], - [11, 22, 33, 40, 42]); - } - - #[test] - fn test_symmetric_difference() { - fn check_symmetric_difference(a: &[int], b: &[int], - expected: &[int]) { - check(a, b, expected, |x, y, f| x.symmetric_difference(y).all(f)) - } - - check_symmetric_difference([], [], []); - check_symmetric_difference([1, 2, 3], [2], [1, 3]); - check_symmetric_difference([2], [1, 2, 3], [1, 3]); - check_symmetric_difference([1, 3, 5, 9, 11], - [-2, 3, 9, 14, 22], - [-2, 1, 5, 11, 14, 22]); - } - - #[test] - fn test_union() { - fn check_union(a: &[int], b: &[int], - expected: &[int]) { - check(a, b, expected, |x, y, f| x.union(y).all(f)) - } - - check_union([], [], []); - check_union([1, 2, 3], [2], [1, 2, 3]); - check_union([2], [1, 2, 3], [1, 2, 3]); - check_union([1, 3, 5, 9, 11, 16, 19, 24], - [-2, 1, 5, 9, 13, 19], - [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24]); - } - - #[test] - fn test_zip() { - let mut x = TreeSet::new(); - x.insert(5u); - x.insert(12u); - x.insert(11u); - - let mut y = TreeSet::new(); - y.insert("foo"); - y.insert("bar"); - - let x = x; - let y = y; - let mut z = x.iter().zip(y.iter()); - - // FIXME: #5801: this needs a type hint to compile... - let result: Option<(&uint, & &'static str)> = z.next(); - assert_eq!(result.unwrap(), (&5u, &("bar"))); - - let result: Option<(&uint, & &'static str)> = z.next(); - assert_eq!(result.unwrap(), (&11u, &("foo"))); - - let result: Option<(&uint, & &'static str)> = z.next(); - assert!(result.is_none()); - } - - #[test] - fn test_swap() { - let mut m = TreeMap::new(); - assert_eq!(m.swap(1u, 2i), None); - assert_eq!(m.swap(1u, 3i), Some(2)); - assert_eq!(m.swap(1u, 4i), Some(3)); - } - - #[test] - fn test_pop() { - let mut m = TreeMap::new(); - m.insert(1u, 2i); - assert_eq!(m.pop(&1), Some(2)); - assert_eq!(m.pop(&1), None); - } - - #[test] - fn test_from_iter() { - let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9]; - - let set: TreeSet = xs.iter().map(|&x| x).collect(); - - for x in xs.iter() { - assert!(set.contains(x)); - } - } - - #[test] - fn test_show() { - let mut set: TreeSet = TreeSet::new(); - let empty: TreeSet = TreeSet::new(); - - set.insert(1); - set.insert(2); - - let set_str = format!("{}", set); - - assert!(set_str == "{1, 2}".to_string()); - assert_eq!(format!("{}", empty), "{}".to_string()); - } -} diff --git a/src/libcollections/tree/mod.rs b/src/libcollections/tree/mod.rs new file mode 100644 index 0000000000000000000000000000000000000000..ac8279c92feeb8f3f73cef427ff69b2eba3a17e3 --- /dev/null +++ b/src/libcollections/tree/mod.rs @@ -0,0 +1,36 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Maps are collections of unique keys with corresponding values, and sets are +//! just unique keys without a corresponding value. The `Map` and `Set` traits in +//! `std::container` define the basic interface. +//! +//! This crate defines the `TreeMap` and `TreeSet` types. Their keys must implement `Ord`. +//! +//! `TreeMap`s are ordered. +//! +//! ## Example +//! +//! ```{rust} +//! use std::collections::TreeSet; +//! +//! let mut tree_set = TreeSet::new(); +//! +//! tree_set.insert(2i); +//! tree_set.insert(1i); +//! tree_set.insert(3i); +//! +//! for i in tree_set.iter() { +//! println!("{}", i) // prints 1, then 2, then 3 +//! } +//! ``` + +pub mod map; +pub mod set; \ No newline at end of file diff --git a/src/libcollections/tree/set.rs b/src/libcollections/tree/set.rs new file mode 100644 index 0000000000000000000000000000000000000000..d24a8234b20b8d3a53b76dd28237cf7e557fc418 --- /dev/null +++ b/src/libcollections/tree/set.rs @@ -0,0 +1,950 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::prelude::*; + +use core::default::Default; +use core::fmt; +use core::fmt::Show; +use core::iter::Peekable; +use core::iter; +use std::hash::{Writer, Hash}; + +use tree_map::{TreeMap, Entries, RevEntries, MoveEntries}; + +/// An implementation of the `Set` trait on top of the `TreeMap` container. The +/// only requirement is that the type of the elements contained ascribes to the +/// `Ord` trait. +/// +/// ## Example +/// +/// ```{rust} +/// use std::collections::TreeSet; +/// +/// let mut set = TreeSet::new(); +/// +/// set.insert(2i); +/// set.insert(1i); +/// set.insert(3i); +/// +/// for i in set.iter() { +/// println!("{}", i) // prints 1, then 2, then 3 +/// } +/// +/// set.remove(&3); +/// +/// if !set.contains(&3) { +/// println!("set does not contain a 3 anymore"); +/// } +/// ``` +/// +/// The easiest way to use `TreeSet` with a custom type is to implement `Ord`. +/// We must also implement `PartialEq`, `Eq` and `PartialOrd`. +/// +/// ``` +/// use std::collections::TreeSet; +/// +/// // We need `Eq` and `PartialEq`, these can be derived. +/// #[deriving(Eq, PartialEq)] +/// struct Troll<'a> { +/// name: &'a str, +/// level: uint, +/// } +/// +/// // Implement `Ord` and sort trolls by level. +/// impl<'a> Ord for Troll<'a> { +/// fn cmp(&self, other: &Troll) -> Ordering { +/// // If we swap `self` and `other`, we get descending ordering. +/// self.level.cmp(&other.level) +/// } +/// } +/// +/// // `PartialOrd` needs to be implemented as well. +/// impl<'a> PartialOrd for Troll<'a> { +/// fn partial_cmp(&self, other: &Troll) -> Option { +/// Some(self.cmp(other)) +/// } +/// } +/// +/// let mut trolls = TreeSet::new(); +/// +/// trolls.insert(Troll { name: "Orgarr", level: 2 }); +/// trolls.insert(Troll { name: "Blargarr", level: 3 }); +/// trolls.insert(Troll { name: "Kron the Smelly One", level: 4 }); +/// trolls.insert(Troll { name: "Wartilda", level: 1 }); +/// +/// println!("You are facing {} trolls!", trolls.len()); +/// +/// // Print the trolls, ordered by level with smallest level first +/// for x in trolls.iter() { +/// println!("level {}: {}!", x.level, x.name); +/// } +/// +/// // Kill all trolls +/// trolls.clear(); +/// assert_eq!(trolls.len(), 0); +/// ``` +#[deriving(Clone)] +pub struct TreeSet { + map: TreeMap +} + +impl PartialEq for TreeSet { + #[inline] + fn eq(&self, other: &TreeSet) -> bool { self.map == other.map } +} + +impl Eq for TreeSet {} + +impl PartialOrd for TreeSet { + #[inline] + fn partial_cmp(&self, other: &TreeSet) -> Option { + self.map.partial_cmp(&other.map) + } +} + +impl Ord for TreeSet { + #[inline] + fn cmp(&self, other: &TreeSet) -> Ordering { + iter::order::cmp(self.iter(), other.iter()) + } +} + +impl Show for TreeSet { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "{{")); + + for (i, x) in self.iter().enumerate() { + if i != 0 { try!(write!(f, ", ")); } + try!(write!(f, "{}", *x)); + } + + write!(f, "}}") + } +} + +impl Default for TreeSet { + #[inline] + fn default() -> TreeSet { TreeSet::new() } +} + +impl TreeSet { + /// Creates an empty `TreeSet`. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// let mut set: TreeSet = TreeSet::new(); + /// ``` + #[inline] + pub fn new() -> TreeSet { TreeSet{map: TreeMap::new()} } + + /// Gets a lazy iterator over the values in the set, in ascending order. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// let set: TreeSet = [1i, 4, 3, 5, 2].iter().map(|&x| x).collect(); + /// + /// // Will print in ascending order. + /// for x in set.iter() { + /// println!("{}", x); + /// } + /// ``` + #[inline] + pub fn iter<'a>(&'a self) -> SetItems<'a, T> { + SetItems{iter: self.map.iter()} + } + + /// Gets a lazy iterator over the values in the set, in descending order. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// let set: TreeSet = [1i, 4, 3, 5, 2].iter().map(|&x| x).collect(); + /// + /// // Will print in descending order. + /// for x in set.rev_iter() { + /// println!("{}", x); + /// } + /// ``` + #[inline] + pub fn rev_iter<'a>(&'a self) -> RevSetItems<'a, T> { + RevSetItems{iter: self.map.rev_iter()} + } + + /// Creates a consuming iterator, that is, one that moves each value out of the + /// set in ascending order. The set cannot be used after calling this. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// let set: TreeSet = [1i, 4, 3, 5, 2].iter().map(|&x| x).collect(); + /// + /// // Not possible with a regular `.iter()` + /// let v: Vec = set.into_iter().collect(); + /// assert_eq!(v, vec![1, 2, 3, 4, 5]); + /// ``` + #[inline] + pub fn into_iter(self) -> MoveSetItems { + self.map.into_iter().map(|(value, _)| value) + } + + /// Gets a lazy iterator pointing to the first value not less than `v` (greater or equal). + /// If all elements in the set are less than `v` empty iterator is returned. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// let set: TreeSet = [2, 4, 6, 8].iter().map(|&x| x).collect(); + /// + /// assert_eq!(set.lower_bound(&4).next(), Some(&4)); + /// assert_eq!(set.lower_bound(&5).next(), Some(&6)); + /// assert_eq!(set.lower_bound(&10).next(), None); + /// ``` + #[inline] + pub fn lower_bound<'a>(&'a self, v: &T) -> SetItems<'a, T> { + SetItems{iter: self.map.lower_bound(v)} + } + + /// Gets a lazy iterator pointing to the first value greater than `v`. + /// If all elements in the set are less than or equal to `v` an + /// empty iterator is returned. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// let set: TreeSet = [2, 4, 6, 8].iter().map(|&x| x).collect(); + /// + /// assert_eq!(set.upper_bound(&4).next(), Some(&6)); + /// assert_eq!(set.upper_bound(&5).next(), Some(&6)); + /// assert_eq!(set.upper_bound(&10).next(), None); + /// ``` + #[inline] + pub fn upper_bound<'a>(&'a self, v: &T) -> SetItems<'a, T> { + SetItems{iter: self.map.upper_bound(v)} + } + + /// Visits the values representing the difference, in ascending order. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let a: TreeSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let b: TreeSet = [3, 4, 5].iter().map(|&x| x).collect(); + /// + /// // Can be seen as `a - b`. + /// for x in a.difference(&b) { + /// println!("{}", x); // Print 1 then 2 + /// } + /// + /// let diff: TreeSet = a.difference(&b).map(|&x| x).collect(); + /// assert_eq!(diff, [1, 2].iter().map(|&x| x).collect()); + /// + /// // Note that difference is not symmetric, + /// // and `b - a` means something else: + /// let diff: TreeSet = b.difference(&a).map(|&x| x).collect(); + /// assert_eq!(diff, [4, 5].iter().map(|&x| x).collect()); + /// ``` + pub fn difference<'a>(&'a self, other: &'a TreeSet) -> DifferenceItems<'a, T> { + DifferenceItems{a: self.iter().peekable(), b: other.iter().peekable()} + } + + /// Visits the values representing the symmetric difference, in ascending order. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let a: TreeSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let b: TreeSet = [3, 4, 5].iter().map(|&x| x).collect(); + /// + /// // Print 1, 2, 4, 5 in ascending order. + /// for x in a.symmetric_difference(&b) { + /// println!("{}", x); + /// } + /// + /// let diff1: TreeSet = a.symmetric_difference(&b).map(|&x| x).collect(); + /// let diff2: TreeSet = b.symmetric_difference(&a).map(|&x| x).collect(); + /// + /// assert_eq!(diff1, diff2); + /// assert_eq!(diff1, [1, 2, 4, 5].iter().map(|&x| x).collect()); + /// ``` + pub fn symmetric_difference<'a>(&'a self, other: &'a TreeSet) + -> SymDifferenceItems<'a, T> { + SymDifferenceItems{a: self.iter().peekable(), b: other.iter().peekable()} + } + + /// Visits the values representing the intersection, in ascending order. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let a: TreeSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let b: TreeSet = [2, 3, 4].iter().map(|&x| x).collect(); + /// + /// // Print 2, 3 in ascending order. + /// for x in a.intersection(&b) { + /// println!("{}", x); + /// } + /// + /// let diff: TreeSet = a.intersection(&b).map(|&x| x).collect(); + /// assert_eq!(diff, [2, 3].iter().map(|&x| x).collect()); + /// ``` + pub fn intersection<'a>(&'a self, other: &'a TreeSet) + -> IntersectionItems<'a, T> { + IntersectionItems{a: self.iter().peekable(), b: other.iter().peekable()} + } + + /// Visits the values representing the union, in ascending order. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let a: TreeSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let b: TreeSet = [3, 4, 5].iter().map(|&x| x).collect(); + /// + /// // Print 1, 2, 3, 4, 5 in ascending order. + /// for x in a.union(&b) { + /// println!("{}", x); + /// } + /// + /// let diff: TreeSet = a.union(&b).map(|&x| x).collect(); + /// assert_eq!(diff, [1, 2, 3, 4, 5].iter().map(|&x| x).collect()); + /// ``` + pub fn union<'a>(&'a self, other: &'a TreeSet) -> UnionItems<'a, T> { + UnionItems{a: self.iter().peekable(), b: other.iter().peekable()} + } + + /// Return the number of elements in the set + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let mut v = TreeSet::new(); + /// assert_eq!(v.len(), 0); + /// v.insert(1i); + /// assert_eq!(v.len(), 1); + /// ``` + #[inline] + pub fn len(&self) -> uint { self.map.len() } + + /// Returns true if the set contains no elements + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let mut v = TreeSet::new(); + /// assert!(v.is_empty()); + /// v.insert(1i); + /// assert!(!v.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { self.len() == 0 } + + /// Clears the set, removing all values. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let mut v = TreeSet::new(); + /// v.insert(1i); + /// v.clear(); + /// assert!(v.is_empty()); + /// ``` + #[inline] + pub fn clear(&mut self) { self.map.clear() } + + /// Returns `true` if the set contains a value. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let set: TreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); + /// assert_eq!(set.contains(&1), true); + /// assert_eq!(set.contains(&4), false); + /// ``` + #[inline] + pub fn contains(&self, value: &T) -> bool { + self.map.contains_key(value) + } + + /// Returns `true` if the set has no elements in common with `other`. + /// This is equivalent to checking for an empty intersection. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let a: TreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); + /// let mut b: TreeSet = TreeSet::new(); + /// + /// assert_eq!(a.is_disjoint(&b), true); + /// b.insert(4); + /// assert_eq!(a.is_disjoint(&b), true); + /// b.insert(1); + /// assert_eq!(a.is_disjoint(&b), false); + /// ``` + pub fn is_disjoint(&self, other: &TreeSet) -> bool { + self.intersection(other).next().is_none() + } + + /// Returns `true` if the set is a subset of another. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let sup: TreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); + /// let mut set: TreeSet = TreeSet::new(); + /// + /// assert_eq!(set.is_subset(&sup), true); + /// set.insert(2); + /// assert_eq!(set.is_subset(&sup), true); + /// set.insert(4); + /// assert_eq!(set.is_subset(&sup), false); + /// ``` + pub fn is_subset(&self, other: &TreeSet) -> bool { + let mut x = self.iter(); + let mut y = other.iter(); + let mut a = x.next(); + let mut b = y.next(); + while a.is_some() { + if b.is_none() { + return false; + } + + let a1 = a.unwrap(); + let b1 = b.unwrap(); + + match b1.cmp(a1) { + Less => (), + Greater => return false, + Equal => a = x.next(), + } + + b = y.next(); + } + true + } + + /// Returns `true` if the set is a superset of another. + /// + /// # Example + /// + /// ``` + /// use std::collections::TreeSet; + /// + /// let sub: TreeSet = [1i, 2].iter().map(|&x| x).collect(); + /// let mut set: TreeSet = TreeSet::new(); + /// + /// assert_eq!(set.is_superset(&sub), false); + /// + /// set.insert(0); + /// set.insert(1); + /// assert_eq!(set.is_superset(&sub), false); + /// + /// set.insert(2); + /// assert_eq!(set.is_superset(&sub), true); + /// ``` + pub fn is_superset(&self, other: &TreeSet) -> bool { + other.is_subset(self) + } + + /// Adds a value to the set. Returns `true` if the value was not already + /// present in the set. + /// + /// # Example + /// + /// ``` + /// use std::collections::BTreeSet; + /// + /// let mut set = BTreeSet::new(); + /// + /// assert_eq!(set.insert(2i), true); + /// assert_eq!(set.insert(2i), false); + /// assert_eq!(set.len(), 1); + /// ``` + #[inline] + pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) } + + /// Removes a value from the set. Returns `true` if the value was + /// present in the set. + /// + /// # Example + /// + /// ``` + /// use std::collections::BTreeSet; + /// + /// let mut set = BTreeSet::new(); + /// + /// set.insert(2i); + /// assert_eq!(set.remove(&2), true); + /// assert_eq!(set.remove(&2), false); + /// ``` + #[inline] + pub fn remove(&mut self, value: &T) -> bool { self.map.remove(value) } +} + +/// A lazy forward iterator over a set. +pub struct SetItems<'a, T:'a> { + iter: Entries<'a, T, ()> +} + +/// A lazy backward iterator over a set. +pub struct RevSetItems<'a, T:'a> { + iter: RevEntries<'a, T, ()> +} + +/// A lazy forward iterator over a set that consumes the set while iterating. +pub type MoveSetItems = iter::Map<'static, (T, ()), T, MoveEntries>; + +/// A lazy iterator producing elements in the set difference (in-order). +pub struct DifferenceItems<'a, T:'a> { + a: Peekable<&'a T, SetItems<'a, T>>, + b: Peekable<&'a T, SetItems<'a, T>>, +} + +/// A lazy iterator producing elements in the set symmetric difference (in-order). +pub struct SymDifferenceItems<'a, T:'a> { + a: Peekable<&'a T, SetItems<'a, T>>, + b: Peekable<&'a T, SetItems<'a, T>>, +} + +/// A lazy iterator producing elements in the set intersection (in-order). +pub struct IntersectionItems<'a, T:'a> { + a: Peekable<&'a T, SetItems<'a, T>>, + b: Peekable<&'a T, SetItems<'a, T>>, +} + +/// A lazy iterator producing elements in the set union (in-order). +pub struct UnionItems<'a, T:'a> { + a: Peekable<&'a T, SetItems<'a, T>>, + b: Peekable<&'a T, SetItems<'a, T>>, +} + +/// Compare `x` and `y`, but return `short` if x is None and `long` if y is None +fn cmp_opt(x: Option<&T>, y: Option<&T>, + short: Ordering, long: Ordering) -> Ordering { + match (x, y) { + (None , _ ) => short, + (_ , None ) => long, + (Some(x1), Some(y1)) => x1.cmp(y1), + } +} + + +impl<'a, T> Iterator<&'a T> for SetItems<'a, T> { + #[inline] + fn next(&mut self) -> Option<&'a T> { + self.iter.next().map(|(value, _)| value) + } +} + +impl<'a, T> Iterator<&'a T> for RevSetItems<'a, T> { + #[inline] + fn next(&mut self) -> Option<&'a T> { + self.iter.next().map(|(value, _)| value) + } +} + +impl<'a, T: Ord> Iterator<&'a T> for DifferenceItems<'a, T> { + fn next(&mut self) -> Option<&'a T> { + loop { + match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) { + Less => return self.a.next(), + Equal => { self.a.next(); self.b.next(); } + Greater => { self.b.next(); } + } + } + } +} + +impl<'a, T: Ord> Iterator<&'a T> for SymDifferenceItems<'a, T> { + fn next(&mut self) -> Option<&'a T> { + loop { + match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) { + Less => return self.a.next(), + Equal => { self.a.next(); self.b.next(); } + Greater => return self.b.next(), + } + } + } +} + +impl<'a, T: Ord> Iterator<&'a T> for IntersectionItems<'a, T> { + fn next(&mut self) -> Option<&'a T> { + loop { + let o_cmp = match (self.a.peek(), self.b.peek()) { + (None , _ ) => None, + (_ , None ) => None, + (Some(a1), Some(b1)) => Some(a1.cmp(b1)), + }; + match o_cmp { + None => return None, + Some(Less) => { self.a.next(); } + Some(Equal) => { self.b.next(); return self.a.next() } + Some(Greater) => { self.b.next(); } + } + } + } +} + +impl<'a, T: Ord> Iterator<&'a T> for UnionItems<'a, T> { + fn next(&mut self) -> Option<&'a T> { + loop { + match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) { + Less => return self.a.next(), + Equal => { self.b.next(); return self.a.next() } + Greater => return self.b.next(), + } + } + } +} + +impl FromIterator for TreeSet { + fn from_iter>(iter: Iter) -> TreeSet { + let mut set = TreeSet::new(); + set.extend(iter); + set + } +} + +impl Extendable for TreeSet { + #[inline] + fn extend>(&mut self, mut iter: Iter) { + for elem in iter { + self.insert(elem); + } + } +} + +impl> Hash for TreeSet { + fn hash(&self, state: &mut S) { + for elt in self.iter() { + elt.hash(state); + } + } +} + +#[cfg(test)] +mod test { + use std::prelude::*; + use std::hash; + + use super::TreeSet; + + #[test] + fn test_clear() { + let mut s = TreeSet::new(); + s.clear(); + assert!(s.insert(5i)); + assert!(s.insert(12)); + assert!(s.insert(19)); + s.clear(); + assert!(!s.contains(&5)); + assert!(!s.contains(&12)); + assert!(!s.contains(&19)); + assert!(s.is_empty()); + } + + #[test] + fn test_disjoint() { + let mut xs = TreeSet::new(); + let mut ys = TreeSet::new(); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(xs.insert(5i)); + assert!(ys.insert(11i)); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(xs.insert(7)); + assert!(xs.insert(19)); + assert!(xs.insert(4)); + assert!(ys.insert(2)); + assert!(ys.insert(-11)); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(ys.insert(7)); + assert!(!xs.is_disjoint(&ys)); + assert!(!ys.is_disjoint(&xs)); + } + + #[test] + fn test_subset_and_superset() { + let mut a = TreeSet::new(); + assert!(a.insert(0i)); + assert!(a.insert(5)); + assert!(a.insert(11)); + assert!(a.insert(7)); + + let mut b = TreeSet::new(); + assert!(b.insert(0i)); + assert!(b.insert(7)); + assert!(b.insert(19)); + assert!(b.insert(250)); + assert!(b.insert(11)); + assert!(b.insert(200)); + + assert!(!a.is_subset(&b)); + assert!(!a.is_superset(&b)); + assert!(!b.is_subset(&a)); + assert!(!b.is_superset(&a)); + + assert!(b.insert(5)); + + assert!(a.is_subset(&b)); + assert!(!a.is_superset(&b)); + assert!(!b.is_subset(&a)); + assert!(b.is_superset(&a)); + } + + #[test] + fn test_iterator() { + let mut m = TreeSet::new(); + + assert!(m.insert(3i)); + assert!(m.insert(0)); + assert!(m.insert(4)); + assert!(m.insert(2)); + assert!(m.insert(1)); + + let mut n = 0; + for x in m.iter() { + assert_eq!(*x, n); + n += 1 + } + } + + #[test] + fn test_rev_iter() { + let mut m = TreeSet::new(); + + assert!(m.insert(3i)); + assert!(m.insert(0)); + assert!(m.insert(4)); + assert!(m.insert(2)); + assert!(m.insert(1)); + + let mut n = 4; + for x in m.rev_iter() { + assert_eq!(*x, n); + n -= 1; + } + } + + #[test] + fn test_move_iter() { + let s: TreeSet = range(0i, 5).collect(); + + let mut n = 0; + for x in s.into_iter() { + assert_eq!(x, n); + n += 1; + } + } + + #[test] + fn test_move_iter_size_hint() { + let s: TreeSet = vec!(0i, 1).into_iter().collect(); + + let mut it = s.into_iter(); + + assert_eq!(it.size_hint(), (2, Some(2))); + assert!(it.next() != None); + + assert_eq!(it.size_hint(), (1, Some(1))); + assert!(it.next() != None); + + assert_eq!(it.size_hint(), (0, Some(0))); + assert_eq!(it.next(), None); + } + + #[test] + fn test_clone_eq() { + let mut m = TreeSet::new(); + + m.insert(1i); + m.insert(2); + + assert!(m.clone() == m); + } + + #[test] + fn test_hash() { + let mut x = TreeSet::new(); + let mut y = TreeSet::new(); + + x.insert(1i); + x.insert(2); + x.insert(3); + + y.insert(3i); + y.insert(2); + y.insert(1); + + assert!(hash::hash(&x) == hash::hash(&y)); + } + + fn check(a: &[int], + b: &[int], + expected: &[int], + f: |&TreeSet, &TreeSet, f: |&int| -> bool| -> bool) { + let mut set_a = TreeSet::new(); + let mut set_b = TreeSet::new(); + + for x in a.iter() { assert!(set_a.insert(*x)) } + for y in b.iter() { assert!(set_b.insert(*y)) } + + let mut i = 0; + f(&set_a, &set_b, |x| { + assert_eq!(*x, expected[i]); + i += 1; + true + }); + assert_eq!(i, expected.len()); + } + + #[test] + fn test_intersection() { + fn check_intersection(a: &[int], b: &[int], expected: &[int]) { + check(a, b, expected, |x, y, f| x.intersection(y).all(f)) + } + + check_intersection([], [], []); + check_intersection([1, 2, 3], [], []); + check_intersection([], [1, 2, 3], []); + check_intersection([2], [1, 2, 3], [2]); + check_intersection([1, 2, 3], [2], [2]); + check_intersection([11, 1, 3, 77, 103, 5, -5], + [2, 11, 77, -9, -42, 5, 3], + [3, 5, 11, 77]); + } + + #[test] + fn test_difference() { + fn check_difference(a: &[int], b: &[int], expected: &[int]) { + check(a, b, expected, |x, y, f| x.difference(y).all(f)) + } + + check_difference([], [], []); + check_difference([1, 12], [], [1, 12]); + check_difference([], [1, 2, 3, 9], []); + check_difference([1, 3, 5, 9, 11], + [3, 9], + [1, 5, 11]); + check_difference([-5, 11, 22, 33, 40, 42], + [-12, -5, 14, 23, 34, 38, 39, 50], + [11, 22, 33, 40, 42]); + } + + #[test] + fn test_symmetric_difference() { + fn check_symmetric_difference(a: &[int], b: &[int], + expected: &[int]) { + check(a, b, expected, |x, y, f| x.symmetric_difference(y).all(f)) + } + + check_symmetric_difference([], [], []); + check_symmetric_difference([1, 2, 3], [2], [1, 3]); + check_symmetric_difference([2], [1, 2, 3], [1, 3]); + check_symmetric_difference([1, 3, 5, 9, 11], + [-2, 3, 9, 14, 22], + [-2, 1, 5, 11, 14, 22]); + } + + #[test] + fn test_union() { + fn check_union(a: &[int], b: &[int], + expected: &[int]) { + check(a, b, expected, |x, y, f| x.union(y).all(f)) + } + + check_union([], [], []); + check_union([1, 2, 3], [2], [1, 2, 3]); + check_union([2], [1, 2, 3], [1, 2, 3]); + check_union([1, 3, 5, 9, 11, 16, 19, 24], + [-2, 1, 5, 9, 13, 19], + [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24]); + } + + #[test] + fn test_zip() { + let mut x = TreeSet::new(); + x.insert(5u); + x.insert(12u); + x.insert(11u); + + let mut y = TreeSet::new(); + y.insert("foo"); + y.insert("bar"); + + let x = x; + let y = y; + let mut z = x.iter().zip(y.iter()); + + // FIXME: #5801: this needs a type hint to compile... + let result: Option<(&uint, & &'static str)> = z.next(); + assert_eq!(result.unwrap(), (&5u, &("bar"))); + + let result: Option<(&uint, & &'static str)> = z.next(); + assert_eq!(result.unwrap(), (&11u, &("foo"))); + + let result: Option<(&uint, & &'static str)> = z.next(); + assert!(result.is_none()); + } + + #[test] + fn test_from_iter() { + let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9]; + + let set: TreeSet = xs.iter().map(|&x| x).collect(); + + for x in xs.iter() { + assert!(set.contains(x)); + } + } + + #[test] + fn test_show() { + let mut set: TreeSet = TreeSet::new(); + let empty: TreeSet = TreeSet::new(); + + set.insert(1); + set.insert(2); + + let set_str = format!("{}", set); + + assert!(set_str == "{1, 2}".to_string()); + assert_eq!(format!("{}", empty), "{}".to_string()); + } +} diff --git a/src/libcollections/trie.rs b/src/libcollections/trie/map.rs similarity index 80% rename from src/libcollections/trie.rs rename to src/libcollections/trie/map.rs index 7a8cc5df55a278a88359db1a11dded11e2e83789..27486de6f1993e0e771329c71edb19ad93e5fe48 100644 --- a/src/libcollections/trie.rs +++ b/src/libcollections/trie/map.rs @@ -654,335 +654,6 @@ fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut T { } } -/// A set implemented as a radix trie. -/// -/// # Example -/// -/// ``` -/// use std::collections::TrieSet; -/// -/// let mut set = TrieSet::new(); -/// set.insert(6); -/// set.insert(28); -/// set.insert(6); -/// -/// assert_eq!(set.len(), 2); -/// -/// if !set.contains(&3) { -/// println!("3 is not in the set"); -/// } -/// -/// // Print contents in order -/// for x in set.iter() { -/// println!("{}", x); -/// } -/// -/// set.remove(&6); -/// assert_eq!(set.len(), 1); -/// -/// set.clear(); -/// assert!(set.is_empty()); -/// ``` -#[deriving(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] -pub struct TrieSet { - map: TrieMap<()> -} - -impl Show for TrieSet { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{{")); - - for (i, x) in self.iter().enumerate() { - if i != 0 { try!(write!(f, ", ")); } - try!(write!(f, "{}", x)); - } - - write!(f, "}}") - } -} - -impl Default for TrieSet { - #[inline] - fn default() -> TrieSet { TrieSet::new() } -} - -impl TrieSet { - /// Creates an empty TrieSet. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// let mut set = TrieSet::new(); - /// ``` - #[inline] - pub fn new() -> TrieSet { - TrieSet{map: TrieMap::new()} - } - - /// Visits all values in reverse order. Aborts traversal when `f` returns `false`. - /// Returns `true` if `f` returns `true` for all elements. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let set: TrieSet = [1, 2, 3, 4, 5].iter().map(|&x| x).collect(); - /// - /// let mut vec = Vec::new(); - /// assert_eq!(true, set.each_reverse(|&x| { vec.push(x); true })); - /// assert_eq!(vec, vec![5, 4, 3, 2, 1]); - /// - /// // Stop when we reach 3 - /// let mut vec = Vec::new(); - /// assert_eq!(false, set.each_reverse(|&x| { vec.push(x); x != 3 })); - /// assert_eq!(vec, vec![5, 4, 3]); - /// ``` - #[inline] - pub fn each_reverse(&self, f: |&uint| -> bool) -> bool { - self.map.each_reverse(|k, _| f(k)) - } - - /// Gets an iterator over the values in the set, in sorted order. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let mut set = TrieSet::new(); - /// set.insert(3); - /// set.insert(2); - /// set.insert(1); - /// set.insert(2); - /// - /// // Print 1, 2, 3 - /// for x in set.iter() { - /// println!("{}", x); - /// } - /// ``` - #[inline] - pub fn iter<'a>(&'a self) -> SetItems<'a> { - SetItems{iter: self.map.iter()} - } - - /// Gets an iterator pointing to the first value that is not less than `val`. - /// If all values in the set are less than `val` an empty iterator is returned. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let set: TrieSet = [2, 4, 6, 8].iter().map(|&x| x).collect(); - /// assert_eq!(set.lower_bound(4).next(), Some(4)); - /// assert_eq!(set.lower_bound(5).next(), Some(6)); - /// assert_eq!(set.lower_bound(10).next(), None); - /// ``` - pub fn lower_bound<'a>(&'a self, val: uint) -> SetItems<'a> { - SetItems{iter: self.map.lower_bound(val)} - } - - /// Gets an iterator pointing to the first value that key is greater than `val`. - /// If all values in the set are less than or equal to `val` an empty iterator is returned. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let set: TrieSet = [2, 4, 6, 8].iter().map(|&x| x).collect(); - /// assert_eq!(set.upper_bound(4).next(), Some(6)); - /// assert_eq!(set.upper_bound(5).next(), Some(6)); - /// assert_eq!(set.upper_bound(10).next(), None); - /// ``` - pub fn upper_bound<'a>(&'a self, val: uint) -> SetItems<'a> { - SetItems{iter: self.map.upper_bound(val)} - } - - /// Return the number of elements in the set - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let mut v = TrieSet::new(); - /// assert_eq!(v.len(), 0); - /// v.insert(1); - /// assert_eq!(v.len(), 1); - /// ``` - #[inline] - pub fn len(&self) -> uint { self.map.len() } - - /// Returns true if the set contains no elements - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let mut v = TrieSet::new(); - /// assert!(v.is_empty()); - /// v.insert(1); - /// assert!(!v.is_empty()); - /// ``` - pub fn is_empty(&self) -> bool { self.len() == 0 } - - /// Clears the set, removing all values. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let mut v = TrieSet::new(); - /// v.insert(1); - /// v.clear(); - /// assert!(v.is_empty()); - /// ``` - #[inline] - pub fn clear(&mut self) { self.map.clear() } - - /// Returns `true` if the set contains a value. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let set: TrieSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// assert_eq!(set.contains(&1), true); - /// assert_eq!(set.contains(&4), false); - /// ``` - #[inline] - pub fn contains(&self, value: &uint) -> bool { - self.map.contains_key(value) - } - - /// Returns `true` if the set has no elements in common with `other`. - /// This is equivalent to checking for an empty intersection. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let a: TrieSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// let mut b: TrieSet = TrieSet::new(); - /// - /// assert_eq!(a.is_disjoint(&b), true); - /// b.insert(4); - /// assert_eq!(a.is_disjoint(&b), true); - /// b.insert(1); - /// assert_eq!(a.is_disjoint(&b), false); - /// ``` - #[inline] - pub fn is_disjoint(&self, other: &TrieSet) -> bool { - self.iter().all(|v| !other.contains(&v)) - } - - /// Returns `true` if the set is a subset of another. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let sup: TrieSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// let mut set: TrieSet = TrieSet::new(); - /// - /// assert_eq!(set.is_subset(&sup), true); - /// set.insert(2); - /// assert_eq!(set.is_subset(&sup), true); - /// set.insert(4); - /// assert_eq!(set.is_subset(&sup), false); - /// ``` - #[inline] - pub fn is_subset(&self, other: &TrieSet) -> bool { - self.iter().all(|v| other.contains(&v)) - } - - /// Returns `true` if the set is a superset of another. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let sub: TrieSet = [1, 2].iter().map(|&x| x).collect(); - /// let mut set: TrieSet = TrieSet::new(); - /// - /// assert_eq!(set.is_superset(&sub), false); - /// - /// set.insert(0); - /// set.insert(1); - /// assert_eq!(set.is_superset(&sub), false); - /// - /// set.insert(2); - /// assert_eq!(set.is_superset(&sub), true); - /// ``` - #[inline] - pub fn is_superset(&self, other: &TrieSet) -> bool { - other.is_subset(self) - } - - /// Adds a value to the set. Returns `true` if the value was not already - /// present in the set. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let mut set = TrieSet::new(); - /// - /// assert_eq!(set.insert(2), true); - /// assert_eq!(set.insert(2), false); - /// assert_eq!(set.len(), 1); - /// ``` - #[inline] - pub fn insert(&mut self, value: uint) -> bool { - self.map.insert(value, ()) - } - - /// Removes a value from the set. Returns `true` if the value was - /// present in the set. - /// - /// # Example - /// - /// ``` - /// use std::collections::TrieSet; - /// - /// let mut set = TrieSet::new(); - /// - /// set.insert(2); - /// assert_eq!(set.remove(&2), true); - /// assert_eq!(set.remove(&2), false); - /// ``` - #[inline] - pub fn remove(&mut self, value: &uint) -> bool { - self.map.remove(value) - } -} - -impl FromIterator for TrieSet { - fn from_iter>(iter: Iter) -> TrieSet { - let mut set = TrieSet::new(); - set.extend(iter); - set - } -} - -impl Extendable for TrieSet { - fn extend>(&mut self, mut iter: Iter) { - for elem in iter { - self.insert(elem); - } - } -} - struct TrieNode { count: uint, children: [Child, ..SIZE] @@ -1255,23 +926,8 @@ fn size_hint(&self) -> (uint, Option) { iterator_impl! { Entries, iter = iter, mutability = } iterator_impl! { MutEntries, iter = iter_mut, mutability = mut } -/// A forward iterator over a set. -pub struct SetItems<'a> { - iter: Entries<'a, ()> -} - -impl<'a> Iterator for SetItems<'a> { - fn next(&mut self) -> Option { - self.iter.next().map(|(key, _)| key) - } - - fn size_hint(&self) -> (uint, Option) { - self.iter.size_hint() - } -} - #[cfg(test)] -mod test_map { +mod test { use std::prelude::*; use std::iter::range_step; use std::uint; @@ -1687,7 +1343,7 @@ fn test_index_nonexistent() { } #[cfg(test)] -mod bench_map { +mod bench { use std::prelude::*; use std::rand::{weak_rng, Rng}; use test::{Bencher, black_box}; @@ -1802,98 +1458,3 @@ fn bench_insert_small_low_bits(b: &mut Bencher) { }) } } - -#[cfg(test)] -mod test_set { - use std::prelude::*; - use std::uint; - - use super::TrieSet; - - #[test] - fn test_sane_chunk() { - let x = 1; - let y = 1 << (uint::BITS - 1); - - let mut trie = TrieSet::new(); - - assert!(trie.insert(x)); - assert!(trie.insert(y)); - - assert_eq!(trie.len(), 2); - - let expected = [x, y]; - - for (i, x) in trie.iter().enumerate() { - assert_eq!(expected[i], x); - } - } - - #[test] - fn test_from_iter() { - let xs = vec![9u, 8, 7, 6, 5, 4, 3, 2, 1]; - - let set: TrieSet = xs.iter().map(|&x| x).collect(); - - for x in xs.iter() { - assert!(set.contains(x)); - } - } - - #[test] - fn test_show() { - let mut set = TrieSet::new(); - let empty = TrieSet::new(); - - set.insert(1); - set.insert(2); - - let set_str = format!("{}", set); - - assert!(set_str == "{1, 2}".to_string()); - assert_eq!(format!("{}", empty), "{}".to_string()); - } - - #[test] - fn test_clone() { - let mut a = TrieSet::new(); - - a.insert(1); - a.insert(2); - a.insert(3); - - assert!(a.clone() == a); - } - - #[test] - fn test_lt() { - let mut a = TrieSet::new(); - let mut b = TrieSet::new(); - - assert!(!(a < b) && !(b < a)); - assert!(b.insert(2u)); - assert!(a < b); - assert!(a.insert(3u)); - assert!(!(a < b) && b < a); - assert!(b.insert(1)); - assert!(b < a); - assert!(a.insert(0)); - assert!(a < b); - assert!(a.insert(6)); - assert!(a < b && !(b < a)); - } - - #[test] - fn test_ord() { - let mut a = TrieSet::new(); - let mut b = TrieSet::new(); - - assert!(a <= b && a >= b); - assert!(a.insert(1u)); - assert!(a > b && a >= b); - assert!(b < a && b <= a); - assert!(b.insert(2u)); - assert!(b > a && b >= a); - assert!(a < b && a <= b); - } -} diff --git a/src/libcollections/trie/mod.rs b/src/libcollections/trie/mod.rs new file mode 100644 index 0000000000000000000000000000000000000000..f0f8f00a6a0db8608717287a7a1e8b6031ffd402 --- /dev/null +++ b/src/libcollections/trie/mod.rs @@ -0,0 +1,20 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Maps are collections of unique keys with corresponding values, and sets are +//! just unique keys without a corresponding value. The `Map` and `Set` traits in +//! `std::container` define the basic interface. +//! +//! This crate defines `TrieMap` and `TrieSet`, which require `uint` keys. +//! +//! `TrieMap` is ordered. + +pub mod map; +pub mod set; \ No newline at end of file diff --git a/src/libcollections/trie/set.rs b/src/libcollections/trie/set.rs new file mode 100644 index 0000000000000000000000000000000000000000..ddddd279b0467b157fc159acacbbe5344cd40ba0 --- /dev/null +++ b/src/libcollections/trie/set.rs @@ -0,0 +1,457 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::prelude::*; + +use core::default::Default; +use core::fmt; +use core::fmt::Show; +use std::hash::Hash; + +use trie_map::{TrieMap, Entries}; + +/// A set implemented as a radix trie. +/// +/// # Example +/// +/// ``` +/// use std::collections::TrieSet; +/// +/// let mut set = TrieSet::new(); +/// set.insert(6); +/// set.insert(28); +/// set.insert(6); +/// +/// assert_eq!(set.len(), 2); +/// +/// if !set.contains(&3) { +/// println!("3 is not in the set"); +/// } +/// +/// // Print contents in order +/// for x in set.iter() { +/// println!("{}", x); +/// } +/// +/// set.remove(&6); +/// assert_eq!(set.len(), 1); +/// +/// set.clear(); +/// assert!(set.is_empty()); +/// ``` +#[deriving(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] +pub struct TrieSet { + map: TrieMap<()> +} + +impl Show for TrieSet { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "{{")); + + for (i, x) in self.iter().enumerate() { + if i != 0 { try!(write!(f, ", ")); } + try!(write!(f, "{}", x)); + } + + write!(f, "}}") + } +} + +impl Default for TrieSet { + #[inline] + fn default() -> TrieSet { TrieSet::new() } +} + +impl TrieSet { + /// Creates an empty TrieSet. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// let mut set = TrieSet::new(); + /// ``` + #[inline] + pub fn new() -> TrieSet { + TrieSet{map: TrieMap::new()} + } + + /// Visits all values in reverse order. Aborts traversal when `f` returns `false`. + /// Returns `true` if `f` returns `true` for all elements. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let set: TrieSet = [1, 2, 3, 4, 5].iter().map(|&x| x).collect(); + /// + /// let mut vec = Vec::new(); + /// assert_eq!(true, set.each_reverse(|&x| { vec.push(x); true })); + /// assert_eq!(vec, vec![5, 4, 3, 2, 1]); + /// + /// // Stop when we reach 3 + /// let mut vec = Vec::new(); + /// assert_eq!(false, set.each_reverse(|&x| { vec.push(x); x != 3 })); + /// assert_eq!(vec, vec![5, 4, 3]); + /// ``` + #[inline] + pub fn each_reverse(&self, f: |&uint| -> bool) -> bool { + self.map.each_reverse(|k, _| f(k)) + } + + /// Gets an iterator over the values in the set, in sorted order. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let mut set = TrieSet::new(); + /// set.insert(3); + /// set.insert(2); + /// set.insert(1); + /// set.insert(2); + /// + /// // Print 1, 2, 3 + /// for x in set.iter() { + /// println!("{}", x); + /// } + /// ``` + #[inline] + pub fn iter<'a>(&'a self) -> SetItems<'a> { + SetItems{iter: self.map.iter()} + } + + /// Gets an iterator pointing to the first value that is not less than `val`. + /// If all values in the set are less than `val` an empty iterator is returned. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let set: TrieSet = [2, 4, 6, 8].iter().map(|&x| x).collect(); + /// assert_eq!(set.lower_bound(4).next(), Some(4)); + /// assert_eq!(set.lower_bound(5).next(), Some(6)); + /// assert_eq!(set.lower_bound(10).next(), None); + /// ``` + pub fn lower_bound<'a>(&'a self, val: uint) -> SetItems<'a> { + SetItems{iter: self.map.lower_bound(val)} + } + + /// Gets an iterator pointing to the first value that key is greater than `val`. + /// If all values in the set are less than or equal to `val` an empty iterator is returned. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let set: TrieSet = [2, 4, 6, 8].iter().map(|&x| x).collect(); + /// assert_eq!(set.upper_bound(4).next(), Some(6)); + /// assert_eq!(set.upper_bound(5).next(), Some(6)); + /// assert_eq!(set.upper_bound(10).next(), None); + /// ``` + pub fn upper_bound<'a>(&'a self, val: uint) -> SetItems<'a> { + SetItems{iter: self.map.upper_bound(val)} + } + + /// Return the number of elements in the set + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let mut v = TrieSet::new(); + /// assert_eq!(v.len(), 0); + /// v.insert(1); + /// assert_eq!(v.len(), 1); + /// ``` + #[inline] + pub fn len(&self) -> uint { self.map.len() } + + /// Returns true if the set contains no elements + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let mut v = TrieSet::new(); + /// assert!(v.is_empty()); + /// v.insert(1); + /// assert!(!v.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { self.len() == 0 } + + /// Clears the set, removing all values. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let mut v = TrieSet::new(); + /// v.insert(1); + /// v.clear(); + /// assert!(v.is_empty()); + /// ``` + #[inline] + pub fn clear(&mut self) { self.map.clear() } + + /// Returns `true` if the set contains a value. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let set: TrieSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// assert_eq!(set.contains(&1), true); + /// assert_eq!(set.contains(&4), false); + /// ``` + #[inline] + pub fn contains(&self, value: &uint) -> bool { + self.map.contains_key(value) + } + + /// Returns `true` if the set has no elements in common with `other`. + /// This is equivalent to checking for an empty intersection. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let a: TrieSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let mut b: TrieSet = TrieSet::new(); + /// + /// assert_eq!(a.is_disjoint(&b), true); + /// b.insert(4); + /// assert_eq!(a.is_disjoint(&b), true); + /// b.insert(1); + /// assert_eq!(a.is_disjoint(&b), false); + /// ``` + #[inline] + pub fn is_disjoint(&self, other: &TrieSet) -> bool { + self.iter().all(|v| !other.contains(&v)) + } + + /// Returns `true` if the set is a subset of another. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let sup: TrieSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let mut set: TrieSet = TrieSet::new(); + /// + /// assert_eq!(set.is_subset(&sup), true); + /// set.insert(2); + /// assert_eq!(set.is_subset(&sup), true); + /// set.insert(4); + /// assert_eq!(set.is_subset(&sup), false); + /// ``` + #[inline] + pub fn is_subset(&self, other: &TrieSet) -> bool { + self.iter().all(|v| other.contains(&v)) + } + + /// Returns `true` if the set is a superset of another. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let sub: TrieSet = [1, 2].iter().map(|&x| x).collect(); + /// let mut set: TrieSet = TrieSet::new(); + /// + /// assert_eq!(set.is_superset(&sub), false); + /// + /// set.insert(0); + /// set.insert(1); + /// assert_eq!(set.is_superset(&sub), false); + /// + /// set.insert(2); + /// assert_eq!(set.is_superset(&sub), true); + /// ``` + #[inline] + pub fn is_superset(&self, other: &TrieSet) -> bool { + other.is_subset(self) + } + + /// Adds a value to the set. Returns `true` if the value was not already + /// present in the set. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let mut set = TrieSet::new(); + /// + /// assert_eq!(set.insert(2), true); + /// assert_eq!(set.insert(2), false); + /// assert_eq!(set.len(), 1); + /// ``` + #[inline] + pub fn insert(&mut self, value: uint) -> bool { + self.map.insert(value, ()) + } + + /// Removes a value from the set. Returns `true` if the value was + /// present in the set. + /// + /// # Example + /// + /// ``` + /// use std::collections::TrieSet; + /// + /// let mut set = TrieSet::new(); + /// + /// set.insert(2); + /// assert_eq!(set.remove(&2), true); + /// assert_eq!(set.remove(&2), false); + /// ``` + #[inline] + pub fn remove(&mut self, value: &uint) -> bool { + self.map.remove(value) + } +} + +impl FromIterator for TrieSet { + fn from_iter>(iter: Iter) -> TrieSet { + let mut set = TrieSet::new(); + set.extend(iter); + set + } +} + +impl Extendable for TrieSet { + fn extend>(&mut self, mut iter: Iter) { + for elem in iter { + self.insert(elem); + } + } +} + +/// A forward iterator over a set. +pub struct SetItems<'a> { + iter: Entries<'a, ()> +} + +impl<'a> Iterator for SetItems<'a> { + fn next(&mut self) -> Option { + self.iter.next().map(|(key, _)| key) + } + + fn size_hint(&self) -> (uint, Option) { + self.iter.size_hint() + } +} + +#[cfg(test)] +mod test { + use std::prelude::*; + use std::uint; + + use super::TrieSet; + + #[test] + fn test_sane_chunk() { + let x = 1; + let y = 1 << (uint::BITS - 1); + + let mut trie = TrieSet::new(); + + assert!(trie.insert(x)); + assert!(trie.insert(y)); + + assert_eq!(trie.len(), 2); + + let expected = [x, y]; + + for (i, x) in trie.iter().enumerate() { + assert_eq!(expected[i], x); + } + } + + #[test] + fn test_from_iter() { + let xs = vec![9u, 8, 7, 6, 5, 4, 3, 2, 1]; + + let set: TrieSet = xs.iter().map(|&x| x).collect(); + + for x in xs.iter() { + assert!(set.contains(x)); + } + } + + #[test] + fn test_show() { + let mut set = TrieSet::new(); + let empty = TrieSet::new(); + + set.insert(1); + set.insert(2); + + let set_str = format!("{}", set); + + assert!(set_str == "{1, 2}".to_string()); + assert_eq!(format!("{}", empty), "{}".to_string()); + } + + #[test] + fn test_clone() { + let mut a = TrieSet::new(); + + a.insert(1); + a.insert(2); + a.insert(3); + + assert!(a.clone() == a); + } + + #[test] + fn test_lt() { + let mut a = TrieSet::new(); + let mut b = TrieSet::new(); + + assert!(!(a < b) && !(b < a)); + assert!(b.insert(2u)); + assert!(a < b); + assert!(a.insert(3u)); + assert!(!(a < b) && b < a); + assert!(b.insert(1)); + assert!(b < a); + assert!(a.insert(0)); + assert!(a < b); + assert!(a.insert(6)); + assert!(a < b && !(b < a)); + } + + #[test] + fn test_ord() { + let mut a = TrieSet::new(); + let mut b = TrieSet::new(); + + assert!(a <= b && a >= b); + assert!(a.insert(1u)); + assert!(a > b && a >= b); + assert!(b < a && b <= a); + assert!(b.insert(2u)); + assert!(b > a && b >= a); + assert!(a < b && a <= b); + } +} diff --git a/src/libcollections/smallintmap.rs b/src/libcollections/vec_map.rs similarity index 84% rename from src/libcollections/smallintmap.rs rename to src/libcollections/vec_map.rs index b2e018743da7d54897728afdc0adb07bc79e3260..c0bc785126c70aaa788802001cf14e3bb56b7b9b 100644 --- a/src/libcollections/smallintmap.rs +++ b/src/libcollections/vec_map.rs @@ -31,9 +31,9 @@ /// # Example /// /// ``` -/// use std::collections::SmallIntMap; +/// use std::collections::VecMap; /// -/// let mut months = SmallIntMap::new(); +/// let mut months = VecMap::new(); /// months.insert(1, "Jan"); /// months.insert(2, "Feb"); /// months.insert(3, "Mar"); @@ -60,23 +60,23 @@ /// assert!(months.is_empty()); /// ``` #[deriving(PartialEq, Eq)] -pub struct SmallIntMap { +pub struct VecMap { v: Vec>, } -impl Default for SmallIntMap { +impl Default for VecMap { #[inline] - fn default() -> SmallIntMap { SmallIntMap::new() } + fn default() -> VecMap { VecMap::new() } } -impl Clone for SmallIntMap { +impl Clone for VecMap { #[inline] - fn clone(&self) -> SmallIntMap { - SmallIntMap { v: self.v.clone() } + fn clone(&self) -> VecMap { + VecMap { v: self.v.clone() } } #[inline] - fn clone_from(&mut self, source: &SmallIntMap) { + fn clone_from(&mut self, source: &VecMap) { self.v.reserve(source.v.len()); for (i, w) in self.v.iter_mut().enumerate() { *w = source.v[i].clone(); @@ -84,34 +84,34 @@ fn clone_from(&mut self, source: &SmallIntMap) { } } -impl > Hash for SmallIntMap { +impl > Hash for VecMap { fn hash(&self, state: &mut S) { self.v.hash(state) } } -impl SmallIntMap { - /// Creates an empty `SmallIntMap`. +impl VecMap { + /// Creates an empty `VecMap`. /// /// # Example /// /// ``` - /// use std::collections::SmallIntMap; - /// let mut map: SmallIntMap<&str> = SmallIntMap::new(); + /// use std::collections::VecMap; + /// let mut map: VecMap<&str> = VecMap::new(); /// ``` - pub fn new() -> SmallIntMap { SmallIntMap{v: vec!()} } + pub fn new() -> VecMap { VecMap{v: vec!()} } - /// Creates an empty `SmallIntMap` with space for at least `capacity` + /// Creates an empty `VecMap` with space for at least `capacity` /// elements before resizing. /// /// # Example /// /// ``` - /// use std::collections::SmallIntMap; - /// let mut map: SmallIntMap<&str> = SmallIntMap::with_capacity(10); + /// use std::collections::VecMap; + /// let mut map: VecMap<&str> = VecMap::with_capacity(10); /// ``` - pub fn with_capacity(capacity: uint) -> SmallIntMap { - SmallIntMap { v: Vec::with_capacity(capacity) } + pub fn with_capacity(capacity: uint) -> VecMap { + VecMap { v: Vec::with_capacity(capacity) } } /// Returns an iterator visiting all keys in ascending order by the keys. @@ -132,9 +132,9 @@ pub fn values<'r>(&'r self) -> Values<'r, V> { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// map.insert(1, "a"); /// map.insert(3, "c"); /// map.insert(2, "b"); @@ -159,9 +159,9 @@ pub fn iter<'r>(&'r self) -> Entries<'r, V> { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// map.insert(1, "a"); /// map.insert(2, "b"); /// map.insert(3, "c"); @@ -183,15 +183,15 @@ pub fn iter_mut<'r>(&'r mut self) -> MutEntries<'r, V> { } /// Returns an iterator visiting all key-value pairs in ascending order by - /// the keys, emptying (but not consuming) the original `SmallIntMap`. + /// the keys, emptying (but not consuming) the original `VecMap`. /// The iterator's element type is `(uint, &'r V)`. /// /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// map.insert(1, "a"); /// map.insert(3, "c"); /// map.insert(2, "b"); @@ -216,9 +216,9 @@ pub fn into_iter(&mut self) /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut a = SmallIntMap::new(); + /// let mut a = VecMap::new(); /// assert_eq!(a.len(), 0); /// a.insert(1, "a"); /// assert_eq!(a.len(), 1); @@ -232,9 +232,9 @@ pub fn len(&self) -> uint { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut a = SmallIntMap::new(); + /// let mut a = VecMap::new(); /// assert!(a.is_empty()); /// a.insert(1, "a"); /// assert!(!a.is_empty()); @@ -248,9 +248,9 @@ pub fn is_empty(&self) -> bool { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut a = SmallIntMap::new(); + /// let mut a = VecMap::new(); /// a.insert(1, "a"); /// a.clear(); /// assert!(a.is_empty()); @@ -262,9 +262,9 @@ pub fn clear(&mut self) { self.v.clear() } /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// map.insert(1, "a"); /// assert_eq!(map.find(&1), Some(&"a")); /// assert_eq!(map.find(&2), None); @@ -285,9 +285,9 @@ pub fn find<'a>(&'a self, key: &uint) -> Option<&'a V> { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// map.insert(1, "a"); /// assert_eq!(map.contains_key(&1), true); /// assert_eq!(map.contains_key(&2), false); @@ -302,9 +302,9 @@ pub fn contains_key(&self, key: &uint) -> bool { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// map.insert(1, "a"); /// match map.find_mut(&1) { /// Some(x) => *x = "b", @@ -330,9 +330,9 @@ pub fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut V> { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// assert_eq!(map.insert(2, "value"), true); /// assert_eq!(map.insert(2, "value2"), false); /// assert_eq!(map[2], "value2"); @@ -353,9 +353,9 @@ pub fn insert(&mut self, key: uint, value: V) -> bool { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// assert_eq!(map.remove(&1), false); /// map.insert(1, "a"); /// assert_eq!(map.remove(&1), true); @@ -370,9 +370,9 @@ pub fn remove(&mut self, key: &uint) -> bool { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// assert_eq!(map.swap(37, "a"), None); /// assert_eq!(map.is_empty(), false); /// @@ -395,9 +395,9 @@ pub fn swap(&mut self, key: uint, value: V) -> Option { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// map.insert(1, "a"); /// assert_eq!(map.pop(&1), Some("a")); /// assert_eq!(map.pop(&1), None); @@ -410,7 +410,7 @@ pub fn pop(&mut self, key: &uint) -> Option { } } -impl SmallIntMap { +impl VecMap { /// Updates a value in the map. If the key already exists in the map, /// modifies the value with `ff` taking `oldval, newval`. /// Otherwise, sets the value to `newval`. @@ -419,9 +419,9 @@ impl SmallIntMap { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// /// // Key does not exist, will do a simple insert /// assert!(map.update(1, vec![1i, 2], |mut old, new| { old.extend(new.into_iter()); old })); @@ -443,9 +443,9 @@ pub fn update(&mut self, key: uint, newval: V, ff: |V, V| -> V) -> bool { /// # Example /// /// ``` - /// use std::collections::SmallIntMap; + /// use std::collections::VecMap; /// - /// let mut map = SmallIntMap::new(); + /// let mut map = VecMap::new(); /// /// // Key does not exist, will do a simple insert /// assert!(map.update_with_key(7, 10, |key, old, new| (old + new) % key)); @@ -468,21 +468,21 @@ pub fn update_with_key(&mut self, } } -impl PartialOrd for SmallIntMap { +impl PartialOrd for VecMap { #[inline] - fn partial_cmp(&self, other: &SmallIntMap) -> Option { + fn partial_cmp(&self, other: &VecMap) -> Option { iter::order::partial_cmp(self.iter(), other.iter()) } } -impl Ord for SmallIntMap { +impl Ord for VecMap { #[inline] - fn cmp(&self, other: &SmallIntMap) -> Ordering { + fn cmp(&self, other: &VecMap) -> Ordering { iter::order::cmp(self.iter(), other.iter()) } } -impl fmt::Show for SmallIntMap { +impl fmt::Show for VecMap { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "{{")); @@ -495,15 +495,15 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl FromIterator<(uint, V)> for SmallIntMap { - fn from_iter>(iter: Iter) -> SmallIntMap { - let mut map = SmallIntMap::new(); +impl FromIterator<(uint, V)> for VecMap { + fn from_iter>(iter: Iter) -> VecMap { + let mut map = VecMap::new(); map.extend(iter); map } } -impl Extendable<(uint, V)> for SmallIntMap { +impl Extendable<(uint, V)> for VecMap { fn extend>(&mut self, mut iter: Iter) { for (k, v) in iter { self.insert(k, v); @@ -511,14 +511,14 @@ fn extend>(&mut self, mut iter: Iter) { } } -impl Index for SmallIntMap { +impl Index for VecMap { #[inline] fn index<'a>(&'a self, i: &uint) -> &'a V { self.find(i).expect("key not present") } } -impl IndexMut for SmallIntMap { +impl IndexMut for VecMap { #[inline] fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V { self.find_mut(i).expect("key not present") @@ -612,11 +612,11 @@ mod test_map { use vec::Vec; use hash; - use super::SmallIntMap; + use super::VecMap; #[test] fn test_find_mut() { - let mut m = SmallIntMap::new(); + let mut m = VecMap::new(); assert!(m.insert(1, 12i)); assert!(m.insert(2, 8)); assert!(m.insert(5, 14)); @@ -629,7 +629,7 @@ fn test_find_mut() { #[test] fn test_len() { - let mut map = SmallIntMap::new(); + let mut map = VecMap::new(); assert_eq!(map.len(), 0); assert!(map.is_empty()); assert!(map.insert(5, 20i)); @@ -645,7 +645,7 @@ fn test_len() { #[test] fn test_clear() { - let mut map = SmallIntMap::new(); + let mut map = VecMap::new(); assert!(map.insert(5, 20i)); assert!(map.insert(11, 12)); assert!(map.insert(14, 22)); @@ -658,7 +658,7 @@ fn test_clear() { #[test] fn test_insert_with_key() { - let mut map = SmallIntMap::new(); + let mut map = VecMap::new(); // given a new key, initialize it with this new count, // given an existing key, add more to its count @@ -688,7 +688,7 @@ fn add_more_to_count_simple(v0: uint, v1: uint) -> uint { #[test] fn test_swap() { - let mut m = SmallIntMap::new(); + let mut m = VecMap::new(); assert_eq!(m.swap(1, 2i), None); assert_eq!(m.swap(1, 3i), Some(2)); assert_eq!(m.swap(1, 4i), Some(3)); @@ -696,7 +696,7 @@ fn test_swap() { #[test] fn test_pop() { - let mut m = SmallIntMap::new(); + let mut m = VecMap::new(); m.insert(1, 2i); assert_eq!(m.pop(&1), Some(2)); assert_eq!(m.pop(&1), None); @@ -704,7 +704,7 @@ fn test_pop() { #[test] fn test_keys() { - let mut map = SmallIntMap::new(); + let mut map = VecMap::new(); map.insert(1, 'a'); map.insert(2, 'b'); map.insert(3, 'c'); @@ -717,7 +717,7 @@ fn test_keys() { #[test] fn test_values() { - let mut map = SmallIntMap::new(); + let mut map = VecMap::new(); map.insert(1, 'a'); map.insert(2, 'b'); map.insert(3, 'c'); @@ -730,7 +730,7 @@ fn test_values() { #[test] fn test_iterator() { - let mut m = SmallIntMap::new(); + let mut m = VecMap::new(); assert!(m.insert(0, 1i)); assert!(m.insert(1, 2)); @@ -755,7 +755,7 @@ fn test_iterator() { #[test] fn test_iterator_size_hints() { - let mut m = SmallIntMap::new(); + let mut m = VecMap::new(); assert!(m.insert(0, 1i)); assert!(m.insert(1, 2)); @@ -771,7 +771,7 @@ fn test_iterator_size_hints() { #[test] fn test_mut_iterator() { - let mut m = SmallIntMap::new(); + let mut m = VecMap::new(); assert!(m.insert(0, 1i)); assert!(m.insert(1, 2)); @@ -794,7 +794,7 @@ fn test_mut_iterator() { #[test] fn test_rev_iterator() { - let mut m = SmallIntMap::new(); + let mut m = VecMap::new(); assert!(m.insert(0, 1i)); assert!(m.insert(1, 2)); @@ -813,7 +813,7 @@ fn test_rev_iterator() { #[test] fn test_mut_rev_iterator() { - let mut m = SmallIntMap::new(); + let mut m = VecMap::new(); assert!(m.insert(0, 1i)); assert!(m.insert(1, 2)); @@ -836,7 +836,7 @@ fn test_mut_rev_iterator() { #[test] fn test_move_iter() { - let mut m = SmallIntMap::new(); + let mut m = VecMap::new(); m.insert(1, box 2i); let mut called = false; for (k, v) in m.into_iter() { @@ -851,8 +851,8 @@ fn test_move_iter() { #[test] fn test_show() { - let mut map = SmallIntMap::new(); - let empty = SmallIntMap::::new(); + let mut map = VecMap::new(); + let empty = VecMap::::new(); map.insert(1, 2i); map.insert(3, 4i); @@ -865,7 +865,7 @@ fn test_show() { #[test] fn test_clone() { - let mut a = SmallIntMap::new(); + let mut a = VecMap::new(); a.insert(1, 'x'); a.insert(4, 'y'); @@ -876,8 +876,8 @@ fn test_clone() { #[test] fn test_eq() { - let mut a = SmallIntMap::new(); - let mut b = SmallIntMap::new(); + let mut a = VecMap::new(); + let mut b = VecMap::new(); assert!(a == b); assert!(a.insert(0, 5i)); @@ -894,8 +894,8 @@ fn test_eq() { #[test] fn test_lt() { - let mut a = SmallIntMap::new(); - let mut b = SmallIntMap::new(); + let mut a = VecMap::new(); + let mut b = VecMap::new(); assert!(!(a < b) && !(b < a)); assert!(b.insert(2u, 5i)); @@ -912,8 +912,8 @@ fn test_lt() { #[test] fn test_ord() { - let mut a = SmallIntMap::new(); - let mut b = SmallIntMap::new(); + let mut a = VecMap::new(); + let mut b = VecMap::new(); assert!(a <= b && a >= b); assert!(a.insert(1u, 1i)); @@ -926,8 +926,8 @@ fn test_ord() { #[test] fn test_hash() { - let mut x = SmallIntMap::new(); - let mut y = SmallIntMap::new(); + let mut x = VecMap::new(); + let mut y = VecMap::new(); assert!(hash::hash(&x) == hash::hash(&y)); x.insert(1, 'a'); @@ -945,7 +945,7 @@ fn test_hash() { fn test_from_iter() { let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]; - let map: SmallIntMap = xs.iter().map(|&x| x).collect(); + let map: VecMap = xs.iter().map(|&x| x).collect(); for &(k, v) in xs.iter() { assert_eq!(map.find(&k), Some(&v)); @@ -954,7 +954,7 @@ fn test_from_iter() { #[test] fn test_index() { - let mut map: SmallIntMap = SmallIntMap::new(); + let mut map: VecMap = VecMap::new(); map.insert(1, 2); map.insert(2, 1); @@ -966,7 +966,7 @@ fn test_index() { #[test] #[should_fail] fn test_index_nonexistent() { - let mut map: SmallIntMap = SmallIntMap::new(); + let mut map: VecMap = VecMap::new(); map.insert(1, 2); map.insert(2, 1); @@ -980,12 +980,12 @@ fn test_index_nonexistent() { mod bench { extern crate test; use self::test::Bencher; - use super::SmallIntMap; + use super::VecMap; use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n}; #[bench] pub fn insert_rand_100(b: &mut Bencher) { - let mut m : SmallIntMap = SmallIntMap::new(); + let mut m : VecMap = VecMap::new(); insert_rand_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); @@ -993,7 +993,7 @@ pub fn insert_rand_100(b: &mut Bencher) { #[bench] pub fn insert_rand_10_000(b: &mut Bencher) { - let mut m : SmallIntMap = SmallIntMap::new(); + let mut m : VecMap = VecMap::new(); insert_rand_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); @@ -1002,7 +1002,7 @@ pub fn insert_rand_10_000(b: &mut Bencher) { // Insert seq #[bench] pub fn insert_seq_100(b: &mut Bencher) { - let mut m : SmallIntMap = SmallIntMap::new(); + let mut m : VecMap = VecMap::new(); insert_seq_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); @@ -1010,7 +1010,7 @@ pub fn insert_seq_100(b: &mut Bencher) { #[bench] pub fn insert_seq_10_000(b: &mut Bencher) { - let mut m : SmallIntMap = SmallIntMap::new(); + let mut m : VecMap = VecMap::new(); insert_seq_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); @@ -1019,7 +1019,7 @@ pub fn insert_seq_10_000(b: &mut Bencher) { // Find rand #[bench] pub fn find_rand_100(b: &mut Bencher) { - let mut m : SmallIntMap = SmallIntMap::new(); + let mut m : VecMap = VecMap::new(); find_rand_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.find(&i); }); @@ -1027,7 +1027,7 @@ pub fn find_rand_100(b: &mut Bencher) { #[bench] pub fn find_rand_10_000(b: &mut Bencher) { - let mut m : SmallIntMap = SmallIntMap::new(); + let mut m : VecMap = VecMap::new(); find_rand_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.find(&i); }); @@ -1036,7 +1036,7 @@ pub fn find_rand_10_000(b: &mut Bencher) { // Find seq #[bench] pub fn find_seq_100(b: &mut Bencher) { - let mut m : SmallIntMap = SmallIntMap::new(); + let mut m : VecMap = VecMap::new(); find_seq_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.find(&i); }); @@ -1044,7 +1044,7 @@ pub fn find_seq_100(b: &mut Bencher) { #[bench] pub fn find_seq_10_000(b: &mut Bencher) { - let mut m : SmallIntMap = SmallIntMap::new(); + let mut m : VecMap = VecMap::new(); find_seq_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.find(&i); }); diff --git a/src/librustc/driver/config.rs b/src/librustc/driver/config.rs index ace5ba26fdbaa9d3196daa34eb953b7e2e13d105..a889093852dddbb9aaa1ffee44af930b5075a600 100644 --- a/src/librustc/driver/config.rs +++ b/src/librustc/driver/config.rs @@ -31,7 +31,7 @@ use syntax::parse::token::InternedString; use std::collections::HashMap; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use getopts::{optopt, optmulti, optflag, optflagopt}; use getopts; use std::cell::{RefCell}; diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 3e53620cbd4757ff9a26e299b42b77b839c5c707..e20f76622c934d00465ee0825a4cd72085d838c8 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -36,7 +36,7 @@ use std::cmp; use std::collections::HashMap; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use std::slice; use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64}; use syntax::abi; diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 92b2382ae64f493d8b7f7e0bf858625d2cc61911..f53b46dc7863c97245bbf3de4c41d5d6c1a79ca7 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -24,7 +24,7 @@ use std::rc::Rc; use std::collections::HashMap; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use syntax::ast; use syntax::abi; use syntax::attr; diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index e6a0363fcbf50f6bb5116c20cca826ae57d657d7..ff78491c2ad9dd4951a684c8c53293b23f726cd7 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -31,7 +31,7 @@ use syntax::diagnostic::expect; use syntax::parse::token; -use std::collections::hashmap::HashMap; +use std::collections::hash_map::HashMap; pub struct MethodInfo { pub name: ast::Name, diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 0df98bfb0b16dd84deda7c93c81852a071d26803..20171ecfd99f73686cb628ee038b51a22ec59755 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -34,7 +34,7 @@ use std::hash; use std::io::extensions::u64_from_be_bytes; use std::io; -use std::collections::hashmap::HashMap; +use std::collections::hash_map::HashMap; use std::rc::Rc; use std::u64; use rbml::reader; diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index 623a763bd7468bd6d2840ac4b18fcc0d12a7dea6..7b67def405176df5a4725af7cc64e31b9b4ba2d7 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -237,7 +237,7 @@ use std::string; use std::collections::{HashMap, HashSet}; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use flate; use time; diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index ad0040608ece86ed511a5f616b79315d4446ac0f..ce91bd1b1538889e7eefc883689136816f5a60a6 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -28,7 +28,7 @@ use syntax::{ast, ast_map, ast_util, codemap}; use std::rc::Rc; -use std::collections::hashmap::Vacant; +use std::collections::hash_map::Vacant; // // This pass classifies expressions by their constant-ness. diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index c297bdc6ca2e70a131fe4dafc61cf9941b5c0f0f..a2bea790c9f46ac796ad6a960b763f174c961d11 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -58,7 +58,7 @@ use syntax::visit::Visitor; use std::collections::{HashMap, HashSet}; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use std::cell::{Cell, RefCell}; use std::mem::replace; use std::rc::{Rc, Weak}; diff --git a/src/librustc/middle/traits/select.rs b/src/librustc/middle/traits/select.rs index f8c1c37452b38c4e93b6ac35a75ee3cbc720b382..d78c9e3a6e28e0932b21ac10ad03633b4cfe7af2 100644 --- a/src/librustc/middle/traits/select.rs +++ b/src/librustc/middle/traits/select.rs @@ -29,7 +29,7 @@ use middle::typeck::infer::{InferCtxt, TypeSkolemizer}; use middle::ty_fold::TypeFoldable; use std::cell::RefCell; -use std::collections::hashmap::HashMap; +use std::collections::hash_map::HashMap; use std::rc::Rc; use syntax::ast; use util::ppaux::Repr; diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index b9af31665a11313ca5e672d66355f739660b9b54..4c088e42243e190d18067c6dfab0e7b3860984f0 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -43,7 +43,7 @@ use std::ops; use std::rc::Rc; use std::collections::{HashMap, HashSet}; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use arena::TypedArena; use syntax::abi; use syntax::ast::{CrateNum, DefId, FnStyle, Ident, ItemTrait, LOCAL_CRATE}; diff --git a/src/librustc/middle/typeck/check/_match.rs b/src/librustc/middle/typeck/check/_match.rs index 97c6cf24f0e1900a31efa8ab15699897dbae3b0c..a686a5e72a0a7cafcbca071db595c5ba8ebc091c 100644 --- a/src/librustc/middle/typeck/check/_match.rs +++ b/src/librustc/middle/typeck/check/_match.rs @@ -19,7 +19,7 @@ use std::cmp; use std::collections::HashMap; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use syntax::ast; use syntax::ast_util; use syntax::codemap::{Span, Spanned}; diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index f334d8016927dfee5de0a9ef62d6b9a57a495c9a..c280474a076a0b28614a3a562aa87c96a2145cce 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -118,7 +118,7 @@ use std::cell::{Cell, Ref, RefCell}; use std::collections::HashMap; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use std::mem::replace; use std::rc::Rc; use syntax::abi; diff --git a/src/librustc/middle/typeck/check/regionck.rs b/src/librustc/middle/typeck/check/regionck.rs index d0338333badee30a46a950d3ef4163817823ef85..acc3cf0307b9655fcc1baf0e4b810299b46459b9 100644 --- a/src/librustc/middle/typeck/check/regionck.rs +++ b/src/librustc/middle/typeck/check/regionck.rs @@ -142,7 +142,7 @@ fn get_i(x: &'a Bar) -> &'a int { use std::cell::{RefCell}; use std::collections::HashMap; -use std::collections::hashmap::{Vacant, Occupied}; +use std::collections::hash_map::{Vacant, Occupied}; /////////////////////////////////////////////////////////////////////////// // PUBLIC ENTRY POINTS diff --git a/src/librustc/middle/typeck/check/regionmanip.rs b/src/librustc/middle/typeck/check/regionmanip.rs index 225a3162af90470c62d7d5d617961817e4b55389..91e9c18853c804b0f44288721bcaf9103c2cc323 100644 --- a/src/librustc/middle/typeck/check/regionmanip.rs +++ b/src/librustc/middle/typeck/check/regionmanip.rs @@ -18,7 +18,7 @@ use syntax::ast; use std::collections::HashMap; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use util::ppaux::Repr; // Helper functions related to manipulating region types. diff --git a/src/librustc/middle/typeck/infer/skolemize.rs b/src/librustc/middle/typeck/infer/skolemize.rs index 0fe1e2b565befa4a12ce0588ba00778b9613de5e..6e5e8d72839eb0959aeef3a75ccc445279bd25e8 100644 --- a/src/librustc/middle/typeck/infer/skolemize.rs +++ b/src/librustc/middle/typeck/infer/skolemize.rs @@ -44,7 +44,7 @@ use middle::ty_fold; use middle::ty_fold::TypeFoldable; use middle::ty_fold::TypeFolder; -use std::collections::hashmap; +use std::collections::hash_map; use super::InferCtxt; use super::unify::InferCtxtMethodsForSimplyUnifiableTypes; @@ -52,7 +52,7 @@ pub struct TypeSkolemizer<'a, 'tcx:'a> { infcx: &'a InferCtxt<'a, 'tcx>, skolemization_count: uint, - skolemization_map: hashmap::HashMap, + skolemization_map: hash_map::HashMap, } impl<'a, 'tcx> TypeSkolemizer<'a, 'tcx> { @@ -60,7 +60,7 @@ pub fn new<'tcx>(infcx: &'a InferCtxt<'a, 'tcx>) -> TypeSkolemizer<'a, 'tcx> { TypeSkolemizer { infcx: infcx, skolemization_count: 0, - skolemization_map: hashmap::HashMap::new(), + skolemization_map: hash_map::HashMap::new(), } } @@ -76,8 +76,8 @@ fn skolemize(&mut self, } match self.skolemization_map.entry(key) { - hashmap::Occupied(entry) => *entry.get(), - hashmap::Vacant(entry) => { + hash_map::Occupied(entry) => *entry.get(), + hash_map::Vacant(entry) => { let index = self.skolemization_count; self.skolemization_count += 1; let t = ty::mk_infer(self.infcx.tcx, skolemizer(index)); diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index d1d9702a134f6fda562e9485918fedd01d28fb6a..9af2b22adea455c1392769e395a9db701e347c88 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -34,7 +34,7 @@ //! both occur before the crate is rendered. use std::collections::{HashMap, HashSet}; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use std::fmt; use std::io::fs::PathExtensions; use std::io::{fs, File, BufferedWriter, MemWriter, BufferedReader}; diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 5f404238beb30dda938e463612fc9eea68aa0989..bd3c618a5ed46149b2075c7ed319ddc38a24b3b9 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -31,7 +31,7 @@ use std::io; use std::io::{File, MemWriter}; use std::collections::HashMap; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; use serialize::{json, Decodable, Encodable}; use externalfiles::ExternalHtml; diff --git a/src/librustrt/local_data.rs b/src/librustrt/local_data.rs index ee69f5f5235dce1ddd0011f09df8089633c5fab8..7129f14720911f8cbaa2b0f588b305349558fa23 100644 --- a/src/librustrt/local_data.rs +++ b/src/librustrt/local_data.rs @@ -41,7 +41,7 @@ use core::prelude::*; use alloc::heap; -use collections::treemap::TreeMap; +use collections::TreeMap; use core::cmp; use core::kinds::marker; use core::mem; diff --git a/src/libstd/collections/hashmap/bench.rs b/src/libstd/collections/hash/bench.rs similarity index 91% rename from src/libstd/collections/hashmap/bench.rs rename to src/libstd/collections/hash/bench.rs index 21bbb38f4893671686fff78f2230e2a42c09a6ba..62b93336a34bdce65776167fba79510a3b17f806 100644 --- a/src/libstd/collections/hashmap/bench.rs +++ b/src/libstd/collections/hash/bench.rs @@ -18,7 +18,7 @@ #[bench] fn new_drop(b : &mut Bencher) { - use super::HashMap; + use super::map::HashMap; b.iter(|| { let m : HashMap = HashMap::new(); @@ -28,7 +28,7 @@ fn new_drop(b : &mut Bencher) { #[bench] fn new_insert_drop(b : &mut Bencher) { - use super::HashMap; + use super::map::HashMap; b.iter(|| { let mut m = HashMap::new(); @@ -39,7 +39,7 @@ fn new_insert_drop(b : &mut Bencher) { #[bench] fn grow_by_insertion(b: &mut Bencher) { - use super::HashMap; + use super::map::HashMap; let mut m = HashMap::new(); @@ -57,7 +57,7 @@ fn grow_by_insertion(b: &mut Bencher) { #[bench] fn find_existing(b: &mut Bencher) { - use super::HashMap; + use super::map::HashMap; let mut m = HashMap::new(); @@ -74,7 +74,7 @@ fn find_existing(b: &mut Bencher) { #[bench] fn find_nonexisting(b: &mut Bencher) { - use super::HashMap; + use super::map::HashMap; let mut m = HashMap::new(); @@ -91,7 +91,7 @@ fn find_nonexisting(b: &mut Bencher) { #[bench] fn hashmap_as_queue(b: &mut Bencher) { - use super::HashMap; + use super::map::HashMap; let mut m = HashMap::new(); @@ -110,7 +110,7 @@ fn hashmap_as_queue(b: &mut Bencher) { #[bench] fn find_pop_insert(b: &mut Bencher) { - use super::HashMap; + use super::map::HashMap; let mut m = HashMap::new(); diff --git a/src/libstd/collections/hashmap/map.rs b/src/libstd/collections/hash/map.rs similarity index 100% rename from src/libstd/collections/hashmap/map.rs rename to src/libstd/collections/hash/map.rs diff --git a/src/libstd/collections/hashmap/mod.rs b/src/libstd/collections/hash/mod.rs similarity index 52% rename from src/libstd/collections/hashmap/mod.rs rename to src/libstd/collections/hash/mod.rs index 6508d4609f1475a68d525f586bc36ab48e14eb89..ee3fc1e6ac3621b5bb7499e66ec8019a72007fef 100644 --- a/src/libstd/collections/hashmap/mod.rs +++ b/src/libstd/collections/hash/mod.rs @@ -10,24 +10,7 @@ //! Unordered containers, implemented as hash-tables -pub use self::map::HashMap; -pub use self::map::Entries; -pub use self::map::MutEntries; -pub use self::map::MoveEntries; -pub use self::map::Entry; -pub use self::map::Occupied; -pub use self::map::Vacant; -pub use self::map::OccupiedEntry; -pub use self::map::VacantEntry; -pub use self::map::Keys; -pub use self::map::Values; -pub use self::map::INITIAL_CAPACITY; -pub use self::set::HashSet; -pub use self::set::SetItems; -pub use self::set::SetMoveItems; -pub use self::set::SetAlgebraItems; - mod bench; -mod map; -mod set; +pub mod map; +pub mod set; mod table; diff --git a/src/libstd/collections/hashmap/set.rs b/src/libstd/collections/hash/set.rs similarity index 99% rename from src/libstd/collections/hashmap/set.rs rename to src/libstd/collections/hash/set.rs index 69f3812425f64216a5ab5b4a40634d2c67d85aaf..823bd49d7a6632488e8c285c2d6284248c8a4eb6 100644 --- a/src/libstd/collections/hashmap/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -22,7 +22,7 @@ use option::{Some, None}; use result::{Ok, Err}; -use super::{HashMap, Entries, MoveEntries, INITIAL_CAPACITY}; +use super::map::{HashMap, Entries, MoveEntries, INITIAL_CAPACITY}; // Future Optimization (FIXME!) diff --git a/src/libstd/collections/hashmap/table.rs b/src/libstd/collections/hash/table.rs similarity index 100% rename from src/libstd/collections/hashmap/table.rs rename to src/libstd/collections/hash/table.rs diff --git a/src/libstd/collections/mod.rs b/src/libstd/collections/mod.rs index be9e22ee9d14c9972e1b592eb955d4e9c369e922..13486d4b8f84d55d5e8299e341cb40174e6777df 100644 --- a/src/libstd/collections/mod.rs +++ b/src/libstd/collections/mod.rs @@ -24,9 +24,9 @@ //! Rust's collections can be grouped into four major categories: //! //! * Sequences: `Vec`, `RingBuf`, `DList`, `BitV` -//! * Maps: `HashMap`, `BTreeMap`, `TreeMap`, `TrieMap`, `SmallIntMap`, `LruCache` +//! * Maps: `HashMap`, `BTreeMap`, `TreeMap`, `TrieMap`, `VecMap`, `LruCache` //! * Sets: `HashSet`, `BTreeSet`, `TreeSet`, `TrieSet`, `BitVSet`, `EnumSet` -//! * Misc: `PriorityQueue` +//! * Misc: `BinaryHeap` //! //! # When Should You Use Which Collection? //! @@ -74,7 +74,7 @@ //! * You want a `HashMap`, but with many potentially large `uint` keys. //! * You want a `BTreeMap`, but with potentially large `uint` keys. //! -//! ### Use a `SmallIntMap` when: +//! ### Use a `VecMap` when: //! * You want a `HashMap` but with known to be small `uint` keys. //! * You want a `BTreeMap`, but with known to be small `uint` keys. //! @@ -88,12 +88,12 @@ //! * You want a bitvector. //! //! ### Use a `BitVSet` when: -//! * You want a `SmallIntSet`. +//! * You want a `VecSet`. //! //! ### Use an `EnumSet` when: //! * You want a C-like enum, stored in a single `uint`. //! -//! ### Use a `PriorityQueue` when: +//! ### Use a `BinaryHeap` when: //! * You want to store a bunch of elements, but only ever want to process the "biggest" //! or "most important" one at any given time. //! * You want a priority queue. @@ -266,7 +266,7 @@ //! #### Counting the number of times each character in a string occurs //! //! ``` -//! use std::collections::btree::{BTreeMap, Occupied, Vacant}; +//! use std::collections::btree_map::{BTreeMap, Occupied, Vacant}; //! //! let mut count = BTreeMap::new(); //! let message = "she sells sea shells by the sea shore"; @@ -293,7 +293,7 @@ //! #### Tracking the inebriation of customers at a bar //! //! ``` -//! use std::collections::btree::{BTreeMap, Occupied, Vacant}; +//! use std::collections::btree_map::{BTreeMap, Occupied, Vacant}; //! //! // A client of the bar. They have an id and a blood alcohol level. //! struct Person { id: u32, blood_alcohol: f32 }; @@ -328,14 +328,27 @@ #![experimental] -pub use core_collections::{Bitv, BitvSet, BTreeMap, BTreeSet, DList, EnumSet}; -pub use core_collections::{PriorityQueue, RingBuf, SmallIntMap}; -pub use core_collections::{TreeMap, TreeSet, TrieMap, TrieSet}; -pub use core_collections::{bitv, btree, dlist, enum_set}; -pub use core_collections::{priority_queue, ringbuf, smallintmap, treemap, trie}; +pub use core_collections::{BinaryHeap, Bitv, BitvSet, BTreeMap, BTreeSet}; +pub use core_collections::{DList, EnumSet, RingBuf}; +pub use core_collections::{TreeMap, TreeSet, TrieMap, TrieSet, VecMap}; -pub use self::hashmap::{HashMap, HashSet}; +pub use core_collections::{binary_heap, bitv, bitv_set, btree_map, btree_set, dlist, enum_set}; +pub use core_collections::{ring_buf, tree_map, tree_set, trie_map, trie_set, vec_map}; + +pub use self::hash_map::HashMap; +pub use self::hash_set::HashSet; pub use self::lru_cache::LruCache; -pub mod hashmap; +mod hash; + +pub mod hash_map { + //! A hashmap + pub use super::hash::map::*; +} + +pub mod hash_set { + //! A hashset + pub use super::hash::set::*; +} + pub mod lru_cache; diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index 840468176ab0310c0c75e5591084e847edcac0a6..bebe16286c97acdc89e8cf18ad879af8bd2d958d 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -20,7 +20,7 @@ use std::cell::RefCell; use std::rc::Rc; use std::collections::HashMap; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map::{Occupied, Vacant}; /// The SCTable contains a table of SyntaxContext_'s. It /// represents a flattened tree structure, to avoid having diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index 2cc694176de5959705d1e854e1bd4532cf07184b..8c184ccbe43a89a09ccfb1a28bd91336f45e7cd9 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -10,8 +10,8 @@ #![allow(missing_docs)] -use std::collections::hashmap; -use std::collections::hashmap::{Occupied, Vacant}; +use std::collections::hash_map; +use std::collections::hash_map::{Occupied, Vacant}; use std::fmt::Show; use std::hash::Hash; use std::io; @@ -440,8 +440,8 @@ pub fn write_boxplot( /// Returns a HashMap with the number of occurrences of every element in the /// sequence that the iterator exposes. -pub fn freq_count, U: Eq+Hash>(mut iter: T) -> hashmap::HashMap { - let mut map: hashmap::HashMap = hashmap::HashMap::new(); +pub fn freq_count, U: Eq+Hash>(mut iter: T) -> hash_map::HashMap { + let mut map: hash_map::HashMap = hash_map::HashMap::new(); for elem in iter { match map.entry(elem) { Occupied(mut entry) => { *entry.get_mut() += 1; }, diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index 4833467922b76abb7040a0a76ff6e9facaaa76e0..8151f2718e35cc1d84cad91b178a90d395d9435a 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -14,7 +14,7 @@ extern crate rand; extern crate time; -use std::collections::bitv::BitvSet; +use std::collections::BitvSet; use std::collections::TreeSet; use std::hash::Hash; use std::collections::HashSet; diff --git a/src/test/bench/std-smallintmap.rs b/src/test/bench/std-smallintmap.rs index 2086980b016fcdbffee1287727937d86145b2ed1..cdcb88d87c6446918c520ce50acf646c4f659804 100644 --- a/src/test/bench/std-smallintmap.rs +++ b/src/test/bench/std-smallintmap.rs @@ -13,17 +13,17 @@ extern crate collections; extern crate time; -use std::collections::SmallIntMap; +use std::collections::VecMap; use std::os; use std::uint; -fn append_sequential(min: uint, max: uint, map: &mut SmallIntMap) { +fn append_sequential(min: uint, max: uint, map: &mut VecMap) { for i in range(min, max) { map.insert(i, i + 22u); } } -fn check_sequential(min: uint, max: uint, map: &SmallIntMap) { +fn check_sequential(min: uint, max: uint, map: &VecMap) { for i in range(min, max) { assert_eq!(map[i], i + 22u); } @@ -45,7 +45,7 @@ fn main() { let mut appendf = 0.0; for _ in range(0u, rep) { - let mut map = SmallIntMap::new(); + let mut map = VecMap::new(); let start = time::precise_time_s(); append_sequential(0u, max, &mut map); let mid = time::precise_time_s(); diff --git a/src/test/run-fail/hashmap-capacity-overflow.rs b/src/test/run-fail/hashmap-capacity-overflow.rs index f68b511d0aa0ddc7b9df6ed23ecea27dcf5cfa33..c86f8a38f63c409f32eeb4885a17da54050f398e 100644 --- a/src/test/run-fail/hashmap-capacity-overflow.rs +++ b/src/test/run-fail/hashmap-capacity-overflow.rs @@ -10,7 +10,7 @@ // error-pattern:capacity overflow -use std::collections::hashmap::HashMap; +use std::collections::hash_map::HashMap; use std::uint; use std::mem::size_of; diff --git a/src/test/run-pass/auto-encode.rs b/src/test/run-pass/auto-encode.rs index 10c3df9388a011f05c105ed4bf8f7f7e7cfd31ba..44006a0039abd31df57562d47f9e9e283f849a38 100644 --- a/src/test/run-pass/auto-encode.rs +++ b/src/test/run-pass/auto-encode.rs @@ -17,7 +17,7 @@ // These tests used to be separate files, but I wanted to refactor all // the common code. -use std::hashmap::{HashMap, HashSet}; +use std::collections::{HashMap, HashSet}; use rbml::reader as EBReader; use rbml::writer as EBWriter; diff --git a/src/test/run-pass/while-let.rs b/src/test/run-pass/while-let.rs index 41f54d47ad42c2771655c7c40a08e2901807c9e8..449b3099dfa4dd2e2973e25ee63062845e406218 100644 --- a/src/test/run-pass/while-let.rs +++ b/src/test/run-pass/while-let.rs @@ -10,10 +10,10 @@ #![feature(while_let)] -use std::collections::PriorityQueue; +use std::collections::BinaryHeap; -fn make_pq() -> PriorityQueue { - PriorityQueue::from_vec(vec![1i,2,3]) +fn make_pq() -> BinaryHeap { + BinaryHeap::from_vec(vec![1i,2,3]) } pub fn main() {