auto merge of #14538 : alexcrichton/rust/libcollections, r=brson

As with the previous commit with `librand`, this commit shuffles around some
`collections` code. The new state of the world is similar to that of librand:

* The libcollections crate now only depends on libcore and liballoc.
* The standard library has a new module, `std::collections`. All functionality
  of libcollections is reexported through this module.

I would like to stress that this change is purely cosmetic. There are very few
alterations to these primitives.

There are a number of notable points about the new organization:

* std::{str, slice, string, vec} all moved to libcollections. There is no reason
  that these primitives shouldn't be necessarily usable in a freestanding
  context that has allocation. These are all reexported in their usual places in
  the standard library.

* The `hashmap`, and transitively the `lru_cache`, modules no longer reside in
  `libcollections`, but rather in libstd. The reason for this is because the
  `HashMap::new` contructor requires access to the OSRng for initially seeding
  the hash map. Beyond this requirement, there is no reason that the hashmap
  could not move to libcollections.

  I do, however, have a plan to move the hash map to the collections module. The
  `HashMap::new` function could be altered to require that the `H` hasher
  parameter ascribe to the `Default` trait, allowing the entire `hashmap` module
  to live in libcollections. The key idea would be that the default hasher would
  be different in libstd. Something along the lines of:

      // src/libstd/collections/mod.rs

      pub type HashMap<K, V, H = RandomizedSipHasher> =
            core_collections::HashMap<K, V, H>;

  This is not possible today because you cannot invoke static methods through
  type aliases. If we modified the compiler, however, to allow invocation of
  static methods through type aliases, then this type definition would
  essentially be switching the default hasher from `SipHasher` in libcollections
  to a libstd-defined `RandomizedSipHasher` type. This type's `Default`
  implementation would randomly seed the `SipHasher` instance, and otherwise
  perform the same as `SipHasher`.

  This future state doesn't seem incredibly far off, but until that time comes,
  the hashmap module will live in libstd to not compromise on functionality.

* In preparation for the hashmap moving to libcollections, the `hash` module has
  moved from libstd to libcollections. A previously snapshotted commit enables a
  distinct `Writer` trait to live in the `hash` module which `Hash`
  implementations are now parameterized over.

  Due to using a custom trait, the `SipHasher` implementation has lost its
  specialized methods for writing integers. These can be re-added
  backwards-compatibly in the future via default methods if necessary, but the
  FNV hashing should satisfy much of the need for speedier hashing.

A list of breaking changes:

* HashMap::{get, get_mut} no longer fails with the key formatted into the error
  message with `{:?}`, instead, a generic message is printed. With backtraces,
  it should still be not-too-hard to track down errors.

* The HashMap, HashSet, and LruCache types are now available through
  std::collections instead of the collections crate.

* Manual implementations of hash should be parameterized over `hash::Writer`
  instead of just `Writer`.

[breaking-change]
This commit is contained in:
bors 2014-06-05 15:01:54 -07:00
commit ba3ba002d5
141 changed files with 714 additions and 697 deletions

View File

@ -60,36 +60,36 @@ DEPS_core :=
DEPS_rlibc :=
DEPS_alloc := core libc native:jemalloc
DEPS_debug := std
DEPS_std := core rand libc alloc native:rustrt native:backtrace
DEPS_std := core rand libc alloc collections native:rustrt native:backtrace
DEPS_graphviz := std
DEPS_green := std native:context_switch
DEPS_rustuv := std native:uv native:uv_support
DEPS_native := std
DEPS_syntax := std term serialize collections log fmt_macros debug
DEPS_syntax := std term serialize log fmt_macros debug
DEPS_rustc := syntax native:rustllvm flate arena serialize sync getopts \
collections time log graphviz debug
DEPS_rustdoc := rustc native:hoedown serialize sync getopts collections \
time log graphviz debug
DEPS_rustdoc := rustc native:hoedown serialize sync getopts \
test time debug
DEPS_flate := std native:miniz
DEPS_arena := std collections
DEPS_arena := std
DEPS_graphviz := std
DEPS_glob := std
DEPS_serialize := std collections log
DEPS_term := std collections log
DEPS_serialize := std log
DEPS_term := std log
DEPS_semver := std
DEPS_uuid := std serialize
DEPS_sync := std alloc
DEPS_getopts := std
DEPS_collections := std debug
DEPS_collections := core alloc
DEPS_fourcc := syntax std
DEPS_hexfloat := syntax std
DEPS_num := std
DEPS_test := std collections getopts serialize term time regex
DEPS_test := std getopts serialize term time regex
DEPS_time := std serialize sync
DEPS_rand := core
DEPS_url := std collections
DEPS_url := std
DEPS_log := std sync
DEPS_regex := std collections
DEPS_regex := std
DEPS_regex_macros = syntax std regex
DEPS_fmt_macros = std
@ -105,6 +105,7 @@ ONLY_RLIB_libc := 1
ONLY_RLIB_rlibc := 1
ONLY_RLIB_alloc := 1
ONLY_RLIB_rand := 1
ONLY_RLIB_collections := 1
################################################################################
# You should not need to edit below this line

View File

@ -2058,8 +2058,7 @@ illegal to copy and pass by value.
Generic `type`, `struct`, and `enum` declarations follow the same pattern:
~~~~
extern crate collections;
type Set<T> = collections::HashMap<T, ()>;
type Set<T> = std::collections::HashMap<T, ()>;
struct Stack<T> {
elements: Vec<T>

View File

@ -28,8 +28,6 @@
html_root_url = "http://doc.rust-lang.org/")]
#![allow(missing_doc)]
extern crate collections;
use std::cell::{Cell, RefCell};
use std::cmp;
use std::intrinsics::{TyDesc, get_tydesc};

View File

@ -10,14 +10,16 @@
#![allow(missing_doc)]
use core::prelude::*;
use std::cmp;
use std::fmt;
use std::iter::RandomAccessIterator;
use std::iter::{Enumerate, Repeat, Map, Zip};
use std::ops;
use std::slice;
use std::uint;
use core::cmp;
use core::fmt;
use core::iter::{Enumerate, Repeat, Map, Zip};
use core::ops;
use core::slice;
use core::uint;
use vec::Vec;
#[deriving(Clone)]
struct SmallBitv {
@ -977,26 +979,26 @@ impl<'a> Iterator<uint> for BitPositions<'a> {
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use std::prelude::*;
use std::uint;
use std::rand;
use std::rand::Rng;
use test::Bencher;
use bitv::{Bitv, SmallBitv, BigBitv, BitvSet, from_bools, from_fn,
from_bytes};
use bitv;
use std::uint;
use std::rand;
use std::rand::Rng;
use vec::Vec;
static BENCH_BITS : uint = 1 << 14;
#[test]
fn test_to_str() {
let zerolen = Bitv::new(0u, false);
assert_eq!(zerolen.to_str(), "".to_string());
assert_eq!(zerolen.to_str().as_slice(), "");
let eightbits = Bitv::new(8u, false);
assert_eq!(eightbits.to_str(), "00000000".to_string());
assert_eq!(eightbits.to_str().as_slice(), "00000000")
}
#[test]
@ -1019,7 +1021,7 @@ mod tests {
let mut b = bitv::Bitv::new(2, false);
b.set(0, true);
b.set(1, false);
assert_eq!(b.to_str(), "10".to_string());
assert_eq!(b.to_str().as_slice(), "10");
}
#[test]
@ -1330,7 +1332,7 @@ mod tests {
fn test_from_bytes() {
let bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]);
let str = format!("{}{}{}", "10110110", "00000000", "11111111");
assert_eq!(bitv.to_str(), str);
assert_eq!(bitv.to_str().as_slice(), str.as_slice());
}
#[test]
@ -1347,8 +1349,8 @@ mod tests {
#[test]
fn test_from_bools() {
assert!(from_bools([true, false, true, true]).to_str() ==
"1011".to_string());
assert!(from_bools([true, false, true, true]).to_str().as_slice() ==
"1011");
}
#[test]

View File

@ -18,8 +18,13 @@
///a length (the height of the tree), and lower and upper bounds on the
///number of elements that a given node can contain.
use std::fmt;
use std::fmt::Show;
use core::prelude::*;
use alloc::owned::Box;
use core::fmt;
use core::fmt::Show;
use vec::Vec;
#[allow(missing_doc)]
pub struct BTree<K, V> {
@ -772,6 +777,7 @@ impl<K: fmt::Show + Ord, V: fmt::Show> fmt::Show for BranchElt<K, V> {
#[cfg(test)]
mod test_btree {
use std::prelude::*;
use super::{BTree, Node, LeafElt};

View File

@ -10,7 +10,7 @@
//! Container traits for collections
use std::container::Mutable;
use core::prelude::*;
/// A double-ended sequence that allows querying, insertion and deletion at both ends.
pub trait Deque<T> : Mutable {
@ -41,11 +41,10 @@ pub trait Deque<T> : Mutable {
#[cfg(test)]
pub mod bench {
extern crate test;
use self::test::Bencher;
use std::container::MutableMap;
use std::prelude::*;
use std::rand;
use std::rand::Rng;
use test::Bencher;
pub fn insert_rand_n<M:MutableMap<uint,uint>>(n: uint,
map: &mut M,

View File

@ -21,9 +21,12 @@
// Backlinks over DList::prev are raw pointers that form a full chain in
// the reverse direction.
use std::iter;
use std::mem;
use std::ptr;
use core::prelude::*;
use alloc::owned::Box;
use core::iter;
use core::mem;
use core::ptr;
use deque::Deque;
@ -607,11 +610,14 @@ impl<A: Clone> Clone for DList<A> {
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use deque::Deque;
use std::prelude::*;
use std::rand;
use test::Bencher;
use test;
use deque::Deque;
use super::{DList, Node, ListInsertion};
use vec::Vec;
pub fn check_links<T>(list: &DList<T>) {
let mut len = 0u;

View File

@ -13,7 +13,9 @@
//! This module defines a container which uses an efficient bit mask
//! representation to hold C-like enum variants.
use std::num::Bitwise;
use core::prelude::*;
use core::num::Bitwise;
#[deriving(Clone, PartialEq, Eq, Hash, Show)]
/// A specialized Set implementation to use enum types.
@ -136,7 +138,7 @@ impl<E:CLike> Iterator<E> for Items<E> {
#[cfg(test)]
mod test {
use std::prelude::*;
use std::mem;
use enum_set::{EnumSet, CLike};

View File

@ -63,22 +63,18 @@
#![allow(unused_must_use)]
use container::Container;
use intrinsics::TypeId;
use iter::Iterator;
use option::{Option, Some, None};
use owned::Box;
use rc::Rc;
use result::{Result, Ok, Err};
use slice::{Vector, ImmutableVector};
use str::{Str, StrSlice};
use core::prelude::*;
use alloc::owned::Box;
use alloc::rc::Rc;
use core::intrinsics::TypeId;
use core::mem;
use vec::Vec;
/// Reexport the `sip::hash` function as our default hasher.
pub use hash = self::sip::hash;
pub use Writer = io::Writer;
pub mod sip;
/// A trait that represents a hashable type. The `S` type parameter is an
@ -96,15 +92,24 @@ pub trait Hasher<S> {
fn hash<T: Hash<S>>(&self, value: &T) -> u64;
}
pub trait Writer {
fn write(&mut self, bytes: &[u8]);
}
//////////////////////////////////////////////////////////////////////////////
fn id<T>(t: T) -> T { t }
macro_rules! impl_hash(
( $( $ty:ty => $method:ident;)* ) => (
( $($ty:ident, $uty:ident, $f:path;)* ) => (
$(
impl<S: Writer> Hash<S> for $ty {
#[inline]
fn hash(&self, state: &mut S) {
state.$method(*self);
let a: [u8, ..::core::$ty::BYTES] = unsafe {
mem::transmute($f(*self as $uty) as $ty)
};
state.write(a.as_slice())
}
}
)*
@ -112,16 +117,26 @@ macro_rules! impl_hash(
)
impl_hash!(
u8 => write_u8;
u16 => write_le_u16;
u32 => write_le_u32;
u64 => write_le_u64;
uint => write_le_uint;
i8 => write_i8;
i16 => write_le_i16;
i32 => write_le_i32;
i64 => write_le_i64;
int => write_le_int;
u8, u8, id;
u16, u16, mem::to_le16;
u32, u32, mem::to_le32;
u64, u64, mem::to_le64;
i8, u8, id;
i16, u16, mem::to_le16;
i32, u32, mem::to_le32;
i64, u64, mem::to_le64;
)
#[cfg(target_word_size = "32")]
impl_hash!(
uint, u32, mem::to_le32;
int, u32, mem::to_le32;
)
#[cfg(target_word_size = "64")]
impl_hash!(
uint, u64, mem::to_le64;
int, u64, mem::to_le64;
)
impl<S: Writer> Hash<S> for bool {
@ -142,7 +157,7 @@ impl<'a, S: Writer> Hash<S> for &'a str {
#[inline]
fn hash(&self, state: &mut S) {
state.write(self.as_bytes());
state.write_u8(0xFF);
0xffu8.hash(state)
}
}
@ -301,14 +316,11 @@ impl<S: Writer, T: Hash<S>, U: Hash<S>> Hash<S> for Result<T, U> {
#[cfg(test)]
mod tests {
use mem;
use io::{IoResult, Writer};
use iter::{Iterator};
use option::{Some, None};
use result::Ok;
use slice::ImmutableVector;
use std::prelude::*;
use std::mem;
use super::{Hash, Hasher};
use slice::ImmutableVector;
use super::{Hash, Hasher, Writer};
struct MyWriterHasher;
@ -326,11 +338,10 @@ mod tests {
impl Writer for MyWriter {
// Most things we'll just add up the bytes.
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
fn write(&mut self, buf: &[u8]) {
for byte in buf.iter() {
self.hash += *byte as u64;
}
Ok(())
}
}

View File

@ -24,17 +24,11 @@
* discouraged.
*/
use clone::Clone;
use container::Container;
use default::Default;
use int;
use io::{IoResult, Writer};
use iter::Iterator;
use result::Ok;
use slice::ImmutableVector;
use uint;
use core::prelude::*;
use super::{Hash, Hasher};
use core::default::Default;
use super::{Hash, Hasher, Writer};
/// `SipState` computes a SipHash 2-4 hash over a stream of bytes.
pub struct SipState {
@ -151,41 +145,11 @@ impl SipState {
v0 ^ v1 ^ v2 ^ v3
}
#[inline]
fn write_le(&mut self, n: u64, size: uint) {
self.tail |= n << 8*self.ntail;
self.ntail += size;
if self.ntail >= 8 {
let m = self.tail;
self.v3 ^= m;
compress!(self.v0, self.v1, self.v2, self.v3);
compress!(self.v0, self.v1, self.v2, self.v3);
self.v0 ^= m;
self.ntail -= 8;
if self.ntail == 0 {
self.tail = 0;
} else {
self.tail = n >> 64 - 8*self.ntail;
}
}
}
}
macro_rules! make_write_le(
($this:expr, $n:expr, $size:expr) => ({
$this.write_le($n as u64, $size);
$this.length += $size;
Ok(())
})
)
impl Writer for SipState {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> {
fn write(&mut self, msg: &[u8]) {
let length = msg.len();
self.length += length;
@ -196,7 +160,7 @@ impl Writer for SipState {
if length < needed {
self.tail |= u8to64_le!(msg, 0, length) << 8*self.ntail;
self.ntail += length;
return Ok(());
return
}
let m = self.tail | u8to64_le!(msg, 0, needed) << 8*self.ntail;
@ -228,60 +192,7 @@ impl Writer for SipState {
self.tail = u8to64_le!(msg, i, left);
self.ntail = left;
Ok(())
}
#[inline]
fn write_u8(&mut self, n: u8) -> IoResult<()> {
make_write_le!(self, n, 1)
}
#[inline]
fn write_le_u16(&mut self, n: u16) -> IoResult<()> {
make_write_le!(self, n, 2)
}
#[inline]
fn write_le_u32(&mut self, n: u32) -> IoResult<()> {
make_write_le!(self, n, 4)
}
#[inline]
fn write_le_u64(&mut self, n: u64) -> IoResult<()> {
make_write_le!(self, n, 8)
}
#[inline]
fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
make_write_le!(self, n, uint::BYTES)
}
#[inline]
fn write_i8(&mut self, n: i8) -> IoResult<()> {
make_write_le!(self, n, 1)
}
#[inline]
fn write_le_i16(&mut self, n: i16) -> IoResult<()> {
make_write_le!(self, n, 2)
}
#[inline]
fn write_le_i32(&mut self, n: i32) -> IoResult<()> {
make_write_le!(self, n, 4)
}
#[inline]
fn write_le_i64(&mut self, n: i64) -> IoResult<()> {
make_write_le!(self, n, 8)
}
#[inline]
fn write_le_int(&mut self, n: int) -> IoResult<()> {
make_write_le!(self, n, int::BYTES)
}
}
impl Clone for SipState {
@ -358,16 +269,15 @@ pub fn hash_with_keys<T: Hash<SipState>>(k0: u64, k1: u64, value: &T) -> u64 {
#[cfg(test)]
mod tests {
extern crate test;
use prelude::*;
use num::ToStrRadix;
use option::{Some, None};
use test::Bencher;
use std::prelude::*;
use std::num::ToStrRadix;
use str::Str;
use string::String;
use slice::{Vector, ImmutableVector};
use self::test::Bencher;
use super::super::Hash;
use super::super::{Hash, Writer};
use super::{SipState, hash, hash_with_keys};
// Hash just the bytes of the slice, without length prefix
@ -488,7 +398,7 @@ mod tests {
}
while t < 64 {
debug!("siphash test {}", t);
debug!("siphash test {}: {}", t, buf);
let vec = u8to64_le!(vecs[t], 0);
let out = hash_with_keys(k0, k1, &Bytes(buf.as_slice()));
debug!("got {:?}, expected {:?}", out, vec);
@ -501,10 +411,14 @@ mod tests {
let v = to_hex_str(&vecs[t]);
debug!("{}: ({}) => inc={} full={}", t, v, i, f);
assert!(f == i && f == v);
debug!("full state {:?}", state_full);
debug!("inc state {:?}", state_inc);
assert_eq!(f, i);
assert_eq!(f, v);
buf.push(t as u8);
state_inc.write_u8(t as u8);
state_inc.write([t as u8]);
t += 1;
}
@ -631,21 +545,4 @@ officia deserunt mollit anim id est laborum.";
assert_eq!(hash(&u), 5254097107239593357);
})
}
#[deriving(Hash)]
struct Compound {
x: u8,
y: u64,
}
#[bench]
fn bench_compound_1(b: &mut Bencher) {
let compound = Compound {
x: 1,
y: 2,
};
b.iter(|| {
assert_eq!(hash(&compound), 12506681940457338191);
})
}
}

View File

@ -14,43 +14,68 @@
#![crate_id = "collections#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/")]
#![feature(macro_rules, managed_boxes, default_type_params, phase)]
#![feature(macro_rules, managed_boxes, default_type_params, phase, globs)]
#![no_std]
#![deny(deprecated_owned_vector)]
extern crate debug;
#[phase(syntax, link)] extern crate core;
extern crate alloc;
#[cfg(test)] extern crate native;
#[cfg(test)] extern crate test;
#[cfg(test)] extern crate debug;
#[cfg(test)] #[phase(syntax, link)] extern crate std;
#[cfg(test)] #[phase(syntax, link)] extern crate log;
pub use bitv::Bitv;
pub use bitv::{Bitv, BitvSet};
pub use btree::BTree;
pub use deque::Deque;
pub use dlist::DList;
pub use enum_set::EnumSet;
pub use hashmap::{HashMap, HashSet};
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};
mod macros;
pub mod bitv;
pub mod btree;
pub mod deque;
pub mod dlist;
pub mod enum_set;
pub mod hashmap;
pub mod lru_cache;
pub mod priority_queue;
pub mod ringbuf;
pub mod smallintmap;
pub mod treemap;
pub mod trie;
pub mod slice;
pub mod str;
pub mod string;
pub mod vec;
pub mod hash;
// Internal unicode fiddly bits for the str module
mod unicode;
// FIXME(#14008) should this actually exist, or should a method be added?
fn expect<T>(a: core::option::Option<T>, b: &str) -> T {
match a {
core::option::Some(a) => a,
core::option::None => fail!("{}", b),
}
}
#[cfg(not(test))]
mod std {
pub use core::fmt; // necessary for fail!()
pub use core::option; // necessary for fail!()
pub use core::clone; // deriving(Clone)
pub use core::cmp; // deriving(Eq, Ord, etc.)
pub use hash; // deriving(Hash)
}

View File

@ -0,0 +1,22 @@
// 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![macro_escape]
/// Create a `std::vec::Vec` containing the arguments.
macro_rules! vec(
($($e:expr),*) => ({
// leading _ to allow empty construction without a warning.
let mut _temp = ::vec::Vec::new();
$(_temp.push($e);)*
_temp
});
($($e:expr),+,) => (vec!($($e),+))
)

View File

@ -12,10 +12,13 @@
#![allow(missing_doc)]
use std::clone::Clone;
use std::mem::{zeroed, replace, swap};
use std::ptr;
use std::slice;
use core::prelude::*;
use core::mem::{zeroed, replace, swap};
use core::ptr;
use slice;
use vec::Vec;
/// A priority queue implemented with a binary heap
#[deriving(Clone)]
@ -238,7 +241,10 @@ impl<T: Ord> Extendable<T> for PriorityQueue<T> {
#[cfg(test)]
mod tests {
use std::prelude::*;
use priority_queue::PriorityQueue;
use vec::Vec;
#[test]
fn test_iterator() {
@ -342,8 +348,8 @@ mod tests {
v.sort();
data.sort();
assert_eq!(v, data);
assert_eq!(heap.into_sorted_vec(), data);
assert_eq!(v.as_slice(), data.as_slice());
assert_eq!(heap.into_sorted_vec().as_slice(), data.as_slice());
}
#[test]

View File

@ -13,12 +13,14 @@
//! RingBuf implements the trait Deque. It should be imported with `use
//! collections::deque::Deque`.
use std::cmp;
use std::fmt;
use std::fmt::Show;
use std::iter::RandomAccessIterator;
use core::prelude::*;
use core::cmp;
use core::fmt;
use core::iter::RandomAccessIterator;
use deque::Deque;
use vec::Vec;
static INITIAL_CAPACITY: uint = 8u; // 2^3
static MINIMUM_CAPACITY: uint = 2u;
@ -393,7 +395,7 @@ impl<A> Extendable<A> for RingBuf<A> {
}
}
impl<T: Show> Show for RingBuf<T> {
impl<T: fmt::Show> fmt::Show for RingBuf<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "["));
@ -408,13 +410,14 @@ impl<T: Show> Show for RingBuf<T> {
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use deque::Deque;
use std::clone::Clone;
use std::cmp::PartialEq;
use std::fmt::Show;
use std::prelude::*;
use test::Bencher;
use test;
use deque::Deque;
use super::RingBuf;
use vec::Vec;
#[test]
fn test_simple() {

View File

@ -99,20 +99,16 @@ There are a number of free functions that create or take vectors, for example:
#![doc(primitive = "slice")]
use mem::transmute;
use clone::Clone;
use cmp::{Ord, Ordering, Less, Greater};
use cmp;
use container::Container;
use iter::*;
use mem::size_of;
use mem;
use ops::Drop;
use option::{None, Option, Some};
use ptr::RawPtr;
use ptr;
use rt::heap::{allocate, deallocate};
use finally::try_finally;
use core::prelude::*;
use alloc::heap::{allocate, deallocate};
use core::cmp;
use core::finally::try_finally;
use core::mem::size_of;
use core::mem::transmute;
use core::mem;
use core::ptr;
use core::iter::{range_step, MultiplicativeIterator};
use vec::Vec;
pub use core::slice::{ref_slice, mut_ref_slice, Splits, Windows};
@ -295,13 +291,14 @@ impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
#[inline]
fn to_owned(&self) -> ~[T] {
use RawVec = core::raw::Vec;
use num::{CheckedAdd, CheckedMul};
use core::num::{CheckedAdd, CheckedMul};
use core::ptr;
let len = self.len();
let data_size = len.checked_mul(&mem::size_of::<T>());
let data_size = data_size.expect("overflow in to_owned()");
let data_size = ::expect(data_size, "overflow in to_owned()");
let size = mem::size_of::<RawVec<()>>().checked_add(&data_size);
let size = size.expect("overflow in to_owned()");
let size = ::expect(size, "overflow in to_owned()");
unsafe {
// this should pass the real required alignment
@ -321,7 +318,7 @@ impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
try_finally(
&mut i, (),
|i, ()| while *i < len {
mem::overwrite(
ptr::write(
&mut(*p.offset(*i as int)),
self.unsafe_ref(*i).clone());
*i += 1;
@ -859,13 +856,17 @@ impl<T> Drop for MoveItems<T> {
#[cfg(test)]
mod tests {
use prelude::*;
use cmp::*;
use mem;
use owned::Box;
use rand::{Rng, task_rng};
use std::cell::Cell;
use std::default::Default;
use std::mem;
use std::prelude::*;
use std::rand::{Rng, task_rng};
use std::rc::Rc;
use std::unstable;
use slice::*;
use vec::Vec;
fn square(n: uint) -> uint { n * n }
fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
@ -1103,9 +1104,9 @@ mod tests {
#[test]
fn test_swap_remove_noncopyable() {
// Tests that we don't accidentally run destructors twice.
let mut v = vec![::unstable::sync::Exclusive::new(()),
::unstable::sync::Exclusive::new(()),
::unstable::sync::Exclusive::new(())];
let mut v = vec![unstable::sync::Exclusive::new(()),
unstable::sync::Exclusive::new(()),
unstable::sync::Exclusive::new(())];
let mut _e = v.swap_remove(0);
assert_eq!(v.len(), 2);
_e = v.swap_remove(1);
@ -1442,8 +1443,6 @@ mod tests {
#[test]
fn test_sort() {
use realstd::slice::Vector;
use realstd::clone::Clone;
for len in range(4u, 25) {
for _ in range(0, 100) {
let mut v = task_rng().gen_iter::<uint>().take(len)
@ -1636,8 +1635,6 @@ mod tests {
#[test]
#[should_fail]
fn test_from_elem_fail() {
use cell::Cell;
use rc::Rc;
struct S {
f: Cell<int>,
@ -1659,7 +1656,6 @@ mod tests {
#[test]
#[should_fail]
fn test_grow_fn_fail() {
use rc::Rc;
let mut v = vec![];
v.grow_fn(100, |i| {
if i == 50 {
@ -1672,7 +1668,6 @@ mod tests {
#[test]
#[should_fail]
fn test_permute_fail() {
use rc::Rc;
let v = [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
(box 0, Rc::new(0)), (box 0, Rc::new(0))];
let mut i = 0;
@ -1705,7 +1700,6 @@ mod tests {
#[test]
fn test_iterator() {
use iter::*;
let xs = [1, 2, 5, 10, 11];
let mut it = xs.iter();
assert_eq!(it.size_hint(), (5, Some(5)));
@ -1724,7 +1718,6 @@ mod tests {
#[test]
fn test_random_access_iterator() {
use iter::*;
let xs = [1, 2, 5, 10, 11];
let mut it = xs.iter();
@ -1763,7 +1756,6 @@ mod tests {
#[test]
fn test_iter_size_hints() {
use iter::*;
let mut xs = [1, 2, 5, 10, 11];
assert_eq!(xs.iter().size_hint(), (5, Some(5)));
assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
@ -1782,7 +1774,6 @@ mod tests {
#[test]
fn test_mut_iterator() {
use iter::*;
let mut xs = [1, 2, 3, 4, 5];
for x in xs.mut_iter() {
*x += 1;
@ -1792,7 +1783,6 @@ mod tests {
#[test]
fn test_rev_iterator() {
use iter::*;
let xs = [1, 2, 5, 10, 11];
let ys = [11, 10, 5, 2, 1];
@ -1806,7 +1796,6 @@ mod tests {
#[test]
fn test_mut_rev_iterator() {
use iter::*;
let mut xs = [1u, 2, 3, 4, 5];
for (i,x) in xs.mut_iter().rev().enumerate() {
*x += i;
@ -1816,14 +1805,12 @@ mod tests {
#[test]
fn test_move_iterator() {
use iter::*;
let xs = box [1u,2,3,4,5];
assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
}
#[test]
fn test_move_rev_iterator() {
use iter::*;
let xs = box [1u,2,3,4,5];
assert_eq!(xs.move_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
}
@ -1999,7 +1986,6 @@ mod tests {
#[test]
fn test_vec_default() {
use default::Default;
macro_rules! t (
($ty:ty) => {{
let v: $ty = Default::default();
@ -2034,7 +2020,6 @@ mod tests {
#[test]
#[should_fail]
fn test_overflow_does_not_cause_segfault_managed() {
use rc::Rc;
let mut v = vec![Rc::new(1)];
v.reserve_exact(-1);
v.push(Rc::new(2));
@ -2262,12 +2247,13 @@ mod tests {
#[cfg(test)]
mod bench {
extern crate test;
use self::test::Bencher;
use mem;
use prelude::*;
use ptr;
use rand::{weak_rng, Rng};
use std::prelude::*;
use std::rand::{weak_rng, Rng};
use std::mem;
use std::ptr;
use test::Bencher;
use vec::Vec;
#[bench]
fn iterator(b: &mut Bencher) {

View File

@ -15,9 +15,13 @@
#![allow(missing_doc)]
use std::iter::{Enumerate, FilterMap};
use std::mem::replace;
use std::{vec, slice};
use core::prelude::*;
use core::iter::{Enumerate, FilterMap};
use core::mem::replace;
use {vec, slice};
use vec::Vec;
#[allow(missing_doc)]
pub struct SmallIntMap<T> {
@ -118,7 +122,7 @@ impl<V> SmallIntMap<V> {
}
pub fn get<'a>(&'a self, key: &uint) -> &'a V {
self.find(key).expect("key not present")
::expect(self.find(key), "key not present")
}
/// An iterator visiting all key-value pairs in ascending order by the keys.
@ -245,6 +249,7 @@ double_ended_iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
#[cfg(test)]
mod test_map {
use std::prelude::*;
use super::SmallIntMap;

View File

@ -67,21 +67,16 @@ is the same as `&[u8]`.
#![doc(primitive = "str")]
use char::Char;
use char;
use clone::Clone;
use cmp::{PartialEq, Eq, PartialOrd, Ord, Equiv, Ordering};
use container::Container;
use default::Default;
use fmt;
use io::Writer;
use iter::{Iterator, range, AdditiveIterator};
use mem::transmute;
use mem;
use option::{None, Option, Some};
use result::Result;
use slice::Vector;
use slice::{ImmutableVector, MutableVector};
use core::prelude::*;
use core::char;
use core::default::Default;
use core::fmt;
use core::cmp;
use core::iter::AdditiveIterator;
use core::mem;
use hash;
use string::String;
use vec::Vec;
@ -201,9 +196,6 @@ Section: Iterators
// Helper functions used for Unicode normalization
fn canonical_sort(comb: &mut [(char, u8)]) {
use iter::range;
use tuple::Tuple2;
let len = comb.len();
for i in range(0, len) {
let mut swapped = false;
@ -638,13 +630,10 @@ impl<'a> Default for MaybeOwned<'a> {
fn default() -> MaybeOwned<'a> { Slice("") }
}
impl<'a, H: Writer> ::hash::Hash<H> for MaybeOwned<'a> {
impl<'a, H: hash::Writer> hash::Hash<H> for MaybeOwned<'a> {
#[inline]
fn hash(&self, hasher: &mut H) {
match *self {
Slice(s) => s.hash(hasher),
Owned(ref s) => s.as_slice().hash(hasher),
}
self.as_slice().hash(hasher)
}
}
@ -660,10 +649,10 @@ impl<'a> fmt::Show for MaybeOwned<'a> {
/// Unsafe operations
pub mod raw {
use c_str::CString;
use libc;
use mem;
use raw::Slice;
use core::prelude::*;
use core::mem;
use core::raw::Slice;
use string::String;
use vec::Vec;
@ -681,9 +670,16 @@ pub mod raw {
}
/// Create a Rust string from a null-terminated C string
pub unsafe fn from_c_str(c_string: *libc::c_char) -> String {
pub unsafe fn from_c_str(c_string: *i8) -> String {
let mut buf = String::new();
buf.push_bytes(CString::new(c_string, false).as_bytes_no_nul());
let mut len = 0;
while *c_string.offset(len) != 0 {
len += 1;
}
buf.push_bytes(mem::transmute(Slice {
data: c_string,
len: len as uint,
}));
buf
}
@ -800,10 +796,8 @@ pub trait StrAllocating: Str {
#[deprecated = "obsolete, use `to_string`"]
#[inline]
fn to_owned(&self) -> String {
use slice::Vector;
unsafe {
::mem::transmute(Vec::from_slice(self.as_slice().as_bytes()))
mem::transmute(Vec::from_slice(self.as_slice().as_bytes()))
}
}
@ -852,9 +846,9 @@ pub trait StrAllocating: Str {
if sc == tc {
*dcol.get_mut(j + 1) = current;
} else {
*dcol.get_mut(j + 1) = ::cmp::min(current, next);
*dcol.get_mut(j + 1) = ::cmp::min(*dcol.get(j + 1),
*dcol.get(j)) + 1;
*dcol.get_mut(j + 1) = cmp::min(current, next);
*dcol.get_mut(j + 1) = cmp::min(*dcol.get(j + 1),
*dcol.get(j)) + 1;
}
current = next;
@ -922,11 +916,13 @@ impl OwnedStr for String {
#[cfg(test)]
mod tests {
use iter::AdditiveIterator;
use default::Default;
use prelude::*;
use std::prelude::*;
use std::iter::AdditiveIterator;
use std::default::Default;
use str::*;
use string::String;
use vec::Vec;
#[test]
fn test_eq_slice() {
@ -1047,7 +1043,7 @@ mod tests {
#[test]
fn test_concat() {
fn t(v: &[String], s: &str) {
assert_eq!(v.concat(), s.to_str().into_string());
assert_eq!(v.concat().as_slice(), s);
}
t(["you".to_string(), "know".to_string(), "I'm".to_string(),
"no".to_string(), "good".to_string()], "youknowI'mnogood");
@ -1059,7 +1055,7 @@ mod tests {
#[test]
fn test_connect() {
fn t(v: &[String], sep: &str, s: &str) {
assert_eq!(v.connect(sep), s.to_str().into_string());
assert_eq!(v.connect(sep).as_slice(), s);
}
t(["you".to_string(), "know".to_string(), "I'm".to_string(),
"no".to_string(), "good".to_string()],
@ -1072,7 +1068,7 @@ mod tests {
#[test]
fn test_concat_slices() {
fn t(v: &[&str], s: &str) {
assert_eq!(v.concat(), s.to_str().into_string());
assert_eq!(v.concat().as_slice(), s);
}
t(["you", "know", "I'm", "no", "good"], "youknowI'mnogood");
let v: &[&str] = [];
@ -1083,7 +1079,7 @@ mod tests {
#[test]
fn test_connect_slices() {
fn t(v: &[&str], sep: &str, s: &str) {
assert_eq!(v.connect(sep), s.to_str().into_string());
assert_eq!(v.connect(sep).as_slice(), s);
}
t(["you", "know", "I'm", "no", "good"],
" ", "you know I'm no good");
@ -1758,7 +1754,6 @@ mod tests {
#[test]
fn test_iterator() {
use iter::*;
let s = "ศไทย中华Việt Nam";
let v = box ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
@ -1774,7 +1769,6 @@ mod tests {
#[test]
fn test_rev_iterator() {
use iter::*;
let s = "ศไทย中华Việt Nam";
let v = box ['m', 'a', 'N', ' ', 't', 'ệ','i','V','华','中','ย','ท','ไ','ศ'];
@ -1830,7 +1824,6 @@ mod tests {
#[test]
fn test_char_indicesator() {
use iter::*;
let s = "ศไทย中华Việt Nam";
let p = [0, 3, 6, 9, 12, 15, 18, 19, 20, 23, 24, 25, 26, 27];
let v = ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
@ -1848,7 +1841,6 @@ mod tests {
#[test]
fn test_char_indices_revator() {
use iter::*;
let s = "ศไทย中华Việt Nam";
let p = [27, 26, 25, 24, 23, 20, 19, 18, 15, 12, 9, 6, 3, 0];
let v = ['m', 'a', 'N', ' ', 't', 'ệ','i','V','华','中','ย','ท','ไ','ศ'];
@ -2032,7 +2024,7 @@ mod tests {
#[test]
fn test_str_default() {
use default::Default;
use std::default::Default;
fn t<S: Default + Str>() {
let s: S = Default::default();
assert_eq!(s.as_slice(), "");
@ -2115,8 +2107,8 @@ mod tests {
#[test]
fn test_from_str() {
let owned: Option<String> = from_str("string");
assert_eq!(owned, Some("string".to_string()));
let owned: Option<::std::string::String> = from_str("string");
assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
}
#[test]
@ -2124,16 +2116,16 @@ mod tests {
let s = Slice("abcde");
assert_eq!(s.len(), 5);
assert_eq!(s.as_slice(), "abcde");
assert_eq!(s.to_str(), "abcde".to_string());
assert_eq!(format!("{}", s), "abcde".to_string());
assert_eq!(s.to_str().as_slice(), "abcde");
assert_eq!(format!("{}", s).as_slice(), "abcde");
assert!(s.lt(&Owned("bcdef".to_string())));
assert_eq!(Slice(""), Default::default());
let o = Owned("abcde".to_string());
assert_eq!(o.len(), 5);
assert_eq!(o.as_slice(), "abcde");
assert_eq!(o.to_str(), "abcde".to_string());
assert_eq!(format!("{}", o), "abcde".to_string());
assert_eq!(o.to_str().as_slice(), "abcde");
assert_eq!(format!("{}", o).as_slice(), "abcde");
assert!(o.lt(&Slice("bcdef")));
assert_eq!(Owned("".to_string()), Default::default());
@ -2180,10 +2172,9 @@ mod tests {
#[cfg(test)]
mod bench {
extern crate test;
use self::test::Bencher;
use test::Bencher;
use super::*;
use prelude::*;
use std::prelude::*;
#[bench]
fn char_iterator(b: &mut Bencher) {

View File

@ -10,23 +10,17 @@
//! An owned, growable string that enforces that its contents are valid UTF-8.
use c_vec::CVec;
use char::Char;
use cmp::Equiv;
use container::{Container, Mutable};
use default::Default;
use fmt;
use from_str::FromStr;
use io::Writer;
use iter::{Extendable, FromIterator, Iterator, range};
use mem;
use option::{None, Option, Some};
use ptr::RawPtr;
use ptr;
use result::{Result, Ok, Err};
use slice::Vector;
use str::{CharRange, Str, StrSlice, StrAllocating};
use core::prelude::*;
use core::default::Default;
use core::fmt;
use core::mem;
use core::ptr;
use core::raw::Slice;
use hash;
use str;
use str::{CharRange, StrAllocating};
use vec::Vec;
/// A growable string stored as a UTF-8 encoded buffer.
@ -168,14 +162,17 @@ impl String {
#[inline]
pub fn push_char(&mut self, ch: char) {
let cur_len = self.len();
unsafe {
// This may use up to 4 bytes.
self.vec.reserve_additional(4);
// This may use up to 4 bytes.
self.vec.reserve_additional(4);
unsafe {
// Attempt to not use an intermediate buffer by just pushing bytes
// directly onto this string.
let mut c_vector = CVec::new(self.vec.as_mut_ptr().offset(cur_len as int), 4);
let used = ch.encode_utf8(c_vector.as_mut_slice());
let slice = Slice {
data: self.vec.as_ptr().offset(cur_len as int),
len: 4,
};
let used = ch.encode_utf8(mem::transmute(slice));
self.vec.set_len(cur_len + used);
}
}
@ -340,7 +337,7 @@ impl fmt::Show for String {
}
}
impl<H:Writer> ::hash::Hash<H> for String {
impl<H: hash::Writer> hash::Hash<H> for String {
#[inline]
fn hash(&self, hasher: &mut H) {
self.as_slice().hash(hasher)
@ -354,18 +351,11 @@ impl<'a, S: Str> Equiv<S> for String {
}
}
impl FromStr for String {
#[inline]
fn from_str(s: &str) -> Option<String> {
Some(s.to_string())
}
}
#[cfg(test)]
mod tests {
extern crate test;
use container::{Container, Mutable};
use self::test::Bencher;
use std::prelude::*;
use test::Bencher;
use str::{Str, StrSlice};
use super::String;

View File

@ -12,13 +12,17 @@
//! trees. The only requirement for the types is that the key implements
//! `Ord`.
use std::cmp::Ordering;
use std::fmt::Show;
use std::fmt;
use std::iter::Peekable;
use std::iter;
use std::mem::{replace, swap};
use std::ptr;
use core::prelude::*;
use alloc::owned::Box;
use core::fmt;
use core::fmt::Show;
use core::iter::Peekable;
use core::iter;
use core::mem::{replace, swap};
use core::ptr;
use vec::Vec;
// This is implemented as an AA tree, which is a simplified variation of
// a red-black tree where red (horizontal) nodes can only be added
@ -998,11 +1002,12 @@ impl<T: Ord> Extendable<T> for TreeSet<T> {
#[cfg(test)]
mod test_treemap {
use super::{TreeMap, TreeNode};
use std::prelude::*;
use std::rand::Rng;
use std::rand;
use super::{TreeMap, TreeNode};
#[test]
fn find_empty() {
let m: TreeMap<int,int> = TreeMap::new();
@ -1432,8 +1437,9 @@ mod test_treemap {
#[cfg(test)]
mod bench {
extern crate test;
use self::test::Bencher;
use std::prelude::*;
use test::Bencher;
use super::TreeMap;
use deque::bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
@ -1492,6 +1498,7 @@ mod bench {
#[cfg(test)]
mod test_set {
use std::prelude::*;
use super::{TreeMap, TreeSet};

View File

@ -10,11 +10,15 @@
//! Ordered containers with integer keys, implemented as radix tries (`TrieSet` and `TrieMap` types)
use std::mem::zeroed;
use std::mem;
use std::slice::{Items, MutItems};
use std::slice;
use std::uint;
use core::prelude::*;
use alloc::owned::Box;
use core::mem::zeroed;
use core::mem;
use core::uint;
use slice::{Items, MutItems};
use slice;
// FIXME: #5244: need to manually update the TrieNode constructor
static SHIFT: uint = 4;
@ -457,7 +461,7 @@ fn insert<T>(count: &mut uint, child: &mut Child<T>, key: uint, value: T,
*child = Internal(new);
return ret;
}
_ => unreachable!()
_ => fail!("unreachable code"),
}
}
@ -637,10 +641,12 @@ impl<'a> Iterator<uint> for SetItems<'a> {
#[cfg(test)]
mod test_map {
use super::{TrieMap, TrieNode, Internal, External, Nothing};
use std::prelude::*;
use std::iter::range_step;
use std::uint;
use super::{TrieMap, TrieNode, Internal, External, Nothing};
fn check_integrity<T>(trie: &TrieNode<T>) {
assert!(trie.count != 0);
@ -913,10 +919,11 @@ mod test_map {
#[cfg(test)]
mod bench_map {
extern crate test;
use super::TrieMap;
use std::prelude::*;
use std::rand::{weak_rng, Rng};
use self::test::Bencher;
use test::Bencher;
use super::TrieMap;
#[bench]
fn bench_iter_small(b: &mut Bencher) {
@ -1021,9 +1028,11 @@ mod bench_map {
#[cfg(test)]
mod test_set {
use super::TrieSet;
use std::prelude::*;
use std::uint;
use super::TrieSet;
#[test]
fn test_sane_chunk() {
let x = 1;

View File

@ -13,11 +13,9 @@
#![allow(missing_doc, non_uppercase_statics)]
pub mod normalization {
use option::{Some, None};
use slice::ImmutableVector;
use core::prelude::*;
fn bsearch_range_value_table(c: char, r: &'static [(char, char, u8)]) -> u8 {
use cmp::{Equal, Less, Greater};
match r.bsearch(|&(lo, hi, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }

View File

@ -10,25 +10,22 @@
//! An owned, growable vector.
use RawVec = raw::Vec;
use clone::Clone;
use cmp::{PartialOrd, PartialEq, Ordering, Eq, Ord, max};
use container::{Container, Mutable};
use default::Default;
use fmt;
use iter::{DoubleEndedIterator, FromIterator, Extendable, Iterator, range};
use mem;
use num::{CheckedMul, CheckedAdd};
use num;
use ops::{Add, Drop};
use option::{None, Option, Some};
use ptr::RawPtr;
use ptr;
use raw::Slice;
use rt::heap::{allocate, reallocate, deallocate};
use slice::{ImmutableEqVector, ImmutableVector, Items, MutItems, MutableVector};
use slice::{MutableOrdVector, OwnedVector, Vector};
use slice::{MutableVectorAllocating};
use core::prelude::*;
use alloc::heap::{allocate, reallocate, deallocate};
use RawVec = core::raw::Vec;
use core::raw::Slice;
use core::cmp::max;
use core::default::Default;
use core::fmt;
use core::mem;
use core::num::{CheckedMul, CheckedAdd};
use core::num;
use core::ptr;
use core::uint;
use slice::{MutableOrdVector, OwnedVector, MutableVectorAllocating};
use slice::{Items, MutItems};
/// An owned, growable vector.
///
@ -90,12 +87,12 @@ impl<T> Vec<T> {
/// ```
pub fn with_capacity(capacity: uint) -> Vec<T> {
if mem::size_of::<T>() == 0 {
Vec { len: 0, cap: ::uint::MAX, ptr: 0 as *mut T }
Vec { len: 0, cap: uint::MAX, ptr: 0 as *mut T }
} else if capacity == 0 {
Vec::new()
} else {
let size = capacity.checked_mul(&mem::size_of::<T>())
.expect("capacity overflow");
let size = ::expect(capacity.checked_mul(&mem::size_of::<T>()),
"capacity overflow");
let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
Vec { len: 0, cap: capacity, ptr: ptr as *mut T }
}
@ -117,8 +114,7 @@ impl<T> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
while xs.len < length {
mem::overwrite(xs.as_mut_slice().unsafe_mut_ref(xs.len),
op(xs.len));
ptr::write(xs.as_mut_slice().unsafe_mut_ref(xs.len), op(xs.len));
xs.len += 1;
}
xs
@ -214,8 +210,8 @@ impl<T: Clone> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
while xs.len < length {
mem::overwrite(xs.as_mut_slice().unsafe_mut_ref(xs.len),
value.clone());
ptr::write(xs.as_mut_slice().unsafe_mut_ref(xs.len),
value.clone());
xs.len += 1;
}
xs
@ -325,7 +321,7 @@ impl<T:Clone> Clone for Vec<T> {
let this_slice = self.as_slice();
while vector.len < len {
unsafe {
mem::overwrite(
ptr::write(
vector.as_mut_slice().unsafe_mut_ref(vector.len),
this_slice.unsafe_ref(vector.len).clone());
}
@ -503,8 +499,8 @@ impl<T> Vec<T> {
if mem::size_of::<T>() == 0 { return }
if capacity > self.cap {
let size = capacity.checked_mul(&mem::size_of::<T>())
.expect("capacity overflow");
let size = ::expect(capacity.checked_mul(&mem::size_of::<T>()),
"capacity overflow");
unsafe {
self.ptr = alloc_or_realloc(self.ptr, size,
self.cap * mem::size_of::<T>());
@ -583,7 +579,7 @@ impl<T> Vec<T> {
pub fn push(&mut self, value: T) {
if mem::size_of::<T>() == 0 {
// zero-size types consume no memory, so we can't rely on the address space running out
self.len = self.len.checked_add(&1).expect("length overflow");
self.len = ::expect(self.len.checked_add(&1), "length overflow");
unsafe { mem::forget(value); }
return
}
@ -600,7 +596,7 @@ impl<T> Vec<T> {
unsafe {
let end = (self.ptr as *T).offset(self.len as int) as *mut T;
mem::overwrite(&mut *end, value);
ptr::write(&mut *end, value);
self.len += 1;
}
}
@ -964,7 +960,7 @@ impl<T> Vec<T> {
ptr::copy_memory(p.offset(1), &*p, len - index);
// Write it in, overwriting the first copy of the `index`th
// element.
mem::overwrite(&mut *p, element);
ptr::write(&mut *p, element);
}
self.set_len(len + 1);
}
@ -1530,9 +1526,9 @@ impl<T> FromVec<T> for ~[T] {
fn from_vec(mut v: Vec<T>) -> ~[T] {
let len = v.len();
let data_size = len.checked_mul(&mem::size_of::<T>());
let data_size = data_size.expect("overflow in from_vec()");
let data_size = ::expect(data_size, "overflow in from_vec()");
let size = mem::size_of::<RawVec<()>>().checked_add(&data_size);
let size = size.expect("overflow in from_vec()");
let size = ::expect(size, "overflow in from_vec()");
// In a post-DST world, we can attempt to reuse the Vec allocation by calling
// shrink_to_fit() on it. That may involve a reallocation+memcpy, but that's no
@ -1563,7 +1559,7 @@ impl<T> FromVec<T> for ~[T] {
/// Unsafe operations
pub mod raw {
use super::Vec;
use ptr;
use core::ptr;
/// Constructs a vector from an unsafe pointer to a buffer.
///
@ -1581,10 +1577,10 @@ pub mod raw {
#[cfg(test)]
mod tests {
use prelude::*;
use mem::size_of;
use kinds::marker;
use super::{unzip, raw, FromVec};
use std::prelude::*;
use std::mem::size_of;
use std::kinds::marker;
use super::{unzip, raw, FromVec, Vec};
#[test]
fn test_small_vec_struct() {

View File

@ -61,9 +61,7 @@
//! types to reintroduce mutability:
//!
//! ```
//! extern crate collections;
//!
//! use collections::HashMap;
//! use std::collections::HashMap;
//! use std::cell::RefCell;
//! use std::rc::Rc;
//!
@ -86,8 +84,6 @@
//! to take `&self`.
//!
//! ```
//! extern crate collections;
//!
//! use std::cell::RefCell;
//!
//! struct Graph {

View File

@ -31,12 +31,6 @@ pub use self::num::radix;
pub use self::num::Radix;
pub use self::num::RadixFmt;
macro_rules! write(
($dst:expr, $($arg:tt)*) => ({
format_args!(|args| { $dst.write_fmt(args) }, $($arg)*)
})
)
mod num;
mod float;
pub mod rt;

View File

@ -54,7 +54,18 @@ macro_rules! assert(
);
)
/// Runtime assertion, only without `--cfg ndebug`
#[macro_export]
macro_rules! debug_assert(
($(a:tt)*) => ({
if cfg!(not(ndebug)) {
assert!($($a)*);
}
})
)
/// Runtime assertion for equality, for details see std::macros
#[macro_export]
macro_rules! assert_eq(
($cond1:expr, $cond2:expr) => ({
let c1 = $cond1;
@ -65,6 +76,16 @@ macro_rules! assert_eq(
})
)
/// Runtime assertion for equality, only without `--cfg ndebug`
#[macro_export]
macro_rules! debug_assert_eq(
($($a:tt)*) => ({
if cfg!(not(ndebug)) {
assert_eq!($($a)*);
}
})
)
/// Runtime assertion, disableable at compile time
#[macro_export]
macro_rules! debug_assert(
@ -86,3 +107,13 @@ macro_rules! vec( ($($e:expr),*) => ({
#[cfg(test)]
macro_rules! format( ($($arg:tt)*) => (format_args!(::fmt::format, $($arg)*)) )
/// Write some formatted data into a stream.
///
/// Identical to the macro in `std::macros`
#[macro_export]
macro_rules! write(
($dst:expr, $($arg:tt)*) => ({
format_args_method!($dst, write_fmt, $($arg)*)
})
)

View File

@ -921,19 +921,22 @@ fn waitpid(pid: pid_t, deadline: u64) -> IoResult<p::ProcessExit> {
// Register a new SIGCHLD handler, returning the reading half of the
// self-pipe plus the old handler registered (return value of sigaction).
//
// Be sure to set up the self-pipe first because as soon as we reigster a
// handler we're going to start receiving signals.
fn register_sigchld() -> (libc::c_int, c::sigaction) {
unsafe {
let mut old: c::sigaction = mem::zeroed();
let mut new: c::sigaction = mem::zeroed();
new.sa_handler = sigchld_handler;
new.sa_flags = c::SA_NOCLDSTOP;
assert_eq!(c::sigaction(c::SIGCHLD, &new, &mut old), 0);
let mut pipes = [0, ..2];
assert_eq!(libc::pipe(pipes.as_mut_ptr()), 0);
util::set_nonblocking(pipes[0], true).unwrap();
util::set_nonblocking(pipes[1], true).unwrap();
WRITE_FD = pipes[1];
let mut old: c::sigaction = mem::zeroed();
let mut new: c::sigaction = mem::zeroed();
new.sa_handler = sigchld_handler;
new.sa_flags = c::SA_NOCLDSTOP;
assert_eq!(c::sigaction(c::SIGCHLD, &new, &mut old), 0);
(pipes[0], old)
}
}

View File

@ -365,7 +365,6 @@
#![feature(macro_rules, phase)]
#![deny(missing_doc, deprecated_owned_vector)]
extern crate collections;
#[cfg(test)]
extern crate stdtest = "test";
#[cfg(test)]

View File

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use collections::HashMap;
use std::collections::HashMap;
use std::fmt;
use std::from_str::from_str;
use std::str::{MaybeOwned, Owned, Slice};

View File

@ -14,7 +14,7 @@ use metadata::cstore;
use metadata::filesearch;
use util::fs;
use collections::HashSet;
use std::collections::HashSet;
use std::os;
use syntax::abi;

View File

@ -31,7 +31,7 @@ use syntax::diagnostic::{ColorConfig, Auto, Always, Never};
use syntax::parse;
use syntax::parse::token::InternedString;
use collections::HashSet;
use std::collections::HashSet;
use getopts::{optopt, optmulti, optflag, optflagopt};
use getopts;
use lib::llvm::llvm;

View File

@ -32,7 +32,6 @@ This API is completely unstable and subject to change.
default_type_params, phase)]
extern crate arena;
extern crate collections;
extern crate debug;
extern crate flate;
extern crate getopts;

View File

@ -15,7 +15,7 @@
use std::c_str::ToCStr;
use std::cell::RefCell;
use collections::HashMap;
use std::collections::HashMap;
use libc::{c_uint, c_ushort, c_void, free, uint64_t};
use std::str::raw::from_c_str;

View File

@ -23,7 +23,7 @@ use metadata::loader;
use metadata::loader::CratePaths;
use std::rc::Rc;
use collections::HashMap;
use std::collections::HashMap;
use syntax::ast;
use syntax::abi;
use syntax::attr;

View File

@ -20,7 +20,7 @@ use metadata::loader;
use std::cell::RefCell;
use std::c_vec::CVec;
use std::rc::Rc;
use collections::HashMap;
use std::collections::HashMap;
use syntax::ast;
use syntax::crateid::CrateId;
use syntax::codemap::Span;

View File

@ -33,7 +33,7 @@ use std::hash;
use std::hash::Hash;
use std::io::MemWriter;
use std::str;
use collections::HashMap;
use std::collections::HashMap;
use syntax::abi;
use syntax::ast::*;
use syntax::ast;

View File

@ -14,7 +14,7 @@ use std::cell::RefCell;
use std::os;
use std::io::fs;
use std::unstable::dynamic_lib::DynamicLibrary;
use collections::HashSet;
use std::collections::HashSet;
use myfs = util::fs;

View File

@ -32,7 +32,7 @@ use std::ptr;
use std::slice;
use std::str;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use flate;
use time;

View File

@ -14,7 +14,7 @@
#![allow(non_camel_case_types)]
use std::cell::RefCell;
use collections::HashMap;
use std::collections::HashMap;
use std::io::MemWriter;
use middle::ty::param_ty;

View File

@ -18,7 +18,7 @@ comments in the section "Moves and initialization" and in `doc.rs`.
use std::cell::RefCell;
use std::rc::Rc;
use std::uint;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use middle::borrowck::*;
use middle::dataflow::DataFlowContext;
use middle::dataflow::DataFlowOperator;

View File

@ -18,7 +18,7 @@ use middle::ty;
use middle::typeck;
use util::nodemap::NodeSet;
use collections::HashSet;
use std::collections::HashSet;
use syntax::ast;
use syntax::ast_map;
use syntax::ast_util::{local_def, def_id_of_def, is_local};

View File

@ -61,7 +61,7 @@
//! Additionally, the algorithm is geared towards finding *any* solution rather
//! than finding a number of solutions (there are normally quite a few).
use collections::HashMap;
use std::collections::HashMap;
use syntax::ast;
use driver::session;

View File

@ -31,7 +31,7 @@ use syntax::parse::token::InternedString;
use syntax::visit::Visitor;
use syntax::visit;
use collections::HashMap;
use std::collections::HashMap;
use std::iter::Enumerate;
use std::slice;

View File

@ -49,7 +49,7 @@ use util::ppaux::{ty_to_str};
use util::nodemap::NodeSet;
use std::cmp;
use collections::HashMap;
use std::collections::HashMap;
use std::i16;
use std::i32;
use std::i64;
@ -60,7 +60,7 @@ use std::u16;
use std::u32;
use std::u64;
use std::u8;
use collections::SmallIntMap;
use std::collections::SmallIntMap;
use syntax::abi;
use syntax::ast_map;
use syntax::ast_util::IdVisitingOperation;

View File

@ -11,7 +11,7 @@
use middle::resolve;
use collections::HashMap;
use std::collections::HashMap;
use syntax::ast::*;
use syntax::ast_util::{path_to_ident, walk_pat};
use syntax::codemap::Span;

View File

@ -21,7 +21,7 @@ use middle::typeck;
use middle::privacy;
use util::nodemap::NodeSet;
use collections::HashSet;
use std::collections::HashSet;
use syntax::abi;
use syntax::ast;
use syntax::ast_map;

View File

@ -27,7 +27,7 @@ use middle::ty;
use util::nodemap::NodeMap;
use std::cell::RefCell;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use syntax::codemap::Span;
use syntax::{ast, visit};
use syntax::visit::{Visitor, FnKind};

View File

@ -31,7 +31,7 @@ use syntax::owned_slice::OwnedSlice;
use syntax::visit;
use syntax::visit::Visitor;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use std::cell::{Cell, RefCell};
use std::mem::replace;
use std::rc::{Rc, Weak};

View File

@ -222,7 +222,7 @@ use middle::ty;
use util::common::indenter;
use util::ppaux::{Repr, vec_map_to_str};
use collections::HashMap;
use std::collections::HashMap;
use std::cell::Cell;
use std::rc::Rc;
use syntax::ast;

View File

@ -19,7 +19,7 @@ use middle::trans::base;
use middle::trans::common::*;
use middle::trans::machine::llalign_of_pref;
use middle::trans::type_::Type;
use collections::HashMap;
use std::collections::HashMap;
use libc::{c_uint, c_ulonglong, c_char};
use std::string::String;
use syntax::codemap::Span;

View File

@ -30,7 +30,7 @@ use util::ppaux::Repr;
use util::nodemap::NodeMap;
use arena::TypedArena;
use collections::HashMap;
use std::collections::HashMap;
use libc::{c_uint, c_longlong, c_ulonglong, c_char};
use std::c_str::ToCStr;
use std::cell::{Cell, RefCell};

View File

@ -31,7 +31,7 @@ use std::cell::{Cell, RefCell};
use std::c_str::ToCStr;
use std::ptr;
use std::rc::Rc;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use syntax::ast;
use syntax::parse::token::InternedString;

View File

@ -145,8 +145,8 @@ use util::ppaux;
use std::c_str::{CString, ToCStr};
use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
use collections::HashMap;
use collections::HashSet;
use std::collections::HashMap;
use std::collections::HashSet;
use libc::{c_uint, c_ulonglong, c_longlong};
use std::ptr;
use std::string::String;

View File

@ -39,12 +39,12 @@ use std::cell::{Cell, RefCell};
use std::cmp;
use std::fmt::Show;
use std::fmt;
use std::hash::{Hash, sip};
use std::hash::{Hash, sip, Writer};
use std::iter::AdditiveIterator;
use std::mem;
use std::ops;
use std::rc::Rc;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use syntax::abi;
use syntax::ast::*;
use syntax::ast_util::{is_local, lit_is_str};
@ -57,7 +57,7 @@ use syntax::parse::token::InternedString;
use syntax::{ast, ast_map};
use syntax::owned_slice::OwnedSlice;
use syntax::util::small_vector::SmallVector;
use collections::enum_set::{EnumSet, CLike};
use std::collections::enum_set::{EnumSet, CLike};
pub type Disr = u64;

View File

@ -19,7 +19,7 @@ use middle::typeck::check::{structure_of, valid_range_bounds};
use middle::typeck::infer;
use middle::typeck::require_same_types;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use syntax::ast;
use syntax::ast_util;
use syntax::parse::token;

View File

@ -96,7 +96,7 @@ use util::common::indenter;
use util::ppaux;
use util::ppaux::Repr;
use collections::HashSet;
use std::collections::HashSet;
use std::rc::Rc;
use syntax::ast::{DefId, SelfValue, SelfRegion};
use syntax::ast::{SelfUniq, SelfStatic};

View File

@ -116,7 +116,7 @@ use util::ppaux::{UserString, Repr};
use util::nodemap::{FnvHashMap, NodeMap};
use std::cell::{Cell, RefCell};
use collections::HashMap;
use std::collections::HashMap;
use std::mem::replace;
use std::rc::Rc;
use std::vec::Vec;

View File

@ -14,7 +14,7 @@ use middle::ty;
use middle::ty_fold;
use middle::ty_fold::TypeFolder;
use collections::HashMap;
use std::collections::HashMap;
use util::ppaux::Repr;
use util::ppaux;

View File

@ -29,7 +29,7 @@ use util::ppaux;
use util::ppaux::Repr;
use std::rc::Rc;
use collections::HashSet;
use std::collections::HashSet;
use syntax::ast;
use syntax::ast_util;
use syntax::codemap::Span;

View File

@ -45,7 +45,7 @@ use syntax::owned_slice::OwnedSlice;
use syntax::parse::token;
use syntax::visit;
use collections::HashSet;
use std::collections::HashSet;
use std::cell::RefCell;
use std::rc::Rc;

View File

@ -47,7 +47,7 @@ use util::ppaux;
use util::ppaux::Repr;
use std::rc::Rc;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use syntax::abi;
use syntax::ast::{StaticRegionTyParamBound, OtherRegionTyParamBound,

View File

@ -59,7 +59,7 @@ time of error detection.
*/
use collections::HashSet;
use std::collections::HashSet;
use middle::ty;
use middle::ty::{Region, ReFree};
use middle::typeck::infer;

View File

@ -24,7 +24,7 @@ use middle::typeck::infer::fold_regions_in_sig;
use syntax::ast::{Many, Once, MutImmutable, MutMutable};
use syntax::ast::{NormalFn, UnsafeFn, NodeId};
use syntax::ast::{Onceness, FnStyle};
use collections::HashMap;
use std::collections::HashMap;
use util::common::{indenter};
use util::ppaux::mt_to_str;

View File

@ -45,7 +45,7 @@ use middle::typeck::infer::sub::Sub;
use middle::typeck::infer::to_str::InferStr;
use util::common::indenter;
use collections::HashMap;
use std::collections::HashMap;
trait LatticeValue {
fn sub(cf: CombineFields, a: &Self, b: &Self) -> ures;

View File

@ -20,7 +20,7 @@ use middle::typeck::infer::to_str::InferStr;
use middle::typeck::infer::{cres, InferCtxt};
use middle::typeck::infer::fold_regions_in_sig;
use middle::typeck::infer::{TypeTrace, Subtype};
use collections::HashMap;
use std::collections::HashMap;
use syntax::ast::{Many, Once, NodeId};
use syntax::ast::{NormalFn, UnsafeFn};
use syntax::ast::{Onceness, FnStyle};

View File

@ -21,7 +21,7 @@ pub use middle::typeck::infer::resolve::{resolve_ivar, resolve_all};
pub use middle::typeck::infer::resolve::{resolve_nested_tvar};
pub use middle::typeck::infer::resolve::{resolve_rvar};
use collections::HashMap;
use std::collections::HashMap;
use middle::ty::{TyVid, IntVid, FloatVid, RegionVid, Vid};
use middle::ty;
use middle::ty_fold;

View File

@ -26,7 +26,7 @@ use util::ppaux::{Repr};
use std::cell::{Cell, RefCell};
use std::uint;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use syntax::ast;
mod doc;

View File

@ -9,7 +9,7 @@
// except according to those terms.
use collections::SmallIntMap;
use std::collections::SmallIntMap;
use middle::ty::{Vid, expected_found, IntVarValue};
use middle::ty;

View File

@ -192,7 +192,7 @@ represents the "variance transform" as defined in the paper:
*/
use collections::HashMap;
use std::collections::HashMap;
use arena;
use arena::Arena;
use middle::ty;

View File

@ -21,7 +21,7 @@ use syntax::parse::token::InternedString;
use syntax::visit::Visitor;
use syntax::visit;
use collections::HashSet;
use std::collections::HashSet;
macro_rules! weak_lang_items( ($($name:ident, $item:ident, $sym:ident;)*) => (

View File

@ -10,9 +10,8 @@
//! An efficient hash map for node IDs
use collections::{HashMap, HashSet};
use std::hash::{Hasher, Hash};
use std::io;
use std::collections::{HashMap, HashSet};
use std::hash::{Hasher, Hash, Writer};
use syntax::ast;
pub type FnvHashMap<K, V> = HashMap<K, V, FnvHasher>;
@ -27,14 +26,14 @@ pub type DefIdSet = FnvHashSet<ast::DefId>;
// Hacks to get good names
pub mod FnvHashMap {
use std::hash::Hash;
use collections::HashMap;
use std::collections::HashMap;
pub fn new<K: Hash<super::FnvState> + Eq, V>() -> super::FnvHashMap<K, V> {
HashMap::with_hasher(super::FnvHasher)
}
}
pub mod FnvHashSet {
use std::hash::Hash;
use collections::HashSet;
use std::collections::HashSet;
pub fn new<V: Hash<super::FnvState> + Eq>() -> super::FnvHashSet<V> {
HashSet::with_hasher(super::FnvHasher)
}
@ -82,13 +81,12 @@ impl Hasher<FnvState> for FnvHasher {
}
impl Writer for FnvState {
fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> {
fn write(&mut self, bytes: &[u8]) {
let FnvState(mut hash) = *self;
for byte in bytes.iter() {
hash = hash ^ (*byte as u64);
hash = hash * 0x100000001b3;
}
*self = FnvState(hash);
Ok(())
}
}

View File

@ -20,7 +20,7 @@ use syntax;
use std::cell::RefCell;
use std::os;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use visit_ast::RustdocVisitor;
use clean;

View File

@ -31,7 +31,7 @@ use std::cell::RefCell;
use std::fmt;
use std::slice;
use std::str;
use collections::HashMap;
use std::collections::HashMap;
use html::toc::TocBuilder;
use html::highlight;
@ -412,4 +412,4 @@ mod tests {
assert_eq!(parse_lang_string("{.sh .should_fail}"), (true,false,false,false))
assert_eq!(parse_lang_string("{.example .rust}"), (false,false,false,false))
}
}
}

View File

@ -33,7 +33,7 @@
//! These tasks are not parallelized (they haven't been a bottleneck yet), and
//! both occur before the crate is rendered.
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::io::{fs, File, BufferedWriter, MemWriter, BufferedReader};
use std::io;

View File

@ -16,7 +16,6 @@
#![feature(globs, struct_variant, managed_boxes, macro_rules, phase)]
extern crate collections;
extern crate debug;
extern crate getopts;
extern crate libc;
@ -403,7 +402,7 @@ fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
// "crate": { parsed crate ... },
// "plugins": { output of plugins ... }
// }
let mut json = box collections::TreeMap::new();
let mut json = box std::collections::TreeMap::new();
json.insert("schema".to_string(),
json::String(SCHEMA_VERSION.to_string()));
let plugins_json = box res.move_iter()

View File

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use collections::HashSet;
use std::collections::HashSet;
use std::{str, io};
use std::string::String;

View File

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use collections::HashSet;
use std::collections::HashSet;
use rustc::util::nodemap::NodeSet;
use std::cmp;
use std::string::String;

View File

@ -17,7 +17,7 @@ use std::str;
use std::string::String;
use std::unstable::dynamic_lib::DynamicLibrary;
use collections::{HashSet, HashMap};
use std::collections::{HashSet, HashMap};
use testing;
use rustc::back::link;
use rustc::driver::config;

View File

@ -15,9 +15,9 @@ use std::default::Default;
use std::hash::{Hash, Hasher};
use {Decodable, Encodable, Decoder, Encoder};
use collections::{DList, RingBuf, TreeMap, TreeSet, Deque, HashMap, HashSet,
TrieMap, TrieSet};
use collections::enum_set::{EnumSet, CLike};
use std::collections::{DList, RingBuf, TreeMap, TreeSet, Deque, HashMap, HashSet,
TrieMap, TrieSet};
use std::collections::enum_set::{EnumSet, CLike};
impl<
E,

View File

@ -99,12 +99,9 @@ A basic `ToJson` example using a TreeMap of attribute name / attribute value:
```rust
extern crate collections;
extern crate serialize;
use std::collections::TreeMap;
use serialize::json;
use serialize::json::ToJson;
use collections::TreeMap;
pub struct MyStruct {
attr1: u8,
@ -190,12 +187,9 @@ This example use the ToJson impl to deserialize the JSON string.
Example of `ToJson` trait implementation for TestStruct1.
```rust
extern crate serialize;
extern crate collections;
use std::collections::TreeMap;
use serialize::json::ToJson;
use serialize::{json, Encodable, Decodable};
use collections::TreeMap;
#[deriving(Decodable, Encodable)] // generate Decodable, Encodable impl.
pub struct TestStruct1 {
@ -234,6 +228,7 @@ fn main() {
*/
use std::char;
use std::collections::{HashMap, TreeMap};
use std::f64;
use std::fmt;
use std::io::MemWriter;
@ -246,7 +241,6 @@ use std::string::String;
use std::vec::Vec;
use Encodable;
use collections::{HashMap, TreeMap};
/// Represents a json value
#[deriving(Clone, PartialEq)]
@ -2290,7 +2284,7 @@ mod tests {
EOFWhileParsingValue, EOFWhileParsingString, KeyMustBeAString, ExpectedColon,
TrailingCharacters};
use std::io;
use collections::TreeMap;
use std::collections::TreeMap;
#[deriving(PartialEq, Encodable, Decodable, Show)]
enum Animal {
@ -3006,7 +3000,7 @@ mod tests {
use std::str::from_utf8;
use std::io::Writer;
use std::io::MemWriter;
use collections::HashMap;
use std::collections::HashMap;
let mut hm: HashMap<uint, bool> = HashMap::new();
hm.insert(1, true);
let mut mem_buf = MemWriter::new();
@ -3026,7 +3020,7 @@ mod tests {
use std::str::from_utf8;
use std::io::Writer;
use std::io::MemWriter;
use collections::HashMap;
use std::collections::HashMap;
let mut hm: HashMap<uint, bool> = HashMap::new();
hm.insert(1, true);
let mut mem_buf = MemWriter::new();
@ -3043,7 +3037,7 @@ mod tests {
}
#[test]
fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
use collections::HashMap;
use std::collections::HashMap;
use Decodable;
let json_str = "{\"1\":true}";
let json_obj = match from_str(json_str) {
@ -3340,7 +3334,7 @@ mod tests {
#[test]
fn test_to_json() {
use collections::{HashMap,TreeMap};
use std::collections::{HashMap,TreeMap};
use super::ToJson;
let list2 = List(vec!(Number(1.0_f64), Number(2.0_f64)));

View File

@ -29,8 +29,6 @@ extern crate test;
#[phase(syntax, link)]
extern crate log;
extern crate collections;
pub use self::serialize::{Decoder, Encoder, Decodable, Encodable,
DecoderHelpers, EncoderHelpers};

View File

@ -10,40 +10,39 @@
//! Unordered containers, implemented as hash-tables (`HashSet` and `HashMap` types)
use std::container::{Container, Mutable, Map, MutableMap, Set, MutableSet};
use std::clone::Clone;
use std::cmp::{PartialEq, Eq, Equiv, max};
use std::default::Default;
use std::fmt;
use std::fmt::Show;
use std::hash::{Hash, Hasher, sip};
use std::iter;
use std::iter::{Iterator, FromIterator, Extendable};
use std::iter::{FilterMap, Chain, Repeat, Zip};
use std::iter::{range, range_inclusive};
use std::mem::replace;
use std::num;
use std::option::{Option, Some, None};
use std::rand;
use std::rand::Rng;
use std::result::{Ok, Err};
use std::slice::ImmutableVector;
use clone::Clone;
use cmp::{max, Eq, Equiv, PartialEq};
use container::{Container, Mutable, Set, MutableSet, Map, MutableMap};
use default::Default;
use fmt::Show;
use fmt;
use hash::{Hash, Hasher, sip};
use iter::{Iterator, FilterMap, Chain, Repeat, Zip, Extendable};
use iter::{range, range_inclusive, FromIterator};
use iter;
use mem::replace;
use num;
use option::{Some, None, Option};
use rand::Rng;
use rand;
use result::{Ok, Err};
mod table {
use std::clone::Clone;
use std::cmp;
use std::cmp::PartialEq;
use std::hash::{Hash, Hasher};
use std::kinds::marker;
use std::num::{CheckedMul, is_power_of_two};
use std::option::{Option, Some, None};
use std::prelude::Drop;
use std::ptr;
use std::ptr::RawPtr;
use std::mem::{min_align_of, size_of};
use std::intrinsics::{move_val_init, set_memory, transmute};
use std::iter::{Iterator, range_step_inclusive};
use std::rt::heap::{allocate, deallocate};
use clone::Clone;
use cmp;
use hash::{Hash, Hasher};
use iter::range_step_inclusive;
use iter::{Iterator, range};
use kinds::marker;
use mem::{min_align_of, size_of};
use mem::{overwrite, transmute};
use num::{CheckedMul, is_power_of_two};
use ops::Drop;
use option::{Some, None, Option};
use ptr::RawPtr;
use ptr::set_memory;
use ptr;
use rt::heap::{allocate, deallocate};
static EMPTY_BUCKET: u64 = 0u64;
@ -217,12 +216,12 @@ mod table {
/// Does not initialize the buckets. The caller should ensure they,
/// at the very least, set every hash to EMPTY_BUCKET.
unsafe fn new_uninitialized(capacity: uint) -> RawTable<K, V> {
let hashes_size =
capacity.checked_mul(&size_of::<u64>()).expect("capacity overflow");
let keys_size =
capacity.checked_mul(&size_of::< K >()).expect("capacity overflow");
let vals_size =
capacity.checked_mul(&size_of::< V >()).expect("capacity overflow");
let hashes_size = capacity.checked_mul(&size_of::<u64>())
.expect("capacity overflow");
let keys_size = capacity.checked_mul(&size_of::< K >())
.expect("capacity overflow");
let vals_size = capacity.checked_mul(&size_of::< V >())
.expect("capacity overflow");
// Allocating hashmaps is a little tricky. We need to allocate three
// arrays, but since we know their sizes and alignments up front,
@ -255,6 +254,7 @@ mod table {
/// Creates a new raw table from a given capacity. All buckets are
/// initially empty.
#[allow(experimental)]
pub fn new(capacity: uint) -> RawTable<K, V> {
unsafe {
let ret = RawTable::new_uninitialized(capacity);
@ -339,8 +339,8 @@ mod table {
unsafe {
debug_assert_eq!(*self.hashes.offset(idx), EMPTY_BUCKET);
*self.hashes.offset(idx) = hash.inspect();
move_val_init(&mut *self.keys.offset(idx), k);
move_val_init(&mut *self.vals.offset(idx), v);
overwrite(&mut *self.keys.offset(idx), k);
overwrite(&mut *self.vals.offset(idx), v);
}
self.size += 1;
@ -411,18 +411,21 @@ mod table {
assert_eq!(size_of::<SafeHash>(), size_of::<u64>())
}
/// Iterator over shared references to entries in a table.
pub struct Entries<'a, K, V> {
table: &'a RawTable<K, V>,
idx: uint,
elems_seen: uint,
}
/// Iterator over mutable references to entries in a table.
pub struct MutEntries<'a, K, V> {
table: &'a mut RawTable<K, V>,
idx: uint,
elems_seen: uint,
}
/// Iterator over the entries in a table, consuming the table.
pub struct MoveEntries<K, V> {
table: RawTable<K, V>,
idx: uint,
@ -519,8 +522,8 @@ mod table {
let hash = idx.hash().inspect();
let (k, v) = self.read(&idx);
*new_ht.hashes.offset(i as int) = hash;
move_val_init(&mut *new_ht.keys.offset(i as int), (*k).clone());
move_val_init(&mut *new_ht.vals.offset(i as int), (*v).clone());
overwrite(&mut *new_ht.keys.offset(i as int), (*k).clone());
overwrite(&mut *new_ht.vals.offset(i as int), (*v).clone());
}
}
}
@ -695,7 +698,7 @@ impl DefaultResizePolicy {
/// # Example
///
/// ```rust
/// use collections::HashMap;
/// use std::collections::HashMap;
///
/// // type inference lets us omit an explicit type signature (which
/// // would be `HashMap<&str, &str>` in this example).
@ -1037,6 +1040,7 @@ impl<K: Hash + Eq, V> HashMap<K, V, sip::SipHasher> {
HashMap::with_capacity(INITIAL_CAPACITY)
}
/// Creates an empty hash map with the given initial capacity.
pub fn with_capacity(capacity: uint) -> HashMap<K, V, sip::SipHasher> {
let mut r = rand::task_rng();
let r0 = r.gen();
@ -1047,6 +1051,9 @@ impl<K: Hash + Eq, V> HashMap<K, V, sip::SipHasher> {
}
impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
/// Creates an empty hashmap which will use the given hasher to hash keys.
///
/// The creates map has the default initial capacity.
pub fn with_hasher(hasher: H) -> HashMap<K, V, H> {
HashMap::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
}
@ -1271,7 +1278,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
/// # Example
///
/// ```rust
/// use collections::HashMap;
/// use std::collections::HashMap;
///
/// // map some strings to vectors of strings
/// let mut map = HashMap::new();
@ -1326,7 +1333,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
pub fn get<'a>(&'a self, k: &K) -> &'a V {
match self.find(k) {
Some(v) => v,
None => fail!("No entry found for key: {:?}", k)
None => fail!("no entry found for key")
}
}
@ -1334,7 +1341,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
pub fn get_mut<'a>(&'a mut self, k: &K) -> &'a mut V {
match self.find_mut(k) {
Some(v) => v,
None => fail!("No entry found for key: {:?}", k)
None => fail!("no entry found for key")
}
}
@ -1533,6 +1540,10 @@ impl<T: Hash + Eq> HashSet<T, sip::SipHasher> {
}
impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
/// Creates a new empty hash set which will use the given hasher to hash
/// keys.
///
/// The hash set is also created with the default initial capacity.
pub fn with_hasher(hasher: H) -> HashSet<T, H> {
HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
}
@ -1632,8 +1643,10 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Extendable<T> for HashSet<T, H>
}
}
impl<T: Eq + Hash> Default for HashSet<T, sip::SipHasher> {
fn default() -> HashSet<T> { HashSet::new() }
impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> {
fn default() -> HashSet<T, H> {
HashSet::with_hasher(Default::default())
}
}
// `Repeat` is used to feed the filter closure an explicit capture
@ -1645,11 +1658,13 @@ pub type SetAlgebraItems<'a, T, H> =
#[cfg(test)]
mod test_map {
use prelude::*;
use super::HashMap;
use std::cmp::Equiv;
use std::hash::Hash;
use std::iter::{Iterator,range_inclusive,range_step_inclusive};
use std::cell::RefCell;
use cmp::Equiv;
use hash;
use iter::{Iterator,range_inclusive,range_step_inclusive};
use cell::RefCell;
struct KindaIntLike(int);
@ -1659,7 +1674,7 @@ mod test_map {
this == *other
}
}
impl<S: Writer> Hash<S> for KindaIntLike {
impl<S: hash::Writer> hash::Hash<S> for KindaIntLike {
fn hash(&self, state: &mut S) {
let KindaIntLike(this) = *self;
this.hash(state)
@ -2137,9 +2152,11 @@ mod test_map {
#[cfg(test)]
mod test_set {
use prelude::*;
use super::HashSet;
use std::container::Container;
use std::slice::ImmutableEqVector;
use container::Container;
use slice::ImmutableEqVector;
#[test]
fn test_disjoint() {
@ -2380,8 +2397,10 @@ mod test_set {
#[cfg(test)]
mod bench {
extern crate test;
use prelude::*;
use self::test::Bencher;
use std::iter::{range_inclusive};
use iter::{range_inclusive};
#[bench]
fn new_drop(b : &mut Bencher) {

View File

@ -17,7 +17,7 @@
//! # Example
//!
//! ```rust
//! use collections::LruCache;
//! use std::collections::LruCache;
//!
//! let mut cache: LruCache<int, int> = LruCache::new(2);
//! cache.put(1, 10);
@ -37,13 +37,18 @@
//! assert!(cache.get(&2).is_none());
//! ```
use std::container::Container;
use std::hash::Hash;
use std::fmt;
use std::mem;
use std::ptr;
use HashMap;
use cmp::{PartialEq, Eq};
use collections::HashMap;
use container::{Container, Mutable, MutableMap};
use fmt;
use hash::Hash;
use iter::{range, Iterator};
use mem;
use ops::Drop;
use option::{Some, None, Option};
use owned::Box;
use ptr;
use result::{Ok, Err};
struct KeyRef<K> { k: *K }
@ -251,6 +256,7 @@ impl<K, V> Drop for LruCache<K, V> {
#[cfg(test)]
mod tests {
use prelude::*;
use super::LruCache;
fn assert_opt_eq<V: PartialEq>(opt: Option<&V>, v: V) {

View File

@ -0,0 +1,25 @@
// Copyright 2013-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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Collection types.
*/
pub use core_collections::{Bitv, BitvSet, BTree, Deque, DList, EnumSet};
pub use core_collections::{PriorityQueue, RingBuf, SmallIntMap};
pub use core_collections::{TreeMap, TreeSet, TrieMap, TrieSet};
pub use core_collections::{bitv, btree, deque, dlist, enum_set};
pub use core_collections::{priority_queue, ringbuf, smallintmap, treemap, trie};
pub use self::hashmap::{HashMap, HashSet};
pub use self::lru_cache::LruCache;
pub mod hashmap;
pub mod lru_cache;

View File

@ -11,6 +11,8 @@
//! The `FromStr` trait for types that can be created from strings
use option::{Option, Some, None};
use string::String;
use str::StrAllocating;
/// A trait to abstract the idea of creating a new instance of a type from a
/// string.
@ -47,6 +49,13 @@ impl FromStr for bool {
}
}
impl FromStr for String {
#[inline]
fn from_str(s: &str) -> Option<String> {
Some(s.to_string())
}
}
#[cfg(test)]
mod test {
use prelude::*;

View File

@ -124,6 +124,7 @@ extern crate alloc;
extern crate core;
extern crate libc;
extern crate core_rand = "rand";
extern crate core_collections = "collections";
// Make std testable by not duplicating lang items. See #2912
#[cfg(test)] extern crate realstd = "std";
@ -160,6 +161,12 @@ pub use core::option;
pub use alloc::owned;
pub use alloc::rc;
pub use core_collections::hash;
pub use core_collections::slice;
pub use core_collections::str;
pub use core_collections::string;
pub use core_collections::vec;
// Run tests with libgreen instead of libnative.
//
// FIXME: This egregiously hacks around starting the test runner in a different
@ -203,10 +210,6 @@ pub mod prelude;
#[path = "num/f32.rs"] pub mod f32;
#[path = "num/f64.rs"] pub mod f64;
pub mod slice;
pub mod vec;
pub mod str;
pub mod string;
pub mod rand;
pub mod ascii;
@ -218,7 +221,10 @@ pub mod gc;
pub mod from_str;
pub mod num;
pub mod to_str;
pub mod hash;
/* Common data structures */
pub mod collections;
/* Tasks and communication */
@ -242,10 +248,6 @@ pub mod cleanup;
#[unstable]
pub mod unstable;
/* For internal use, not exported */
mod unicode;
// FIXME #7809: This shouldn't be pub, and it should be reexported under 'unstable'
// but name resolution doesn't work without it being pub.
#[unstable]

View File

@ -10,16 +10,17 @@
//! POSIX file path handling
use container::Container;
use c_str::{CString, ToCStr};
use clone::Clone;
use cmp::{PartialEq, Eq};
use container::Container;
use from_str::FromStr;
use hash;
use io::Writer;
use iter::{DoubleEndedIterator, AdditiveIterator, Extendable, Iterator, Map};
use option::{Option, None, Some};
use str;
use str::Str;
use str;
use slice::{CloneableVector, Splits, Vector, VectorVector,
ImmutableEqVector, OwnedVector, ImmutableVector};
use vec::Vec;
@ -105,7 +106,7 @@ impl<'a> ToCStr for &'a Path {
}
}
impl<S: Writer> ::hash::Hash<S> for Path {
impl<S: hash::Writer> hash::Hash<S> for Path {
#[inline]
fn hash(&self, state: &mut S) {
self.repr.hash(state)

View File

@ -16,6 +16,7 @@ use clone::Clone;
use cmp::{PartialEq, Eq};
use container::Container;
use from_str::FromStr;
use hash;
use io::Writer;
use iter::{AdditiveIterator, DoubleEndedIterator, Extendable, Iterator, Map};
use mem;
@ -126,7 +127,7 @@ impl<'a> ToCStr for &'a Path {
}
}
impl<S: Writer> ::hash::Hash<S> for Path {
impl<S: hash::Writer> hash::Hash<S> for Path {
#[cfg(not(test))]
#[inline]
fn hash(&self, state: &mut S) {

View File

@ -20,8 +20,8 @@ use parse::token::InternedString;
use parse::token;
use crateid::CrateId;
use collections::HashSet;
use collections::bitv::BitvSet;
use std::collections::HashSet;
use std::collections::BitvSet;
local_data_key!(used_attrs: BitvSet)

View File

@ -19,7 +19,7 @@ use parse::token;
use parse::token::{InternedString, intern, str_to_ident};
use util::small_vector::SmallVector;
use collections::HashMap;
use std::collections::HashMap;
// new-style macro! tt code:
//

View File

@ -18,7 +18,7 @@ use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token;
use collections::HashMap;
use std::collections::HashMap;
use std::string::String;
pub fn expand_deriving_show(cx: &mut ExtCtxt,

View File

@ -19,7 +19,7 @@ use parse::token;
use rsparse = parse;
use parse = fmt_macros;
use collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
#[deriving(PartialEq)]
enum ArgumentType {

View File

@ -19,8 +19,7 @@ use ast::{Ident, Mrk, Name, SyntaxContext};
use std::cell::RefCell;
use std::rc::Rc;
use collections::HashMap;
use std::collections::HashMap;
// the SCTable contains a table of SyntaxContext_'s. It
// represents a flattened tree structure, to avoid having
@ -267,7 +266,7 @@ mod tests {
use super::{resolve, xor_push, new_mark_internal, new_sctable_internal};
use super::{new_rename_internal, marksof_internal, resolve_internal};
use super::{SCTable, EmptyCtxt, Mark, Rename, IllegalCtxt};
use collections::HashMap;
use std::collections::HashMap;
#[test]
fn xorpush_test () {

View File

@ -22,7 +22,7 @@ use parse::token::{Token, EOF, Nonterminal};
use parse::token;
use std::rc::Rc;
use collections::HashMap;
use std::collections::HashMap;
/* This is an Earley-like parser, without support for in-grammar nonterminals,
only by calling out to the main rust parser for named nonterminals (which it

View File

@ -18,7 +18,7 @@ use parse::token;
use parse::lexer::TokenAndSpan;
use std::rc::Rc;
use collections::HashMap;
use std::collections::HashMap;
///an unzipping of `TokenTree`s
#[deriving(Clone)]

View File

@ -32,7 +32,6 @@ This API is completely unstable and subject to change.
extern crate serialize;
extern crate term;
extern crate collections;
#[phase(syntax, link)]
extern crate log;
extern crate fmt_macros;

View File

@ -9,7 +9,7 @@
// except according to those terms.
use std::default::Default;
use std::hash::Hash;
use std::hash;
use std::{mem, raw, ptr, slice};
use serialize::{Encodable, Decodable, Encoder, Decoder};
@ -107,7 +107,7 @@ impl<T: Clone> Clone for OwnedSlice<T> {
}
}
impl<S: Writer, T: Hash<S>> Hash<S> for OwnedSlice<T> {
impl<S: hash::Writer, T: hash::Hash<S>> hash::Hash<S> for OwnedSlice<T> {
fn hash(&self, state: &mut S) {
self.as_slice().hash(state)
}

View File

@ -76,7 +76,7 @@ use parse::token;
use parse::{new_sub_parser_from_file, ParseSess};
use owned_slice::OwnedSlice;
use collections::HashSet;
use std::collections::HashSet;
use std::mem::replace;
use std::rc::Rc;
use std::string::String;

View File

@ -14,7 +14,7 @@
use ast::Name;
use collections::HashMap;
use std::collections::HashMap;
use std::cell::RefCell;
use std::cmp::Equiv;
use std::fmt;

View File

@ -52,7 +52,6 @@
#![deny(missing_doc)]
#[phase(syntax, link)] extern crate log;
extern crate collections;
pub use terminfo::TerminfoTerminal;
#[cfg(windows)]

View File

@ -10,7 +10,7 @@
//! Terminfo database interface.
use collections::HashMap;
use std::collections::HashMap;
use std::io::IoResult;
use std::os;

Some files were not shown because too many files have changed in this diff Show More