Right now the `std::isize::BYTES` typedef is `#[unstable]`, but liblibc is using
this, preventing it from compiling on stable Rust.
* [Looping](looping.md)
* [Strings](strings.md)
* [Arrays, Vectors, and Slices](arrays-vectors-and-slices.md)
- * [Standard Input](standard-input.md)
* [Intermediate Rust](intermediate.md)
* [Crates and Modules](crates-and-modules.md)
* [Testing](testing.md)
+++ /dev/null
-% Standard Input
-
-Getting input from the keyboard is pretty easy, but uses some things
-we haven't seen before. Here's a simple program that reads some input,
-and then prints it back out:
-
-```{rust,ignore}
-# #![feature(old_io)]
-fn main() {
- println!("Type something!");
-
- let input = std::old_io::stdin().read_line().ok().expect("Failed to read line");
-
- println!("{}", input);
-}
-```
-
-Let's go over these chunks, one by one:
-
-```{rust,ignore}
-std::old_io::stdin();
-```
-
-This calls a function, `stdin()`, that lives inside the `std::old_io` module. As
-you can imagine, everything in `std` is provided by Rust, the 'standard
-library.' We'll talk more about the module system later.
-
-Since writing the fully qualified name all the time is annoying, we can use
-the `use` statement to import it in:
-
-```{rust}
-# #![feature(old_io)]
-use std::old_io::stdin;
-
-stdin();
-```
-
-However, it's considered better practice to not import individual functions, but
-to import the module, and only use one level of qualification:
-
-```{rust}
-# #![feature(old_io)]
-use std::old_io;
-
-old_io::stdin();
-```
-
-Let's update our example to use this style:
-
-```{rust,ignore}
-use std::old_io;
-
-fn main() {
- println!("Type something!");
-
- let input = old_io::stdin().read_line().ok().expect("Failed to read line");
-
- println!("{}", input);
-}
-```
-
-Next up:
-
-```{rust,ignore}
-.read_line()
-```
-
-The `read_line()` method can be called on the result of `stdin()` to return
-a full line of input. Nice and easy.
-
-```{rust,ignore}
-.ok().expect("Failed to read line");
-```
-
-Do you remember this code?
-
-```{rust}
-enum OptionalInt {
- Value(i32),
- Missing,
-}
-
-fn main() {
- let x = OptionalInt::Value(5);
- let y = OptionalInt::Missing;
-
- match x {
- OptionalInt::Value(n) => println!("x is {}", n),
- OptionalInt::Missing => println!("x is missing!"),
- }
-
- match y {
- OptionalInt::Value(n) => println!("y is {}", n),
- OptionalInt::Missing => println!("y is missing!"),
- }
-}
-```
-
-We had to match each time to see if we had a value or not. In this case,
-though, we _know_ that `x` has a `Value`, but `match` forces us to handle
-the `missing` case. This is what we want 99% of the time, but sometimes, we
-know better than the compiler.
-
-Likewise, `read_line()` does not return a line of input. It _might_ return a
-line of input, though it might also fail to do so. This could happen if our program
-isn't running in a terminal, but as part of a cron job, or some other context
-where there's no standard input. Because of this, `read_line` returns a type
-very similar to our `OptionalInt`: an `IoResult<T>`. We haven't talked about
-`IoResult<T>` yet because it is the *generic* form of our `OptionalInt`.
-Until then, you can think of it as being the same thing, just for any type –
-not just `i32`s.
-
-Rust provides a method on these `IoResult<T>`s called `ok()`, which does the
-same thing as our `match` statement but assumes that we have a valid value.
-We then call `expect()` on the result, which will terminate our program if we
-don't have a valid value. In this case, if we can't get input, our program
-doesn't work, so we're okay with that. In most cases, we would want to handle
-the error case explicitly. `expect()` allows us to give an error message if
-this crash happens.
-
-We will cover the exact details of how all of this works later in the Guide in
-[Error Handling]. For now, this gives you enough of a basic understanding to
-work with.
-
-Back to the code we were working on! Here's a refresher:
-
-```{rust,ignore}
-use std::old_io;
-
-fn main() {
- println!("Type something!");
-
- let input = old_io::stdin().read_line().ok().expect("Failed to read line");
-
- println!("{}", input);
-}
-```
-
-With long lines like this, Rust gives you some flexibility with the whitespace.
-We _could_ write the example like this:
-
-```{rust,ignore}
-use std::old_io;
-
-fn main() {
- println!("Type something!");
-
- // here, we'll show the types at each step
-
- let input = old_io::stdin() // std::old_io::stdio::StdinReader
- .read_line() // IoResult<String>
- .ok() // Option<String>
- .expect("Failed to read line"); // String
-
- println!("{}", input);
-}
-```
-
-Sometimes, this makes things more readable – sometimes, less. Use your judgement
-here.
-
-That's all you need to get basic input from the standard input! It's not too
-complicated, but there are a number of small parts.
-
-
-[Error Handling]: ./error-handling.html
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- try!(write!(f, "{{"));
-
- for (i, (k, v)) in self.iter().enumerate() {
- if i != 0 { try!(write!(f, ", ")); }
- try!(write!(f, "{:?}: {:?}", *k, *v));
- }
-
- write!(f, "}}")
+ self.iter().fold(f.debug_map(), |b, (k, v)| b.entry(k, v)).finish()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Debug> Debug for BTreeSet<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- try!(write!(f, "{{"));
-
- for (i, x) in self.iter().enumerate() {
- if i != 0 { try!(write!(f, ", ")); }
- try!(write!(f, "{:?}", *x));
- }
-
- write!(f, "}}")
+ self.iter().fold(f.debug_set(), |b, e| b.entry(e)).finish()
}
}
#![feature(str_char)]
#![feature(convert)]
#![feature(slice_patterns)]
+#![feature(debug_builders)]
#![cfg_attr(test, feature(rand, rustc_private, test, hash, collections))]
#![cfg_attr(test, allow(deprecated))] // rand
#[stable(feature = "rust1", since = "1.0.0")]
impl<A: fmt::Debug> fmt::Debug for LinkedList<A> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- try!(write!(f, "["));
-
- for (i, e) in self.iter().enumerate() {
- if i != 0 { try!(write!(f, ", ")); }
- try!(write!(f, "{:?}", *e));
- }
-
- write!(f, "]")
+ self.iter().fold(f.debug_list(), |b, e| b.entry(e)).finish()
}
}
#[cfg(test)]
mod test {
use std::clone::Clone;
- use std::iter::{Iterator, IteratorExt};
+ use std::iter::Iterator;
use std::option::Option::{Some, None, self};
use std::rand;
use std::thread;
//! iterators.
//! * Further methods that return iterators are `.split()`, `.splitn()`,
//! `.chunks()`, `.windows()` and more.
-
#![doc(primitive = "slice")]
#![stable(feature = "rust1", since = "1.0.0")]
use core::clone::Clone;
use core::cmp::Ordering::{self, Greater, Less};
use core::cmp::{self, Ord, PartialEq};
-use core::iter::{Iterator, IteratorExt};
+use core::iter::Iterator;
use core::iter::MultiplicativeIterator;
use core::marker::Sized;
use core::mem::size_of;
use alloc::boxed::Box;
use core::clone::Clone;
#[cfg(test)]
- use core::iter::{Iterator, IteratorExt};
+ use core::iter::Iterator;
use core::mem;
#[cfg(test)]
use core::option::Option::{Some, None};
use core::clone::Clone;
use core::iter::AdditiveIterator;
-use core::iter::{Iterator, IteratorExt, Extend};
+use core::iter::{Iterator, Extend};
use core::option::Option::{self, Some, None};
use core::result::Result;
use core::str as core_str;
#[cfg(test)]
mod test {
- use core::iter::{IteratorExt, self};
+ use core::iter::{Iterator, self};
use core::option::Option::Some;
use test;
($name: ident, $n: expr, $map: ident) => (
#[bench]
pub fn $name(b: &mut ::test::Bencher) {
- use std::iter::IteratorExt;
+ use std::iter::Iterator;
use std::rand::Rng;
use std::rand;
use std::vec::Vec;
}
}
+struct DebugInner<'a, 'b: 'a> {
+ fmt: &'a mut fmt::Formatter<'b>,
+ result: fmt::Result,
+ has_fields: bool,
+}
+
+impl<'a, 'b: 'a> DebugInner<'a, 'b> {
+ fn entry(&mut self, entry: &fmt::Debug) {
+ self.result = self.result.and_then(|_| {
+ if self.is_pretty() {
+ let mut writer = PadAdapter::new(self.fmt);
+ let prefix = if self.has_fields { "," } else { "" };
+ fmt::write(&mut writer, format_args!("{}\n{:#?}", prefix, entry))
+ } else {
+ let prefix = if self.has_fields { ", " } else { "" };
+ write!(self.fmt, "{}{:?}", prefix, entry)
+ }
+ });
+
+ self.has_fields = true;
+ }
+
+ pub fn finish(&mut self) {
+ let prefix = if self.is_pretty() && self.has_fields { "\n" } else { "" };
+ self.result = self.result.and_then(|_| self.fmt.write_str(prefix));
+ }
+
+ fn is_pretty(&self) -> bool {
+ self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
+ }
+}
+
/// A struct to help with `fmt::Debug` implementations.
///
/// Constructed by the `Formatter::debug_set` method.
#[must_use]
pub struct DebugSet<'a, 'b: 'a> {
- fmt: &'a mut fmt::Formatter<'b>,
- result: fmt::Result,
- has_fields: bool,
+ inner: DebugInner<'a, 'b>,
}
-pub fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str) -> DebugSet<'a, 'b> {
- let result = write!(fmt, "{} {{", name);
+pub fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> {
+ let result = write!(fmt, "{{");
DebugSet {
- fmt: fmt,
- result: result,
- has_fields: false,
+ inner: DebugInner {
+ fmt: fmt,
+ result: result,
+ has_fields: false,
+ }
}
}
/// Adds a new entry to the set output.
#[unstable(feature = "debug_builders", reason = "method was just created")]
pub fn entry(mut self, entry: &fmt::Debug) -> DebugSet<'a, 'b> {
- self.result = self.result.and_then(|_| {
- let prefix = if self.has_fields {
- ","
- } else {
- ""
- };
-
- if self.is_pretty() {
- let mut writer = PadAdapter::new(self.fmt);
- fmt::write(&mut writer, format_args!("{}\n{:#?}", prefix, entry))
- } else {
- write!(self.fmt, "{} {:?}", prefix, entry)
- }
- });
-
- self.has_fields = true;
+ self.inner.entry(entry);
self
}
/// Consumes the `DebugSet`, finishing output and returning any error
/// encountered.
#[unstable(feature = "debug_builders", reason = "method was just created")]
- pub fn finish(self) -> fmt::Result {
- self.result.and_then(|_| {
- let end = match (self.has_fields, self.is_pretty()) {
- (false, _) => "}",
- (true, false) => " }",
- (true, true) => "\n}",
- };
- self.fmt.write_str(end)
- })
+ pub fn finish(mut self) -> fmt::Result {
+ self.inner.finish();
+ self.inner.result.and_then(|_| self.inner.fmt.write_str("}"))
}
+}
- fn is_pretty(&self) -> bool {
- self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
+/// A struct to help with `fmt::Debug` implementations.
+///
+/// Constructed by the `Formatter::debug_list` method.
+#[must_use]
+pub struct DebugList<'a, 'b: 'a> {
+ inner: DebugInner<'a, 'b>,
+}
+
+pub fn debug_list_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugList<'a, 'b> {
+ let result = write!(fmt, "[");
+ DebugList {
+ inner: DebugInner {
+ fmt: fmt,
+ result: result,
+ has_fields: false,
+ }
+ }
+}
+
+impl<'a, 'b: 'a> DebugList<'a, 'b> {
+ /// Adds a new entry to the set output.
+ #[unstable(feature = "debug_builders", reason = "method was just created")]
+ pub fn entry(mut self, entry: &fmt::Debug) -> DebugList<'a, 'b> {
+ self.inner.entry(entry);
+ self
+ }
+
+ /// Consumes the `DebugSet`, finishing output and returning any error
+ /// encountered.
+ #[unstable(feature = "debug_builders", reason = "method was just created")]
+ pub fn finish(mut self) -> fmt::Result {
+ self.inner.finish();
+ self.inner.result.and_then(|_| self.inner.fmt.write_str("]"))
}
}
has_fields: bool,
}
-pub fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str) -> DebugMap<'a, 'b> {
- let result = write!(fmt, "{} {{", name);
+pub fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugMap<'a, 'b> {
+ let result = write!(fmt, "{{");
DebugMap {
fmt: fmt,
result: result,
#[unstable(feature = "debug_builders", reason = "method was just created")]
pub fn entry(mut self, key: &fmt::Debug, value: &fmt::Debug) -> DebugMap<'a, 'b> {
self.result = self.result.and_then(|_| {
- let prefix = if self.has_fields {
- ","
- } else {
- ""
- };
-
if self.is_pretty() {
let mut writer = PadAdapter::new(self.fmt);
+ let prefix = if self.has_fields { "," } else { "" };
fmt::write(&mut writer, format_args!("{}\n{:#?}: {:#?}", prefix, key, value))
} else {
- write!(self.fmt, "{} {:?}: {:?}", prefix, key, value)
+ let prefix = if self.has_fields { ", " } else { "" };
+ write!(self.fmt, "{}{:?}: {:?}", prefix, key, value)
}
});
self.has_fields = true;
-
self
}
/// encountered.
#[unstable(feature = "debug_builders", reason = "method was just created")]
pub fn finish(self) -> fmt::Result {
- self.result.and_then(|_| {
- let end = match (self.has_fields, self.is_pretty()) {
- (false, _) => "}",
- (true, false) => " }",
- (true, true) => "\n}",
- };
- self.fmt.write_str(end)
- })
+ let prefix = if self.is_pretty() && self.has_fields { "\n" } else { "" };
+ self.result.and_then(|_| write!(self.fmt, "{}}}", prefix))
}
fn is_pretty(&self) -> bool {
use char;
use char::CharExt;
use fmt;
-use iter::IteratorExt;
+use iter::Iterator;
use num::{cast, Float, ToPrimitive};
use num::FpCategory as Fp;
use ops::FnOnce;
use any;
use cell::{Cell, RefCell, Ref, RefMut, BorrowState};
use char::CharExt;
-use iter::{Iterator, IteratorExt};
+use iter::Iterator;
use marker::{Copy, PhantomData, Sized};
use mem;
use option::Option;
pub use self::num::Radix;
pub use self::num::RadixFmt;
-pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugMap};
+pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
mod num;
mod float;
/// // prints "Foo { bar: 10, baz: "Hello World" }"
/// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
/// ```
- #[unstable(feature = "core", reason = "method was just created")]
+ #[unstable(feature = "debug_builders", reason = "method was just created")]
#[inline]
pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
builders::debug_struct_new(self, name)
/// // prints "Foo(10, "Hello World")"
/// println!("{:?}", Foo(10, "Hello World".to_string()));
/// ```
- #[unstable(feature = "core", reason = "method was just created")]
+ #[unstable(feature = "debug_builders", reason = "method was just created")]
#[inline]
pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
builders::debug_tuple_new(self, name)
}
+ /// Creates a `DebugList` builder designed to assist with creation of
+ /// `fmt::Debug` implementations for list-like structures.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # #![feature(debug_builders, core)]
+ /// use std::fmt;
+ ///
+ /// struct Foo(Vec<i32>);
+ ///
+ /// impl fmt::Debug for Foo {
+ /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ /// self.0.iter().fold(fmt.debug_list(), |b, e| b.entry(e)).finish()
+ /// }
+ /// }
+ ///
+ /// // prints "[10, 11]"
+ /// println!("{:?}", Foo(vec![10, 11]));
+ /// ```
+ #[unstable(feature = "debug_builders", reason = "method was just created")]
+ #[inline]
+ pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
+ builders::debug_list_new(self)
+ }
+
/// Creates a `DebugSet` builder designed to assist with creation of
/// `fmt::Debug` implementations for set-like structures.
///
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- /// let mut builder = fmt.debug_set("Foo");
- /// for i in &self.0 {
- /// builder = builder.entry(i);
- /// }
- /// builder.finish()
+ /// self.0.iter().fold(fmt.debug_set(), |b, e| b.entry(e)).finish()
/// }
/// }
///
- /// // prints "Foo { 10, 11 }"
+ /// // prints "{10, 11}"
/// println!("{:?}", Foo(vec![10, 11]));
/// ```
- #[unstable(feature = "core", reason = "method was just created")]
+ #[unstable(feature = "debug_builders", reason = "method was just created")]
#[inline]
- pub fn debug_set<'b>(&'b mut self, name: &str) -> DebugSet<'b, 'a> {
- builders::debug_set_new(self, name)
+ pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
+ builders::debug_set_new(self)
}
/// Creates a `DebugMap` builder designed to assist with creation of
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- /// let mut builder = fmt.debug_map("Foo");
- /// for &(ref key, ref value) in &self.0 {
- /// builder = builder.entry(key, value);
- /// }
- /// builder.finish()
+ /// self.0.iter().fold(fmt.debug_map(), |b, &(ref k, ref v)| b.entry(k, v)).finish()
/// }
/// }
///
- /// // prints "Foo { "A": 10, "B": 11 }"
+ /// // prints "{"A": 10, "B": 11}"
/// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
/// ```
- #[unstable(feature = "core", reason = "method was just created")]
+ #[unstable(feature = "debug_builders", reason = "method was just created")]
#[inline]
- pub fn debug_map<'b>(&'b mut self, name: &str) -> DebugMap<'b, 'a> {
- builders::debug_map_new(self, name)
+ pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
+ builders::debug_map_new(self)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Debug> Debug for [T] {
fn fmt(&self, f: &mut Formatter) -> Result {
- if f.flags & (1 << (FlagV1::Alternate as u32)) == 0 {
- try!(write!(f, "["));
- }
- let mut is_first = true;
- for x in self {
- if is_first {
- is_first = false;
- } else {
- try!(write!(f, ", "));
- }
- try!(write!(f, "{:?}", *x))
- }
- if f.flags & (1 << (FlagV1::Alternate as u32)) == 0 {
- try!(write!(f, "]"));
- }
- Ok(())
+ self.iter().fold(f.debug_list(), |b, e| b.entry(e)).finish()
}
}
#![allow(unsigned_negation)]
use fmt;
-use iter::IteratorExt;
+use iter::Iterator;
use num::{Int, cast};
use slice::SliceExt;
use str;
use marker::Sized;
use usize;
+fn _assert_is_object_safe(_: &Iterator) {}
+
/// 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
/// being located on the call stack.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
- type Item = I::Item;
- fn next(&mut self) -> Option<I::Item> { (**self).next() }
- fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
-}
-
-/// Conversion from an `Iterator`
-#[stable(feature = "rust1", since = "1.0.0")]
-#[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
- built from an iterator over elements of type `{A}`"]
-pub trait FromIterator<A> {
- /// Build a container with elements from something iterable.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn from_iter<T: IntoIterator<Item=A>>(iterator: T) -> Self;
-}
-
-/// Conversion into an `Iterator`
-#[stable(feature = "rust1", since = "1.0.0")]
-pub trait IntoIterator {
- /// The type of the elements being iterated
- #[stable(feature = "rust1", since = "1.0.0")]
- type Item;
-
- /// A container for iterating over elements of type Item
- #[stable(feature = "rust1", since = "1.0.0")]
- type IntoIter: Iterator<Item=Self::Item>;
-
- /// Consumes `Self` and returns an iterator over it
- #[stable(feature = "rust1", since = "1.0.0")]
- fn into_iter(self) -> Self::IntoIter;
-}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I: Iterator> IntoIterator for I {
- type Item = I::Item;
- type IntoIter = I;
-
- fn into_iter(self) -> I {
- self
- }
-}
-
-/// A type growable from an `Iterator` implementation
-#[stable(feature = "rust1", since = "1.0.0")]
-pub trait Extend<A> {
- /// Extend a container with the elements yielded by an arbitrary iterator
- #[stable(feature = "rust1", since = "1.0.0")]
- fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
-}
-
-/// An extension trait providing numerous methods applicable to all iterators.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub trait IteratorExt: Iterator + Sized {
/// Counts the number of elements in this iterator.
///
/// # Examples
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn count(self) -> usize {
+ fn count(self) -> usize where Self: Sized {
self.fold(0, |cnt, _x| cnt + 1)
}
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn last(self) -> Option<Self::Item> {
+ fn last(self) -> Option<Self::Item> where Self: Sized {
let mut last = None;
for x in self { last = Some(x); }
last
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
+ fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
for x in self.by_ref() {
if n == 0 { return Some(x) }
n -= 1;
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn chain<U>(self, other: U) -> Chain<Self, U> where
- U: Iterator<Item=Self::Item>,
+ Self: Sized, U: Iterator<Item=Self::Item>,
{
Chain{a: self, b: other, flag: false}
}
/// both produce the same output.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn zip<U: Iterator>(self, other: U) -> Zip<Self, U> {
+ fn zip<U: Iterator>(self, other: U) -> Zip<Self, U> where Self: Sized {
Zip{a: self, b: other}
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn map<B, F>(self, f: F) -> Map<Self, F> where
- F: FnMut(Self::Item) -> B,
+ Self: Sized, F: FnMut(Self::Item) -> B,
{
Map{iter: self, f: f}
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn filter<P>(self, predicate: P) -> Filter<Self, P> where
- P: FnMut(&Self::Item) -> bool,
+ Self: Sized, P: FnMut(&Self::Item) -> bool,
{
Filter{iter: self, predicate: predicate}
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
- F: FnMut(Self::Item) -> Option<B>,
+ Self: Sized, F: FnMut(Self::Item) -> Option<B>,
{
FilterMap { iter: self, f: f }
}
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn enumerate(self) -> Enumerate<Self> {
+ fn enumerate(self) -> Enumerate<Self> where Self: Sized {
Enumerate{iter: self, count: 0}
}
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn peekable(self) -> Peekable<Self> {
+ fn peekable(self) -> Peekable<Self> where Self: Sized {
Peekable{iter: self, peeked: None}
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
- P: FnMut(&Self::Item) -> bool,
+ Self: Sized, P: FnMut(&Self::Item) -> bool,
{
SkipWhile{iter: self, flag: false, predicate: predicate}
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
- P: FnMut(&Self::Item) -> bool,
+ Self: Sized, P: FnMut(&Self::Item) -> bool,
{
TakeWhile{iter: self, flag: false, predicate: predicate}
}
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn skip(self, n: usize) -> Skip<Self> {
+ fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
Skip{iter: self, n: n}
}
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn take(self, n: usize) -> Take<Self> {
+ fn take(self, n: usize) -> Take<Self> where Self: Sized, {
Take{iter: self, n: n}
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
- where F: FnMut(&mut St, Self::Item) -> Option<B>,
+ where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
{
Scan{iter: self, f: f, state: initial_state}
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
- where U: Iterator, F: FnMut(Self::Item) -> U,
+ where Self: Sized, U: Iterator, F: FnMut(Self::Item) -> U,
{
FlatMap{iter: self, f: f, frontiter: None, backiter: None }
}
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn fuse(self) -> Fuse<Self> {
+ fn fuse(self) -> Fuse<Self> where Self: Sized {
Fuse{iter: self, done: false}
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn inspect<F>(self, f: F) -> Inspect<Self, F> where
- F: FnMut(&Self::Item),
+ Self: Sized, F: FnMut(&Self::Item),
{
Inspect{iter: self, f: f}
}
/// assert!(it.next() == Some(5));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
- fn by_ref(&mut self) -> &mut Self { self }
+ fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
/// Loops through the entire iterator, collecting all of the elements into
/// a container implementing `FromIterator`.
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn collect<B: FromIterator<Self::Item>>(self) -> B {
+ fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
FromIterator::from_iter(self)
}
#[unstable(feature = "core",
reason = "recently added as part of collections reform")]
fn partition<B, F>(self, mut f: F) -> (B, B) where
+ Self: Sized,
B: Default + Extend<Self::Item>,
F: FnMut(&Self::Item) -> bool
{
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn fold<B, F>(self, init: B, mut f: F) -> B where
- F: FnMut(B, Self::Item) -> B,
+ Self: Sized, F: FnMut(B, Self::Item) -> B,
{
let mut accum = init;
for x in self {
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn all<F>(&mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
+ fn all<F>(&mut self, mut f: F) -> bool where
+ Self: Sized, F: FnMut(Self::Item) -> bool
+ {
for x in self.by_ref() { if !f(x) { return false; } }
true
}
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn any<F>(&mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
+ fn any<F>(&mut self, mut f: F) -> bool where
+ Self: Sized,
+ F: FnMut(Self::Item) -> bool
+ {
for x in self.by_ref() { if f(x) { return true; } }
false
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
+ Self: Sized,
P: FnMut(&Self::Item) -> bool,
{
for x in self.by_ref() {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
+ Self: Sized,
P: FnMut(Self::Item) -> bool,
{
let mut i = 0;
#[stable(feature = "rust1", since = "1.0.0")]
fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
P: FnMut(Self::Item) -> bool,
- Self: ExactSizeIterator + DoubleEndedIterator
+ Self: Sized + ExactSizeIterator + DoubleEndedIterator
{
let mut i = self.len();
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn max(self) -> Option<Self::Item> where Self::Item: Ord
+ fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
{
self.fold(None, |max, x| {
match max {
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn min(self) -> Option<Self::Item> where Self::Item: Ord
+ fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
{
self.fold(None, |min, x| {
match min {
/// 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
+ fn min_max(mut self) -> MinMaxResult<Self::Item> where Self: Sized, Self::Item: Ord
{
let (mut min, mut max) = match self.next() {
None => return NoElements,
#[unstable(feature = "core",
reason = "may want to produce an Ordering directly; see #15311")]
fn max_by<B: Ord, F>(self, mut f: F) -> Option<Self::Item> where
+ Self: Sized,
F: FnMut(&Self::Item) -> B,
{
self.fold(None, |max: Option<(Self::Item, B)>, x| {
#[unstable(feature = "core",
reason = "may want to produce an Ordering directly; see #15311")]
fn min_by<B: Ord, F>(self, mut f: F) -> Option<Self::Item> where
+ Self: Sized,
F: FnMut(&Self::Item) -> B,
{
self.fold(None, |min: Option<(Self::Item, B)>, x| {
/// `std::usize::MAX` elements of the original iterator.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- fn rev(self) -> Rev<Self> {
+ fn rev(self) -> Rev<Self> where Self: Sized {
Rev{iter: self}
}
fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
- Self: Iterator<Item=(A, B)>,
+ Self: Sized + Iterator<Item=(A, B)>,
{
struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
impl<A> Iterator for SizeHint<A> {
/// converting an Iterator<&T> to an Iterator<T>.
#[stable(feature = "rust1", since = "1.0.0")]
fn cloned<'a, T: 'a>(self) -> Cloned<Self>
- where Self: Iterator<Item=&'a T>, T: Clone
+ where Self: Sized + Iterator<Item=&'a T>, T: Clone
{
Cloned { it: self }
}
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
- fn cycle(self) -> Cycle<Self> where Self: Clone {
+ fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
Cycle{orig: self.clone(), iter: self}
}
#[unstable(feature = "core",
reason = "uncertain about placement or widespread use")]
fn reverse_in_place<'a, T: 'a>(&mut self) where
- Self: Iterator<Item=&'a mut T> + DoubleEndedIterator
+ Self: Sized + Iterator<Item=&'a mut T> + DoubleEndedIterator
{
loop {
match (self.next(), self.next_back()) {
}
#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> IteratorExt for I where I: Iterator {}
+impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
+ type Item = I::Item;
+ fn next(&mut self) -> Option<I::Item> { (**self).next() }
+ fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
+}
+
+/// Conversion from an `Iterator`
+#[stable(feature = "rust1", since = "1.0.0")]
+#[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
+ built from an iterator over elements of type `{A}`"]
+pub trait FromIterator<A> {
+ /// Build a container with elements from something iterable.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn from_iter<T: IntoIterator<Item=A>>(iterator: T) -> Self;
+}
+
+/// Conversion into an `Iterator`
+#[stable(feature = "rust1", since = "1.0.0")]
+pub trait IntoIterator {
+ /// The type of the elements being iterated
+ #[stable(feature = "rust1", since = "1.0.0")]
+ type Item;
+
+ /// A container for iterating over elements of type Item
+ #[stable(feature = "rust1", since = "1.0.0")]
+ type IntoIter: Iterator<Item=Self::Item>;
+
+ /// Consumes `Self` and returns an iterator over it
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn into_iter(self) -> Self::IntoIter;
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I: Iterator> IntoIterator for I {
+ type Item = I::Item;
+ type IntoIter = I;
+
+ fn into_iter(self) -> I {
+ self
+ }
+}
+
+/// A type growable from an `Iterator` implementation
+#[stable(feature = "rust1", since = "1.0.0")]
+pub trait Extend<A> {
+ /// Extend a container with the elements yielded by an arbitrary iterator
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
+}
/// A range iterator able to yield elements from both ends
///
impl_multiplicative! { f32, 1.0 }
impl_multiplicative! { f64, 1.0 }
-/// `MinMaxResult` is an enum returned by `min_max`. See `IteratorOrdExt::min_max` for more detail.
+/// `MinMaxResult` is an enum returned by `min_max`. See `Iterator::min_max` for more detail.
#[derive(Clone, PartialEq, Debug)]
#[unstable(feature = "core",
reason = "unclear whether such a fine-grained result is widely useful")]
use error::Error;
use fmt;
use intrinsics;
-use iter::IteratorExt;
+use iter::Iterator;
use marker::Copy;
use mem::size_of;
use ops::{Add, Sub, Mul, Div, Rem, Neg};
use cmp::{Eq, Ord};
use default::Default;
use iter::ExactSizeIterator;
-use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, IntoIterator};
+use iter::{Iterator, DoubleEndedIterator, FromIterator, IntoIterator};
use mem;
use ops::FnOnce;
use result::Result::{Ok, Err};
pub use clone::Clone;
pub use cmp::{PartialEq, PartialOrd, Eq, Ord};
pub use convert::{AsRef, AsMut, Into, From};
-pub use iter::{Extend, IteratorExt};
+pub use iter::Extend;
pub use iter::{Iterator, DoubleEndedIterator};
pub use iter::{ExactSizeIterator};
pub use option::Option::{self, Some, None};
use clone::Clone;
use fmt;
-use iter::{Iterator, IteratorExt, DoubleEndedIterator,
- FromIterator, ExactSizeIterator, IntoIterator};
+use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator};
use ops::{FnMut, FnOnce};
use option::Option::{self, None, Some};
#[allow(deprecated)]
use error::Error;
use fmt;
use iter::ExactSizeIterator;
-use iter::{Map, Iterator, IteratorExt, DoubleEndedIterator};
+use iter::{Map, Iterator, DoubleEndedIterator};
use marker::Sized;
use mem;
#[allow(deprecated)]
mod traits {
use cmp::{Ordering, Ord, PartialEq, PartialOrd, Eq};
use cmp::Ordering::{Less, Equal, Greater};
- use iter::IteratorExt;
+ use iter::Iterator;
use option::Option;
use option::Option::Some;
use ops;
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.debug_map("Foo").finish()
+ fmt.debug_map().finish()
}
}
- assert_eq!("Foo {}", format!("{:?}", Foo));
- assert_eq!("Foo {}", format!("{:#?}", Foo));
+ assert_eq!("{}", format!("{:?}", Foo));
+ assert_eq!("{}", format!("{:#?}", Foo));
}
#[test]
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.debug_map("Foo")
+ fmt.debug_map()
.entry(&"bar", &true)
.finish()
}
}
- assert_eq!("Foo { \"bar\": true }", format!("{:?}", Foo));
+ assert_eq!("{\"bar\": true}", format!("{:?}", Foo));
assert_eq!(
-"Foo {
+"{
\"bar\": true
}",
format!("{:#?}", Foo));
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.debug_map("Foo")
+ fmt.debug_map()
.entry(&"bar", &true)
.entry(&10i32, &format_args!("{}/{}", 10i32, 20i32))
.finish()
}
}
- assert_eq!("Foo { \"bar\": true, 10: 10/20 }", format!("{:?}", Foo));
+ assert_eq!("{\"bar\": true, 10: 10/20}", format!("{:?}", Foo));
assert_eq!(
-"Foo {
+"{
\"bar\": true,
10: 10/20
}",
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.debug_map("Foo")
+ fmt.debug_map()
.entry(&"bar", &true)
.entry(&10i32, &format_args!("{}/{}", 10i32, 20i32))
.finish()
impl fmt::Debug for Bar {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.debug_map("Bar")
+ fmt.debug_map()
.entry(&"foo", &Foo)
.entry(&Foo, &"world")
.finish()
}
}
- assert_eq!("Bar { \"foo\": Foo { \"bar\": true, 10: 10/20 }, \
- Foo { \"bar\": true, 10: 10/20 }: \"world\" }",
+ assert_eq!("{\"foo\": {\"bar\": true, 10: 10/20}, \
+ {\"bar\": true, 10: 10/20}: \"world\"}",
format!("{:?}", Bar));
assert_eq!(
-"Bar {
- \"foo\": Foo {
+"{
+ \"foo\": {
\"bar\": true,
10: 10/20
},
- Foo {
+ {
\"bar\": true,
10: 10/20
}: \"world\"
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.debug_set("Foo").finish()
+ fmt.debug_set().finish()
}
}
- assert_eq!("Foo {}", format!("{:?}", Foo));
- assert_eq!("Foo {}", format!("{:#?}", Foo));
+ assert_eq!("{}", format!("{:?}", Foo));
+ assert_eq!("{}", format!("{:#?}", Foo));
}
#[test]
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.debug_set("Foo")
+ fmt.debug_set()
.entry(&true)
.finish()
}
}
- assert_eq!("Foo { true }", format!("{:?}", Foo));
+ assert_eq!("{true}", format!("{:?}", Foo));
assert_eq!(
-"Foo {
+"{
true
}",
format!("{:#?}", Foo));
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.debug_set("Foo")
+ fmt.debug_set()
.entry(&true)
.entry(&format_args!("{}/{}", 10i32, 20i32))
.finish()
}
}
- assert_eq!("Foo { true, 10/20 }", format!("{:?}", Foo));
+ assert_eq!("{true, 10/20}", format!("{:?}", Foo));
assert_eq!(
-"Foo {
+"{
true,
10/20
}",
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.debug_set("Foo")
+ fmt.debug_set()
.entry(&true)
.entry(&format_args!("{}/{}", 10i32, 20i32))
.finish()
impl fmt::Debug for Bar {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.debug_set("Bar")
+ fmt.debug_set()
.entry(&Foo)
.entry(&"world")
.finish()
}
}
- assert_eq!("Bar { Foo { true, 10/20 }, \"world\" }",
+ assert_eq!("{{true, 10/20}, \"world\"}",
format!("{:?}", Bar));
assert_eq!(
-"Bar {
- Foo {
+"{
+ {
true,
10/20
},
format!("{:#?}", Bar));
}
}
+
+mod debug_list {
+ use std::fmt;
+
+ #[test]
+ fn test_empty() {
+ struct Foo;
+
+ impl fmt::Debug for Foo {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ fmt.debug_list().finish()
+ }
+ }
+
+ assert_eq!("[]", format!("{:?}", Foo));
+ assert_eq!("[]", format!("{:#?}", Foo));
+ }
+
+ #[test]
+ fn test_single() {
+ struct Foo;
+
+ impl fmt::Debug for Foo {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ fmt.debug_list()
+ .entry(&true)
+ .finish()
+ }
+ }
+
+ assert_eq!("[true]", format!("{:?}", Foo));
+ assert_eq!(
+"[
+ true
+]",
+ format!("{:#?}", Foo));
+ }
+
+ #[test]
+ fn test_multiple() {
+ struct Foo;
+
+ impl fmt::Debug for Foo {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ fmt.debug_list()
+ .entry(&true)
+ .entry(&format_args!("{}/{}", 10i32, 20i32))
+ .finish()
+ }
+ }
+
+ assert_eq!("[true, 10/20]", format!("{:?}", Foo));
+ assert_eq!(
+"[
+ true,
+ 10/20
+]",
+ format!("{:#?}", Foo));
+ }
+
+ #[test]
+ fn test_nested() {
+ struct Foo;
+
+ impl fmt::Debug for Foo {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ fmt.debug_list()
+ .entry(&true)
+ .entry(&format_args!("{}/{}", 10i32, 20i32))
+ .finish()
+ }
+ }
+
+ struct Bar;
+
+ impl fmt::Debug for Bar {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ fmt.debug_list()
+ .entry(&Foo)
+ .entry(&"world")
+ .finish()
+ }
+ }
+
+ assert_eq!("[[true, 10/20], \"world\"]",
+ format!("{:?}", Bar));
+ assert_eq!(
+"[
+ [
+ true,
+ 10/20
+ ],
+ \"world\"
+]",
+ format!("{:#?}", Bar));
+ }
+}
use std::collections::HashSet;
use syntax::ast;
use syntax::ast_util::local_def;
-use syntax::attr;
use syntax::codemap::Span;
use syntax::parse::token::{self, special_idents};
use syntax::visit;
&fcx.inh.param_env.free_substs,
&trait_ref);
- // There are special rules that apply to drop.
- if
- fcx.tcx().lang_items.drop_trait() == Some(trait_ref.def_id) &&
- !attr::contains_name(&item.attrs, "unsafe_destructor")
- {
- match self_ty.sty {
- ty::ty_struct(def_id, _) |
- ty::ty_enum(def_id, _) => {
- check_struct_safe_for_destructor(fcx, item.span, def_id);
- }
- _ => {
- // Coherence already reports an error in this case.
- }
- }
- }
-
if fcx.tcx().lang_items.copy_trait() == Some(trait_ref.def_id) {
// This is checked in coherence.
return
}
result
}
-
-///////////////////////////////////////////////////////////////////////////
-// Special drop trait checking
-
-fn check_struct_safe_for_destructor<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
- span: Span,
- struct_did: ast::DefId) {
- let struct_tpt = ty::lookup_item_type(fcx.tcx(), struct_did);
- if struct_tpt.generics.has_type_params(subst::TypeSpace)
- || struct_tpt.generics.has_region_params(subst::TypeSpace)
- {
- span_err!(fcx.tcx().sess, span, E0141,
- "cannot implement a destructor on a structure \
- with type parameters");
- span_note!(fcx.tcx().sess, span,
- "use \"#[unsafe_destructor]\" on the implementation \
- to force the compiler to allow this");
- }
-}
use default::Default;
use fmt::{self, Debug};
use hash::{Hash, SipHasher};
-use iter::{self, Iterator, ExactSizeIterator, IntoIterator, IteratorExt, FromIterator, Extend, Map};
+use iter::{self, Iterator, ExactSizeIterator, IntoIterator, FromIterator, Extend, Map};
use marker::Sized;
use mem::{self, replace};
use ops::{Deref, FnMut, FnOnce, Index};
where K: Eq + Hash + Debug, V: Debug, S: HashState
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- try!(write!(f, "{{"));
-
- for (i, (k, v)) in self.iter().enumerate() {
- if i != 0 { try!(write!(f, ", ")); }
- try!(write!(f, "{:?}: {:?}", *k, *v));
- }
-
- write!(f, "}}")
+ self.iter().fold(f.debug_map(), |b, (k, v)| b.entry(k, v)).finish()
}
}
use fmt::Debug;
use fmt;
use hash::Hash;
-use iter::{
- Iterator, IntoIterator, ExactSizeIterator, IteratorExt, FromIterator, Map, Chain, Extend,
-};
+use iter::{Iterator, IntoIterator, ExactSizeIterator, FromIterator, Map, Chain, Extend};
use ops::{BitOr, BitAnd, BitXor, Sub};
use option::Option::{Some, None, self};
S: HashState
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- try!(write!(f, "{{"));
-
- for (i, x) in self.iter().enumerate() {
- if i != 0 { try!(write!(f, ", ")); }
- try!(write!(f, "{:?}", *x));
- }
-
- write!(f, "}}")
+ self.iter().fold(f.debug_set(), |b, e| b.entry(e)).finish()
}
}
use clone::Clone;
use cmp;
use hash::{Hash, Hasher};
-use iter::{Iterator, IteratorExt, ExactSizeIterator, count};
+use iter::{Iterator, ExactSizeIterator, count};
use marker::{Copy, Send, Sync, Sized, self};
use mem::{min_align_of, size_of};
use mem;
#[cfg(target_os = "windows")]
mod dl {
use ffi::OsStr;
- use iter::IteratorExt;
+ use iter::Iterator;
use libc;
use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED;
use ops::FnOnce;
use error::{Error, FromError};
use fmt;
use io;
-use iter::IteratorExt;
+use iter::Iterator;
use libc;
use mem;
#[allow(deprecated)]
use unicode::str as core_str;
use error as std_error;
use fmt;
-use iter::{self, Iterator, IteratorExt, Extend};
+use iter::{self, Iterator, Extend};
use marker::Sized;
use ops::{Drop, FnOnce};
use option::Option::{self, Some, None};
#![feature(into_cow)]
#![feature(slice_patterns)]
#![feature(std_misc)]
+#![feature(debug_builders)]
#![cfg_attr(test, feature(test, rustc_private, std_misc))]
// Don't link to std. We are std.
use cmp;
use fmt;
use old_io::{Reader, Writer, Stream, Buffer, DEFAULT_BUF_SIZE, IoResult};
-use iter::{IteratorExt, ExactSizeIterator, repeat};
+use iter::{Iterator, ExactSizeIterator, repeat};
use ops::Drop;
use option::Option;
use option::Option::{Some, None};
extern crate test as test_crate;
use old_io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek, Buffer};
use prelude::v1::{Ok, Err, Vec, AsSlice};
- use prelude::v1::IteratorExt;
+ use prelude::v1::Iterator;
use old_io;
use iter::repeat;
use self::test_crate::Bencher;
use error::Error;
use fmt;
use isize;
-use iter::{Iterator, IteratorExt};
+use iter::Iterator;
use marker::{PhantomFn, Sized};
use mem::transmute;
use ops::FnOnce;
pub use self::Flag::*;
pub use self::Protocol::*;
-use iter::IteratorExt;
+use iter::Iterator;
use old_io::IoResult;
use old_io::net::ip::{SocketAddr, IpAddr};
use option::Option;
use fmt;
use old_io::{self, IoResult, IoError};
use old_io::net;
-use iter::{Iterator, IteratorExt};
+use iter::Iterator;
use ops::{FnOnce, FnMut};
use option::Option;
use option::Option::{None, Some};
#![allow(deprecated)] // rand
use env;
-use iter::IteratorExt;
+use iter::Iterator;
use old_io::{fs, IoError, IoErrorKind, IoResult};
use old_io;
use ops::Drop;
use ffi::CString;
use clone::Clone;
use fmt;
-use iter::IteratorExt;
+use iter::Iterator;
use option::Option;
use option::Option::{None, Some};
use str;
use hash;
use old_io::Writer;
use iter::{AdditiveIterator, Extend};
-use iter::{Iterator, IteratorExt, Map};
+use iter::{Iterator, Map};
use marker::Sized;
use option::Option::{self, Some, None};
use result::Result::{self, Ok, Err};
use super::*;
use clone::Clone;
- use iter::IteratorExt;
use option::Option::{self, Some, None};
use old_path::GenericPath;
use slice::AsSlice;
use str::{self, Str};
use string::ToString;
use vec::Vec;
+ use iter::Iterator;
macro_rules! t {
(s: $path:expr, $exp:expr) => (
use hash;
use old_io::Writer;
use iter::{AdditiveIterator, Extend};
-use iter::{Iterator, IteratorExt, Map, repeat};
+use iter::{Iterator, Map, repeat};
use mem;
use option::Option::{self, Some, None};
use result::Result::{self, Ok, Err};
use super::*;
use clone::Clone;
- use iter::IteratorExt;
+ use iter::Iterator;
use option::Option::{self, Some, None};
use old_path::GenericPath;
use slice::AsSlice;
use error::{FromError, Error};
use ffi::{OsString, OsStr};
use fmt;
-use iter::{Iterator, IteratorExt};
+use iter::Iterator;
use libc::{c_void, c_int, c_char};
use libc;
use marker::{Copy, Send};
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use iter::ExactSizeIterator;
#[stable(feature = "rust1", since = "1.0.0")]
-#[doc(no_inline)] pub use iter::{Iterator, IteratorExt, Extend};
+#[doc(no_inline)] pub use iter::{Iterator, Extend};
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use option::Option::{self, Some, None};
#[stable(feature = "rust1", since = "1.0.0")]
use cell::RefCell;
use clone::Clone;
use old_io::IoResult;
-use iter::{Iterator, IteratorExt};
+use iter::Iterator;
use mem;
use rc::Rc;
use result::Result::{Ok, Err};
try!(writeln!(w, "stack backtrace:"));
// 100 lines should be enough
- const SIZE: uint = 100;
+ const SIZE: usize = 100;
let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()};
- let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as uint};
+ let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as usize};
// skipping the first one as it is write itself
let iter = (1..cnt).map(|i| {
let info = objc_msgSend(klass, process_info_sel);
let args = objc_msgSend(info, arguments_sel);
- let cnt: int = mem::transmute(objc_msgSend(args, count_sel));
+ let cnt: usize = mem::transmute(objc_msgSend(args, count_sel));
for i in (0..cnt) {
let tmp = objc_msgSend(args, object_at_sel, i);
let utf_c_str: *const libc::c_char =
use env::split_paths;
use mem;
- use iter::IteratorExt;
+ use iter::Iterator;
// To have the spawning semantics of unix/windows stay the same, we need to
// read the *child's* PATH if one is provided. See #15149 for more details.
("log_syntax", "1.0.0", Active),
("trace_macros", "1.0.0", Active),
("concat_idents", "1.0.0", Active),
- ("unsafe_destructor", "1.0.0", Active),
("intrinsics", "1.0.0", Active),
("lang_items", "1.0.0", Active),
("start", "1.0.0", Active),
("main", "1.0.0", Active),
+ // Deprecate after snapshot
+ // SNAP a923278
+ ("unsafe_destructor", "1.0.0", Active),
+
// A temporary feature gate used to enable parser extensions needed
// to bootstrap fix for #5723.
("issue_5723_bootstrap", "1.0.0", Accepted),
("repr", Normal),
("path", Normal),
("abi", Normal),
- ("unsafe_destructor", Normal),
("automatically_derived", Normal),
("no_mangle", Normal),
("no_link", Normal),
("link_args", Normal),
("macro_escape", Normal),
-
+ ("unsafe_destructor", Gated("unsafe_destructor",
+ "`#[unsafe_destructor]` does nothing anymore")),
("staged_api", Gated("staged_api",
"staged_api is for use by rustc only")),
("plugin", Gated("plugin",
_ => {}
}
- if attr::contains_name(&i.attrs,
- "unsafe_destructor") {
- self.gate_feature("unsafe_destructor",
- i.span,
- "`#[unsafe_destructor]` allows too \
- many unsafe patterns and may be \
- removed in the future");
- }
-
if attr::contains_name(&i.attrs[..],
"old_orphan_check") {
self.gate_feature(
// Test that `#[unsafe_destructor]` attribute is gated by `unsafe_destructor`
// feature gate.
+//
+// (This test can be removed entirely when we remove the
+// `unsafe_destructor` feature itself.)
struct D<'a>(&'a u32);
#[unsafe_destructor]
+//~^ ERROR `#[unsafe_destructor]` does nothing anymore
+//~| HELP: add #![feature(unsafe_destructor)] to the crate attributes to enable
+// (but of couse there is no point in doing so)
impl<'a> Drop for D<'a> {
- //~^ ERROR `#[unsafe_destructor]` allows too many unsafe patterns
fn drop(&mut self) { }
}
-//~^ HELP: add #![feature(unsafe_destructor)] to the crate attributes to enable
pub fn main() { }
+++ /dev/null
-// 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.
-
-#![crate_type = "lib"]
-
-use std::marker::PhantomData;
-
-enum NodeContents<'a> {
- Children(Vec<Node<'a>>),
-}
-
-impl<'a> Drop for NodeContents<'a> {
- //~^ ERROR cannot implement a destructor on a structure with type parameters
- fn drop( &mut self ) {
- }
-}
-
-struct Node<'a> {
- contents: NodeContents<'a>,
- marker: PhantomData<&'a ()>,
-}
-
-impl<'a> Node<'a> {
- fn noName(contents: NodeContents<'a>) -> Node<'a> {
- Node { contents: contents, marker: PhantomData }
- }
-}
-
-fn main() {}
+++ /dev/null
-// 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.
-
-struct AutoBuilder<'a> {
- context: &'a isize
-}
-
-impl<'a> Drop for AutoBuilder<'a> {
- //~^ ERROR cannot implement a destructor on a structure with type parameters
- fn drop(&mut self) {
- }
-}
-
-fn main() {}
+++ /dev/null
-// 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.
-
-// Used to cause an ICE
-
-struct Foo<T>{
- x : T
-}
-
-type FooInt = Foo<isize>;
-
-impl Drop for FooInt {
-//~^ ERROR cannot implement a destructor on a structure with type parameters
- fn drop(&mut self){}
-}
-
-fn main() {}
+++ /dev/null
-// 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.
-
-
-struct Bar<'a> {
- f: &'a isize,
-}
-
-impl<'a> Drop for Bar<'a> {
-//~^ ERROR E0141
- fn drop(&mut self) {
- }
-}
-
-struct Baz {
- f: &'static isize,
-}
-
-impl Drop for Baz {
- fn drop(&mut self) {
- }
-}
-
-fn main() { }
+++ /dev/null
-// 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.
-
-
-
-// Regression test for issue #15557
-
-#![allow(dead_code)]
-struct AReg1<'a>(&'a u32);
-
-impl<'a> Drop for AReg1<'a> {
-//~^ ERROR: cannot implement a destructor on a structure with type parameters
- fn drop(&mut self) {}
-}
-
-fn main() {}