diff options
Diffstat (limited to 'src/libstd')
50 files changed, 335 insertions, 585 deletions
diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 4ce9639bedb..ae295c3e8e4 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -1,4 +1,4 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -18,7 +18,7 @@ use borrow::BorrowFrom; use clone::Clone; use cmp::{max, Eq, PartialEq}; use default::Default; -use fmt::{self, Show}; +use fmt::{self, Debug}; use hash::{self, Hash, SipHasher}; use iter::{self, Iterator, ExactSizeIterator, IteratorExt, FromIterator, Extend, Map}; use marker::Sized; @@ -76,7 +76,7 @@ impl DefaultResizePolicy { // min_capacity(size) must be smaller than the internal capacity, // so that the map is not resized: // `min_capacity(usable_capacity(x)) <= x`. - // The lef-hand side can only be smaller due to flooring by integer + // The left-hand side can only be smaller due to flooring by integer // division. // // This doesn't have to be checked for overflow since allocation size @@ -270,7 +270,7 @@ fn test_resize_policy() { /// ``` /// use std::collections::HashMap; /// -/// #[derive(Hash, Eq, PartialEq, Show)] +/// #[derive(Hash, Eq, PartialEq, Debug)] /// struct Viking { /// name: String, /// country: String, @@ -838,8 +838,8 @@ impl<K, V, S, H> HashMap<K, V, S> /// map.insert("b", 2); /// map.insert("c", 3); /// - /// for key in map.values() { - /// println!("{}", key); + /// for val in map.values() { + /// println!("{}", val); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -939,7 +939,7 @@ impl<K, V, S, H> HashMap<K, V, S> search_entry_hashed(&mut self.table, hash, key) } - /// Return the number of elements in the map. + /// Returns the number of elements in the map. /// /// # Example /// @@ -954,7 +954,7 @@ impl<K, V, S, H> HashMap<K, V, S> #[stable(feature = "rust1", since = "1.0.0")] pub fn len(&self) -> uint { self.table.size() } - /// Return true if the map contains no elements. + /// Returns true if the map contains no elements. /// /// # Example /// @@ -1218,8 +1218,8 @@ impl<K, V, S, H> Eq for HashMap<K, V, S> {} #[stable(feature = "rust1", since = "1.0.0")] -impl<K, V, S, H> Show for HashMap<K, V, S> - where K: Eq + Hash<H> + Show, V: Show, +impl<K, V, S, H> Debug for HashMap<K, V, S> + where K: Eq + Hash<H> + Debug, V: Debug, S: HashState<Hasher=H>, H: hash::Hasher<Output=u64> { @@ -1276,7 +1276,7 @@ impl<K, V, S, H, Q: ?Sized> IndexMut<Q> for HashMap<K, V, S> } } -/// HashMap iterator +/// HashMap iterator. #[stable(feature = "rust1", since = "1.0.0")] pub struct Iter<'a, K: 'a, V: 'a> { inner: table::Iter<'a, K, V> @@ -1291,13 +1291,13 @@ impl<'a, K, V> Clone for Iter<'a, K, V> { } } -/// HashMap mutable values iterator +/// HashMap mutable values iterator. #[stable(feature = "rust1", since = "1.0.0")] pub struct IterMut<'a, K: 'a, V: 'a> { inner: table::IterMut<'a, K, V> } -/// HashMap move iterator +/// HashMap move iterator. #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter<K, V> { inner: iter::Map< @@ -1308,7 +1308,7 @@ pub struct IntoIter<K, V> { > } -/// HashMap keys iterator +/// HashMap keys iterator. #[stable(feature = "rust1", since = "1.0.0")] pub struct Keys<'a, K: 'a, V: 'a> { inner: Map<(&'a K, &'a V), &'a K, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K> @@ -1323,7 +1323,7 @@ impl<'a, K, V> Clone for Keys<'a, K, V> { } } -/// HashMap values iterator +/// HashMap values iterator. #[stable(feature = "rust1", since = "1.0.0")] pub struct Values<'a, K: 'a, V: 'a> { inner: Map<(&'a K, &'a V), &'a V, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V> @@ -1338,7 +1338,7 @@ impl<'a, K, V> Clone for Values<'a, K, V> { } } -/// HashMap drain iterator +/// HashMap drain iterator. #[unstable(feature = "std_misc", reason = "matches collection reform specification, waiting for dust to settle")] pub struct Drain<'a, K: 'a, V: 'a> { @@ -1350,14 +1350,14 @@ pub struct Drain<'a, K: 'a, V: 'a> { > } -/// A view into a single occupied location in a HashMap +/// A view into a single occupied location in a HashMap. #[unstable(feature = "std_misc", reason = "precise API still being fleshed out")] pub struct OccupiedEntry<'a, K: 'a, V: 'a> { elem: FullBucket<K, V, &'a mut RawTable<K, V>>, } -/// A view into a single empty location in a HashMap +/// A view into a single empty location in a HashMap. #[unstable(feature = "std_misc", reason = "precise API still being fleshed out")] pub struct VacantEntry<'a, K: 'a, V: 'a> { @@ -1366,22 +1366,22 @@ pub struct VacantEntry<'a, K: 'a, V: 'a> { elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>, } -/// A view into a single location in a map, which may be vacant or occupied +/// A view into a single location in a map, which may be vacant or occupied. #[unstable(feature = "std_misc", reason = "precise API still being fleshed out")] pub enum Entry<'a, K: 'a, V: 'a> { - /// An occupied Entry + /// An occupied Entry. Occupied(OccupiedEntry<'a, K, V>), - /// A vacant Entry + /// A vacant Entry. Vacant(VacantEntry<'a, K, V>), } -/// Possible states of a VacantEntry +/// Possible states of a VacantEntry. enum VacantEntryState<K, V, M> { /// The index is occupied, but the key to insert has precedence, - /// and will kick the current one out on insertion + /// and will kick the current one out on insertion. NeqElem(FullBucket<K, V, M>, uint), - /// The index is genuinely vacant + /// The index is genuinely vacant. NoElem(EmptyBucket<K, V, M>), } @@ -1460,7 +1460,7 @@ impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> { #[unstable(feature = "std_misc", reason = "matches collection reform v2 specification, waiting for dust to settle")] impl<'a, K, V> Entry<'a, K, V> { - /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant + /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant. pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> { match self { Occupied(entry) => Ok(entry.into_mut()), @@ -1472,12 +1472,12 @@ impl<'a, K, V> Entry<'a, K, V> { #[unstable(feature = "std_misc", reason = "matches collection reform v2 specification, waiting for dust to settle")] impl<'a, K, V> OccupiedEntry<'a, K, V> { - /// Gets a reference to the value in the entry + /// Gets a reference to the value in the entry. pub fn get(&self) -> &V { self.elem.read().1 } - /// Gets a mutable reference to the value in the entry + /// Gets a mutable reference to the value in the entry. pub fn get_mut(&mut self) -> &mut V { self.elem.read_mut().1 } @@ -2009,8 +2009,8 @@ mod test_map { let map_str = format!("{:?}", map); - assert!(map_str == "HashMap {1i: 2i, 3i: 4i}" || - map_str == "HashMap {3i: 4i, 1i: 2i}"); + assert!(map_str == "HashMap {1: 2, 3: 4}" || + map_str == "HashMap {3: 4, 1: 2}"); assert_eq!(format!("{:?}", empty), "HashMap {}"); } diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index a6ebc402ade..84f01f70c3e 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -15,7 +15,7 @@ use clone::Clone; use cmp::{Eq, PartialEq}; use core::marker::Sized; use default::Default; -use fmt::Show; +use fmt::Debug; use fmt; use hash::{self, Hash}; use iter::{Iterator, ExactSizeIterator, IteratorExt, FromIterator, Map, Chain, Extend}; @@ -71,7 +71,7 @@ use super::state::HashState; /// /// ``` /// use std::collections::HashSet; -/// #[derive(Hash, Eq, PartialEq, Show)] +/// #[derive(Hash, Eq, PartialEq, Debug)] /// struct Viking<'a> { /// name: &'a str, /// power: uint, @@ -597,8 +597,8 @@ impl<T, S, H> Eq for HashSet<T, S> {} #[stable(feature = "rust1", since = "1.0.0")] -impl<T, S, H> fmt::Show for HashSet<T, S> - where T: Eq + Hash<H> + fmt::Show, +impl<T, S, H> fmt::Debug for HashSet<T, S> + where T: Eq + Hash<H> + fmt::Debug, S: HashState<Hasher=H>, H: hash::Hasher<Output=u64> { @@ -1180,7 +1180,7 @@ mod test_set { let set_str = format!("{:?}", set); - assert!(set_str == "HashSet {1i, 2i}" || set_str == "HashSet {2i, 1i}"); + assert!(set_str == "HashSet {1, 2}" || set_str == "HashSet {2, 1}"); assert_eq!(format!("{:?}", empty), "HashSet {}"); } diff --git a/src/libstd/collections/mod.rs b/src/libstd/collections/mod.rs index 1b8780120b1..0c55850b32a 100644 --- a/src/libstd/collections/mod.rs +++ b/src/libstd/collections/mod.rs @@ -49,8 +49,8 @@ //! * You want a double-ended queue (deque). //! //! ### Use a `DList` when: -//! * You want a `Vec` or `RingBuf` of unknown size, and can't tolerate inconsistent -//! performance during insertions. +//! * You want a `Vec` or `RingBuf` of unknown size, and can't tolerate amortization. +//! * You want to efficiently split and append lists. //! * You are *absolutely* certain you *really*, *truly*, want a doubly linked list. //! //! ### Use a `HashMap` when: @@ -85,6 +85,56 @@ //! or "most important" one at any given time. //! * You want a priority queue. //! +//! # Performance +//! +//! Choosing the right collection for the job requires an understanding of what each collection +//! is good at. Here we briefly summarize the performance of different collections for certain +//! important operations. For further details, see each type's documentation. +//! +//! Throughout the documentation, we will follow a few conventions. For all operations, +//! the collection's size is denoted by n. If another collection is involved in the operation, it +//! contains m elements. Operations which have an *amortized* cost are suffixed with a `*`. +//! Operations with an *expected* cost are suffixed with a `~`. +//! +//! All amortized costs are for the potential need to resize when capacity is exhausted. +//! If a resize occurs it will take O(n) time. Our collections never automatically shrink, +//! so removal operations aren't amortized. Over a sufficiently large series of +//! operations, the average cost per operation will deterministically equal the given cost. +//! +//! Only HashMap has expected costs, due to the probabilistic nature of hashing. It is +//! theoretically possible, though very unlikely, for HashMap to experience worse performance. +//! +//! ## Sequences +//! +//! | | get(i) | insert(i) | remove(i) | append | split_off(i) | +//! |---------|----------------|-----------------|----------------|--------|----------------| +//! | Vec | O(1) | O(n-i)* | O(n-i) | O(m)* | O(n-i) | +//! | RingBuf | O(1) | O(min(i, n-i))* | O(min(i, n-i)) | O(m)* | O(min(i, n-i)) | +//! | DList | O(min(i, n-i)) | O(min(i, n-i)) | O(min(i, n-i)) | O(1) | O(min(i, n-i)) | +//! | Bitv | O(1) | O(n-i)* | O(n-i) | O(m)* | O(n-i) | +//! +//! Note that where ties occur, Vec is generally going to be faster than RingBuf, and RingBuf +//! is generally going to be faster than DList. Bitv is not a general purpose collection, and +//! therefore cannot reasonably be compared. +//! +//! ## Maps +//! +//! For Sets, all operations have the cost of the equivalent Map operation. For BitvSet, +//! refer to VecMap. +//! +//! | | get | insert | remove | predecessor | +//! |----------|-----------|----------|----------|-------------| +//! | HashMap | O(1)~ | O(1)~* | O(1)~ | N/A | +//! | BTreeMap | O(log n) | O(log n) | O(log n) | O(log n) | +//! | VecMap | O(1) | O(1)? | O(1) | O(n) | +//! +//! Note that VecMap is *incredibly* inefficient in terms of space. The O(1) insertion time +//! assumes space for the element is already allocated. Otherwise, a large key may require a +//! massive reallocation, with no direct relation to the number of elements in the collection. +//! VecMap should only be seriously considered for small keys. +//! +//! Note also that BTreeMap's precise preformance depends on the value of B. +//! //! # Correct and Efficient Usage of Collections //! //! Of course, knowing which collection is the right one for the job doesn't instantly diff --git a/src/libstd/error.rs b/src/libstd/error.rs deleted file mode 100644 index 68ad3193e74..00000000000 --- a/src/libstd/error.rs +++ /dev/null @@ -1,139 +0,0 @@ -// 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. - -//! Traits for working with Errors. -//! -//! # The `Error` trait -//! -//! `Error` is a trait representing the basic expectations for error values, -//! i.e. values of type `E` in `Result<T, E>`. At a minimum, errors must provide -//! a description, but they may optionally provide additional detail and cause -//! chain information: -//! -//! ``` -//! trait Error { -//! fn description(&self) -> &str; -//! -//! fn detail(&self) -> Option<String> { None } -//! fn cause(&self) -> Option<&Error> { None } -//! } -//! ``` -//! -//! The `cause` method is generally used when errors cross "abstraction -//! boundaries", i.e. when a one module must report an error that is "caused" -//! by an error from a lower-level module. This setup makes it possible for the -//! high-level module to provide its own errors that do not commit to any -//! particular implementation, but also reveal some of its implementation for -//! debugging via `cause` chains. -//! -//! # The `FromError` trait -//! -//! `FromError` is a simple trait that expresses conversions between different -//! error types. To provide maximum flexibility, it does not require either of -//! the types to actually implement the `Error` trait, although this will be the -//! common case. -//! -//! The main use of this trait is in the `try!` macro, which uses it to -//! automatically convert a given error to the error specified in a function's -//! return type. -//! -//! For example, -//! -//! ``` -//! use std::error::FromError; -//! use std::io::{File, IoError}; -//! use std::os::{MemoryMap, MapError}; -//! use std::path::Path; -//! -//! enum MyError { -//! Io(IoError), -//! Map(MapError) -//! } -//! -//! impl FromError<IoError> for MyError { -//! fn from_error(err: IoError) -> MyError { -//! MyError::Io(err) -//! } -//! } -//! -//! impl FromError<MapError> for MyError { -//! fn from_error(err: MapError) -> MyError { -//! MyError::Map(err) -//! } -//! } -//! -//! #[allow(unused_variables)] -//! fn open_and_map() -> Result<(), MyError> { -//! let f = try!(File::open(&Path::new("foo.txt"))); -//! let m = try!(MemoryMap::new(0, &[])); -//! // do something interesting here... -//! Ok(()) -//! } -//! ``` - -#![stable(feature = "rust1", since = "1.0.0")] - -use prelude::v1::*; - -use str::Utf8Error; -use string::{FromUtf8Error, FromUtf16Error}; - -/// Base functionality for all errors in Rust. -#[unstable(feature = "std_misc", - reason = "the exact API of this trait may change")] -pub trait Error { - /// A short description of the error; usually a static string. - fn description(&self) -> &str; - - /// A detailed description of the error, usually including dynamic information. - fn detail(&self) -> Option<String> { None } - - /// The lower-level cause of this error, if any. - fn cause(&self) -> Option<&Error> { None } -} - -/// A trait for types that can be converted from a given error type `E`. -#[stable(feature = "rust1", since = "1.0.0")] -pub trait FromError<E> { - /// Perform the conversion. - #[stable(feature = "rust1", since = "1.0.0")] - fn from_error(err: E) -> Self; -} - -// Any type is convertable from itself -#[stable(feature = "rust1", since = "1.0.0")] -impl<E> FromError<E> for E { - fn from_error(err: E) -> E { - err - } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl Error for Utf8Error { - fn description(&self) -> &str { - match *self { - Utf8Error::TooShort => "invalid utf-8: not enough bytes", - Utf8Error::InvalidByte(..) => "invalid utf-8: corrupt contents", - } - } - - fn detail(&self) -> Option<String> { Some(self.to_string()) } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl Error for FromUtf8Error { - fn description(&self) -> &str { "invalid utf-8" } - fn detail(&self) -> Option<String> { Some(self.to_string()) } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl Error for FromUtf16Error { - fn description(&self) -> &str { "invalid utf-16" } -} diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index d7f8eb2e415..fdd7aa216d3 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -115,11 +115,12 @@ impl Deref for CString { type Target = [libc::c_char]; fn deref(&self) -> &[libc::c_char] { - self.inner.slice_to(self.inner.len() - 1) + &self.inner[..(self.inner.len() - 1)] } } -impl fmt::Show for CString { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Debug for CString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { String::from_utf8_lossy(self.as_bytes()).fmt(f) } @@ -215,4 +216,10 @@ mod tests { assert_eq!(s.as_bytes(), b"\0"); } } + + #[test] + fn formatted() { + let s = CString::from_slice(b"12"); + assert_eq!(format!("{:?}", s), "\"12\""); + } } diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs index 57b57bdfe95..6f2e011d595 100644 --- a/src/libstd/fmt.rs +++ b/src/libstd/fmt.rs @@ -123,8 +123,8 @@ //! This allows multiple actual types to be formatted via `{:x}` (like `i8` as //! well as `int`). The current mapping of types to traits is: //! -//! * *nothing* ⇒ `String` -//! * `?` ⇒ `Show` +//! * *nothing* ⇒ `Display` +//! * `?` ⇒ `Debug` //! * `o` ⇒ `Octal` //! * `x` ⇒ `LowerHex` //! * `X` ⇒ `UpperHex` @@ -137,7 +137,7 @@ //! `std::fmt::Binary` trait can then be formatted with `{:b}`. Implementations //! are provided for these traits for a number of primitive types by the //! standard library as well. If no format is specified (as in `{}` or `{:6}`), -//! then the format trait used is the `String` trait. +//! then the format trait used is the `Display` trait. //! //! When implementing a format trait for your own type, you will have to //! implement a method of the signature: @@ -145,7 +145,7 @@ //! ```rust //! # use std::fmt; //! # struct Foo; // our custom type -//! # impl fmt::Show for Foo { +//! # impl fmt::Display for Foo { //! fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result { //! # write!(f, "testing, testing") //! # } } @@ -171,13 +171,13 @@ //! use std::f64; //! use std::num::Float; //! -//! #[derive(Show)] +//! #[derive(Debug)] //! struct Vector2D { //! x: int, //! y: int, //! } //! -//! impl fmt::String for Vector2D { +//! impl fmt::Display for Vector2D { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! // The `f` value implements the `Writer` trait, which is what the //! // write! macro is expecting. Note that this formatting ignores the @@ -211,22 +211,22 @@ //! } //! ``` //! -//! #### fmt::String vs fmt::Show +//! #### fmt::Display vs fmt::Debug //! //! These two formatting traits have distinct purposes: //! -//! - `fmt::String` implementations assert that the type can be faithfully +//! - `fmt::Display` implementations assert that the type can be faithfully //! represented as a UTF-8 string at all times. It is **not** expected that -//! all types implement the `String` trait. -//! - `fmt::Show` implementations should be implemented for **all** public types. +//! all types implement the `Display` trait. +//! - `fmt::Debug` implementations should be implemented for **all** public types. //! Output will typically represent the internal state as faithfully as possible. -//! The purpose of the `Show` trait is to facilitate debugging Rust code. In -//! most cases, using `#[derive(Show)]` is sufficient and recommended. +//! The purpose of the `Debug` trait is to facilitate debugging Rust code. In +//! most cases, using `#[derive(Debug)]` is sufficient and recommended. //! //! Some examples of the output from both traits: //! //! ``` -//! assert_eq!(format!("{} {:?}", 3i32, 4i32), "3 4i32"); +//! assert_eq!(format!("{} {:?}", 3i32, 4i32), "3 4"); //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'"); //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\""); //! ``` @@ -409,6 +409,7 @@ use string; pub use core::fmt::{Formatter, Result, Writer, rt}; pub use core::fmt::{Show, String, Octal, Binary}; +pub use core::fmt::{Display, Debug}; pub use core::fmt::{LowerHex, UpperHex, Pointer}; pub use core::fmt::{LowerExp, UpperExp}; pub use core::fmt::Error; diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 8c38bc009cc..1c1c73cddd1 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -52,7 +52,8 @@ pub struct BufferedReader<R> { cap: uint, } -impl<R> fmt::Show for BufferedReader<R> where R: fmt::Show { +#[stable(feature = "rust1", since = "1.0.0")] +impl<R> fmt::Debug for BufferedReader<R> where R: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "BufferedReader {{ reader: {:?}, buffer: {}/{} }}", self.inner, self.cap - self.pos, self.buf.len()) @@ -150,7 +151,8 @@ pub struct BufferedWriter<W> { pos: uint } -impl<W> fmt::Show for BufferedWriter<W> where W: fmt::Show { +#[stable(feature = "rust1", since = "1.0.0")] +impl<W> fmt::Debug for BufferedWriter<W> where W: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "BufferedWriter {{ writer: {:?}, buffer: {}/{} }}", self.inner.as_ref().unwrap(), self.pos, self.buf.len()) @@ -219,7 +221,7 @@ impl<W: Writer> Writer for BufferedWriter<W> { if buf.len() > self.buf.len() { self.inner.as_mut().unwrap().write(buf) } else { - let dst = self.buf.slice_from_mut(self.pos); + let dst = &mut self.buf[self.pos..]; slice::bytes::copy_memory(dst, buf); self.pos += buf.len(); Ok(()) @@ -249,7 +251,8 @@ pub struct LineBufferedWriter<W> { inner: BufferedWriter<W>, } -impl<W> fmt::Show for LineBufferedWriter<W> where W: fmt::Show { +#[stable(feature = "rust1", since = "1.0.0")] +impl<W> fmt::Debug for LineBufferedWriter<W> where W: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "LineBufferedWriter {{ writer: {:?}, buffer: {}/{} }}", self.inner.inner, self.inner.pos, self.inner.buf.len()) @@ -281,9 +284,9 @@ impl<W: Writer> Writer for LineBufferedWriter<W> { fn write(&mut self, buf: &[u8]) -> IoResult<()> { match buf.iter().rposition(|&b| b == b'\n') { Some(i) => { - try!(self.inner.write(&buf[..(i + 1)])); + try!(self.inner.write(&buf[..i + 1])); try!(self.inner.flush()); - try!(self.inner.write(&buf[(i + 1)..])); + try!(self.inner.write(&buf[i + 1..])); Ok(()) } None => self.inner.write(buf), @@ -339,7 +342,8 @@ pub struct BufferedStream<S> { inner: BufferedReader<InternalBufferedWriter<S>> } -impl<S> fmt::Show for BufferedStream<S> where S: fmt::Show { +#[stable(feature = "rust1", since = "1.0.0")] +impl<S> fmt::Debug for BufferedStream<S> where S: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let reader = &self.inner; let writer = &self.inner.inner.0; diff --git a/src/libstd/io/comm_adapters.rs b/src/libstd/io/comm_adapters.rs index 20901d9c50e..d3d49d41a67 100644 --- a/src/libstd/io/comm_adapters.rs +++ b/src/libstd/io/comm_adapters.rs @@ -72,7 +72,7 @@ impl Buffer for ChanReader { if self.closed { Err(io::standard_error(io::EndOfFile)) } else { - Ok(self.buf.slice_from(self.pos)) + Ok(&self.buf[self.pos..]) } } @@ -88,7 +88,7 @@ impl Reader for ChanReader { loop { let count = match self.fill_buf().ok() { Some(src) => { - let dst = buf.slice_from_mut(num_read); + let dst = &mut buf[num_read..]; let count = cmp::min(src.len(), dst.len()); bytes::copy_memory(dst, &src[..count]); count diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index 64406d88253..cc36c5640d0 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -156,7 +156,7 @@ impl File { }) } }).update_err("couldn't open path as file", |e| { - format!("{}; path={:?}; mode={}; access={}", e, path.display(), + format!("{}; path={}; mode={}; access={}", e, path.display(), mode_string(mode), access_string(access)) }) } @@ -211,7 +211,7 @@ impl File { pub fn fsync(&mut self) -> IoResult<()> { self.fd.fsync() .update_err("couldn't fsync file", - |e| format!("{}; path={:?}", e, self.path.display())) + |e| format!("{}; path={}", e, self.path.display())) } /// This function is similar to `fsync`, except that it may not synchronize @@ -221,7 +221,7 @@ impl File { pub fn datasync(&mut self) -> IoResult<()> { self.fd.datasync() .update_err("couldn't datasync file", - |e| format!("{}; path={:?}", e, self.path.display())) + |e| format!("{}; path={}", e, self.path.display())) } /// Either truncates or extends the underlying file, updating the size of @@ -235,7 +235,7 @@ impl File { pub fn truncate(&mut self, size: i64) -> IoResult<()> { self.fd.truncate(size) .update_err("couldn't truncate file", |e| - format!("{}; path={:?}; size={:?}", e, self.path.display(), size)) + format!("{}; path={}; size={}", e, self.path.display(), size)) } /// Returns true if the stream has reached the end of the file. @@ -255,7 +255,7 @@ impl File { pub fn stat(&self) -> IoResult<FileStat> { self.fd.fstat() .update_err("couldn't fstat file", |e| - format!("{}; path={:?}", e, self.path.display())) + format!("{}; path={}", e, self.path.display())) } } @@ -283,7 +283,7 @@ impl File { pub fn unlink(path: &Path) -> IoResult<()> { fs_imp::unlink(path) .update_err("couldn't unlink path", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } /// Given a path, query the file system to get information about a file, @@ -310,7 +310,7 @@ pub fn unlink(path: &Path) -> IoResult<()> { pub fn stat(path: &Path) -> IoResult<FileStat> { fs_imp::stat(path) .update_err("couldn't stat path", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } /// Perform the same operation as the `stat` function, except that this @@ -324,7 +324,7 @@ pub fn stat(path: &Path) -> IoResult<FileStat> { pub fn lstat(path: &Path) -> IoResult<FileStat> { fs_imp::lstat(path) .update_err("couldn't lstat path", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } /// Rename a file or directory to a new name. @@ -424,14 +424,14 @@ pub fn copy(from: &Path, to: &Path) -> IoResult<()> { pub fn chmod(path: &Path, mode: io::FilePermission) -> IoResult<()> { fs_imp::chmod(path, mode.bits() as uint) .update_err("couldn't chmod path", |e| - format!("{}; path={:?}; mode={:?}", e, path.display(), mode)) + format!("{}; path={}; mode={:?}", e, path.display(), mode)) } /// Change the user and group owners of a file at the specified path. pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> { fs_imp::chown(path, uid, gid) .update_err("couldn't chown path", |e| - format!("{}; path={:?}; uid={}; gid={}", e, path.display(), uid, gid)) + format!("{}; path={}; uid={}; gid={}", e, path.display(), uid, gid)) } /// Creates a new hard link on the filesystem. The `dst` path will be a @@ -460,7 +460,7 @@ pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> { pub fn readlink(path: &Path) -> IoResult<Path> { fs_imp::readlink(path) .update_err("couldn't resolve symlink for path", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } /// Create a new, empty directory at the provided path @@ -483,7 +483,7 @@ pub fn readlink(path: &Path) -> IoResult<Path> { pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> { fs_imp::mkdir(path, mode.bits() as uint) .update_err("couldn't create directory", |e| - format!("{}; path={:?}; mode={:?}", e, path.display(), mode)) + format!("{}; path={}; mode={}", e, path.display(), mode)) } /// Remove an existing, empty directory @@ -505,7 +505,7 @@ pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> { pub fn rmdir(path: &Path) -> IoResult<()> { fs_imp::rmdir(path) .update_err("couldn't remove directory", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } /// Retrieve a vector containing all entries within a provided directory @@ -545,7 +545,7 @@ pub fn rmdir(path: &Path) -> IoResult<()> { pub fn readdir(path: &Path) -> IoResult<Vec<Path>> { fs_imp::readdir(path) .update_err("couldn't read directory", - |e| format!("{}; path={:?}", e, path.display())) + |e| format!("{}; path={}", e, path.display())) } /// Returns an iterator that will recursively walk the directory structure @@ -555,7 +555,7 @@ pub fn readdir(path: &Path) -> IoResult<Vec<Path>> { pub fn walk_dir(path: &Path) -> IoResult<Directories> { Ok(Directories { stack: try!(readdir(path).update_err("couldn't walk directory", - |e| format!("{}; path={:?}", e, path.display()))) + |e| format!("{}; path={}", e, path.display()))) }) } @@ -605,7 +605,7 @@ pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> { let result = mkdir(&curpath, mode) .update_err("couldn't recursively mkdir", - |e| format!("{}; path={:?}", e, path.display())); + |e| format!("{}; path={}", e, path.display())); match result { Err(mkdir_err) => { @@ -632,7 +632,7 @@ pub fn rmdir_recursive(path: &Path) -> IoResult<()> { rm_stack.push(path.clone()); fn rmdir_failed(err: &IoError, path: &Path) -> String { - format!("rmdir_recursive failed; path={:?}; cause={}", + format!("rmdir_recursive failed; path={}; cause={}", path.display(), err) } @@ -692,14 +692,14 @@ pub fn rmdir_recursive(path: &Path) -> IoResult<()> { pub fn change_file_times(path: &Path, atime: u64, mtime: u64) -> IoResult<()> { fs_imp::utime(path, atime, mtime) .update_err("couldn't change_file_times", |e| - format!("{}; path={:?}", e, path.display())) + format!("{}; path={}", e, path.display())) } impl Reader for File { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { fn update_err<T>(result: IoResult<T>, file: &File) -> IoResult<T> { result.update_err("couldn't read file", - |e| format!("{}; path={:?}", + |e| format!("{}; path={}", e, file.path.display())) } @@ -722,7 +722,7 @@ impl Writer for File { fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.fd.write(buf) .update_err("couldn't write to file", - |e| format!("{}; path={:?}", e, self.path.display())) + |e| format!("{}; path={}", e, self.path.display())) } } @@ -730,7 +730,7 @@ impl Seek for File { fn tell(&self) -> IoResult<u64> { self.fd.tell() .update_err("couldn't retrieve file cursor (`tell`)", - |e| format!("{}; path={:?}", e, self.path.display())) + |e| format!("{}; path={}", e, self.path.display())) } fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> { @@ -743,7 +743,7 @@ impl Seek for File { Err(e) => Err(e), }; err.update_err("couldn't seek in file", - |e| format!("{}; path={:?}", e, self.path.display())) + |e| format!("{}; path={}", e, self.path.display())) } } @@ -906,7 +906,7 @@ mod test { if cfg!(unix) { error!(result, "no such file or directory"); } - error!(result, format!("path={:?}; mode=open; access=read", filename.display())); + error!(result, format!("path={}; mode=open; access=read", filename.display())); } #[test] @@ -920,7 +920,7 @@ mod test { if cfg!(unix) { error!(result, "no such file or directory"); } - error!(result, format!("path={:?}", filename.display())); + error!(result, format!("path={}", filename.display())); } #[test] @@ -1188,7 +1188,7 @@ mod test { error!(result, "couldn't recursively mkdir"); error!(result, "couldn't create directory"); error!(result, "mode=0700"); - error!(result, format!("path={:?}", file.display())); + error!(result, format!("path={}", file.display())); } #[test] diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index bbc3f80dd86..8c0de781994 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -161,8 +161,8 @@ impl Reader for MemReader { let write_len = min(buf.len(), self.buf.len() - self.pos); { - let input = &self.buf[self.pos.. (self.pos + write_len)]; - let output = buf.slice_to_mut(write_len); + let input = &self.buf[self.pos.. self.pos + write_len]; + let output = &mut buf[..write_len]; assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); } @@ -207,11 +207,11 @@ impl<'a> Reader for &'a [u8] { let write_len = min(buf.len(), self.len()); { let input = &self[..write_len]; - let output = buf.slice_to_mut(write_len); + let output = &mut buf[.. write_len]; slice::bytes::copy_memory(output, input); } - *self = self.slice_from(write_len); + *self = &self[write_len..]; Ok(write_len) } @@ -272,7 +272,7 @@ impl<'a> BufWriter<'a> { impl<'a> Writer for BufWriter<'a> { #[inline] fn write(&mut self, src: &[u8]) -> IoResult<()> { - let dst = self.buf.slice_from_mut(self.pos); + let dst = &mut self.buf[self.pos..]; let dst_len = dst.len(); if dst_len == 0 { @@ -351,8 +351,8 @@ impl<'a> Reader for BufReader<'a> { let write_len = min(buf.len(), self.buf.len() - self.pos); { - let input = &self.buf[self.pos.. (self.pos + write_len)]; - let output = buf.slice_to_mut(write_len); + let input = &self.buf[self.pos.. self.pos + write_len]; + let output = &mut buf[..write_len]; assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); } @@ -434,8 +434,8 @@ mod test { writer.write(&[]).unwrap(); assert_eq!(writer.tell(), Ok(8)); - assert_eq!(writer.write(&[8, 9]).unwrap_err().kind, io::ShortWrite(1)); - assert_eq!(writer.write(&[10]).unwrap_err().kind, io::EndOfFile); + assert_eq!(writer.write(&[8, 9]).err().unwrap().kind, io::ShortWrite(1)); + assert_eq!(writer.write(&[10]).err().unwrap().kind, io::EndOfFile); } let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8]; assert_eq!(buf, b); diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 0046a323d07..cc7f9f5b892 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -228,13 +228,12 @@ pub use self::FileAccess::*; pub use self::IoErrorKind::*; use char::CharExt; -use clone::Clone; use default::Default; -use error::{FromError, Error}; +use error::Error; use fmt; use int; use iter::{Iterator, IteratorExt}; -use marker::{Sized, Send}; +use marker::Sized; use mem::transmute; use ops::FnOnce; use option::Option; @@ -340,7 +339,8 @@ impl IoError { } } -impl fmt::String for IoError { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for IoError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } => @@ -354,19 +354,7 @@ impl fmt::String for IoError { } impl Error for IoError { - fn description(&self) -> &str { - self.desc - } - - fn detail(&self) -> Option<String> { - self.detail.clone() - } -} - -impl FromError<IoError> for Box<Error + Send> { - fn from_error(err: IoError) -> Box<Error + Send> { - box err - } + fn description(&self) -> &str { self.desc } } /// A list specifying general categories of I/O error. @@ -516,7 +504,7 @@ pub trait Reader { while read < min { let mut zeroes = 0; loop { - match self.read(buf.slice_from_mut(read)) { + match self.read(&mut buf[read..]) { Ok(0) => { zeroes += 1; if zeroes >= NO_PROGRESS_LIMIT { @@ -1436,33 +1424,31 @@ pub trait Buffer: Reader { fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> { let mut res = Vec::new(); - let mut used; loop { - { + let (done, used) = { let available = match self.fill_buf() { Ok(n) => n, Err(ref e) if res.len() > 0 && e.kind == EndOfFile => { - used = 0; - break + return Ok(res); } Err(e) => return Err(e) }; match available.iter().position(|&b| b == byte) { Some(i) => { - res.push_all(&available[..(i + 1)]); - used = i + 1; - break + res.push_all(&available[..i + 1]); + (true, i + 1) } None => { res.push_all(available); - used = available.len(); + (false, available.len()) } } - } + }; self.consume(used); + if done { + return Ok(res); + } } - self.consume(used); - Ok(res) } /// Reads the next utf8-encoded character from the underlying stream. @@ -1481,7 +1467,7 @@ pub trait Buffer: Reader { { let mut start = 1; while start < width { - match try!(self.read(buf.slice_mut(start, width))) { + match try!(self.read(&mut buf[start .. width])) { n if n == width - start => break, n if n < width - start => { start += n; } _ => return Err(standard_error(InvalidInput)), @@ -1780,6 +1766,7 @@ pub struct UnstableFileStat { bitflags! { /// A set of permissions for a file or directory is represented by a set of /// flags which are or'd together. + #[derive(Show)] flags FilePermission: u32 { const USER_READ = 0o400, const USER_WRITE = 0o200, @@ -1821,13 +1808,8 @@ impl Default for FilePermission { fn default() -> FilePermission { FilePermission::empty() } } -impl fmt::Show for FilePermission { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - -impl fmt::String for FilePermission { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for FilePermission { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:04o}", self.bits) } diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index adc122ff447..7e7603c826e 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -38,7 +38,8 @@ pub enum IpAddr { Ipv6Addr(u16, u16, u16, u16, u16, u16, u16, u16) } -impl fmt::String for IpAddr { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for IpAddr { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Ipv4Addr(a, b, c, d) => @@ -69,7 +70,8 @@ pub struct SocketAddr { pub port: Port, } -impl fmt::String for SocketAddr { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for SocketAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.ip { Ipv4Addr(..) => write!(f, "{}:{}", self.ip, self.port), @@ -251,7 +253,7 @@ impl<'a> Parser<'a> { assert!(head.len() + tail.len() <= 8); let mut gs = [0u16; 8]; gs.clone_from_slice(head); - gs.slice_mut(8 - tail.len(), 8).clone_from_slice(tail); + gs[(8 - tail.len()) .. 8].clone_from_slice(tail); Ipv6Addr(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7]) } diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 6b09ac9a58f..a406d3c2788 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -20,9 +20,6 @@ use prelude::v1::*; use collections::HashMap; use ffi::CString; use fmt; -// NOTE(stage0) remove import after a snapshot -#[cfg(stage0)] -use hash::Hash; use io::pipe::{PipeStream, PipePair}; use io::{IoResult, IoError}; use io; @@ -396,7 +393,7 @@ impl Command { } } -impl fmt::String for Command { +impl fmt::Debug for Command { /// Format the program and arguments of a Command for display. Any /// non-utf8 data is lossily converted using the utf8 replacement /// character. @@ -495,7 +492,7 @@ pub enum StdioContainer { /// Describes the result of a process after it has terminated. /// Note that Windows have no signals, so the result is usually ExitStatus. -#[derive(PartialEq, Eq, Clone, Copy)] +#[derive(PartialEq, Eq, Clone, Copy, Show)] pub enum ProcessExit { /// Normal termination with an exit status. ExitStatus(int), @@ -504,15 +501,8 @@ pub enum ProcessExit { ExitSignal(int), } -impl fmt::Show for ProcessExit { - /// Format a ProcessExit enum, to nicely present the information. - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - - -impl fmt::String for ProcessExit { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for ProcessExit { /// Format a ProcessExit enum, to nicely present the information. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 9ee2f5705b8..a5664b9f013 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -40,6 +40,7 @@ use mem; use option::Option; use option::Option::{Some, None}; use ops::{Deref, DerefMut, FnOnce}; +use ptr; use result::Result::{Ok, Err}; use rt; use slice::SliceExt; @@ -238,7 +239,7 @@ pub fn stdin() -> StdinReader { // Make sure to free it at exit rt::at_exit(|| { mem::transmute::<_, Box<StdinReader>>(STDIN); - STDIN = 0 as *const _; + STDIN = ptr::null(); }); }); diff --git a/src/libstd/io/timer.rs b/src/libstd/io/timer.rs index 844a97dea2d..68ae7d0ff20 100644 --- a/src/libstd/io/timer.rs +++ b/src/libstd/io/timer.rs @@ -228,6 +228,12 @@ mod test { use time::Duration; #[test] + fn test_timer_send() { + let mut timer = Timer::new().unwrap(); + Thread::spawn(move || timer.sleep(Duration::milliseconds(1))); + } + + #[test] fn test_io_timer_sleep_simple() { let mut timer = Timer::new().unwrap(); timer.sleep(Duration::milliseconds(1)); diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index adfd88644cc..e4bf38a9ef5 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -48,7 +48,7 @@ impl<R: Reader> Reader for LimitReader<R> { } let len = cmp::min(self.limit, buf.len()); - let res = self.inner.read(buf.slice_to_mut(len)); + let res = self.inner.read(&mut buf[..len]); match res { Ok(len) => self.limit -= len, _ => {} diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index d708f4df2a5..4827bc2b3c8 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -176,6 +176,7 @@ pub use core::raw; pub use core::simd; pub use core::result; pub use core::option; +pub use core::error; #[cfg(not(test))] pub use alloc::boxed; pub use alloc::rc; @@ -236,7 +237,6 @@ pub mod thunk; /* Common traits */ -pub mod error; pub mod num; /* Runtime and platform support */ diff --git a/src/libstd/num/mod.rs b/src/libstd/num/mod.rs index c81dfad63d7..dad8b70ceac 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num/mod.rs @@ -16,7 +16,7 @@ #![stable(feature = "rust1", since = "1.0.0")] #![allow(missing_docs)] -#[cfg(test)] use fmt::Show; +#[cfg(test)] use fmt::Debug; use ops::{Add, Sub, Mul, Div, Rem, Neg}; use marker::Copy; @@ -353,7 +353,7 @@ pub fn test_num<T>(ten: T, two: T) where T: PartialEq + NumCast + Add<Output=T> + Sub<Output=T> + Mul<Output=T> + Div<Output=T> - + Rem<Output=T> + Show + + Rem<Output=T> + Debug + Copy { assert_eq!(ten.add(two), cast(12i).unwrap()); diff --git a/src/libstd/num/strconv.rs b/src/libstd/num/strconv.rs index 67fe599ecd6..1d3bf484edb 100644 --- a/src/libstd/num/strconv.rs +++ b/src/libstd/num/strconv.rs @@ -379,14 +379,14 @@ pub fn float_to_str_bytes_common<T: Float>( // only resize buf if we actually remove digits if i < buf_max_i { - buf = buf.slice(0, i + 1).to_vec(); + buf = buf[.. (i + 1)].to_vec(); } } } // If exact and trailing '.', just cut that else { let max_i = buf.len() - 1; if buf[max_i] == b'.' { - buf = buf.slice(0, max_i).to_vec(); + buf = buf[.. max_i].to_vec(); } } diff --git a/src/libstd/os.rs b/src/libstd/os.rs index efd571be9e2..d81e2b3aa4b 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -855,7 +855,7 @@ pub enum MapOption { impl Copy for MapOption {} /// Possible errors when creating a map. -#[derive(Copy)] +#[derive(Copy, Show)] pub enum MapError { /// # The following are POSIX-specific /// @@ -900,7 +900,8 @@ pub enum MapError { ErrMapViewOfFile(uint) } -impl fmt::Show for MapError { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for MapError { fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result { let str = match *self { ErrFdNotAvail => "fd not available for reading or writing", @@ -934,13 +935,6 @@ impl fmt::Show for MapError { impl Error for MapError { fn description(&self) -> &str { "memory map error" } - fn detail(&self) -> Option<String> { Some(format!("{:?}", self)) } -} - -impl FromError<MapError> for Box<Error + Send> { - fn from_error(err: MapError) -> Box<Error + Send> { - box err - } } // Round up `from` to be divisible by `to` diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 7a34a1d8c38..e4a662f8463 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -399,7 +399,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { match name.rposition_elem(&dot) { None | Some(0) => None, Some(1) if name == b".." => None, - Some(pos) => Some(&name[(pos+1)..]) + Some(pos) => Some(&name[pos+1..]) } } } @@ -823,13 +823,15 @@ pub struct Display<'a, P:'a> { filename: bool } -impl<'a, P: GenericPath> fmt::Show for Display<'a, P> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, P: GenericPath> fmt::Debug for Display<'a, P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Debug::fmt(&self.as_cow(), f) } } -impl<'a, P: GenericPath> fmt::String for Display<'a, P> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, P: GenericPath> fmt::Display for Display<'a, P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_cow().fmt(f) } diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index aab64639ab5..07fdd1a830f 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -57,9 +57,10 @@ pub fn is_sep(c: char) -> bool { c == SEP } -impl fmt::Show for Path { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Debug for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(&self.display(), f) + fmt::Debug::fmt(&self.display(), f) } } @@ -126,7 +127,7 @@ impl GenericPathUnsafe for Path { None => { self.repr = Path::normalize(filename); } - Some(idx) if &self.repr[(idx+1)..] == b".." => { + Some(idx) if &self.repr[idx+1..] == b".." => { let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len()); v.push_all(self.repr.as_slice()); v.push(SEP_BYTE); @@ -136,7 +137,7 @@ impl GenericPathUnsafe for Path { } Some(idx) => { let mut v = Vec::with_capacity(idx + 1 + filename.len()); - v.push_all(&self.repr[..(idx+1)]); + v.push_all(&self.repr[..idx+1]); v.push_all(filename); // FIXME: this is slow self.repr = Path::normalize(v.as_slice()); @@ -178,7 +179,7 @@ impl GenericPath for Path { None if b".." == self.repr => self.repr.as_slice(), None => dot_static, Some(0) => &self.repr[..1], - Some(idx) if &self.repr[(idx+1)..] == b".." => self.repr.as_slice(), + Some(idx) if &self.repr[idx+1..] == b".." => self.repr.as_slice(), Some(idx) => &self.repr[..idx] } } @@ -188,9 +189,9 @@ impl GenericPath for Path { None if b"." == self.repr || b".." == self.repr => None, None => Some(self.repr.as_slice()), - Some(idx) if &self.repr[(idx+1)..] == b".." => None, + Some(idx) if &self.repr[idx+1..] == b".." => None, Some(0) if self.repr[1..].is_empty() => None, - Some(idx) => Some(&self.repr[(idx+1)..]) + Some(idx) => Some(&self.repr[idx+1..]) } } diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 3cff1c67be3..ebded1f0855 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -85,9 +85,10 @@ pub struct Path { sepidx: Option<uint> // index of the final separator in the non-prefix portion of repr } -impl fmt::Show for Path { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Debug for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(&self.display(), f) + fmt::Debug::fmt(&self.display(), f) } } @@ -428,10 +429,10 @@ impl GenericPath for Path { if self.prefix.is_some() { Some(Path::new(match self.prefix { Some(DiskPrefix) if self.is_absolute() => { - &self.repr[..(self.prefix_len()+1)] + &self.repr[..self.prefix_len()+1] } Some(VerbatimDiskPrefix) => { - &self.repr[..(self.prefix_len()+1)] + &self.repr[..self.prefix_len()+1] } _ => &self.repr[..self.prefix_len()] })) @@ -635,7 +636,7 @@ impl Path { Some(_) => { let plen = self.prefix_len(); if repr.len() > plen && repr.as_bytes()[plen] == SEP_BYTE { - &repr[(plen+1)..] + &repr[plen+1..] } else { &repr[plen..] } } None if repr.as_bytes()[0] == SEP_BYTE => &repr[1..], @@ -786,9 +787,9 @@ impl Path { } Some(UNCPrefix(a,b)) => { s.push_str("\\\\"); - s.push_str(&prefix_[2..(a+2)]); + s.push_str(&prefix_[2..a+2]); s.push(SEP); - s.push_str(&prefix_[(3+a)..(3+a+b)]); + s.push_str(&prefix_[3+a..3+a+b]); } Some(_) => s.push_str(prefix_), None => () @@ -813,7 +814,7 @@ impl Path { fn update_sepidx(&mut self) { let s = if self.has_nonsemantic_trailing_slash() { - &self.repr[..(self.repr.len()-1)] + &self.repr[..self.repr.len()-1] } else { &self.repr[] }; let sep_test: fn(char) -> bool = if !prefix_is_verbatim(self.prefix) { is_sep @@ -1029,7 +1030,7 @@ fn parse_prefix<'a>(mut path: &'a str) -> Option<PathPrefix> { None => return None, Some(x) => x }; - path = &path[(idx_a+1)..]; + path = &path[idx_a+1..]; let idx_b = path.find(f).unwrap_or(path.len()); Some((idx_a, idx_b)) } diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index 68ba7e1dd29..bafbde2511d 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -65,7 +65,7 @@ mod imp { let mut read = 0; let len = v.len(); while read < len { - let result = getrandom(v.slice_from_mut(read)); + let result = getrandom(&mut v[read..]); if result == -1 { let err = errno() as libc::c_int; if err == libc::EINTR { diff --git a/src/libstd/rt/unwind.rs b/src/libstd/rt/unwind.rs index 7d886f9936f..18298f1c7f4 100644 --- a/src/libstd/rt/unwind.rs +++ b/src/libstd/rt/unwind.rs @@ -152,7 +152,7 @@ pub unsafe fn try<F: FnOnce()>(f: F) -> Result<(), Box<Any + Send>> { } } -/// Test if the current thread is currently panicking. +/// Determines whether the current thread is unwinding because of panic. pub fn panicking() -> bool { PANICKING.with(|s| s.get()) } diff --git a/src/libstd/rt/util.rs b/src/libstd/rt/util.rs index 235cedcda52..4023a0a4c10 100644 --- a/src/libstd/rt/util.rs +++ b/src/libstd/rt/util.rs @@ -130,7 +130,7 @@ pub fn abort(args: fmt::Arguments) -> ! { } impl<'a> fmt::Writer for BufWriter<'a> { fn write_str(&mut self, bytes: &str) -> fmt::Result { - let left = self.buf.slice_from_mut(self.pos); + let left = &mut self.buf[self.pos..]; let to_write = &bytes.as_bytes()[..cmp::min(bytes.len(), left.len())]; slice::bytes::copy_memory(left, to_write); self.pos += to_write.len(); diff --git a/src/libstd/sync/mpsc/blocking.rs b/src/libstd/sync/mpsc/blocking.rs index 17e690e9540..61ffb532d36 100644 --- a/src/libstd/sync/mpsc/blocking.rs +++ b/src/libstd/sync/mpsc/blocking.rs @@ -14,8 +14,6 @@ use thread::Thread; use sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use sync::Arc; use marker::{Sync, Send}; -#[cfg(stage0)] // NOTE remove use after next snapshot -use marker::{NoSend, NoSync}; use mem; use clone::Clone; @@ -32,42 +30,14 @@ pub struct SignalToken { inner: Arc<Inner>, } -#[cfg(stage0)] // NOTE remove impl after next snapshot pub struct WaitToken { inner: Arc<Inner>, - no_send: NoSend, - no_sync: NoSync, } -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct WaitToken { - inner: Arc<Inner>, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !Send for WaitToken {} -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !Sync for WaitToken {} -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub fn tokens() -> (WaitToken, SignalToken) { - let inner = Arc::new(Inner { - thread: Thread::current(), - woken: ATOMIC_BOOL_INIT, - }); - let wait_token = WaitToken { - inner: inner.clone(), - no_send: NoSend, - no_sync: NoSync, - }; - let signal_token = SignalToken { - inner: inner - }; - (wait_token, signal_token) -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn tokens() -> (WaitToken, SignalToken) { let inner = Arc::new(Inner { thread: Thread::current(), diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 8fce8cbabcc..101af8d5e9a 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -319,7 +319,6 @@ use prelude::v1::*; use sync::Arc; use fmt; -use marker; use mem; use cell::UnsafeCell; @@ -369,31 +368,21 @@ unsafe impl<T:Send> Send for Sender<T> { } /// The sending-half of Rust's synchronous channel type. This half can only be /// owned by one task, but it can be cloned to send to other tasks. -#[cfg(stage0)] // NOTE remove impl after next snapshot #[stable(feature = "rust1", since = "1.0.0")] pub struct SyncSender<T> { - inner: Arc<RacyCell<sync::Packet<T>>>, - // can't share in an arc - _marker: marker::NoSync, + inner: Arc<UnsafeCell<sync::Packet<T>>>, } -/// The sending-half of Rust's synchronous channel type. This half can only be -/// owned by one task, but it can be cloned to send to other tasks. -#[stable(feature = "rust1", since = "1.0.0")] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct SyncSender<T> { - inner: Arc<RacyCell<sync::Packet<T>>>, -} +unsafe impl<T:Send> Send for SyncSender<T> {} -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -impl<T> !marker::Sync for SyncSender<T> {} +impl<T> !Sync for SyncSender<T> {} /// An error returned from the `send` function on channels. /// /// A `send` operation can only fail if the receiving end of a channel is /// disconnected, implying that the data could never be received. The error /// contains the data being sent as a payload so it can be recovered. -#[derive(PartialEq, Eq)] +#[derive(PartialEq, Eq, Show)] #[stable(feature = "rust1", since = "1.0.0")] pub struct SendError<T>(pub T); @@ -401,13 +390,13 @@ pub struct SendError<T>(pub T); /// /// The `recv` operation can only fail if the sending half of a channel is /// disconnected, implying that no further messages will ever be received. -#[derive(PartialEq, Eq, Clone, Copy)] +#[derive(PartialEq, Eq, Clone, Copy, Show)] #[stable(feature = "rust1", since = "1.0.0")] pub struct RecvError; /// This enumeration is the list of the possible reasons that try_recv could not /// return data when called. -#[derive(PartialEq, Clone, Copy)] +#[derive(PartialEq, Clone, Copy, Show)] #[stable(feature = "rust1", since = "1.0.0")] pub enum TryRecvError { /// This channel is currently empty, but the sender(s) have not yet @@ -423,7 +412,7 @@ pub enum TryRecvError { /// This enumeration is the list of the possible error outcomes for the /// `SyncSender::try_send` method. -#[derive(PartialEq, Clone)] +#[derive(PartialEq, Clone, Show)] #[stable(feature = "rust1", since = "1.0.0")] pub enum TrySendError<T> { /// The data could not be sent on the channel because it would require that @@ -442,10 +431,10 @@ pub enum TrySendError<T> { } enum Flavor<T> { - Oneshot(Arc<RacyCell<oneshot::Packet<T>>>), - Stream(Arc<RacyCell<stream::Packet<T>>>), - Shared(Arc<RacyCell<shared::Packet<T>>>), - Sync(Arc<RacyCell<sync::Packet<T>>>), + Oneshot(Arc<UnsafeCell<oneshot::Packet<T>>>), + Stream(Arc<UnsafeCell<stream::Packet<T>>>), + Shared(Arc<UnsafeCell<shared::Packet<T>>>), + Sync(Arc<UnsafeCell<sync::Packet<T>>>), } #[doc(hidden)] @@ -497,7 +486,7 @@ impl<T> UnsafeFlavor<T> for Receiver<T> { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) { - let a = Arc::new(RacyCell::new(oneshot::Packet::new())); + let a = Arc::new(UnsafeCell::new(oneshot::Packet::new())); (Sender::new(Flavor::Oneshot(a.clone())), Receiver::new(Flavor::Oneshot(a))) } @@ -537,7 +526,7 @@ pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn sync_channel<T: Send>(bound: uint) -> (SyncSender<T>, Receiver<T>) { - let a = Arc::new(RacyCell::new(sync::Packet::new(bound))); + let a = Arc::new(UnsafeCell::new(sync::Packet::new(bound))); (SyncSender::new(a.clone()), Receiver::new(Flavor::Sync(a))) } @@ -589,7 +578,7 @@ impl<T: Send> Sender<T> { return (*p).send(t).map_err(SendError); } else { let a = - Arc::new(RacyCell::new(stream::Packet::new())); + Arc::new(UnsafeCell::new(stream::Packet::new())); let rx = Receiver::new(Flavor::Stream(a.clone())); match (*p).upgrade(rx) { oneshot::UpSuccess => { @@ -631,7 +620,7 @@ impl<T: Send> Clone for Sender<T> { fn clone(&self) -> Sender<T> { let (packet, sleeper, guard) = match *unsafe { self.inner() } { Flavor::Oneshot(ref p) => { - let a = Arc::new(RacyCell::new(shared::Packet::new())); + let a = Arc::new(UnsafeCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); let rx = Receiver::new(Flavor::Shared(a.clone())); @@ -643,7 +632,7 @@ impl<T: Send> Clone for Sender<T> { } } Flavor::Stream(ref p) => { - let a = Arc::new(RacyCell::new(shared::Packet::new())); + let a = Arc::new(UnsafeCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); let rx = Receiver::new(Flavor::Shared(a.clone())); @@ -689,13 +678,7 @@ impl<T: Send> Drop for Sender<T> { //////////////////////////////////////////////////////////////////////////////// impl<T: Send> SyncSender<T> { - #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(inner: Arc<RacyCell<sync::Packet<T>>>) -> SyncSender<T> { - SyncSender { inner: inner, _marker: marker::NoSync } - } - - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot - fn new(inner: Arc<RacyCell<sync::Packet<T>>>) -> SyncSender<T> { + fn new(inner: Arc<UnsafeCell<sync::Packet<T>>>) -> SyncSender<T> { SyncSender { inner: inner } } @@ -978,33 +961,15 @@ impl<T: Send> Drop for Receiver<T> { } } -/// A version of `UnsafeCell` intended for use in concurrent data -/// structures (for example, you might put it in an `Arc`). -struct RacyCell<T>(pub UnsafeCell<T>); - -impl<T> RacyCell<T> { - - fn new(value: T) -> RacyCell<T> { - RacyCell(UnsafeCell { value: value }) - } - - unsafe fn get(&self) -> *mut T { - self.0.get() - } - -} - -unsafe impl<T:Send> Send for RacyCell<T> { } - -unsafe impl<T> Sync for RacyCell<T> { } // Oh dear - -impl<T> fmt::Show for SendError<T> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<T> fmt::Display for SendError<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "sending on a closed channel".fmt(f) } } -impl<T> fmt::Show for TrySendError<T> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<T> fmt::Display for TrySendError<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { TrySendError::Full(..) => { @@ -1017,13 +982,15 @@ impl<T> fmt::Show for TrySendError<T> { } } -impl fmt::Show for RecvError { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for RecvError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "receiving on a closed channel".fmt(f) } } -impl fmt::Show for TryRecvError { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for TryRecvError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { TryRecvError::Empty => { diff --git a/src/libstd/sync/mpsc/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs index 92aec5cde07..c222c313ba6 100644 --- a/src/libstd/sync/mpsc/mpsc_queue.rs +++ b/src/libstd/sync/mpsc/mpsc_queue.rs @@ -46,6 +46,7 @@ use core::prelude::*; use alloc::boxed::Box; use core::mem; +use core::ptr; use core::cell::UnsafeCell; use sync::atomic::{AtomicPtr, Ordering}; @@ -82,7 +83,7 @@ unsafe impl<T:Send> Sync for Queue<T> { } impl<T> Node<T> { unsafe fn new(v: Option<T>) -> *mut Node<T> { mem::transmute(box Node { - next: AtomicPtr::new(0 as *mut Node<T>), + next: AtomicPtr::new(ptr::null_mut()), value: v, }) } diff --git a/src/libstd/sync/mpsc/select.rs b/src/libstd/sync/mpsc/select.rs index ee4d3a55481..e97c82a5b1b 100644 --- a/src/libstd/sync/mpsc/select.rs +++ b/src/libstd/sync/mpsc/select.rs @@ -60,6 +60,7 @@ use core::prelude::*; use core::cell::Cell; use core::marker; use core::mem; +use core::ptr; use core::uint; use sync::mpsc::{Receiver, RecvError}; @@ -67,24 +68,12 @@ use sync::mpsc::blocking::{self, SignalToken}; /// The "receiver set" of the select interface. This structure is used to manage /// a set of receivers which are being selected over. -#[cfg(stage0)] // NOTE remove impl after next snapshot pub struct Select { head: *mut Handle<'static, ()>, tail: *mut Handle<'static, ()>, next_id: Cell<uint>, - marker1: marker::NoSend, } -/// The "receiver set" of the select interface. This structure is used to manage -/// a set of receivers which are being selected over. -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct Select { - head: *mut Handle<'static, ()>, - tail: *mut Handle<'static, ()>, - next_id: Cell<uint>, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl !marker::Send for Select {} /// A handle to a receiver which is currently a member of a `Select` set of @@ -127,26 +116,10 @@ impl Select { /// /// Usage of this struct directly can sometimes be burdensome, and usage is /// rather much easier through the `select!` macro. - #[cfg(stage0)] // NOTE remove impl after next snapshot - pub fn new() -> Select { - Select { - marker1: marker::NoSend, - head: 0 as *mut Handle<'static, ()>, - tail: 0 as *mut Handle<'static, ()>, - next_id: Cell::new(1), - } - } - - /// Creates a new selection structure. This set is initially empty and - /// `wait` will panic!() if called. - /// - /// Usage of this struct directly can sometimes be burdensome, and usage is - /// rather much easier through the `select!` macro. - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot pub fn new() -> Select { Select { - head: 0 as *mut Handle<'static, ()>, - tail: 0 as *mut Handle<'static, ()>, + head: ptr::null_mut(), + tail: ptr::null_mut(), next_id: Cell::new(1), } } @@ -160,8 +133,8 @@ impl Select { Handle { id: id, selector: self, - next: 0 as *mut Handle<'static, ()>, - prev: 0 as *mut Handle<'static, ()>, + next: ptr::null_mut(), + prev: ptr::null_mut(), added: false, rx: rx, packet: rx, @@ -326,8 +299,8 @@ impl<'rx, T: Send> Handle<'rx, T> { (*self.next).prev = self.prev; } - self.next = 0 as *mut Handle<'static, ()>; - self.prev = 0 as *mut Handle<'static, ()>; + self.next = ptr::null_mut(); + self.prev = ptr::null_mut(); self.added = false; } diff --git a/src/libstd/sync/mpsc/spsc_queue.rs b/src/libstd/sync/mpsc/spsc_queue.rs index 893260415eb..c1983fcab19 100644 --- a/src/libstd/sync/mpsc/spsc_queue.rs +++ b/src/libstd/sync/mpsc/spsc_queue.rs @@ -39,6 +39,7 @@ use core::prelude::*; use alloc::boxed::Box; use core::mem; +use core::ptr; use core::cell::UnsafeCell; use sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; @@ -82,7 +83,7 @@ impl<T: Send> Node<T> { unsafe { mem::transmute(box Node { value: None, - next: AtomicPtr::new(0 as *mut Node<T>), + next: AtomicPtr::new(ptr::null_mut::<Node<T>>()), }) } } @@ -131,7 +132,7 @@ impl<T: Send> Queue<T> { let n = self.alloc(); assert!((*n).value.is_none()); (*n).value = Some(t); - (*n).next.store(0 as *mut Node<T>, Ordering::Relaxed); + (*n).next.store(ptr::null_mut(), Ordering::Relaxed); (**self.head.get()).next.store(n, Ordering::Release); *self.head.get() = n; } diff --git a/src/libstd/sync/mpsc/sync.rs b/src/libstd/sync/mpsc/sync.rs index 30304dffb75..d38f14a9130 100644 --- a/src/libstd/sync/mpsc/sync.rs +++ b/src/libstd/sync/mpsc/sync.rs @@ -40,6 +40,7 @@ use self::Blocker::*; use vec::Vec; use core::mem; +use core::ptr; use sync::atomic::{Ordering, AtomicUsize}; use sync::mpsc::blocking::{self, WaitToken, SignalToken}; @@ -145,8 +146,8 @@ impl<T: Send> Packet<T> { cap: cap, canceled: None, queue: Queue { - head: 0 as *mut Node, - tail: 0 as *mut Node, + head: ptr::null_mut(), + tail: ptr::null_mut(), }, buf: Buffer { buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(), @@ -160,7 +161,7 @@ impl<T: Send> Packet<T> { // wait until a send slot is available, returning locked access to // the channel state. fn acquire_send_slot(&self) -> MutexGuard<State<T>> { - let mut node = Node { token: None, next: 0 as *mut Node }; + let mut node = Node { token: None, next: ptr::null_mut() }; loop { let mut guard = self.lock.lock().unwrap(); // are we ready to go? @@ -343,8 +344,8 @@ impl<T: Send> Packet<T> { Vec::new() }; let mut queue = mem::replace(&mut guard.queue, Queue { - head: 0 as *mut Node, - tail: 0 as *mut Node, + head: ptr::null_mut(), + tail: ptr::null_mut(), }); let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) { @@ -453,7 +454,7 @@ impl Queue { fn enqueue(&mut self, node: &mut Node) -> WaitToken { let (wait_token, signal_token) = blocking::tokens(); node.token = Some(signal_token); - node.next = 0 as *mut Node; + node.next = ptr::null_mut(); if self.tail.is_null() { self.head = node as *mut Node; @@ -475,10 +476,10 @@ impl Queue { let node = self.head; self.head = unsafe { (*node).next }; if self.head.is_null() { - self.tail = 0 as *mut Node; + self.tail = ptr::null_mut(); } unsafe { - (*node).next = 0 as *mut Node; + (*node).next = ptr::null_mut(); Some((*node).token.take().unwrap()) } } diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index d74e030a018..f7fdd60eb8c 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -160,7 +160,6 @@ unsafe impl Sync for StaticMutex {} /// The data protected by the mutex can be access through this guard via its /// Deref and DerefMut implementations #[must_use] -#[cfg(stage0)] // NOTE remove impl after next snapshot #[stable(feature = "rust1", since = "1.0.0")] pub struct MutexGuard<'a, T: 'a> { // funny underscores due to how Deref/DerefMut currently work (they @@ -168,26 +167,8 @@ pub struct MutexGuard<'a, T: 'a> { __lock: &'a StaticMutex, __data: &'a UnsafeCell<T>, __poison: poison::Guard, - __marker: marker::NoSend, } -/// An RAII implementation of a "scoped lock" of a mutex. When this structure is -/// dropped (falls out of scope), the lock will be unlocked. -/// -/// The data protected by the mutex can be access through this guard via its -/// Deref and DerefMut implementations -#[must_use] -#[stable(feature = "rust1", since = "1.0.0")] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct MutexGuard<'a, T: 'a> { - // funny underscores due to how Deref/DerefMut currently work (they - // disregard field privacy). - __lock: &'a StaticMutex, - __data: &'a UnsafeCell<T>, - __poison: poison::Guard, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl<'a, T> !marker::Send for MutexGuard<'a, T> {} /// Static initialization of a mutex. This constant can be used to initialize @@ -304,20 +285,7 @@ impl StaticMutex { } impl<'mutex, T> MutexGuard<'mutex, T> { - #[cfg(stage0)] // NOTE remove afte next snapshot - fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>) - -> LockResult<MutexGuard<'mutex, T>> { - poison::map_result(lock.poison.borrow(), |guard| { - MutexGuard { - __lock: lock, - __data: data, - __poison: guard, - __marker: marker::NoSend, - } - }) - } - #[cfg(not(stage0))] // NOTE remove cfg afte next snapshot fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>) -> LockResult<MutexGuard<'mutex, T>> { poison::map_result(lock.poison.borrow(), |guard| { diff --git a/src/libstd/sync/poison.rs b/src/libstd/sync/poison.rs index 6c5cb302ab1..b04c2310fc0 100644 --- a/src/libstd/sync/poison.rs +++ b/src/libstd/sync/poison.rs @@ -53,6 +53,7 @@ pub struct Guard { /// is held. The precise semantics for when a lock is poisoned is documented on /// each lock, but once a lock is poisoned then all future acquisitions will /// return this error. +#[derive(Show)] #[stable(feature = "rust1", since = "1.0.0")] pub struct PoisonError<T> { guard: T, @@ -60,6 +61,7 @@ pub struct PoisonError<T> { /// An enumeration of possible errors which can occur while calling the /// `try_lock` method. +#[derive(Show)] #[stable(feature = "rust1", since = "1.0.0")] pub enum TryLockError<T> { /// The lock could not be acquired because another task failed while holding @@ -90,7 +92,8 @@ pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>; #[stable(feature = "rust1", since = "1.0.0")] pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>; -impl<T> fmt::Show for PoisonError<T> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<T> fmt::Display for PoisonError<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.description().fmt(f) } @@ -131,7 +134,8 @@ impl<T> FromError<PoisonError<T>> for TryLockError<T> { } } -impl<T> fmt::Show for TryLockError<T> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<T> fmt::Display for TryLockError<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.description().fmt(f) } diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 01389047df6..12befbf72e3 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -112,54 +112,35 @@ pub const RW_LOCK_INIT: StaticRwLock = StaticRwLock { /// dropped. #[must_use] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg(stage0)] // NOTE remove impl after next snapshot pub struct RwLockReadGuard<'a, T: 'a> { __lock: &'a StaticRwLock, __data: &'a UnsafeCell<T>, - __marker: marker::NoSend, } -/// RAII structure used to release the shared read access of a lock when -/// dropped. -#[must_use] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -#[stable(feature = "rust1", since = "1.0.0")] -pub struct RwLockReadGuard<'a, T: 'a> { - __lock: &'a StaticRwLock, - __data: &'a UnsafeCell<T>, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl<'a, T> !marker::Send for RwLockReadGuard<'a, T> {} /// RAII structure used to release the exclusive write access of a lock when /// dropped. #[must_use] -#[cfg(stage0)] // NOTE remove impl after next snapshot #[stable(feature = "rust1", since = "1.0.0")] pub struct RwLockWriteGuard<'a, T: 'a> { __lock: &'a StaticRwLock, __data: &'a UnsafeCell<T>, __poison: poison::Guard, - __marker: marker::NoSend, } -/// RAII structure used to release the exclusive write access of a lock when -/// dropped. -#[must_use] -#[stable(feature = "rust1", since = "1.0.0")] -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot -pub struct RwLockWriteGuard<'a, T: 'a> { - __lock: &'a StaticRwLock, - __data: &'a UnsafeCell<T>, - __poison: poison::Guard, -} - -#[cfg(not(stage0))] // NOTE remove cfg after next snapshot impl<'a, T> !marker::Send for RwLockWriteGuard<'a, T> {} impl<T: Send + Sync> RwLock<T> { - /// Creates a new instance of an RwLock which is unlocked and read to go. + /// Creates a new instance of an `RwLock<T>` which is unlocked. + /// + /// # Examples + /// + /// ``` + /// use std::sync::RwLock; + /// + /// let lock = RwLock::new(5); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(t: T) -> RwLock<T> { RwLock { inner: box RW_LOCK_INIT, data: UnsafeCell::new(t) } @@ -339,19 +320,7 @@ impl StaticRwLock { } impl<'rwlock, T> RwLockReadGuard<'rwlock, T> { - #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell<T>) - -> LockResult<RwLockReadGuard<'rwlock, T>> { - poison::map_result(lock.poison.borrow(), |_| { - RwLockReadGuard { - __lock: lock, - __data: data, - __marker: marker::NoSend, - } - }) - } - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell<T>) -> LockResult<RwLockReadGuard<'rwlock, T>> { poison::map_result(lock.poison.borrow(), |_| { @@ -363,20 +332,7 @@ impl<'rwlock, T> RwLockReadGuard<'rwlock, T> { } } impl<'rwlock, T> RwLockWriteGuard<'rwlock, T> { - #[cfg(stage0)] // NOTE remove impl after next snapshot - fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell<T>) - -> LockResult<RwLockWriteGuard<'rwlock, T>> { - poison::map_result(lock.poison.borrow(), |guard| { - RwLockWriteGuard { - __lock: lock, - __data: data, - __poison: guard, - __marker: marker::NoSend, - } - }) - } - #[cfg(not(stage0))] // NOTE remove cfg after next snapshot fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell<T>) -> LockResult<RwLockWriteGuard<'rwlock, T>> { poison::map_result(lock.poison.borrow(), |guard| { diff --git a/src/libstd/sys/common/backtrace.rs b/src/libstd/sys/common/backtrace.rs index d8b85987236..d069d9ee3b8 100644 --- a/src/libstd/sys/common/backtrace.rs +++ b/src/libstd/sys/common/backtrace.rs @@ -42,10 +42,10 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { let mut valid = true; let mut inner = s; if s.len() > 4 && s.starts_with("_ZN") && s.ends_with("E") { - inner = s.slice(3, s.len() - 1); + inner = &s[3 .. s.len() - 1]; // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" form too. } else if s.len() > 3 && s.starts_with("ZN") && s.ends_with("E") { - inner = s.slice(2, s.len() - 1); + inner = &s[2 .. s.len() - 1]; } else { valid = false; } @@ -83,11 +83,11 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { } let mut rest = inner; while rest.char_at(0).is_numeric() { - rest = rest.slice_from(1); + rest = &rest[1..]; } - let i: uint = inner.slice_to(inner.len() - rest.len()).parse().unwrap(); - inner = rest.slice_from(i); - rest = rest.slice_to(i); + let i: uint = inner[.. (inner.len() - rest.len())].parse().unwrap(); + inner = &rest[i..]; + rest = &rest[..i]; while rest.len() > 0 { if rest.starts_with("$") { macro_rules! demangle { @@ -128,8 +128,8 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { None => rest.len(), Some(i) => i, }; - try!(writer.write_str(rest.slice_to(idx))); - rest = rest.slice_from(idx); + try!(writer.write_str(&rest[..idx])); + rest = &rest[idx..]; } } } diff --git a/src/libstd/sys/common/helper_thread.rs b/src/libstd/sys/common/helper_thread.rs index f940b6ed368..6f6179a436e 100644 --- a/src/libstd/sys/common/helper_thread.rs +++ b/src/libstd/sys/common/helper_thread.rs @@ -24,6 +24,7 @@ use prelude::v1::*; use cell::UnsafeCell; use mem; +use ptr; use rt; use sync::{StaticMutex, StaticCondvar}; use sync::mpsc::{channel, Sender, Receiver}; @@ -132,7 +133,7 @@ impl<M: Send> Helper<M> { // Close the channel by destroying it let chan: Box<Sender<M>> = mem::transmute(*self.chan.get()); - *self.chan.get() = 0 as *mut Sender<M>; + *self.chan.get() = ptr::null_mut(); drop(chan); helper_signal::signal(*self.signal.get() as helper_signal::signal); diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index 70b9c012b00..cb2edf50ebd 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -353,7 +353,7 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> { if state.is_null() { return output(w, idx, addr, None) } - let mut data = 0 as *const libc::c_char; + let mut data = ptr::null(); let data_addr = &mut data as *mut *const libc::c_char; let ret = unsafe { backtrace_syminfo(state, addr as libc::uintptr_t, @@ -418,7 +418,7 @@ mod uw { trace_argument: *mut libc::c_void) -> _Unwind_Reason_Code; - #[cfg(all(not(target_os = "android"), + #[cfg(all(not(all(target_os = "android", target_arch = "arm")), not(all(target_os = "linux", target_arch = "arm"))))] pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t; @@ -431,7 +431,7 @@ mod uw { // On android, the function _Unwind_GetIP is a macro, and this is the // expansion of the macro. This is all copy/pasted directly from the // header file with the definition of _Unwind_GetIP. - #[cfg(any(target_os = "android", + #[cfg(any(all(target_os = "android", target_arch = "arm"), all(target_os = "linux", target_arch = "arm")))] pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t { #[repr(C)] diff --git a/src/libstd/sys/unix/condvar.rs b/src/libstd/sys/unix/condvar.rs index 85a65bbef50..3bc41473152 100644 --- a/src/libstd/sys/unix/condvar.rs +++ b/src/libstd/sys/unix/condvar.rs @@ -10,6 +10,7 @@ use cell::UnsafeCell; use libc; +use ptr; use std::option::Option::{Some, None}; use sys::mutex::{self, Mutex}; use sys::time; @@ -62,7 +63,7 @@ impl Condvar { // time. let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 }; let stable_now = time::SteadyTime::now(); - let r = ffi::gettimeofday(&mut sys_now, 0 as *mut _); + let r = ffi::gettimeofday(&mut sys_now, ptr::null_mut()); debug_assert_eq!(r, 0); let seconds = NumCast::from(dur.num_seconds()); diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index c53f9d22790..dd478347f81 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -19,6 +19,7 @@ use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append}; use io; use libc::{self, c_int, c_void}; use mem; +use ptr; use sys::retry; use sys_common::{keep_going, eof, mkerr_libc}; @@ -207,7 +208,7 @@ pub fn readdir(p: &Path) -> IoResult<Vec<Path>> { if dir_ptr as uint != 0 { let mut paths = vec!(); - let mut entry_ptr = 0 as *mut dirent_t; + let mut entry_ptr = ptr::null_mut(); while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } { if entry_ptr.is_null() { break } paths.push(unsafe { diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index 175c4e2e353..2c25af055ee 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -143,7 +143,7 @@ pub unsafe fn get_env_pairs() -> Vec<Vec<u8>> { os::last_os_error()); } let mut result = Vec::new(); - while *environ != 0 as *const _ { + while *environ != ptr::null() { let env_pair = ffi::c_str_to_bytes(&*environ).to_vec(); result.push(env_pair); environ = environ.offset(1); diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs index 36bf696dba5..2b4d168d881 100644 --- a/src/libstd/sys/unix/process.rs +++ b/src/libstd/sys/unix/process.rs @@ -125,9 +125,9 @@ impl Process { let mut bytes = [0; 8]; return match input.read(&mut bytes) { Ok(8) => { - assert!(combine(CLOEXEC_MSG_FOOTER) == combine(bytes.slice(4, 8)), + assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]), "Validation on the CLOEXEC pipe failed: {:?}", bytes); - let errno = combine(bytes.slice(0, 4)); + let errno = combine(&bytes[0.. 4]); assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic"); Err(super::decode_error(errno)) } @@ -251,7 +251,7 @@ impl Process { fn setgroups(ngroups: libc::c_int, ptr: *const libc::c_void) -> libc::c_int; } - let _ = setgroups(0, 0 as *const libc::c_void); + let _ = setgroups(0, ptr::null()); if libc::setuid(u as libc::uid_t) != 0 { fail(&mut output); diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index ee2dd14955b..cba7d81937a 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -31,6 +31,7 @@ use mem; use ops::Drop; use option::Option::{Some, None}; use path::Path; +use ptr; use result::Result::{Ok, Err}; use slice::SliceExt; use str::{self, StrExt}; @@ -327,7 +328,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> { let image = arch::init_frame(&mut frame, &context); // Initialize this process's symbols - let ret = SymInitialize(process, 0 as *mut libc::c_void, libc::TRUE); + let ret = SymInitialize(process, ptr::null_mut(), libc::TRUE); if ret != libc::TRUE { return Ok(()) } let _c = Cleanup { handle: process, SymCleanup: SymCleanup }; @@ -335,10 +336,10 @@ pub fn write(w: &mut Writer) -> IoResult<()> { let mut i = 0i; try!(write!(w, "stack backtrace:\n")); while StackWalk64(image, process, thread, &mut frame, &mut context, - 0 as *mut libc::c_void, - 0 as *mut libc::c_void, - 0 as *mut libc::c_void, - 0 as *mut libc::c_void) == libc::TRUE{ + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut()) == libc::TRUE{ let addr = frame.AddrPC.Offset; if addr == frame.AddrReturn.Offset || addr == 0 || frame.AddrReturn.Offset == 0 { break } @@ -362,7 +363,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> { let bytes = unsafe { ffi::c_str_to_bytes(&ptr) }; match str::from_utf8(bytes) { Ok(s) => try!(demangle(w, s)), - Err(..) => try!(w.write(&bytes[..(bytes.len()-1)])), + Err(..) => try!(w.write(&bytes[..bytes.len()-1])), } } try!(w.write(&['\n' as u8])); diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index a7330f7c67c..cb8ef7eb66b 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -376,7 +376,7 @@ pub fn readlink(p: &Path) -> IoResult<Path> { }); let ret = match ret { Some(ref s) if s.starts_with(r"\\?\") => { // " - Ok(Path::new(s.slice_from(4))) + Ok(Path::new(&s[4..])) } Some(s) => Ok(Path::new(s)), None => Err(super::last_error()), diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index e9490dc95c9..36dc9b2afe4 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -146,7 +146,7 @@ pub fn fill_utf16_buf_and_decode<F>(mut f: F) -> Option<String> where done = true; } if k != 0 && done { - let sub = buf.slice(0, k as uint); + let sub = &buf[.. (k as uint)]; // We want to explicitly catch the case when the // closure returned invalid UTF-16, rather than // set `res` to None and continue. diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs index d371023f218..d148f82184b 100644 --- a/src/libstd/sys/windows/thread_local.rs +++ b/src/libstd/sys/windows/thread_local.rs @@ -13,6 +13,7 @@ use prelude::v1::*; use libc::types::os::arch::extra::{DWORD, LPVOID, BOOL}; use mem; +use ptr; use rt; use sys_common::mutex::{MUTEX_INIT, Mutex}; @@ -137,7 +138,7 @@ unsafe fn init_dtors() { rt::at_exit(move|| { DTOR_LOCK.lock(); let dtors = DTORS; - DTORS = 0 as *mut _; + DTORS = ptr::null_mut(); mem::transmute::<_, Box<Vec<(Key, Dtor)>>>(dtors); assert!(DTORS.is_null()); // can't re-init after destructing DTOR_LOCK.unlock(); @@ -250,7 +251,7 @@ unsafe fn run_dtors() { for &(key, dtor) in dtors.iter() { let ptr = TlsGetValue(key); if !ptr.is_null() { - TlsSetValue(key, 0 as *mut _); + TlsSetValue(key, ptr::null_mut()); dtor(ptr as *mut _); any_run = true; } diff --git a/src/libstd/sys/windows/timer.rs b/src/libstd/sys/windows/timer.rs index 1ae3979cd9a..12b4e56bf52 100644 --- a/src/libstd/sys/windows/timer.rs +++ b/src/libstd/sys/windows/timer.rs @@ -48,9 +48,9 @@ pub enum Req { RemoveTimer(libc::HANDLE, Sender<()>), } +unsafe impl Send for Timer {} unsafe impl Send for Req {} - fn helper(input: libc::HANDLE, messages: Receiver<Req>, _: ()) { let mut objs = vec![input]; let mut chans = vec![]; diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index ec2718bef69..09f50059936 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -388,7 +388,7 @@ impl Thread { unsafe { imp::yield_now() } } - /// Determines whether the current thread is panicking. + /// Determines whether the current thread is unwinding because of panic. #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn panicking() -> bool { @@ -527,14 +527,14 @@ mod test { fn test_unnamed_thread() { Thread::scoped(move|| { assert!(Thread::current().name().is_none()); - }).join().map_err(|_| ()).unwrap(); + }).join().ok().unwrap(); } #[test] fn test_named_thread() { Builder::new().name("ada lovelace".to_string()).scoped(move|| { assert!(Thread::current().name().unwrap() == "ada lovelace".to_string()); - }).join().map_err(|_| ()).unwrap(); + }).join().ok().unwrap(); } #[test] @@ -670,7 +670,7 @@ mod test { Err(e) => { type T = &'static str; assert!(e.is::<T>()); - assert_eq!(*e.downcast::<T>().unwrap(), "static string"); + assert_eq!(*e.downcast::<T>().ok().unwrap(), "static string"); } Ok(()) => panic!() } @@ -684,7 +684,7 @@ mod test { Err(e) => { type T = String; assert!(e.is::<T>()); - assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string()); + assert_eq!(*e.downcast::<T>().ok().unwrap(), "owned string".to_string()); } Ok(()) => panic!() } @@ -698,9 +698,9 @@ mod test { Err(e) => { type T = Box<Any + Send>; assert!(e.is::<T>()); - let any = e.downcast::<T>().unwrap(); + let any = e.downcast::<T>().ok().unwrap(); assert!(any.is::<u16>()); - assert_eq!(*any.downcast::<u16>().unwrap(), 413u16); + assert_eq!(*any.downcast::<u16>().ok().unwrap(), 413u16); } Ok(()) => panic!() } diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index f7be63212ab..2a9bf452329 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -429,7 +429,7 @@ mod imp { dtor(ptr); } ptr = DTORS.get(); - DTORS.set(0 as *mut _); + DTORS.set(ptr::null_mut()); } } } @@ -463,6 +463,7 @@ mod imp { use cell::UnsafeCell; use mem; + use ptr; use sys_common::thread_local::StaticKey as OsStaticKey; #[doc(hidden)] @@ -526,7 +527,7 @@ mod imp { let key = ptr.key; key.os.set(1 as *mut u8); drop(ptr); - key.os.set(0 as *mut u8); + key.os.set(ptr::null_mut()); } } diff --git a/src/libstd/time/duration.rs b/src/libstd/time/duration.rs index 1bf3454eaa1..fdd9cbdccf5 100644 --- a/src/libstd/time/duration.rs +++ b/src/libstd/time/duration.rs @@ -334,7 +334,8 @@ impl Div<i32> for Duration { } } -impl fmt::String for Duration { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for Duration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // technically speaking, negative duration is not valid ISO 8601, // but we need to print it anyway. |
