diff options
| author | Brian Anderson <banderson@mozilla.com> | 2015-01-24 09:15:42 -0800 |
|---|---|---|
| committer | Brian Anderson <banderson@mozilla.com> | 2015-01-25 01:20:55 -0800 |
| commit | 63fcbcf3ce8f0ca391c18b2d61833ae6beb3ac70 (patch) | |
| tree | c732033c0822f25f2aebcdf193de1b257bac1855 /src/libcore | |
| parent | b44ee371b8beea77aa1364460acbba14a8516559 (diff) | |
| parent | 0430a43d635841db44978bb648e9cf7e7cfa1bba (diff) | |
| download | rust-63fcbcf3ce8f0ca391c18b2d61833ae6beb3ac70.tar.gz rust-63fcbcf3ce8f0ca391c18b2d61833ae6beb3ac70.zip | |
Merge remote-tracking branch 'rust-lang/master'
Conflicts: mk/tests.mk src/liballoc/arc.rs src/liballoc/boxed.rs src/liballoc/rc.rs src/libcollections/bit.rs src/libcollections/btree/map.rs src/libcollections/btree/set.rs src/libcollections/dlist.rs src/libcollections/ring_buf.rs src/libcollections/slice.rs src/libcollections/str.rs src/libcollections/string.rs src/libcollections/vec.rs src/libcollections/vec_map.rs src/libcore/any.rs src/libcore/array.rs src/libcore/borrow.rs src/libcore/error.rs src/libcore/fmt/mod.rs src/libcore/iter.rs src/libcore/marker.rs src/libcore/ops.rs src/libcore/result.rs src/libcore/slice.rs src/libcore/str/mod.rs src/libregex/lib.rs src/libregex/re.rs src/librustc/lint/builtin.rs src/libstd/collections/hash/map.rs src/libstd/collections/hash/set.rs src/libstd/sync/mpsc/mod.rs src/libstd/sync/mutex.rs src/libstd/sync/poison.rs src/libstd/sync/rwlock.rs src/libsyntax/feature_gate.rs src/libsyntax/test.rs
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/any.rs | 17 | ||||
| -rw-r--r-- | src/libcore/array.rs | 7 | ||||
| -rw-r--r-- | src/libcore/borrow.rs | 24 | ||||
| -rw-r--r-- | src/libcore/cell.rs | 4 | ||||
| -rw-r--r-- | src/libcore/error.rs | 112 | ||||
| -rw-r--r-- | src/libcore/fmt/float.rs | 4 | ||||
| -rw-r--r-- | src/libcore/fmt/mod.rs | 143 | ||||
| -rw-r--r-- | src/libcore/fmt/num.rs | 20 | ||||
| -rw-r--r-- | src/libcore/intrinsics.rs | 6 | ||||
| -rw-r--r-- | src/libcore/iter.rs | 625 | ||||
| -rw-r--r-- | src/libcore/lib.rs | 3 | ||||
| -rw-r--r-- | src/libcore/marker.rs | 21 | ||||
| -rw-r--r-- | src/libcore/ops.rs | 115 | ||||
| -rw-r--r-- | src/libcore/result.rs | 10 | ||||
| -rw-r--r-- | src/libcore/slice.rs | 81 | ||||
| -rw-r--r-- | src/libcore/str/mod.rs | 142 |
16 files changed, 753 insertions, 581 deletions
diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 955497861f5..87030ed778d 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -34,11 +34,11 @@ //! use runtime reflection instead. //! //! ```rust -//! use std::fmt::Show; +//! use std::fmt::Debug; //! use std::any::Any; //! -//! // Logger function for any type that implements Show. -//! fn log<T: Any+Show>(value: &T) { +//! // Logger function for any type that implements Debug. +//! fn log<T: Any + Debug>(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to @@ -55,7 +55,7 @@ //! } //! //! // This function wants to log its parameter out prior to doing work with it. -//! fn do_work<T: Show+'static>(value: &T) { +//! fn do_work<T: Debug + 'static>(value: &T) { //! log(value); //! // ...do some other work //! } @@ -75,7 +75,7 @@ use mem::transmute; use option::Option::{self, Some, None}; use raw::TraitObject; use intrinsics; -#[cfg(not(stage0))] use marker::Sized; +use marker::Sized; /////////////////////////////////////////////////////////////////////////////// // Any trait @@ -176,7 +176,6 @@ pub struct TypeId { impl TypeId { /// Returns the `TypeId` of the type this generic function has been /// instantiated with - #[cfg(not(stage0))] #[unstable(feature = "core", reason = "may grow a `Reflect` bound soon via marker traits")] pub fn of<T: ?Sized + 'static>() -> TypeId { @@ -184,10 +183,4 @@ impl TypeId { t: unsafe { intrinsics::type_id::<T>() }, } } - - /// dox - #[cfg(stage0)] - pub fn of<T: 'static>() -> TypeId { - unsafe { intrinsics::type_id::<T>() } - } } diff --git a/src/libcore/array.rs b/src/libcore/array.rs index c38c1b279cc..44541c34ee2 100644 --- a/src/libcore/array.rs +++ b/src/libcore/array.rs @@ -39,11 +39,10 @@ macro_rules! array_impls { } } - #[unstable(feature = "core", - reason = "waiting for Show to stabilize")] - impl<T:fmt::Show> fmt::Show for [T; $N] { + #[stable(feature = "rust1", since = "1.0.0")] + impl<T: fmt::Debug> fmt::Debug for [T; $N] { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(&&self[], f) + fmt::Debug::fmt(&&self[], f) } } diff --git a/src/libcore/borrow.rs b/src/libcore/borrow.rs index 0897710aaaa..be144b052c7 100644 --- a/src/libcore/borrow.rs +++ b/src/libcore/borrow.rs @@ -134,7 +134,6 @@ impl<T> ToOwned<T> for T where T: Clone { /// } /// } /// ``` -#[derive(Show)] pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned<T> { /// Borrowed data. Borrowed(&'a B), @@ -240,14 +239,27 @@ impl<'a, T, B: ?Sized> PartialOrd for Cow<'a, T, B> where B: PartialOrd + ToOwne } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, T, B: ?Sized> fmt::String for Cow<'a, T, B> where - B: fmt::String + ToOwned<T>, - T: fmt::String, +impl<'a, T, B: ?Sized> fmt::Debug for Cow<'a, T, B> where + B: fmt::Debug + ToOwned<T>, + T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Borrowed(ref b) => fmt::String::fmt(b, f), - Owned(ref o) => fmt::String::fmt(o, f), + Borrowed(ref b) => fmt::Debug::fmt(b, f), + Owned(ref o) => fmt::Debug::fmt(o, f), + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, T, B: ?Sized> fmt::Display for Cow<'a, T, B> where + B: fmt::Display + ToOwned<T>, + T: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Borrowed(ref b) => fmt::Display::fmt(b, f), + Owned(ref o) => fmt::Display::fmt(o, f), } } } diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index aa04f9c1b20..3f25432e87a 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -74,6 +74,10 @@ //! } //! ``` //! +//! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded +//! scenarios. Consider using `Mutex<T>` if you need shared mutability in a multi-threaded +//! situation. +//! //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that diff --git a/src/libcore/error.rs b/src/libcore/error.rs new file mode 100644 index 00000000000..9519539f000 --- /dev/null +++ b/src/libcore/error.rs @@ -0,0 +1,112 @@ +// 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 (via +//! `Display`) and cause chain information: +//! +//! ``` +//! use std::fmt::Display; +//! +//! trait Error: Display { +//! fn description(&self) -> &str; +//! +//! 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::*; +use fmt::Display; + +/// Base functionality for all errors in Rust. +#[unstable(feature = "core", + reason = "the exact API of this trait may change")] +pub trait Error: Display { + /// A short description of the error; usually a static string. + fn description(&self) -> &str; + + /// 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 + } +} diff --git a/src/libcore/fmt/float.rs b/src/libcore/fmt/float.rs index f1b9ebe6d90..245dc00d838 100644 --- a/src/libcore/fmt/float.rs +++ b/src/libcore/fmt/float.rs @@ -179,7 +179,7 @@ pub fn float_to_str_bytes_common<T: Float, U, F>( _ => () } - buf.slice_to_mut(end).reverse(); + buf[..end].reverse(); // Remember start of the fractional digits. // Points one beyond end of buf if none get generated, @@ -316,7 +316,7 @@ pub fn float_to_str_bytes_common<T: Float, U, F>( impl<'a> fmt::Writer for Filler<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { - slice::bytes::copy_memory(self.buf.slice_from_mut(*self.end), + slice::bytes::copy_memory(&mut self.buf[(*self.end)..], s.as_bytes()); *self.end += s.len(); Ok(()) diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index fceb301cc04..b4e141b9bc7 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -26,12 +26,15 @@ use ops::{Deref, FnOnce}; use result; use slice::SliceExt; use slice; -use str::{self, StrExt, Utf8Error}; +use str::{self, StrExt}; pub use self::num::radix; pub use self::num::Radix; pub use self::num::RadixFmt; +#[cfg(stage0)] pub use self::Debug as Show; +#[cfg(stage0)] pub use self::Display as String; + mod num; mod float; pub mod rt; @@ -48,7 +51,7 @@ pub type Result = result::Result<(), Error>; /// some other means. #[unstable(feature = "core", reason = "core and I/O reconciliation may alter this definition")] -#[derive(Copy)] +#[derive(Copy, Show)] pub struct Error; /// A collection of methods that are required to format a message into a stream. @@ -138,7 +141,7 @@ pub struct Argument<'a> { impl<'a> Argument<'a> { #[inline(never)] fn show_uint(x: &uint, f: &mut Formatter) -> Result { - Show::fmt(x, f) + Display::fmt(x, f) } fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter) -> Result) -> Argument<'b> { @@ -221,14 +224,15 @@ pub struct Arguments<'a> { args: &'a [Argument<'a>], } -impl<'a> Show for Arguments<'a> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> Debug for Arguments<'a> { fn fmt(&self, fmt: &mut Formatter) -> Result { - String::fmt(self, fmt) + Display::fmt(self, fmt) } } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a> String for Arguments<'a> { +impl<'a> Display for Arguments<'a> { fn fmt(&self, fmt: &mut Formatter) -> Result { write(fmt.buf, *self) } @@ -238,20 +242,52 @@ impl<'a> String for Arguments<'a> { /// should implement this. #[unstable(feature = "core", reason = "I/O and core have yet to be reconciled")] +#[deprecated(since = "1.0.0", reason = "renamed to Debug")] +#[cfg(not(stage0))] pub trait Show { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } +/// Format trait for the `:?` format. Useful for debugging, most all types +/// should implement this. +#[unstable(feature = "core", + reason = "I/O and core have yet to be reconciled")] +pub trait Debug { + /// Formats the value using the given formatter. + fn fmt(&self, &mut Formatter) -> Result; +} + +#[cfg(not(stage0))] +impl<T: Show + ?Sized> Debug for T { + #[allow(deprecated)] + fn fmt(&self, f: &mut Formatter) -> Result { Show::fmt(self, f) } +} + +/// When a value can be semantically expressed as a String, this trait may be +/// used. It corresponds to the default format, `{}`. +#[unstable(feature = "core")] +#[deprecated(since = "1.0.0", reason = "renamed to Display")] +#[cfg(not(stage0))] +pub trait String { + /// Formats the value using the given formatter. + fn fmt(&self, &mut Formatter) -> Result; +} + /// When a value can be semantically expressed as a String, this trait may be /// used. It corresponds to the default format, `{}`. #[unstable(feature = "core", reason = "I/O and core have yet to be reconciled")] -pub trait String { +pub trait Display { /// Formats the value using the given formatter. fn fmt(&self, &mut Formatter) -> Result; } +#[cfg(not(stage0))] +impl<T: String + ?Sized> Display for T { + #[allow(deprecated)] + fn fmt(&self, f: &mut Formatter) -> Result { String::fmt(self, f) } +} /// Format trait for the `o` character #[unstable(feature = "core", @@ -605,9 +641,10 @@ impl<'a> Formatter<'a> { pub fn precision(&self) -> Option<uint> { self.precision } } -impl Show for Error { +#[stable(feature = "rust1", since = "1.0.0")] +impl Display for Error { fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt("an error occurred when formatting an argument", f) + Display::fmt("an error occurred when formatting an argument", f) } } @@ -635,9 +672,11 @@ pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> { macro_rules! fmt_refs { ($($tr:ident),*) => { $( + #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized + $tr> $tr for &'a T { fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) } } + #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized + $tr> $tr for &'a mut T { fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) } } @@ -645,22 +684,24 @@ macro_rules! fmt_refs { } } -fmt_refs! { Show, String, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp } +fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp } -impl Show for bool { +#[stable(feature = "rust1", since = "1.0.0")] +impl Debug for bool { fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt(self, f) + Display::fmt(self, f) } } #[stable(feature = "rust1", since = "1.0.0")] -impl String for bool { +impl Display for bool { fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt(if *self { "true" } else { "false" }, f) + Display::fmt(if *self { "true" } else { "false" }, f) } } -impl Show for str { +#[stable(feature = "rust1", since = "1.0.0")] +impl Debug for str { fn fmt(&self, f: &mut Formatter) -> Result { try!(write!(f, "\"")); for c in self.chars().flat_map(|c| c.escape_default()) { @@ -671,13 +712,14 @@ impl Show for str { } #[stable(feature = "rust1", since = "1.0.0")] -impl String for str { +impl Display for str { fn fmt(&self, f: &mut Formatter) -> Result { f.pad(self) } } -impl Show for char { +#[stable(feature = "rust1", since = "1.0.0")] +impl Debug for char { fn fmt(&self, f: &mut Formatter) -> Result { use char::CharExt; try!(write!(f, "'")); @@ -689,15 +731,16 @@ impl Show for char { } #[stable(feature = "rust1", since = "1.0.0")] -impl String for char { +impl Display for char { fn fmt(&self, f: &mut Formatter) -> Result { let mut utf8 = [0u8; 4]; let amt = self.encode_utf8(&mut utf8).unwrap_or(0); let s: &str = unsafe { mem::transmute(&utf8[..amt]) }; - String::fmt(s, f) + Display::fmt(s, f) } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> Pointer for *const T { fn fmt(&self, f: &mut Formatter) -> Result { f.flags |= 1 << (rt::FlagAlternate as uint); @@ -707,18 +750,21 @@ impl<T> Pointer for *const T { } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> Pointer for *mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(*self as *const T), f) } } +#[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> Pointer for &'a T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(*self as *const T), f) } } +#[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> Pointer for &'a mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(&(&**self as *const T), f) @@ -727,15 +773,15 @@ impl<'a, T> Pointer for &'a mut T { macro_rules! floating { ($ty:ident) => { - impl Show for $ty { + #[stable(feature = "rust1", since = "1.0.0")] + impl Debug for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { - try!(String::fmt(self, fmt)); - fmt.write_str(stringify!($ty)) + Display::fmt(self, fmt) } } #[stable(feature = "rust1", since = "1.0.0")] - impl String for $ty { + impl Display for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -756,6 +802,7 @@ macro_rules! floating { ($ty:ident) => { } } + #[stable(feature = "rust1", since = "1.0.0")] impl LowerExp for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -777,6 +824,7 @@ macro_rules! floating { ($ty:ident) => { } } + #[stable(feature = "rust1", since = "1.0.0")] impl UpperExp for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -801,12 +849,14 @@ macro_rules! floating { ($ty:ident) => { floating! { f32 } floating! { f64 } -// Implementation of Show for various core types +// Implementation of Display/Debug for various core types -impl<T> Show for *const T { +#[stable(feature = "rust1", since = "1.0.0")] +impl<T> Debug for *const T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } -impl<T> Show for *mut T { +#[stable(feature = "rust1", since = "1.0.0")] +impl<T> Debug for *mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } @@ -817,7 +867,8 @@ macro_rules! peel { macro_rules! tuple { () => (); ( $($name:ident,)+ ) => ( - impl<$($name:Show),*> Show for ($($name,)*) { + #[stable(feature = "rust1", since = "1.0.0")] + impl<$($name:Debug),*> Debug for ($($name,)*) { #[allow(non_snake_case, unused_assignments)] fn fmt(&self, f: &mut Formatter) -> Result { try!(write!(f, "(")); @@ -842,11 +893,13 @@ macro_rules! tuple { tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, } -impl<'a> Show for &'a (any::Any+'a) { +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a> Debug for &'a (any::Any+'a) { fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") } } -impl<T: Show> Show for [T] { +#[stable(feature = "rust1", since = "1.0.0")] +impl<T: Debug> Debug for [T] { fn fmt(&self, f: &mut Formatter) -> Result { if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 { try!(write!(f, "[")); @@ -867,20 +920,22 @@ impl<T: Show> Show for [T] { } } -impl Show for () { +#[stable(feature = "rust1", since = "1.0.0")] +impl Debug for () { fn fmt(&self, f: &mut Formatter) -> Result { f.pad("()") } } -impl<T: Copy + Show> Show for Cell<T> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<T: Copy + Debug> Debug for Cell<T> { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "Cell {{ value: {:?} }}", self.get()) } } -#[unstable(feature = "core")] -impl<T: Show> Show for RefCell<T> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<T: Debug> Debug for RefCell<T> { fn fmt(&self, f: &mut Formatter) -> Result { match self.try_borrow() { Some(val) => write!(f, "RefCell {{ value: {:?} }}", val), @@ -889,29 +944,17 @@ impl<T: Show> Show for RefCell<T> { } } -impl<'b, T: Show> Show for Ref<'b, T> { - fn fmt(&self, f: &mut Formatter) -> Result { - Show::fmt(&**self, f) - } -} - -impl<'b, T: Show> Show for RefMut<'b, T> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<'b, T: Debug> Debug for Ref<'b, T> { fn fmt(&self, f: &mut Formatter) -> Result { - Show::fmt(&*(self.deref()), f) + Debug::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] -impl String for Utf8Error { +impl<'b, T: Debug> Debug for RefMut<'b, T> { fn fmt(&self, f: &mut Formatter) -> Result { - match *self { - Utf8Error::InvalidByte(n) => { - write!(f, "invalid utf-8: invalid byte at index {}", n) - } - Utf8Error::TooShort => { - write!(f, "invalid utf-8: byte slice too short") - } - } + Debug::fmt(&*(self.deref()), f) } } diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index 83397e5dc99..47da8d0c419 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -157,13 +157,14 @@ pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> { macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident, $S:expr) => { - impl fmt::Show for RadixFmt<$T, Radix> { + #[stable(feature = "rust1", since = "1.0.0")] + impl fmt::Debug for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(fmt::String::fmt(self, f)); - f.write_str($S) + fmt::Display::fmt(self, f) } } - impl fmt::String for RadixFmt<$T, Radix> { + #[stable(feature = "rust1", since = "1.0.0")] + impl fmt::Display for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) } } @@ -172,6 +173,7 @@ macro_rules! radix_fmt { } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { + #[stable(feature = "rust1", since = "1.0.0")] impl fmt::$Trait for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { $Radix.fmt_int(*self as $U, f) @@ -182,10 +184,10 @@ macro_rules! int_base { macro_rules! show { ($T:ident with $S:expr) => { - impl fmt::Show for $T { + #[stable(feature = "rust1", since = "1.0.0")] + impl fmt::Debug for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(fmt::String::fmt(self, f)); - f.write_str($S) + fmt::Display::fmt(self, f) } } } @@ -195,7 +197,7 @@ macro_rules! integer { integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) } }; ($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => { - int_base! { String for $Int as $Int -> Decimal } + int_base! { Display for $Int as $Int -> Decimal } int_base! { Binary for $Int as $Uint -> Binary } int_base! { Octal for $Int as $Uint -> Octal } int_base! { LowerHex for $Int as $Uint -> LowerHex } @@ -203,7 +205,7 @@ macro_rules! integer { radix_fmt! { $Int as $Int, fmt_int, $SI } show! { $Int with $SI } - int_base! { String for $Uint as $Uint -> Decimal } + int_base! { Display for $Uint as $Uint -> Decimal } int_base! { Binary for $Uint as $Uint -> Binary } int_base! { Octal for $Uint as $Uint -> Octal } int_base! { LowerHex for $Uint as $Uint -> LowerHex } diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index c48df72e446..dd6b1e7b4e8 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -44,8 +44,6 @@ use marker::Sized; -#[cfg(stage0)] use any::TypeId; - pub type GlueFn = extern "Rust" fn(*const i8); #[lang="ty_desc"] @@ -208,12 +206,8 @@ extern "rust-intrinsic" { /// Gets an identifier which is globally unique to the specified type. This /// function will return the same value for a type regardless of whichever /// crate it is invoked in. - #[cfg(not(stage0))] pub fn type_id<T: ?Sized + 'static>() -> u64; - #[cfg(stage0)] - pub fn type_id<T: ?Sized + 'static>() -> TypeId; - /// Create a value initialized to zero. /// /// `init` is unsafe because it returns a zeroed-out datum, diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 9cf6d6ac64e..8289c7403d2 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -32,7 +32,7 @@ //! into a `loop`, for example, the `for` loop in this example is essentially //! translated to the `loop` below. //! -//! ```rust +//! ``` //! let values = vec![1i, 2, 3]; //! //! // "Syntactical sugar" taking advantage of an iterator @@ -68,7 +68,7 @@ use ops::{Add, Deref, FnMut}; use option::Option; use option::Option::{Some, None}; use std::marker::Sized; -use uint; +use usize; /// An interface for dealing with "external iterators". These types of iterators /// can be resumed at any time as all state is stored internally as opposed to @@ -93,10 +93,24 @@ pub trait Iterator { /// Returns a lower and upper bound on the remaining length of the iterator. /// /// An upper bound of `None` means either there is no known upper bound, or the upper bound - /// does not fit within a `uint`. + /// does not fit within a `usize`. #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn size_hint(&self) -> (uint, Option<uint>) { (0, None) } + fn size_hint(&self) -> (usize, Option<usize>) { (0, None) } +} + +// FIXME(#21363) remove `old_impl_check` when bug is fixed +#[old_impl_check] +impl<'a, T> Iterator for &'a mut (Iterator<Item=T> + 'a) { + type Item = T; + + fn next(&mut self) -> Option<T> { + (**self).next() + } + + fn size_hint(&self) -> (usize, Option<usize>) { + (**self).size_hint() + } } /// Conversion from an `Iterator` @@ -121,26 +135,25 @@ pub trait Extend<A> { pub trait IteratorExt: Iterator + Sized { /// Counts the number of elements in this iterator. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; - /// let mut it = a.iter(); - /// assert!(it.count() == 5); + /// ``` + /// let a = [1, 2, 3, 4, 5]; + /// assert_eq!(a.iter().count(), 5); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn count(self) -> uint { + fn count(self) -> usize { self.fold(0, |cnt, _x| cnt + 1) } /// Loops through the entire iterator, returning the last element of the /// iterator. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// assert!(a.iter().last().unwrap() == &5); /// ``` #[inline] @@ -154,17 +167,17 @@ pub trait IteratorExt: Iterator + Sized { /// Loops through `n` iterations, returning the `n`th element of the /// iterator. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter(); /// assert!(it.nth(2).unwrap() == &3); /// assert!(it.nth(2) == None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn nth(&mut self, mut n: uint) -> Option<Self::Item> { + fn nth(&mut self, mut n: usize) -> Option<Self::Item> { for x in *self { if n == 0 { return Some(x) } n -= 1; @@ -176,11 +189,11 @@ pub trait IteratorExt: Iterator + Sized { /// finish iterating over the current iterator, and then iterate /// over the other specified iterator. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [0i]; - /// let b = [1i]; + /// ``` + /// let a = [0]; + /// let b = [1]; /// let mut it = a.iter().chain(b.iter()); /// assert_eq!(it.next().unwrap(), &0); /// assert_eq!(it.next().unwrap(), &1); @@ -199,14 +212,13 @@ pub trait IteratorExt: Iterator + Sized { /// either iterator returns None, all further invocations of next() will /// return None. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [0i]; - /// let b = [1i]; + /// ``` + /// let a = [0]; + /// let b = [1]; /// let mut it = a.iter().zip(b.iter()); - /// let (x0, x1) = (0i, 1i); - /// assert_eq!(it.next().unwrap(), (&x0, &x1)); + /// assert_eq!(it.next().unwrap(), (&0, &1)); /// assert!(it.next().is_none()); /// ``` #[inline] @@ -220,10 +232,10 @@ pub trait IteratorExt: Iterator + Sized { /// Creates a new iterator that will apply the specified function to each /// element returned by the first, yielding the mapped element instead. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2]; + /// ``` + /// let a = [1, 2]; /// let mut it = a.iter().map(|&x| 2 * x); /// assert_eq!(it.next().unwrap(), 2); /// assert_eq!(it.next().unwrap(), 4); @@ -238,13 +250,13 @@ pub trait IteratorExt: Iterator + Sized { } /// Creates an iterator that applies the predicate to each element returned - /// by this iterator. Only elements that have the predicate evaluate to - /// `true` will be yielded. + /// by this iterator. The only elements that will be yieled are those that + /// make the predicate evaluate to `true`. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2]; + /// ``` + /// let a = [1, 2]; /// let mut it = a.iter().filter(|&x| *x > 1); /// assert_eq!(it.next().unwrap(), &2); /// assert!(it.next().is_none()); @@ -261,10 +273,10 @@ pub trait IteratorExt: Iterator + Sized { /// If the specified function returns None, the element is skipped. /// Otherwise the option is unwrapped and the new value is yielded. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2]; + /// ``` + /// let a = [1, 2]; /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None}); /// assert_eq!(it.next().unwrap(), 4); /// assert!(it.next().is_none()); @@ -280,14 +292,13 @@ pub trait IteratorExt: Iterator + Sized { /// Creates an iterator that yields a pair of the value returned by this /// iterator plus the current index of iteration. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [100i, 200]; + /// ``` + /// let a = [100, 200]; /// let mut it = a.iter().enumerate(); - /// let (x100, x200) = (100i, 200i); - /// assert_eq!(it.next().unwrap(), (0, &x100)); - /// assert_eq!(it.next().unwrap(), (1, &x200)); + /// assert_eq!(it.next().unwrap(), (0, &100)); + /// assert_eq!(it.next().unwrap(), (1, &200)); /// assert!(it.next().is_none()); /// ``` #[inline] @@ -299,10 +310,10 @@ pub trait IteratorExt: Iterator + Sized { /// Creates an iterator that has a `.peek()` method /// that returns an optional reference to the next element. /// - /// # Example + /// # Examples /// - /// ```rust - /// let xs = [100i, 200, 300]; + /// ``` + /// let xs = [100, 200, 300]; /// let mut it = xs.iter().map(|x| *x).peekable(); /// assert_eq!(*it.peek().unwrap(), 100); /// assert_eq!(it.next().unwrap(), 100); @@ -323,14 +334,14 @@ pub trait IteratorExt: Iterator + Sized { /// until it returns false. Once the predicate returns false, that /// element and all further elements are yielded. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 2, 1]; + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter().skip_while(|&a| *a < 3); /// assert_eq!(it.next().unwrap(), &3); - /// assert_eq!(it.next().unwrap(), &2); - /// assert_eq!(it.next().unwrap(), &1); + /// assert_eq!(it.next().unwrap(), &4); + /// assert_eq!(it.next().unwrap(), &5); /// assert!(it.next().is_none()); /// ``` #[inline] @@ -345,10 +356,10 @@ pub trait IteratorExt: Iterator + Sized { /// returns true. After the predicate returns false for the first time, no /// further elements will be yielded. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 2, 1]; + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter().take_while(|&a| *a < 3); /// assert_eq!(it.next().unwrap(), &1); /// assert_eq!(it.next().unwrap(), &2); @@ -365,10 +376,10 @@ pub trait IteratorExt: Iterator + Sized { /// Creates an iterator that skips the first `n` elements of this iterator, /// and then yields all further items. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter().skip(3); /// assert_eq!(it.next().unwrap(), &4); /// assert_eq!(it.next().unwrap(), &5); @@ -376,17 +387,17 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn skip(self, n: uint) -> Skip<Self> { + fn skip(self, n: usize) -> Skip<Self> { Skip{iter: self, n: n} } /// Creates an iterator that yields the first `n` elements of this - /// iterator, and then will always return None. + /// iterator. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter().take(3); /// assert_eq!(it.next().unwrap(), &1); /// assert_eq!(it.next().unwrap(), &2); @@ -395,7 +406,7 @@ pub trait IteratorExt: Iterator + Sized { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn take(self, n: uint) -> Take<Self> { + fn take(self, n: usize) -> Take<Self> { Take{iter: self, n: n} } @@ -404,10 +415,10 @@ pub trait IteratorExt: Iterator + Sized { /// mutated as necessary. The yielded values from the closure are yielded /// from the Scan instance when not None. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter().scan(1, |fac, &x| { /// *fac = *fac * x; /// Some(*fac) @@ -432,21 +443,17 @@ pub trait IteratorExt: Iterator + Sized { } /// Creates an iterator that maps each element to an iterator, - /// and yields the elements of the produced iterators - /// - /// # Example + /// and yields the elements of the produced iterators. /// - /// ```rust - /// use std::iter::count; + /// # Examples /// - /// let xs = [2u, 3]; - /// let ys = [0u, 1, 0, 1, 2]; - /// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x)); + /// ``` + /// let xs = [2, 3]; + /// let ys = [0, 1, 0, 1, 2]; + /// let it = xs.iter().flat_map(|&x| std::iter::count(0, 1).take(x)); /// // Check that `it` has the same elements as `ys` - /// let mut i = 0; - /// for x in it { + /// for (i, x) in it.enumerate() { /// assert_eq!(x, ys[i]); - /// i += 1; /// } /// ``` #[inline] @@ -462,10 +469,10 @@ pub trait IteratorExt: Iterator + Sized { /// iterator yields `None`. Random-access iterator behavior is not /// affected, only single and double-ended iterator behavior. /// - /// # Example + /// # Examples /// - /// ```rust - /// fn process<U: Iterator<Item=int>>(it: U) -> int { + /// ``` + /// fn process<U: Iterator<Item=isize>>(it: U) -> isize { /// let mut it = it.fuse(); /// let mut sum = 0; /// for x in it { @@ -480,9 +487,9 @@ pub trait IteratorExt: Iterator + Sized { /// } /// sum /// } - /// let x = vec![1i,2,3,7,8,9]; + /// let x = vec![1, 2, 3, 7, 8, 9]; /// assert_eq!(process(x.into_iter()), 6); - /// let x = vec![1i,2,3]; + /// let x = vec![1, 2, 3]; /// assert_eq!(process(x.into_iter()), 1006); /// ``` #[inline] @@ -495,13 +502,13 @@ pub trait IteratorExt: Iterator + Sized { /// element before yielding it. This is often useful for debugging an /// iterator pipeline. /// - /// # Example + /// # Examples /// - /// ```rust + /// ``` /// use std::iter::AdditiveIterator; /// - /// let xs = [1u, 4, 2, 3, 8, 9, 6]; - /// let sum = xs.iter() + /// let a = [1, 4, 2, 3, 8, 9, 6]; + /// let sum = a.iter() /// .map(|&x| x) /// .inspect(|&x| println!("filtering {}", x)) /// .filter(|&x| x % 2 == 0) @@ -522,15 +529,14 @@ pub trait IteratorExt: Iterator + Sized { /// This is useful to allow applying iterator adaptors while still /// retaining ownership of the original iterator value. /// - /// # Example + /// # Examples /// - /// ```rust - /// let mut xs = range(0u, 10); + /// ``` + /// let mut it = 0..10; /// // sum the first five values - /// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b); + /// let partial_sum = it.by_ref().take(5).fold(0, |a, b| a + b); /// assert!(partial_sum == 10); - /// // xs.next() is now `5` - /// assert!(xs.next() == Some(5)); + /// assert!(it.next() == Some(5)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> { @@ -540,12 +546,12 @@ pub trait IteratorExt: Iterator + Sized { /// Loops through the entire iterator, collecting all of the elements into /// a container implementing `FromIterator`. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; - /// let b: Vec<int> = a.iter().map(|&x| x).collect(); - /// assert!(a.as_slice() == b.as_slice()); + /// ``` + /// let a = [1, 2, 3, 4, 5]; + /// let b: Vec<_> = a.iter().map(|&x| x).collect(); + /// assert_eq!(a, b); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -559,8 +565,8 @@ pub trait IteratorExt: Iterator + Sized { /// do not. /// /// ``` - /// let vec = vec![1i, 2i, 3i, 4i]; - /// let (even, odd): (Vec<int>, Vec<int>) = vec.into_iter().partition(|&n| n % 2 == 0); + /// let vec = vec![1, 2, 3, 4]; + /// let (even, odd): (Vec<_>, Vec<_>) = vec.into_iter().partition(|&n| n % 2 == 0); /// assert_eq!(even, vec![2, 4]); /// assert_eq!(odd, vec![1, 3]); /// ``` @@ -587,10 +593,10 @@ pub trait IteratorExt: Iterator + Sized { /// Performs a fold operation over the entire iterator, returning the /// eventual state at the end of the iteration. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// assert!(a.iter().fold(0, |a, &b| a + b) == 15); /// ``` #[inline] @@ -607,9 +613,9 @@ pub trait IteratorExt: Iterator + Sized { /// Tests whether the predicate holds true for all elements in the iterator. /// - /// # Example + /// # Examples /// - /// ```rust + /// ``` /// let a = [1i, 2, 3, 4, 5]; /// assert!(a.iter().all(|x| *x > 0)); /// assert!(!a.iter().all(|x| *x > 2)); @@ -621,16 +627,18 @@ pub trait IteratorExt: Iterator + Sized { true } - /// Tests whether any element of an iterator satisfies the specified - /// predicate. + /// Tests whether any element of an iterator satisfies the specified predicate. /// - /// # Example + /// Does not consume the iterator past the first found element. /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// # Examples + /// + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter(); /// assert!(it.any(|x| *x == 3)); - /// assert!(!it.any(|x| *x == 3)); + /// assert_eq!(it.as_slice(), [4, 5]); + /// /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -642,6 +650,14 @@ pub trait IteratorExt: Iterator + Sized { /// Returns the first element satisfying the specified predicate. /// /// Does not consume the iterator past the first found element. + /// + /// # Examples + /// + /// ``` + /// let a = [1, 2, 3, 4, 5]; + /// let mut it = a.iter(); + /// assert_eq!(it.find(|&x| *x == 3).unwrap(), &3); + /// assert_eq!(it.as_slice(), [4, 5]); #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where @@ -654,9 +670,19 @@ pub trait IteratorExt: Iterator + Sized { } /// Return the index of the first element satisfying the specified predicate + /// + /// Does not consume the iterator past the first found element. + /// + /// # Examples + /// + /// ``` + /// let a = [1, 2, 3, 4, 5]; + /// let mut it = a.iter(); + /// assert_eq!(it.position(|x| *x == 3).unwrap(), 2); + /// assert_eq!(it.as_slice(), [4, 5]); #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn position<P>(&mut self, mut predicate: P) -> Option<uint> where + fn position<P>(&mut self, mut predicate: P) -> Option<usize> where P: FnMut(Self::Item) -> bool, { let mut i = 0; @@ -672,9 +698,19 @@ pub trait IteratorExt: Iterator + Sized { /// Return the index of the last element satisfying the specified predicate /// /// If no element matches, None is returned. + /// + /// Does not consume the iterator *before* the first found element. + /// + /// # Examples + /// + /// ``` + /// let a = [1, 2, 2, 4, 5]; + /// let mut it = a.iter(); + /// assert_eq!(it.rposition(|x| *x == 2).unwrap(), 2); + /// assert_eq!(it.as_slice(), [1, 2]); #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn rposition<P>(&mut self, mut predicate: P) -> Option<uint> where + fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where P: FnMut(Self::Item) -> bool, Self: ExactSizeIterator + DoubleEndedIterator { @@ -689,10 +725,10 @@ pub trait IteratorExt: Iterator + Sized { /// Consumes the entire iterator to return the maximum element. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// assert!(a.iter().max().unwrap() == &5); /// ``` #[inline] @@ -709,10 +745,10 @@ pub trait IteratorExt: Iterator + Sized { /// Consumes the entire iterator to return the minimum element. /// - /// # Example + /// # Examples /// - /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// assert!(a.iter().min().unwrap() == &1); /// ``` #[inline] @@ -740,25 +776,22 @@ pub trait IteratorExt: Iterator + Sized { /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons, /// and so is faster than calling `min` and `max` separately which does `2 * n` comparisons. /// - /// # Example + /// # Examples /// - /// ```rust + /// ``` /// use std::iter::MinMaxResult::{NoElements, OneElement, MinMax}; /// - /// let v: [int; 0] = []; - /// assert_eq!(v.iter().min_max(), NoElements); + /// let a: [isize; 0] = []; + /// assert_eq!(a.iter().min_max(), NoElements); /// - /// let v = [1i]; - /// assert!(v.iter().min_max() == OneElement(&1)); + /// let a = [1]; + /// assert!(a.iter().min_max() == OneElement(&1)); /// - /// let v = [1i, 2, 3, 4, 5]; - /// assert!(v.iter().min_max() == MinMax(&1, &5)); + /// let a = [1, 2, 3, 4, 5]; + /// assert!(a.iter().min_max() == MinMax(&1, &5)); /// - /// let v = [1i, 2, 3, 4, 5, 6]; - /// assert!(v.iter().min_max() == MinMax(&1, &6)); - /// - /// let v = [1i, 1, 1, 1]; - /// assert!(v.iter().min_max() == MinMax(&1, &1)); + /// let a = [1, 1, 1, 1]; + /// assert!(a.iter().min_max() == MinMax(&1, &1)); /// ``` #[unstable(feature = "core", reason = "return type may change")] fn min_max(mut self) -> MinMaxResult<Self::Item> where Self::Item: Ord @@ -808,13 +841,13 @@ pub trait IteratorExt: Iterator + Sized { /// Return the element that gives the maximum value from the /// specified function. /// - /// # Example + /// # Examples /// - /// ```rust + /// ``` /// use core::num::SignedInt; /// - /// let xs = [-3i, 0, 1, 5, -10]; - /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); + /// let a = [-3, 0, 1, 5, -10]; + /// assert_eq!(*a.iter().max_by(|x| x.abs()).unwrap(), -10); /// ``` #[inline] #[unstable(feature = "core", @@ -838,13 +871,13 @@ pub trait IteratorExt: Iterator + Sized { /// Return the element that gives the minimum value from the /// specified function. /// - /// # Example + /// # Examples /// - /// ```rust + /// ``` /// use core::num::SignedInt; /// - /// let xs = [-3i, 0, 1, 5, -10]; - /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); + /// let a = [-3, 0, 1, 5, -10]; + /// assert_eq!(*a.iter().min_by(|x| x.abs()).unwrap(), 0); /// ``` #[inline] #[unstable(feature = "core", @@ -876,7 +909,7 @@ pub trait IteratorExt: Iterator + Sized { /// of the original iterator. /// /// Note: Random access with flipped indices still only applies to the first - /// `uint::MAX` elements of the original iterator. + /// `std::usize::MAX` elements of the original iterator. #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn rev(self) -> Rev<Self> { @@ -887,18 +920,27 @@ pub trait IteratorExt: Iterator + Sized { /// /// Loops through the entire iterator, collecting the first component of /// each item into one new container, and the second component into another. + /// + /// # Examples + /// + /// ``` + /// let a = [(1, 2), (3, 4)]; + /// let (left, right): (Vec<_>, Vec<_>) = a.iter().map(|&x| x).unzip(); + /// assert_eq!([1, 3], left); + /// assert_eq!([2, 4], right); + /// ``` #[unstable(feature = "core", reason = "recent addition")] fn unzip<A, B, FromA, FromB>(mut self) -> (FromA, FromB) where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Iterator<Item=(A, B)>, { - struct SizeHint<A>(uint, Option<uint>); + struct SizeHint<A>(usize, Option<usize>); impl<A> Iterator for SizeHint<A> { type Item = A; fn next(&mut self) -> Option<A> { None } - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { (self.0, self.1) } } @@ -931,15 +973,14 @@ pub trait IteratorExt: Iterator + Sized { /// Repeats an iterator endlessly /// - /// # Example - /// - /// ```rust - /// use std::iter::count; + /// # Examples /// - /// let a = count(1i,1i).take(1); - /// let mut cy = a.cycle(); - /// assert_eq!(cy.next(), Some(1)); - /// assert_eq!(cy.next(), Some(1)); + /// ``` + /// let a = [1, 2]; + /// let mut it = a.iter().cycle(); + /// assert_eq!(it.next().unwrap(), &1); + /// assert_eq!(it.next().unwrap(), &2); + /// assert_eq!(it.next().unwrap(), &1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] @@ -976,7 +1017,7 @@ pub trait DoubleEndedIterator: Iterator { fn next_back(&mut self) -> Option<Self::Item>; } -/// An object implementing random access indexing by `uint` +/// An object implementing random access indexing by `usize` /// /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`. /// Calling `next()` or `next_back()` on a `RandomAccessIterator` @@ -985,12 +1026,12 @@ pub trait DoubleEndedIterator: Iterator { #[unstable(feature = "core", reason = "not widely used, may be better decomposed into Index and ExactSizeIterator")] pub trait RandomAccessIterator: Iterator { - /// Return the number of indexable elements. At most `std::uint::MAX` + /// Return the number of indexable elements. At most `std::usize::MAX` /// elements are indexable, even if the iterator represents a longer range. - fn indexable(&self) -> uint; + fn indexable(&self) -> usize; /// Return an element at an index, or `None` if the index is out of bounds - fn idx(&mut self, index: uint) -> Option<Self::Item>; + fn idx(&mut self, index: usize) -> Option<Self::Item>; } /// An iterator that knows its exact length @@ -999,12 +1040,12 @@ pub trait RandomAccessIterator: Iterator { /// it can support double-ended enumeration. /// /// `Iterator::size_hint` *must* return the exact size of the iterator. -/// Note that the size must fit in `uint`. +/// Note that the size must fit in `usize`. #[stable(feature = "rust1", since = "1.0.0")] pub trait ExactSizeIterator: Iterator { #[inline] /// Return the exact length of the iterator. - fn len(&self) -> uint { + fn len(&self) -> usize { let (lower, upper) = self.size_hint(); // Note: This assertion is overly defensive, but it checks the invariant // guaranteed by the trait. If this trait were rust-internal, @@ -1049,7 +1090,7 @@ impl<I> Iterator for Rev<I> where I: DoubleEndedIterator { #[inline] fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() } + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1061,9 +1102,9 @@ impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator { #[unstable(feature = "core", reason = "trait is experimental")] impl<I> RandomAccessIterator for Rev<I> where I: DoubleEndedIterator + RandomAccessIterator { #[inline] - fn indexable(&self) -> uint { self.iter.indexable() } + fn indexable(&self) -> usize { self.iter.indexable() } #[inline] - fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> { + fn idx(&mut self, index: usize) -> Option<<I as Iterator>::Item> { let amt = self.indexable(); self.iter.idx(amt - index - 1) } @@ -1083,7 +1124,7 @@ impl<'a, I> Iterator for ByRef<'a, I> where I: 'a + Iterator { #[inline] fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() } + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1092,15 +1133,18 @@ impl<'a, I> DoubleEndedIterator for ByRef<'a, I> where I: 'a + DoubleEndedIterat fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() } } +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, I> ExactSizeIterator for ByRef<'a, I> where I: 'a + ExactSizeIterator {} + /// A trait for iterators over elements which can be added together #[unstable(feature = "core", reason = "needs to be re-evaluated as part of numerics reform")] pub trait AdditiveIterator<A> { /// Iterates over the entire iterator, summing up all the elements /// - /// # Example + /// # Examples /// - /// ```rust + /// ``` /// use std::iter::AdditiveIterator; /// /// let a = [1i, 2, 3, 4, 5]; @@ -1125,12 +1169,12 @@ impl_additive! { i8, 0 } impl_additive! { i16, 0 } impl_additive! { i32, 0 } impl_additive! { i64, 0 } -impl_additive! { int, 0 } +impl_additive! { isize, 0 } impl_additive! { u8, 0 } impl_additive! { u16, 0 } impl_additive! { u32, 0 } impl_additive! { u64, 0 } -impl_additive! { uint, 0 } +impl_additive! { usize, 0 } impl_additive! { f32, 0.0 } impl_additive! { f64, 0.0 } @@ -1140,12 +1184,12 @@ impl_additive! { f64, 0.0 } pub trait MultiplicativeIterator<A> { /// Iterates over the entire iterator, multiplying all the elements /// - /// # Example + /// # Examples /// - /// ```rust + /// ``` /// use std::iter::{count, MultiplicativeIterator}; /// - /// fn factorial(n: uint) -> uint { + /// fn factorial(n: usize) -> usize { /// count(1u, 1).take_while(|&i| i <= n).product() /// } /// assert!(factorial(0) == 1); @@ -1170,12 +1214,12 @@ impl_multiplicative! { i8, 1 } impl_multiplicative! { i16, 1 } impl_multiplicative! { i32, 1 } impl_multiplicative! { i64, 1 } -impl_multiplicative! { int, 1 } +impl_multiplicative! { isize, 1 } impl_multiplicative! { u8, 1 } impl_multiplicative! { u16, 1 } impl_multiplicative! { u32, 1 } impl_multiplicative! { u64, 1 } -impl_multiplicative! { uint, 1 } +impl_multiplicative! { usize, 1 } impl_multiplicative! { f32, 1.0 } impl_multiplicative! { f64, 1.0 } @@ -1200,19 +1244,19 @@ impl<T: Clone> MinMaxResult<T> { /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`, /// performing this operation will make one clone of `x`. /// - /// # Example + /// # Examples /// - /// ```rust + /// ``` /// use std::iter::MinMaxResult::{self, NoElements, OneElement, MinMax}; /// - /// let r: MinMaxResult<int> = NoElements; + /// let r: MinMaxResult<isize> = NoElements; /// assert_eq!(r.into_option(), None); /// - /// let r = OneElement(1i); - /// assert_eq!(r.into_option(), Some((1,1))); + /// let r = OneElement(1); + /// assert_eq!(r.into_option(), Some((1, 1))); /// - /// let r = MinMax(1i,2i); - /// assert_eq!(r.into_option(), Some((1,2))); + /// let r = MinMax(1, 2); + /// assert_eq!(r.into_option(), Some((1, 2))); /// ``` #[unstable(feature = "core", reason = "type is unstable")] pub fn into_option(self) -> Option<(T,T)> { @@ -1244,7 +1288,7 @@ impl<T, D, I> Iterator for Cloned<I> where self.it.next().cloned() } - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() } } @@ -1289,12 +1333,12 @@ impl<I> Iterator for Cycle<I> where I: Clone + Iterator { } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { // the cycle iterator is either empty or infinite match self.orig.size_hint() { sz @ (0, Some(0)) => sz, (0, _) => (0, None), - _ => (uint::MAX, None) + _ => (usize::MAX, None) } } } @@ -1304,16 +1348,16 @@ impl<I> RandomAccessIterator for Cycle<I> where I: Clone + RandomAccessIterator, { #[inline] - fn indexable(&self) -> uint { + fn indexable(&self) -> usize { if self.orig.indexable() > 0 { - uint::MAX + usize::MAX } else { 0 } } #[inline] - fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> { + fn idx(&mut self, index: usize) -> Option<<I as Iterator>::Item> { let liter = self.iter.indexable(); let lorig = self.orig.indexable(); if lorig == 0 { @@ -1355,7 +1399,7 @@ impl<T, A, B> Iterator for Chain<A, B> where A: Iterator<Item=T>, B: Iterator<It } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (a_lower, a_upper) = self.a.size_hint(); let (b_lower, b_upper) = self.b.size_hint(); @@ -1390,13 +1434,13 @@ impl<T, A, B> RandomAccessIterator for Chain<A, B> where B: RandomAccessIterator<Item=T>, { #[inline] - fn indexable(&self) -> uint { + fn indexable(&self) -> usize { let (a, b) = (self.a.indexable(), self.b.indexable()); a.saturating_add(b) } #[inline] - fn idx(&mut self, index: uint) -> Option<T> { + fn idx(&mut self, index: usize) -> Option<T> { let len = self.a.indexable(); if index < len { self.a.idx(index) @@ -1434,7 +1478,7 @@ impl<T, U, A, B> Iterator for Zip<A, B> where } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (a_lower, a_upper) = self.a.size_hint(); let (b_lower, b_upper) = self.b.size_hint(); @@ -1482,12 +1526,12 @@ impl<T, U, A, B> RandomAccessIterator for Zip<A, B> where B: RandomAccessIterator<Item=U>, { #[inline] - fn indexable(&self) -> uint { + fn indexable(&self) -> usize { cmp::min(self.a.indexable(), self.b.indexable()) } #[inline] - fn idx(&mut self, index: uint) -> Option<(T, U)> { + fn idx(&mut self, index: usize) -> Option<(T, U)> { match self.a.idx(index) { None => None, Some(x) => match self.b.idx(index) { @@ -1541,7 +1585,7 @@ impl<A, B, I, F> Iterator for Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMu } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } @@ -1564,12 +1608,12 @@ impl<A, B, I, F> RandomAccessIterator for Map<A, B, I, F> where F: FnMut(A) -> B, { #[inline] - fn indexable(&self) -> uint { + fn indexable(&self) -> usize { self.iter.indexable() } #[inline] - fn idx(&mut self, index: uint) -> Option<B> { + fn idx(&mut self, index: usize) -> Option<B> { let elt = self.iter.idx(index); self.do_map(elt) } @@ -1614,7 +1658,7 @@ impl<A, I, P> Iterator for Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(& } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the predicate } @@ -1677,7 +1721,7 @@ impl<A, B, I, F> Iterator for FilterMap<A, B, I, F> where } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the predicate } @@ -1706,15 +1750,15 @@ impl<A, B, I, F> DoubleEndedIterator for FilterMap<A, B, I, F> where #[stable(feature = "rust1", since = "1.0.0")] pub struct Enumerate<I> { iter: I, - count: uint + count: usize } #[stable(feature = "rust1", since = "1.0.0")] impl<I> Iterator for Enumerate<I> where I: Iterator { - type Item = (uint, <I as Iterator>::Item); + type Item = (usize, <I as Iterator>::Item); #[inline] - fn next(&mut self) -> Option<(uint, <I as Iterator>::Item)> { + fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> { match self.iter.next() { Some(a) => { let ret = Some((self.count, a)); @@ -1726,7 +1770,7 @@ impl<I> Iterator for Enumerate<I> where I: Iterator { } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } @@ -1736,7 +1780,7 @@ impl<I> DoubleEndedIterator for Enumerate<I> where I: ExactSizeIterator + DoubleEndedIterator { #[inline] - fn next_back(&mut self) -> Option<(uint, <I as Iterator>::Item)> { + fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> { match self.iter.next_back() { Some(a) => { let len = self.iter.len(); @@ -1750,12 +1794,12 @@ impl<I> DoubleEndedIterator for Enumerate<I> where #[unstable(feature = "core", reason = "trait is experimental")] impl<I> RandomAccessIterator for Enumerate<I> where I: RandomAccessIterator { #[inline] - fn indexable(&self) -> uint { + fn indexable(&self) -> usize { self.iter.indexable() } #[inline] - fn idx(&mut self, index: uint) -> Option<(uint, <I as Iterator>::Item)> { + fn idx(&mut self, index: usize) -> Option<(usize, <I as Iterator>::Item)> { match self.iter.idx(index) { Some(a) => Some((self.count + index, a)), _ => None, @@ -1783,7 +1827,7 @@ impl<T, I> Iterator for Peekable<T, I> where I: Iterator<Item=T> { } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (lo, hi) = self.iter.size_hint(); if self.peeked.is_some() { let lo = lo.saturating_add(1); @@ -1799,6 +1843,9 @@ impl<T, I> Iterator for Peekable<T, I> where I: Iterator<Item=T> { } #[stable(feature = "rust1", since = "1.0.0")] +impl<T, I> ExactSizeIterator for Peekable<T, I> where I: ExactSizeIterator<Item = T> {} + +#[stable(feature = "rust1", since = "1.0.0")] impl<T, I> Peekable<T, I> where I: Iterator<Item=T> { /// Return a reference to the next element of the iterator with out advancing it, /// or None if the iterator is exhausted. @@ -1860,7 +1907,7 @@ impl<A, I, P> Iterator for SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMu } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the predicate } @@ -1914,7 +1961,7 @@ impl<A, I, P> Iterator for TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMu } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the predicate } @@ -1926,7 +1973,7 @@ impl<A, I, P> Iterator for TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMu #[stable(feature = "rust1", since = "1.0.0")] pub struct Skip<I> { iter: I, - n: uint + n: usize } #[stable(feature = "rust1", since = "1.0.0")] @@ -1959,7 +2006,7 @@ impl<I> Iterator for Skip<I> where I: Iterator { } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (lower, upper) = self.iter.size_hint(); let lower = lower.saturating_sub(self.n); @@ -1976,12 +2023,12 @@ impl<I> Iterator for Skip<I> where I: Iterator { #[unstable(feature = "core", reason = "trait is experimental")] impl<I> RandomAccessIterator for Skip<I> where I: RandomAccessIterator{ #[inline] - fn indexable(&self) -> uint { + fn indexable(&self) -> usize { self.iter.indexable().saturating_sub(self.n) } #[inline] - fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> { + fn idx(&mut self, index: usize) -> Option<<I as Iterator>::Item> { if index >= self.indexable() { None } else { @@ -1990,13 +2037,16 @@ impl<I> RandomAccessIterator for Skip<I> where I: RandomAccessIterator{ } } +#[stable(feature = "rust1", since = "1.0.0")] +impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {} + /// An iterator that only iterates over the first `n` iterations of `iter`. #[derive(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] pub struct Take<I> { iter: I, - n: uint + n: usize } #[stable(feature = "rust1", since = "1.0.0")] @@ -2014,7 +2064,7 @@ impl<I> Iterator for Take<I> where I: Iterator{ } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (lower, upper) = self.iter.size_hint(); let lower = cmp::min(lower, self.n); @@ -2031,12 +2081,12 @@ impl<I> Iterator for Take<I> where I: Iterator{ #[unstable(feature = "core", reason = "trait is experimental")] impl<I> RandomAccessIterator for Take<I> where I: RandomAccessIterator{ #[inline] - fn indexable(&self) -> uint { + fn indexable(&self) -> usize { cmp::min(self.iter.indexable(), self.n) } #[inline] - fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> { + fn idx(&mut self, index: usize) -> Option<<I as Iterator>::Item> { if index >= self.n { None } else { @@ -2045,6 +2095,9 @@ impl<I> RandomAccessIterator for Take<I> where I: RandomAccessIterator{ } } +#[stable(feature = "rust1", since = "1.0.0")] +impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {} + /// An iterator to maintain state while iterating another iterator #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] @@ -2086,7 +2139,7 @@ impl<A, B, I, St, F> Iterator for Scan<A, B, I, St, F> where } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the scan function } @@ -2149,7 +2202,7 @@ impl<A, B, I, U, F> Iterator for FlatMap<A, B, I, U, F> where } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint()); let lo = flo.saturating_add(blo); @@ -2213,7 +2266,7 @@ impl<I> Iterator for Fuse<I> where I: Iterator { } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { if self.done { (0, Some(0)) } else { @@ -2244,16 +2297,19 @@ impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator { #[unstable(feature = "core", reason = "trait is experimental")] impl<I> RandomAccessIterator for Fuse<I> where I: RandomAccessIterator { #[inline] - fn indexable(&self) -> uint { + fn indexable(&self) -> usize { self.iter.indexable() } #[inline] - fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> { + fn idx(&mut self, index: usize) -> Option<<I as Iterator>::Item> { self.iter.idx(index) } } +#[stable(feature = "rust1", since = "1.0.0")] +impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {} + impl<I> Fuse<I> { /// Resets the fuse such that the next call to .next() or .next_back() will /// call the underlying iterator again even if it previously returned None. @@ -2310,7 +2366,7 @@ impl<A, I, F> Iterator for Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut( } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } @@ -2333,12 +2389,12 @@ impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where F: FnMut(&A), { #[inline] - fn indexable(&self) -> uint { + fn indexable(&self) -> usize { self.iter.indexable() } #[inline] - fn idx(&mut self, index: uint) -> Option<A> { + fn idx(&mut self, index: usize) -> Option<A> { let element = self.iter.idx(index); self.do_inspect(element) } @@ -2350,7 +2406,7 @@ impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where /// /// An iterator that yields sequential Fibonacci numbers, and stops on overflow. /// -/// ```rust +/// ``` /// use std::iter::Unfold; /// use std::num::Int; // For `.checked_add()` /// @@ -2420,7 +2476,7 @@ impl<A, St, F> Iterator for Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { // no possible known bounds at this point (0, None) } @@ -2458,8 +2514,8 @@ impl<A: Add<Output=A> + Clone> Iterator for Counter<A> { } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { - (uint::MAX, None) // Too bad we can't specify an infinite lower bound + fn size_hint(&self) -> (usize, Option<usize>) { + (usize::MAX, None) // Too bad we can't specify an infinite lower bound } } @@ -2476,9 +2532,9 @@ pub struct Range<A> { /// Returns an iterator over the given range [start, stop) (that is, starting /// at start (inclusive), and ending at stop (exclusive)). /// -/// # Example +/// # Examples /// -/// ```rust +/// ``` /// let array = [0, 1, 2, 3, 4]; /// /// for i in range(0, 5u) { @@ -2515,9 +2571,9 @@ impl<A: Int + ToPrimitive> Iterator for Range<A> { } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { // This first checks if the elements are representable as i64. If they aren't, try u64 (to - // handle cases like range(huge, huger)). We don't use uint/int because the difference of + // handle cases like range(huge, huger)). We don't use usize/isize because the difference of // the i64/u64 might lie within their range. let bound = match self.state.to_i64() { Some(a) => { @@ -2604,7 +2660,7 @@ impl<A: Int + ToPrimitive> Iterator for RangeInclusive<A> { } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { let (lo, hi) = self.range.size_hint(); if self.done { (lo, hi) @@ -2725,64 +2781,93 @@ impl<A: Int> Iterator for RangeStepInclusive<A> { } } - -/// The `Step` trait identifies objects which can be stepped over in both -/// directions. The `steps_between` function provides a way to -/// compare two Step objects (it could be provided using `step()` and `Ord`, -/// but the implementation would be so inefficient as to be useless). -#[unstable(feature = "core", - reason = "design of range notation/iteration is in flux")] -pub trait Step: Ord { - /// Change self to the next object. - fn step(&mut self); - /// Change self to the previous object. - fn step_back(&mut self); - /// The steps_between two step objects. - /// start should always be less than end, so the result should never be negative. - /// Return None if it is not possible to calculate steps_between without - /// overflow. - fn steps_between(start: &Self, end: &Self) -> Option<uint>; -} - -macro_rules! step_impl { +macro_rules! range_impl { ($($t:ty)*) => ($( - #[unstable(feature = "core", reason = "Trait is unstable.")] - impl Step for $t { - #[inline] - fn step(&mut self) { *self += 1; } + #[stable(feature = "rust1", since = "1.0.0")] + impl Iterator for ::ops::Range<$t> { + type Item = $t; + #[inline] - fn step_back(&mut self) { *self -= 1; } + fn next(&mut self) -> Option<$t> { + if self.start < self.end { + let result = self.start; + self.start += 1; + return Some(result); + } + + return None; + } + #[inline] - fn steps_between(start: &$t, end: &$t) -> Option<uint> { - debug_assert!(end >= start); - Some((*end - *start) as uint) + fn size_hint(&self) -> (usize, Option<usize>) { + debug_assert!(self.end >= self.start); + let hint = (self.end - self.start) as usize; + (hint, Some(hint)) } } + + #[stable(feature = "rust1", since = "1.0.0")] + impl ExactSizeIterator for ::ops::Range<$t> {} )*) } -macro_rules! step_impl_no_between { +macro_rules! range_impl_no_hint { ($($t:ty)*) => ($( - #[unstable(feature = "core", reason = "Trait is unstable.")] - impl Step for $t { + #[stable(feature = "rust1", since = "1.0.0")] + impl Iterator for ::ops::Range<$t> { + type Item = $t; + #[inline] - fn step(&mut self) { *self += 1; } + fn next(&mut self) -> Option<$t> { + if self.start < self.end { + let result = self.start; + self.start += 1; + return Some(result); + } + + return None; + } + } + )*) +} + +macro_rules! range_other_impls { + ($($t:ty)*) => ($( + #[stable(feature = "rust1", since = "1.0.0")] + impl DoubleEndedIterator for ::ops::Range<$t> { #[inline] - fn step_back(&mut self) { *self -= 1; } + fn next_back(&mut self) -> Option<$t> { + if self.start < self.end { + self.end -= 1; + return Some(self.end); + } + + return None; + } + } + + #[stable(feature = "rust1", since = "1.0.0")] + impl Iterator for ::ops::RangeFrom<$t> { + type Item = $t; + #[inline] - fn steps_between(_start: &$t, _end: &$t) -> Option<uint> { - None + fn next(&mut self) -> Option<$t> { + let result = self.start; + self.start += 1; + debug_assert!(result < self.start); + return Some(result); } } )*) } -step_impl!(uint u8 u16 u32 int i8 i16 i32); +range_impl!(usize u8 u16 u32 isize i8 i16 i32); #[cfg(target_pointer_width = "64")] -step_impl!(u64 i64); +range_impl!(u64 i64); #[cfg(target_pointer_width = "32")] -step_impl_no_between!(u64 i64); +range_impl_no_hint!(u64 i64); +range_other_impls!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); /// An iterator that repeats an element endlessly #[derive(Clone)] @@ -2798,7 +2883,7 @@ impl<A: Clone> Iterator for Repeat<A> { #[inline] fn next(&mut self) -> Option<A> { self.idx(0) } #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) } + fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) } } #[stable(feature = "rust1", since = "1.0.0")] @@ -2810,9 +2895,9 @@ impl<A: Clone> DoubleEndedIterator for Repeat<A> { #[unstable(feature = "core", reason = "trait is experimental")] impl<A: Clone> RandomAccessIterator for Repeat<A> { #[inline] - fn indexable(&self) -> uint { uint::MAX } + fn indexable(&self) -> usize { usize::MAX } #[inline] - fn idx(&mut self, _: uint) -> Option<A> { Some(self.element.clone()) } + fn idx(&mut self, _: usize) -> Option<A> { Some(self.element.clone()) } } type IterateState<T, F> = (F, Option<T>, bool); diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index ea697ed769d..d4ca5e3f8dc 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -64,6 +64,8 @@ #![feature(unboxed_closures)] #![allow(unknown_features)] #![feature(int_uint)] #![feature(on_unimplemented)] +// FIXME(#21363) remove `old_impl_check` when bug is fixed +#![feature(old_impl_check)] #![deny(missing_docs)] #[macro_use] @@ -137,6 +139,7 @@ pub mod slice; pub mod str; pub mod hash; pub mod fmt; +pub mod error; // note: does not need to be public mod tuple; diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs index 7d9c131a721..0a31cb01ca2 100644 --- a/src/libcore/marker.rs +++ b/src/libcore/marker.rs @@ -386,17 +386,6 @@ pub struct ContravariantLifetime<'a>; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct InvariantLifetime<'a>; -/// A type which is considered "not sendable", meaning that it cannot -/// be safely sent between tasks, even if it is owned. This is -/// typically embedded in other types, such as `Gc`, to ensure that -/// their instances remain thread-local. -#[unstable(feature = "core", - reason = "likely to change with new variance strategy")] -#[lang="no_send_bound"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct NoSend; - /// A type which is considered "not POD", meaning that it is not /// implicitly copyable. This is typically embedded in other types to /// ensure that they are never copied, even if they lack a destructor. @@ -407,16 +396,6 @@ pub struct NoSend; #[allow(missing_copy_implementations)] pub struct NoCopy; -/// A type which is considered "not sync", meaning that -/// its contents are not threadsafe, hence they cannot be -/// shared between tasks. -#[unstable(feature = "core", - reason = "likely to change with new variance strategy")] -#[lang="no_sync_bound"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -#[cfg(stage0)] // NOTE remove impl after next snapshot -pub struct NoSync; - /// A type which is considered managed by the GC. This is typically /// embedded in other types. #[unstable(feature = "core", diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 248e2f232e8..d482888e3bc 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -33,8 +33,6 @@ //! demonstrates adding and subtracting two `Point`s. //! //! ```rust -//! #![feature(associated_types)] -//! //! use std::ops::{Add, Sub}; //! //! #[derive(Show)] @@ -69,10 +67,7 @@ #![stable(feature = "rust1", since = "1.0.0")] -use clone::Clone; -use iter::{Step, Iterator,DoubleEndedIterator,ExactSizeIterator}; use marker::Sized; -use option::Option::{self, Some, None}; use fmt; /// The `Drop` trait is used to run some code when a value goes out of scope. This @@ -168,8 +163,6 @@ macro_rules! forward_ref_binop { /// calling `add`, and therefore, `main` prints `Adding!`. /// /// ```rust -/// #![feature(associated_types)] -/// /// use std::ops::Add; /// /// #[derive(Copy)] @@ -223,8 +216,6 @@ add_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 } /// calling `sub`, and therefore, `main` prints `Subtracting!`. /// /// ```rust -/// #![feature(associated_types)] -/// /// use std::ops::Sub; /// /// #[derive(Copy)] @@ -278,8 +269,6 @@ sub_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 } /// calling `mul`, and therefore, `main` prints `Multiplying!`. /// /// ```rust -/// #![feature(associated_types)] -/// /// use std::ops::Mul; /// /// #[derive(Copy)] @@ -333,8 +322,6 @@ mul_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 } /// calling `div`, and therefore, `main` prints `Dividing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Div; /// /// #[derive(Copy)] @@ -388,8 +375,6 @@ div_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 } /// calling `rem`, and therefore, `main` prints `Remainder-ing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Rem; /// /// #[derive(Copy)] @@ -462,8 +447,6 @@ rem_float_impl! { f64, fmod } /// `neg`, and therefore, `main` prints `Negating!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Neg; /// /// struct Foo; @@ -541,8 +524,6 @@ neg_uint_impl! { u64, i64 } /// `not`, and therefore, `main` prints `Not-ing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Not; /// /// struct Foo; @@ -597,8 +578,6 @@ not_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 } /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::BitAnd; /// /// #[derive(Copy)] @@ -652,8 +631,6 @@ bitand_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 } /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::BitOr; /// /// #[derive(Copy)] @@ -707,8 +684,6 @@ bitor_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 } /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::BitXor; /// /// #[derive(Copy)] @@ -762,8 +737,6 @@ bitxor_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 } /// calling `shl`, and therefore, `main` prints `Shifting left!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Shl; /// /// #[derive(Copy)] @@ -835,8 +808,6 @@ shl_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize } /// calling `shr`, and therefore, `main` prints `Shifting right!`. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Shr; /// /// #[derive(Copy)] @@ -928,10 +899,12 @@ shr_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize } /// } /// ``` #[lang="index"] +#[stable(feature = "rust1", since = "1.0.0")] pub trait Index<Index: ?Sized> { type Output: ?Sized; /// The method for the indexing (`Foo[Bar]`) operation + #[stable(feature = "rust1", since = "1.0.0")] fn index<'a>(&'a self, index: &Index) -> &'a Self::Output; } @@ -964,30 +937,32 @@ pub trait Index<Index: ?Sized> { /// } /// ``` #[lang="index_mut"] +#[stable(feature = "rust1", since = "1.0.0")] pub trait IndexMut<Index: ?Sized> { type Output: ?Sized; /// The method for the indexing (`Foo[Bar]`) operation + #[stable(feature = "rust1", since = "1.0.0")] fn index_mut<'a>(&'a mut self, index: &Index) -> &'a mut Self::Output; } /// An unbounded range. #[derive(Copy, Clone, PartialEq, Eq)] #[lang="full_range"] -#[unstable(feature = "core", reason = "API still in development")] +#[unstable(feature = "core", reason = "may be renamed to RangeFull")] pub struct FullRange; -#[unstable(feature = "core", reason = "API still in development")] -impl fmt::Show for FullRange { +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Debug for FullRange { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt("..", fmt) + fmt::Debug::fmt("..", fmt) } } /// A (half-open) range which is bounded at both ends. #[derive(Copy, Clone, PartialEq, Eq)] #[lang="range"] -#[unstable(feature = "core", reason = "API still in development")] +#[stable(feature = "rust1", since = "1.0.0")] pub struct Range<Idx> { /// The lower bound of the range (inclusive). pub start: Idx, @@ -995,49 +970,8 @@ pub struct Range<Idx> { pub end: Idx, } -#[unstable(feature = "core", reason = "API still in development")] -impl<Idx: Clone + Step> Iterator for Range<Idx> { - type Item = Idx; - - #[inline] - fn next(&mut self) -> Option<Idx> { - if self.start < self.end { - let result = self.start.clone(); - self.start.step(); - return Some(result); - } - - return None; - } - - #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { - if let Some(hint) = Step::steps_between(&self.start, &self.end) { - (hint, Some(hint)) - } else { - (0, None) - } - } -} - -#[unstable(feature = "core", reason = "API still in development")] -impl<Idx: Clone + Step> DoubleEndedIterator for Range<Idx> { - #[inline] - fn next_back(&mut self) -> Option<Idx> { - if self.start < self.end { - self.end.step_back(); - return Some(self.end.clone()); - } - - return None; - } -} - -#[unstable(feature = "core", reason = "API still in development")] -impl<Idx: Clone + Step> ExactSizeIterator for Range<Idx> {} - -#[unstable(feature = "core", reason = "API still in development")] -impl<Idx: fmt::Show> fmt::Show for Range<Idx> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}..{:?}", self.start, self.end) } @@ -1046,27 +980,16 @@ impl<Idx: fmt::Show> fmt::Show for Range<Idx> { /// A range which is only bounded below. #[derive(Copy, Clone, PartialEq, Eq)] #[lang="range_from"] -#[unstable(feature = "core", reason = "API still in development")] +#[stable(feature = "rust1", since = "1.0.0")] pub struct RangeFrom<Idx> { /// The lower bound of the range (inclusive). pub start: Idx, } -#[unstable(feature = "core", reason = "API still in development")] -impl<Idx: Clone + Step> Iterator for RangeFrom<Idx> { - type Item = Idx; - #[inline] - fn next(&mut self) -> Option<Idx> { - // Deliberately overflow so we loop forever. - let result = self.start.clone(); - self.start.step(); - return Some(result); - } -} -#[unstable(feature = "core", reason = "API still in development")] -impl<Idx: fmt::Show> fmt::Show for RangeFrom<Idx> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}..", self.start) } @@ -1075,14 +998,14 @@ impl<Idx: fmt::Show> fmt::Show for RangeFrom<Idx> { /// A range which is only bounded above. #[derive(Copy, Clone, PartialEq, Eq)] #[lang="range_to"] -#[unstable(feature = "core", reason = "API still in development")] +#[stable(feature = "rust1", since = "1.0.0")] pub struct RangeTo<Idx> { /// The upper bound of the range (exclusive). pub end: Idx, } -#[unstable(feature = "core", reason = "API still in development")] -impl<Idx: fmt::Show> fmt::Show for RangeTo<Idx> { +#[stable(feature = "rust1", since = "1.0.0")] +impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "..{:?}", self.end) } @@ -1098,8 +1021,6 @@ impl<Idx: fmt::Show> fmt::Show for RangeTo<Idx> { /// struct. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::Deref; /// /// struct DerefExample<T> { @@ -1153,8 +1074,6 @@ impl<'a, T: ?Sized> Deref for &'a mut T { /// struct. /// /// ``` -/// #![feature(associated_types)] -/// /// use std::ops::{Deref, DerefMut}; /// /// struct DerefMutExample<T> { diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 4dec5fb9b3f..3441512e552 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -229,7 +229,7 @@ use self::Result::{Ok, Err}; use clone::Clone; -use fmt::Show; +use fmt::Display; use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator}; use ops::{FnMut, FnOnce}; use option::Option::{self, None, Some}; @@ -715,7 +715,7 @@ impl<T, E> Result<T, E> { } #[stable(feature = "rust1", since = "1.0.0")] -impl<T, E: Show> Result<T, E> { +impl<T, E: Display> Result<T, E> { /// Unwraps a result, yielding the content of an `Ok`. /// /// # Panics @@ -740,13 +740,13 @@ impl<T, E: Show> Result<T, E> { match self { Ok(t) => t, Err(e) => - panic!("called `Result::unwrap()` on an `Err` value: {:?}", e) + panic!("called `Result::unwrap()` on an `Err` value: {}", e) } } } #[stable(feature = "rust1", since = "1.0.0")] -impl<T: Show, E> Result<T, E> { +impl<T: Display, E> Result<T, E> { /// Unwraps a result, yielding the content of an `Err`. /// /// # Panics @@ -770,7 +770,7 @@ impl<T: Show, E> Result<T, E> { pub fn unwrap_err(self) -> E { match self { Ok(t) => - panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t), + panic!("called `Result::unwrap_err()` on an `Ok` value: {}", t), Err(e) => e } } diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 9f44fe96126..2b682111781 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -67,9 +67,6 @@ use raw::Slice as RawSlice; pub trait SliceExt { type Item; - fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [Self::Item]; - fn slice_from<'a>(&'a self, start: uint) -> &'a [Self::Item]; - fn slice_to<'a>(&'a self, end: uint) -> &'a [Self::Item]; fn split_at<'a>(&'a self, mid: uint) -> (&'a [Self::Item], &'a [Self::Item]); fn iter<'a>(&'a self) -> Iter<'a, Self::Item>; fn split<'a, P>(&'a self, pred: P) -> Split<'a, Self::Item, P> @@ -93,9 +90,6 @@ pub trait SliceExt { fn is_empty(&self) -> bool { self.len() == 0 } fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut Self::Item>; fn as_mut_slice<'a>(&'a mut self) -> &'a mut [Self::Item]; - fn slice_mut<'a>(&'a mut self, start: uint, end: uint) -> &'a mut [Self::Item]; - fn slice_from_mut<'a>(&'a mut self, start: uint) -> &'a mut [Self::Item]; - fn slice_to_mut<'a>(&'a mut self, end: uint) -> &'a mut [Self::Item]; fn iter_mut<'a>(&'a mut self) -> IterMut<'a, Self::Item>; fn first_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>; fn tail_mut<'a>(&'a mut self) -> &'a mut [Self::Item]; @@ -136,28 +130,6 @@ impl<T> SliceExt for [T] { type Item = T; #[inline] - fn slice(&self, start: uint, end: uint) -> &[T] { - assert!(start <= end); - assert!(end <= self.len()); - unsafe { - transmute(RawSlice { - data: self.as_ptr().offset(start as int), - len: (end - start) - }) - } - } - - #[inline] - fn slice_from(&self, start: uint) -> &[T] { - self.slice(start, self.len()) - } - - #[inline] - fn slice_to(&self, end: uint) -> &[T] { - self.slice(0, end) - } - - #[inline] fn split_at(&self, mid: uint) -> (&[T], &[T]) { (&self[..mid], &self[mid..]) } @@ -240,7 +212,7 @@ impl<T> SliceExt for [T] { #[inline] fn init(&self) -> &[T] { - &self[..(self.len() - 1)] + &self[..self.len() - 1] } #[inline] @@ -291,20 +263,6 @@ impl<T> SliceExt for [T] { #[inline] fn as_mut_slice(&mut self) -> &mut [T] { self } - fn slice_mut(&mut self, start: uint, end: uint) -> &mut [T] { - ops::IndexMut::index_mut(self, &ops::Range { start: start, end: end } ) - } - - #[inline] - fn slice_from_mut(&mut self, start: uint) -> &mut [T] { - ops::IndexMut::index_mut(self, &ops::RangeFrom { start: start } ) - } - - #[inline] - fn slice_to_mut(&mut self, end: uint) -> &mut [T] { - ops::IndexMut::index_mut(self, &ops::RangeTo { end: end } ) - } - #[inline] fn split_at_mut(&mut self, mid: uint) -> (&mut [T], &mut [T]) { unsafe { @@ -345,13 +303,13 @@ impl<T> SliceExt for [T] { #[inline] fn tail_mut(&mut self) -> &mut [T] { - self.slice_from_mut(1) + &mut self[1 ..] } #[inline] fn init_mut(&mut self) -> &mut [T] { let len = self.len(); - self.slice_to_mut(len-1) + &mut self[.. (len - 1)] } #[inline] @@ -449,7 +407,7 @@ impl<T> SliceExt for [T] { #[inline] fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq { let (m, n) = (self.len(), needle.len()); - m >= n && needle == &self[(m-n)..] + m >= n && needle == &self[m-n..] } #[unstable(feature = "core")] @@ -483,7 +441,7 @@ impl<T> SliceExt for [T] { self.swap(j, i-1); // Step 4: Reverse the (previously) weakly decreasing part - self.slice_from_mut(i).reverse(); + self[i..].reverse(); true } @@ -505,7 +463,7 @@ impl<T> SliceExt for [T] { } // Step 2: Reverse the weakly increasing part - self.slice_from_mut(i).reverse(); + self[i..].reverse(); // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1) let mut j = self.len() - 1; @@ -522,8 +480,8 @@ impl<T> SliceExt for [T] { #[inline] fn clone_from_slice(&mut self, src: &[T]) -> uint where T: Clone { let min = cmp::min(self.len(), src.len()); - let dst = self.slice_to_mut(min); - let src = src.slice_to(min); + let dst = &mut self[.. min]; + let src = &src[.. min]; for i in range(0, min) { dst[i].clone_from(&src[i]); } @@ -531,6 +489,7 @@ impl<T> SliceExt for [T] { } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Index<uint> for [T] { type Output = T; @@ -541,6 +500,7 @@ impl<T> ops::Index<uint> for [T] { } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::IndexMut<uint> for [T] { type Output = T; @@ -551,6 +511,7 @@ impl<T> ops::IndexMut<uint> for [T] { } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Index<ops::Range<uint>> for [T] { type Output = [T]; #[inline] @@ -565,6 +526,7 @@ impl<T> ops::Index<ops::Range<uint>> for [T] { } } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Index<ops::RangeTo<uint>> for [T] { type Output = [T]; #[inline] @@ -572,6 +534,7 @@ impl<T> ops::Index<ops::RangeTo<uint>> for [T] { self.index(&ops::Range{ start: 0, end: index.end }) } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Index<ops::RangeFrom<uint>> for [T] { type Output = [T]; #[inline] @@ -579,6 +542,7 @@ impl<T> ops::Index<ops::RangeFrom<uint>> for [T] { self.index(&ops::Range{ start: index.start, end: self.len() }) } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::Index<ops::FullRange> for [T] { type Output = [T]; #[inline] @@ -587,6 +551,7 @@ impl<T> ops::Index<ops::FullRange> for [T] { } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::IndexMut<ops::Range<uint>> for [T] { type Output = [T]; #[inline] @@ -601,6 +566,7 @@ impl<T> ops::IndexMut<ops::Range<uint>> for [T] { } } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::IndexMut<ops::RangeTo<uint>> for [T] { type Output = [T]; #[inline] @@ -608,6 +574,7 @@ impl<T> ops::IndexMut<ops::RangeTo<uint>> for [T] { self.index_mut(&ops::Range{ start: 0, end: index.end }) } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::IndexMut<ops::RangeFrom<uint>> for [T] { type Output = [T]; #[inline] @@ -616,6 +583,7 @@ impl<T> ops::IndexMut<ops::RangeFrom<uint>> for [T] { self.index_mut(&ops::Range{ start: index.start, end: len }) } } +#[stable(feature = "rust1", since = "1.0.0")] impl<T> ops::IndexMut<ops::FullRange> for [T] { type Output = [T]; #[inline] @@ -974,7 +942,7 @@ impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool { None => self.finish(), Some(idx) => { let ret = Some(&self.v[..idx]); - self.v = &self.v[(idx + 1)..]; + self.v = &self.v[idx + 1..]; ret } } @@ -999,7 +967,7 @@ impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> boo match self.v.iter().rposition(|x| (self.pred)(x)) { None => self.finish(), Some(idx) => { - let ret = Some(&self.v[(idx + 1)..]); + let ret = Some(&self.v[idx + 1..]); self.v = &self.v[..idx]; ret } @@ -1052,7 +1020,7 @@ impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool { Some(idx) => { let tmp = mem::replace(&mut self.v, &mut []); let (head, tail) = tmp.split_at_mut(idx); - self.v = tail.slice_from_mut(1); + self.v = &mut tail[1..]; Some(head) } } @@ -1088,7 +1056,7 @@ impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where let tmp = mem::replace(&mut self.v, &mut []); let (head, tail) = tmp.split_at_mut(idx); self.v = head; - Some(tail.slice_from_mut(1)) + Some(&mut tail[1..]) } } } @@ -1270,6 +1238,9 @@ impl<'a, T> DoubleEndedIterator for Chunks<'a, T> { } } +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, T> ExactSizeIterator for Chunks<'a, T> {} + #[unstable(feature = "core", reason = "trait is experimental")] impl<'a, T> RandomAccessIterator for Chunks<'a, T> { #[inline] @@ -1348,6 +1319,8 @@ impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> { } } +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {} // // Free functions diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 37f643db54e..92c5de937cc 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -20,8 +20,10 @@ use self::Searcher::{Naive, TwoWay, TwoWayLong}; use cmp::{self, Eq}; use default::Default; -use iter::range; +use error::Error; +use fmt; use iter::ExactSizeIterator; +use iter::range; use iter::{Map, Iterator, IteratorExt, DoubleEndedIterator}; use marker::Sized; use mem; @@ -247,6 +249,30 @@ impl<'a> CharEq for &'a [char] { } } +#[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", + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for Utf8Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Utf8Error::InvalidByte(n) => { + write!(f, "invalid utf-8: invalid byte at index {}", n) + } + Utf8Error::TooShort => { + write!(f, "invalid utf-8: byte slice too short") + } + } + } +} + /* Section: Iterators */ @@ -907,13 +933,13 @@ impl<'a> Iterator for SplitStr<'a> { match self.it.next() { Some((from, to)) => { - let ret = Some(self.it.haystack.slice(self.last_end, from)); + let ret = Some(&self.it.haystack[self.last_end .. from]); self.last_end = to; ret } None => { self.finished = true; - Some(self.it.haystack.slice(self.last_end, self.it.haystack.len())) + Some(&self.it.haystack[self.last_end .. self.it.haystack.len()]) } } } @@ -1121,27 +1147,90 @@ mod traits { } } + /// Returns a slice of the given string from the byte range + /// [`begin`..`end`). + /// + /// This operation is `O(1)`. + /// + /// Panics when `begin` and `end` do not point to valid characters + /// or point beyond the last character of the string. + /// + /// # Example + /// + /// ```rust + /// let s = "Löwe 老虎 Léopard"; + /// assert_eq!(&s[0 .. 1], "L"); + /// + /// assert_eq!(&s[1 .. 9], "öwe 老"); + /// + /// // these will panic: + /// // byte 2 lies within `ö`: + /// // &s[2 ..3]; + /// + /// // byte 8 lies within `老` + /// // &s[1 .. 8]; + /// + /// // byte 100 is outside the string + /// // &s[3 .. 100]; + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::Range<uint>> for str { type Output = str; #[inline] fn index(&self, index: &ops::Range<uint>) -> &str { - self.slice(index.start, index.end) + // is_char_boundary checks that the index is in [0, .len()] + if index.start <= index.end && + self.is_char_boundary(index.start) && + self.is_char_boundary(index.end) { + unsafe { self.slice_unchecked(index.start, index.end) } + } else { + super::slice_error_fail(self, index.start, index.end) + } } } + + /// Returns a slice of the string from the beginning to byte + /// `end`. + /// + /// Equivalent to `self[0 .. end]`. + /// + /// Panics when `end` does not point to a valid character, or is + /// out of bounds. + #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::RangeTo<uint>> for str { type Output = str; #[inline] fn index(&self, index: &ops::RangeTo<uint>) -> &str { - self.slice_to(index.end) + // is_char_boundary checks that the index is in [0, .len()] + if self.is_char_boundary(index.end) { + unsafe { self.slice_unchecked(0, index.end) } + } else { + super::slice_error_fail(self, 0, index.end) + } } } + + /// Returns a slice of the string from `begin` to its end. + /// + /// Equivalent to `self[begin .. self.len()]`. + /// + /// Panics when `begin` does not point to a valid character, or is + /// out of bounds. + #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::RangeFrom<uint>> for str { type Output = str; #[inline] fn index(&self, index: &ops::RangeFrom<uint>) -> &str { - self.slice_from(index.start) + // is_char_boundary checks that the index is in [0, .len()] + if self.is_char_boundary(index.start) { + unsafe { self.slice_unchecked(index.start, self.len()) } + } else { + super::slice_error_fail(self, index.start, self.len()) + } } } + + #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::FullRange> for str { type Output = str; #[inline] @@ -1154,7 +1243,7 @@ mod traits { /// Any string that can be represented as a slice #[unstable(feature = "core", reason = "Instead of taking this bound generically, this trait will be \ - replaced with one of slicing syntax, deref coercions, or \ + replaced with one of slicing syntax (&foo[]), deref coercions, or \ a more generic conversion trait")] pub trait Str { /// Work with `self` as a slice. @@ -1216,9 +1305,6 @@ pub trait StrExt { fn lines<'a>(&'a self) -> Lines<'a>; fn lines_any<'a>(&'a self) -> LinesAny<'a>; fn char_len(&self) -> uint; - fn slice<'a>(&'a self, begin: uint, end: uint) -> &'a str; - fn slice_from<'a>(&'a self, begin: uint) -> &'a str; - fn slice_to<'a>(&'a self, end: uint) -> &'a str; fn slice_chars<'a>(&'a self, begin: uint, end: uint) -> &'a str; unsafe fn slice_unchecked<'a>(&'a self, begin: uint, end: uint) -> &'a str; fn starts_with(&self, pat: &str) -> bool; @@ -1340,7 +1426,7 @@ impl StrExt for str { fn lines_any(&self) -> LinesAny { fn f(line: &str) -> &str { let l = line.len(); - if l > 0 && line.as_bytes()[l - 1] == b'\r' { line.slice(0, l - 1) } + if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] } else { line } } @@ -1351,38 +1437,6 @@ impl StrExt for str { #[inline] fn char_len(&self) -> uint { self.chars().count() } - #[inline] - fn slice(&self, begin: uint, end: uint) -> &str { - // is_char_boundary checks that the index is in [0, .len()] - if begin <= end && - self.is_char_boundary(begin) && - self.is_char_boundary(end) { - unsafe { self.slice_unchecked(begin, end) } - } else { - slice_error_fail(self, begin, end) - } - } - - #[inline] - fn slice_from(&self, begin: uint) -> &str { - // is_char_boundary checks that the index is in [0, .len()] - if self.is_char_boundary(begin) { - unsafe { self.slice_unchecked(begin, self.len()) } - } else { - slice_error_fail(self, begin, self.len()) - } - } - - #[inline] - fn slice_to(&self, end: uint) -> &str { - // is_char_boundary checks that the index is in [0, .len()] - if self.is_char_boundary(end) { - unsafe { self.slice_unchecked(0, end) } - } else { - slice_error_fail(self, 0, end) - } - } - fn slice_chars(&self, begin: uint, end: uint) -> &str { assert!(begin <= end); let mut count = 0; @@ -1423,7 +1477,7 @@ impl StrExt for str { #[inline] fn ends_with(&self, needle: &str) -> bool { let (m, n) = (self.len(), needle.len()); - m >= n && needle.as_bytes() == &self.as_bytes()[(m-n)..] + m >= n && needle.as_bytes() == &self.as_bytes()[m-n..] } #[inline] |
