Skip to content

Commit

Permalink
Move std::{trie, hashmap} to libcollections
Browse files Browse the repository at this point in the history
These two containers are indeed collections, so their place is in
libcollections, not in libstd. There will always be a hash map as part of the
standard distribution of Rust, but by moving it out of the standard library it
makes libstd that much more portable to more platforms and environments.

This conveniently also removes the stuttering of 'std::hashmap::HashMap',
although 'collections::HashMap' is only one character shorter.
  • Loading branch information
alexcrichton committed Feb 23, 2014
1 parent edf351e commit 2a14e08
Show file tree
Hide file tree
Showing 109 changed files with 448 additions and 436 deletions.
2 changes: 1 addition & 1 deletion mk/crates.mk
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ DEPS_flate := std native:miniz
DEPS_arena := std collections
DEPS_glob := std
DEPS_serialize := std
DEPS_term := std
DEPS_term := std collections
DEPS_semver := std
DEPS_uuid := std serialize
DEPS_sync := std
Expand Down
2 changes: 1 addition & 1 deletion src/doc/rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ expression context, the final namespace qualifier is omitted.
Two examples of paths with type arguments:

~~~~
# use std::hashmap::HashMap;
# struct HashMap<K, V>;
# fn f() {
# fn id<T>(t: T) -> T { t }
type T = HashMap<int,~str>; // Type arguments used in a type expression
Expand Down
5 changes: 3 additions & 2 deletions src/doc/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -1977,8 +1977,8 @@ illegal to copy and pass by value.
Generic `type`, `struct`, and `enum` declarations follow the same pattern:
~~~~
use std::hashmap::HashMap;
type Set<T> = HashMap<T, ()>;
extern crate collections;
type Set<T> = collections::HashMap<T, ()>;
struct Stack<T> {
elements: ~[T]
Expand All @@ -1988,6 +1988,7 @@ enum Option<T> {
Some(T),
None
}
# fn main() {}
~~~~
These declarations can be instantiated to valid types like `Set<int>`,
Expand Down
2 changes: 2 additions & 0 deletions src/etc/combine-tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ def scrub(b):
#[crate_id=\"run_pass_stage2#0.1\"];
#[feature(globs, macro_rules, struct_variant, managed_boxes)];
#[allow(warnings)];
extern crate collections;
extern crate extra;
"""
)
for t in stage2_tests:
Expand Down
156 changes: 129 additions & 27 deletions src/libstd/hashmap.rs → src/libcollections/hashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//! # Example
//!
//! ```rust
//! use std::hashmap::HashMap;
//! use collections::HashMap;
//!
//! // type inference lets us omit an explicit type signature (which
//! // would be `HashMap<&str, &str>` in this example).
Expand Down Expand Up @@ -52,24 +52,20 @@
//! }
//! ```
use container::{Container, Mutable, Map, MutableMap, Set, MutableSet};
use clone::Clone;
use cmp::{Eq, Equiv, max};
use default::Default;
use fmt;
use hash_old::Hash;
use iter;
use iter::{Iterator, FromIterator, Extendable};
use iter::{FilterMap, Chain, Repeat, Zip};
use mem::replace;
use num;
use option::{None, Option, Some};
use rand::Rng;
use rand;
use result::{Ok, Err};
use vec::{ImmutableVector, MutableVector, OwnedVector, Items, MutItems};
use vec_ng;
use vec_ng::Vec;
use std::cmp::max;
use std::fmt;
use std::hash_old::Hash;
use std::iter::{FilterMap, Chain, Repeat, Zip};
use std::iter;
use std::mem::replace;
use std::num;
use std::rand::Rng;
use std::rand;
use std::vec::{Items, MutItems};
use std::vec_ng::Vec;
use std::vec_ng;

use serialize::{Encodable, Decodable, Encoder, Decoder};

static INITIAL_CAPACITY: uint = 32u; // 2^5

Expand Down Expand Up @@ -404,7 +400,7 @@ impl<K: Hash + Eq, V> HashMap<K, V> {
/// # Example
///
/// ```rust
/// use std::hashmap::HashMap;
/// use collections::HashMap;
///
/// // map some strings to vectors of strings
/// let mut map = HashMap::<~str, ~[~str]>::new();
Expand Down Expand Up @@ -613,6 +609,10 @@ impl<A: fmt::Show + Hash + Eq, B: fmt::Show> fmt::Show for HashMap<A, B> {
}
}

impl<K: fmt::Show + Hash + Eq, V: fmt::Show> ToStr for HashMap<K, V> {
fn to_str(&self) -> ~str { format!("{}", *self) }
}

/// HashMap iterator
#[deriving(Clone)]
pub struct Entries<'a, K, V> {
Expand Down Expand Up @@ -891,6 +891,10 @@ impl<A: fmt::Show + Hash + Eq> fmt::Show for HashSet<A> {
}
}

impl<A: fmt::Show + Hash + Eq> ToStr for HashSet<A> {
fn to_str(&self) -> ~str { format!("{}", *self) }
}

impl<K: Eq + Hash> FromIterator<K> for HashSet<K> {
fn from_iterator<T: Iterator<K>>(iter: &mut T) -> HashSet<K> {
let (lower, _) = iter.size_hint();
Expand Down Expand Up @@ -919,12 +923,75 @@ pub type SetAlgebraItems<'a, T> =
FilterMap<'static,(&'a HashSet<T>, &'a T), &'a T,
Zip<Repeat<&'a HashSet<T>>,SetItems<'a,T>>>;

impl<
E: Encoder,
K: Encodable<E> + Hash + IterBytes + Eq,
V: Encodable<E>
> Encodable<E> for HashMap<K, V> {
fn encode(&self, e: &mut E) {
e.emit_map(self.len(), |e| {
let mut i = 0;
for (key, val) in self.iter() {
e.emit_map_elt_key(i, |e| key.encode(e));
e.emit_map_elt_val(i, |e| val.encode(e));
i += 1;
}
})
}
}

impl<
D: Decoder,
K: Decodable<D> + Hash + IterBytes + Eq,
V: Decodable<D>
> Decodable<D> for HashMap<K, V> {
fn decode(d: &mut D) -> HashMap<K, V> {
d.read_map(|d, len| {
let mut map = HashMap::with_capacity(len);
for i in range(0u, len) {
let key = d.read_map_elt_key(i, |d| Decodable::decode(d));
let val = d.read_map_elt_val(i, |d| Decodable::decode(d));
map.insert(key, val);
}
map
})
}
}

impl<
S: Encoder,
T: Encodable<S> + Hash + IterBytes + Eq
> Encodable<S> for HashSet<T> {
fn encode(&self, s: &mut S) {
s.emit_seq(self.len(), |s| {
let mut i = 0;
for e in self.iter() {
s.emit_seq_elt(i, |s| e.encode(s));
i += 1;
}
})
}
}

impl<
D: Decoder,
T: Decodable<D> + Hash + IterBytes + Eq
> Decodable<D> for HashSet<T> {
fn decode(d: &mut D) -> HashSet<T> {
d.read_seq(|d, len| {
let mut set = HashSet::with_capacity(len);
for i in range(0u, len) {
set.insert(d.read_seq_elt(i, |d| Decodable::decode(d)));
}
set
})
}
}

#[cfg(test)]
mod test_map {
use prelude::*;
use super::*;
use fmt;
use super::{HashMap, HashSet};
use std::fmt;

#[test]
fn test_create_capacity_zero() {
Expand Down Expand Up @@ -1180,14 +1247,49 @@ mod test_map {
assert!(table_str == ~"{1: s2, 3: s4}" || table_str == ~"{3: s4, 1: s2}");
assert_eq!(format!("{}", empty), ~"{}");
}
struct StructWithToStrWithoutEqOrHash {
value: int
}
impl fmt::Show for StructWithToStrWithoutEqOrHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "s{}", self.value)
}
}
#[test]
fn test_hashset() {
let mut set: HashSet<int> = HashSet::new();
let empty_set: HashSet<int> = HashSet::new();
set.insert(1);
set.insert(2);
let set_str = set.to_str();
assert!(set_str == ~"{1, 2}" || set_str == ~"{2, 1}");
assert_eq!(empty_set.to_str(), ~"{}");
}
#[test]
fn test_hashmap() {
let mut table: HashMap<int, StructWithToStrWithoutEqOrHash> = HashMap::new();
let empty: HashMap<int, StructWithToStrWithoutEqOrHash> = HashMap::new();
table.insert(3, StructWithToStrWithoutEqOrHash { value: 4 });
table.insert(1, StructWithToStrWithoutEqOrHash { value: 2 });
let table_str = table.to_str();
assert!(table_str == ~"{1: s2, 3: s4}" || table_str == ~"{3: s4, 1: s2}");
assert_eq!(empty.to_str(), ~"{}");
}
}
#[cfg(test)]
mod test_set {
use super::*;
use prelude::*;
use container::Container;
use vec::ImmutableEqVector;
use super::HashSet;
#[test]
fn test_disjoint() {
Expand Down
4 changes: 4 additions & 0 deletions src/libcollections/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,25 @@ pub use btree::BTree;
pub use deque::Deque;
pub use dlist::DList;
pub use enum_set::EnumSet;
pub use hashmap::{HashMap, HashSet};
pub use list::List;
pub use lru_cache::LruCache;
pub use priority_queue::PriorityQueue;
pub use ringbuf::RingBuf;
pub use smallintmap::SmallIntMap;
pub use treemap::{TreeMap, TreeSet};
pub use trie::{TrieMap, TrieSet};

pub mod bitv;
pub mod btree;
pub mod deque;
pub mod dlist;
pub mod enum_set;
pub mod hashmap;
pub mod list;
pub mod lru_cache;
pub mod priority_queue;
pub mod ringbuf;
pub mod smallintmap;
pub mod treemap;
pub mod trie;
3 changes: 2 additions & 1 deletion src/libcollections/lru_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,12 @@
//! ```
use std::container::Container;
use std::hashmap::HashMap;
use std::to_bytes::Cb;
use std::ptr;
use std::cast;

use HashMap;

struct KeyRef<K> { k: *K }

struct LruEntry<K, V> {
Expand Down
Loading

5 comments on commit 2a14e08

@bors
Copy link
Contributor

@bors bors commented on 2a14e08 Feb 23, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

saw approval from brson
at alexcrichton@2a14e08

@bors
Copy link
Contributor

@bors bors commented on 2a14e08 Feb 23, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merging alexcrichton/rust/move-hashmap = 2a14e08 into auto

@bors
Copy link
Contributor

@bors bors commented on 2a14e08 Feb 23, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alexcrichton/rust/move-hashmap = 2a14e08 merged ok, testing candidate = c250c16

@bors
Copy link
Contributor

@bors bors commented on 2a14e08 Feb 23, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bors
Copy link
Contributor

@bors bors commented on 2a14e08 Feb 23, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fast-forwarding master to auto = c250c16

Please sign in to comment.