auto merge of #17339 : treeman/rust/doc-things, r=alexcrichton
Also some cleanup to conform to documentation style.
This commit is contained in:
commit
8a458181dd
10 changed files with 633 additions and 245 deletions
|
@ -138,10 +138,10 @@ pub struct RadixFmt<T, R>(T, R);
|
|||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// use std::fmt::radix;
|
||||
/// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
|
||||
/// ~~~
|
||||
/// ```
|
||||
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
|
||||
RadixFmt(x, Radix::new(base))
|
||||
}
|
||||
|
|
|
@ -61,10 +61,10 @@ pub trait Zero: Add<Self, Self> {
|
|||
///
|
||||
/// # Laws
|
||||
///
|
||||
/// ~~~text
|
||||
/// ```{.text}
|
||||
/// a + 0 = a ∀ a ∈ Self
|
||||
/// 0 + a = a ∀ a ∈ Self
|
||||
/// ~~~
|
||||
/// ```
|
||||
///
|
||||
/// # Purity
|
||||
///
|
||||
|
@ -114,10 +114,10 @@ pub trait One: Mul<Self, Self> {
|
|||
///
|
||||
/// # Laws
|
||||
///
|
||||
/// ~~~text
|
||||
/// ```{.text}
|
||||
/// a * 1 = a ∀ a ∈ Self
|
||||
/// 1 * a = a ∀ a ∈ Self
|
||||
/// ~~~
|
||||
/// ```
|
||||
///
|
||||
/// # Purity
|
||||
///
|
||||
|
|
|
@ -175,6 +175,16 @@ impl<T> Option<T> {
|
|||
/////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Returns `true` if the option is a `Some` value
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x: Option<uint> = Some(2);
|
||||
/// assert_eq!(x.is_some(), true);
|
||||
///
|
||||
/// let x: Option<uint> = None;
|
||||
/// assert_eq!(x.is_some(), false);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn is_some(&self) -> bool {
|
||||
|
@ -185,6 +195,16 @@ impl<T> Option<T> {
|
|||
}
|
||||
|
||||
/// Returns `true` if the option is a `None` value
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x: Option<uint> = Some(2);
|
||||
/// assert_eq!(x.is_none(), false);
|
||||
///
|
||||
/// let x: Option<uint> = None;
|
||||
/// assert_eq!(x.is_none(), true);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn is_none(&self) -> bool {
|
||||
|
@ -218,6 +238,17 @@ impl<T> Option<T> {
|
|||
}
|
||||
|
||||
/// Convert from `Option<T>` to `Option<&mut T>`
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let mut x = Some(2u);
|
||||
/// match x.as_mut() {
|
||||
/// Some(&ref mut v) => *v = 42,
|
||||
/// None => {},
|
||||
/// }
|
||||
/// assert_eq!(x, Some(42u));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for mut conventions"]
|
||||
pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> {
|
||||
|
@ -225,6 +256,19 @@ impl<T> Option<T> {
|
|||
}
|
||||
|
||||
/// Convert from `Option<T>` to `&mut [T]` (without copying)
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let mut x = Some("Diamonds");
|
||||
/// {
|
||||
/// let v = x.as_mut_slice();
|
||||
/// assert!(v == ["Diamonds"]);
|
||||
/// v[0] = "Dirt";
|
||||
/// assert!(v == ["Dirt"]);
|
||||
/// }
|
||||
/// assert_eq!(x, Some("Dirt"));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for mut conventions"]
|
||||
pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
|
||||
|
@ -250,6 +294,18 @@ impl<T> Option<T> {
|
|||
///
|
||||
/// Fails if the value is a `None` with a custom failure message provided by
|
||||
/// `msg`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x = Some("value");
|
||||
/// assert_eq!(x.expect("the world is ending"), "value");
|
||||
/// ```
|
||||
///
|
||||
/// ```{.should_fail}
|
||||
/// let x: Option<&str> = None;
|
||||
/// x.expect("the world is ending"); // fails with `world is ending`
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for conventions"]
|
||||
pub fn expect(self, msg: &str) -> T {
|
||||
|
@ -270,6 +326,18 @@ impl<T> Option<T> {
|
|||
/// In general, because this function may fail, its use is discouraged.
|
||||
/// Instead, prefer to use pattern matching and handle the `None`
|
||||
/// case explicitly.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x = Some("air");
|
||||
/// assert_eq!(x.unwrap(), "air");
|
||||
/// ```
|
||||
///
|
||||
/// ```{.should_fail}
|
||||
/// let x: Option<&str> = None;
|
||||
/// assert_eq!(x.unwrap(), "air"); // fails
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for conventions"]
|
||||
pub fn unwrap(self) -> T {
|
||||
|
@ -280,6 +348,13 @@ impl<T> Option<T> {
|
|||
}
|
||||
|
||||
/// Returns the contained value or a default.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// assert_eq!(Some("car").unwrap_or("bike"), "car");
|
||||
/// assert_eq!(None.unwrap_or("bike"), "bike");
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for conventions"]
|
||||
pub fn unwrap_or(self, def: T) -> T {
|
||||
|
@ -290,6 +365,14 @@ impl<T> Option<T> {
|
|||
}
|
||||
|
||||
/// Returns the contained value or computes it from a closure.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let k = 10u;
|
||||
/// assert_eq!(Some(4u).unwrap_or_else(|| 2 * k), 4u);
|
||||
/// assert_eq!(None.unwrap_or_else(|| 2 * k), 20u);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for conventions"]
|
||||
pub fn unwrap_or_else(self, f: || -> T) -> T {
|
||||
|
@ -321,6 +404,16 @@ impl<T> Option<T> {
|
|||
}
|
||||
|
||||
/// Applies a function to the contained value or returns a default.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x = Some("foo");
|
||||
/// assert_eq!(x.map_or(42u, |v| v.len()), 3u);
|
||||
///
|
||||
/// let x: Option<&str> = None;
|
||||
/// assert_eq!(x.map_or(42u, |v| v.len()), 42u);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for unboxed closures"]
|
||||
pub fn map_or<U>(self, def: U, f: |T| -> U) -> U {
|
||||
|
@ -328,6 +421,18 @@ impl<T> Option<T> {
|
|||
}
|
||||
|
||||
/// Applies a function to the contained value or computes a default.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let k = 21u;
|
||||
///
|
||||
/// let x = Some("foo");
|
||||
/// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3u);
|
||||
///
|
||||
/// let x: Option<&str> = None;
|
||||
/// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42u);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for unboxed closures"]
|
||||
pub fn map_or_else<U>(self, def: || -> U, f: |T| -> U) -> U {
|
||||
|
@ -366,6 +471,16 @@ impl<T> Option<T> {
|
|||
/////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Returns an iterator over the possibly contained value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x = Some(4u);
|
||||
/// assert_eq!(x.iter().next(), Some(&4));
|
||||
///
|
||||
/// let x: Option<uint> = None;
|
||||
/// assert_eq!(x.iter().next(), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for iterator conventions"]
|
||||
pub fn iter<'r>(&'r self) -> Item<&'r T> {
|
||||
|
@ -379,6 +494,20 @@ impl<T> Option<T> {
|
|||
}
|
||||
|
||||
/// Returns a mutable iterator over the possibly contained value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let mut x = Some(4u);
|
||||
/// match x.iter_mut().next() {
|
||||
/// Some(&ref mut v) => *v = 42u,
|
||||
/// None => {},
|
||||
/// }
|
||||
/// assert_eq!(x, Some(42));
|
||||
///
|
||||
/// let mut x: Option<uint> = None;
|
||||
/// assert_eq!(x.iter_mut().next(), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for iterator conventions"]
|
||||
pub fn iter_mut<'r>(&'r mut self) -> Item<&'r mut T> {
|
||||
|
@ -392,6 +521,18 @@ impl<T> Option<T> {
|
|||
}
|
||||
|
||||
/// Returns a consuming iterator over the possibly contained value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x = Some("string");
|
||||
/// let v: Vec<&str> = x.into_iter().collect();
|
||||
/// assert_eq!(v, vec!["string"]);
|
||||
///
|
||||
/// let x = None;
|
||||
/// let v: Vec<&str> = x.into_iter().collect();
|
||||
/// assert_eq!(v, vec![]);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for iterator conventions"]
|
||||
pub fn into_iter(self) -> Item<T> {
|
||||
|
@ -403,6 +544,26 @@ impl<T> Option<T> {
|
|||
/////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Returns `None` if the option is `None`, otherwise returns `optb`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x = Some(2u);
|
||||
/// let y: Option<&str> = None;
|
||||
/// assert_eq!(x.and(y), None);
|
||||
///
|
||||
/// let x: Option<uint> = None;
|
||||
/// let y = Some("foo");
|
||||
/// assert_eq!(x.and(y), None);
|
||||
///
|
||||
/// let x = Some(2u);
|
||||
/// let y = Some("foo");
|
||||
/// assert_eq!(x.and(y), Some("foo"));
|
||||
///
|
||||
/// let x: Option<uint> = None;
|
||||
/// let y: Option<&str> = None;
|
||||
/// assert_eq!(x.and(y), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn and<U>(self, optb: Option<U>) -> Option<U> {
|
||||
|
@ -414,6 +575,18 @@ impl<T> Option<T> {
|
|||
|
||||
/// Returns `None` if the option is `None`, otherwise calls `f` with the
|
||||
/// wrapped value and returns the result.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// fn sq(x: uint) -> Option<uint> { Some(x * x) }
|
||||
/// fn nope(_: uint) -> Option<uint> { None }
|
||||
///
|
||||
/// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
|
||||
/// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
|
||||
/// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
|
||||
/// assert_eq!(None.and_then(sq).and_then(sq), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for unboxed closures"]
|
||||
pub fn and_then<U>(self, f: |T| -> Option<U>) -> Option<U> {
|
||||
|
@ -424,6 +597,26 @@ impl<T> Option<T> {
|
|||
}
|
||||
|
||||
/// Returns the option if it contains a value, otherwise returns `optb`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x = Some(2u);
|
||||
/// let y = None;
|
||||
/// assert_eq!(x.or(y), Some(2u));
|
||||
///
|
||||
/// let x = None;
|
||||
/// let y = Some(100u);
|
||||
/// assert_eq!(x.or(y), Some(100u));
|
||||
///
|
||||
/// let x = Some(2u);
|
||||
/// let y = Some(100u);
|
||||
/// assert_eq!(x.or(y), Some(2u));
|
||||
///
|
||||
/// let x: Option<uint> = None;
|
||||
/// let y = None;
|
||||
/// assert_eq!(x.or(y), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn or(self, optb: Option<T>) -> Option<T> {
|
||||
|
@ -435,6 +628,17 @@ impl<T> Option<T> {
|
|||
|
||||
/// Returns the option if it contains a value, otherwise calls `f` and
|
||||
/// returns the result.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// fn nobody() -> Option<&'static str> { None }
|
||||
/// fn vikings() -> Option<&'static str> { Some("vikings") }
|
||||
///
|
||||
/// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
|
||||
/// assert_eq!(None.or_else(vikings), Some("vikings"));
|
||||
/// assert_eq!(None.or_else(nobody), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for unboxed closures"]
|
||||
pub fn or_else(self, f: || -> Option<T>) -> Option<T> {
|
||||
|
@ -449,6 +653,18 @@ impl<T> Option<T> {
|
|||
/////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Takes the value out of the option, leaving a `None` in its place.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let mut x = Some(2u);
|
||||
/// x.take();
|
||||
/// assert_eq!(x, None);
|
||||
///
|
||||
/// let mut x: Option<uint> = None;
|
||||
/// x.take();
|
||||
/// assert_eq!(x, None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn take(&mut self) -> Option<T> {
|
||||
|
@ -613,7 +829,7 @@ impl<T> Default for Option<T> {
|
|||
|
||||
/// An `Option` iterator that yields either one or zero elements
|
||||
///
|
||||
/// The `Item` iterator is returned by the `iter`, `mut_iter` and `move_iter`
|
||||
/// The `Item` iterator is returned by the `iter`, `iter_mut` and `into_iter`
|
||||
/// methods on `Option`.
|
||||
#[deriving(Clone)]
|
||||
#[unstable = "waiting for iterator conventions"]
|
||||
|
|
|
@ -15,12 +15,12 @@
|
|||
//! success and containing a value, and `Err(E)`, representing error
|
||||
//! and containing an error value.
|
||||
//!
|
||||
//! ~~~
|
||||
//! ```
|
||||
//! enum Result<T, E> {
|
||||
//! Ok(T),
|
||||
//! Err(E)
|
||||
//! }
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! Functions return `Result` whenever errors are expected and
|
||||
//! recoverable. In the `std` crate `Result` is most prominently used
|
||||
|
@ -29,7 +29,7 @@
|
|||
//! A simple function returning `Result` might be
|
||||
//! defined and used like so:
|
||||
//!
|
||||
//! ~~~
|
||||
//! ```
|
||||
//! #[deriving(Show)]
|
||||
//! enum Version { Version1, Version2 }
|
||||
//!
|
||||
|
@ -53,13 +53,13 @@
|
|||
//! println!("error parsing header: {}", e);
|
||||
//! }
|
||||
//! }
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! Pattern matching on `Result`s is clear and straightforward for
|
||||
//! simple cases, but `Result` comes with some convenience methods
|
||||
//! that make working it more succinct.
|
||||
//!
|
||||
//! ~~~
|
||||
//! ```
|
||||
//! let good_result: Result<int, int> = Ok(10);
|
||||
//! let bad_result: Result<int, int> = Err(10);
|
||||
//!
|
||||
|
@ -79,7 +79,7 @@
|
|||
//!
|
||||
//! // Consume the result and return the contents with `unwrap`.
|
||||
//! let final_awesome_result = good_result.ok().unwrap();
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! # Results must be used
|
||||
//!
|
||||
|
@ -94,13 +94,13 @@
|
|||
//! Consider the `write_line` method defined for I/O types
|
||||
//! by the [`Writer`](../io/trait.Writer.html) trait:
|
||||
//!
|
||||
//! ~~~
|
||||
//! ```
|
||||
//! use std::io::IoError;
|
||||
//!
|
||||
//! trait Writer {
|
||||
//! fn write_line(&mut self, s: &str) -> Result<(), IoError>;
|
||||
//! }
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! *Note: The actual definition of `Writer` uses `IoResult`, which
|
||||
//! is just a synonym for `Result<T, IoError>`.*
|
||||
|
@ -109,7 +109,7 @@
|
|||
//! fail. It's crucial to handle the error case, and *not* write
|
||||
//! something like this:
|
||||
//!
|
||||
//! ~~~ignore
|
||||
//! ```{.ignore}
|
||||
//! use std::io::{File, Open, Write};
|
||||
//!
|
||||
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
|
||||
|
@ -117,7 +117,7 @@
|
|||
//! // value is ignored.
|
||||
//! file.write_line("important message");
|
||||
//! drop(file);
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! If you *do* write that in Rust, the compiler will by give you a
|
||||
//! warning (by default, controlled by the `unused_must_use` lint).
|
||||
|
@ -127,27 +127,27 @@
|
|||
//! success with `expect`. This will fail if the write fails, proving
|
||||
//! a marginally useful message indicating why:
|
||||
//!
|
||||
//! ~~~no_run
|
||||
//! ```{.no_run}
|
||||
//! use std::io::{File, Open, Write};
|
||||
//!
|
||||
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
|
||||
//! file.write_line("important message").ok().expect("failed to write message");
|
||||
//! drop(file);
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! You might also simply assert success:
|
||||
//!
|
||||
//! ~~~no_run
|
||||
//! ```{.no_run}
|
||||
//! # use std::io::{File, Open, Write};
|
||||
//!
|
||||
//! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
|
||||
//! assert!(file.write_line("important message").is_ok());
|
||||
//! # drop(file);
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! Or propagate the error up the call stack with `try!`:
|
||||
//!
|
||||
//! ~~~
|
||||
//! ```
|
||||
//! # use std::io::{File, Open, Write, IoError};
|
||||
//! fn write_message() -> Result<(), IoError> {
|
||||
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
|
||||
|
@ -155,7 +155,7 @@
|
|||
//! drop(file);
|
||||
//! return Ok(());
|
||||
//! }
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! # The `try!` macro
|
||||
//!
|
||||
|
@ -166,7 +166,7 @@
|
|||
//!
|
||||
//! It replaces this:
|
||||
//!
|
||||
//! ~~~
|
||||
//! ```
|
||||
//! use std::io::{File, Open, Write, IoError};
|
||||
//!
|
||||
//! struct Info {
|
||||
|
@ -188,11 +188,11 @@
|
|||
//! }
|
||||
//! return file.write_line(format!("rating: {}", info.rating).as_slice());
|
||||
//! }
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! With this:
|
||||
//!
|
||||
//! ~~~
|
||||
//! ```
|
||||
//! use std::io::{File, Open, Write, IoError};
|
||||
//!
|
||||
//! struct Info {
|
||||
|
@ -209,7 +209,7 @@
|
|||
//! try!(file.write_line(format!("rating: {}", info.rating).as_slice()));
|
||||
//! return Ok(());
|
||||
//! }
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! *It's much nicer!*
|
||||
//!
|
||||
|
@ -218,13 +218,13 @@
|
|||
//! `Err` is returned early from the enclosing function. Its simple definition
|
||||
//! makes it clear:
|
||||
//!
|
||||
//! ~~~
|
||||
//! ```
|
||||
//! # #![feature(macro_rules)]
|
||||
//! macro_rules! try(
|
||||
//! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
|
||||
//! )
|
||||
//! # fn main() { }
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! `try!` is imported by the prelude, and is available everywhere.
|
||||
//!
|
||||
|
@ -245,10 +245,10 @@
|
|||
//!
|
||||
//! Converting to an `Option` with `ok()` to handle an error:
|
||||
//!
|
||||
//! ~~~
|
||||
//! ```
|
||||
//! use std::io::Timer;
|
||||
//! let mut t = Timer::new().ok().expect("failed to create timer!");
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! # `Result` vs. `fail!`
|
||||
//!
|
||||
|
@ -311,14 +311,13 @@ impl<T, E> Result<T, E> {
|
|||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ~~~
|
||||
/// use std::io::{File, Open, Write};
|
||||
/// ```
|
||||
/// let x: Result<int, &str> = Ok(-3);
|
||||
/// assert_eq!(x.is_ok(), true);
|
||||
///
|
||||
/// # fn do_not_run_example() { // creates a file
|
||||
/// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
|
||||
/// assert!(file.write_line("it's cold in here").is_ok());
|
||||
/// # }
|
||||
/// ~~~
|
||||
/// let x: Result<int, &str> = Err("Some error message");
|
||||
/// assert_eq!(x.is_ok(), false);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn is_ok(&self) -> bool {
|
||||
|
@ -332,14 +331,13 @@ impl<T, E> Result<T, E> {
|
|||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ~~~
|
||||
/// use std::io::{File, Open, Read};
|
||||
/// ```
|
||||
/// let x: Result<int, &str> = Ok(-3);
|
||||
/// assert_eq!(x.is_err(), false);
|
||||
///
|
||||
/// // When opening with `Read` access, if the file does not exist
|
||||
/// // then `open_mode` returns an error.
|
||||
/// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
|
||||
/// assert!(bogus.is_err());
|
||||
/// ~~~
|
||||
/// let x: Result<int, &str> = Err("Some error message");
|
||||
/// assert_eq!(x.is_err(), true);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn is_err(&self) -> bool {
|
||||
|
@ -356,18 +354,15 @@ impl<T, E> Result<T, E> {
|
|||
/// Converts `self` into an `Option<T>`, consuming `self`,
|
||||
/// and discarding the error, if any.
|
||||
///
|
||||
/// To convert to an `Option` without discarding the error value,
|
||||
/// use `as_ref` to first convert the `Result<T, E>` into a
|
||||
/// `Result<&T, &E>`.
|
||||
/// # Example
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// let x: Result<uint, &str> = Ok(2);
|
||||
/// assert_eq!(x.ok(), Some(2));
|
||||
///
|
||||
/// ~~~{.should_fail}
|
||||
/// use std::io::{File, IoResult};
|
||||
///
|
||||
/// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
|
||||
/// let bdays: File = bdays.ok().expect("unable to open birthday file");
|
||||
/// ~~~
|
||||
/// let x: Result<uint, &str> = Err("Nothing here");
|
||||
/// assert_eq!(x.ok(), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn ok(self) -> Option<T> {
|
||||
|
@ -381,6 +376,16 @@ impl<T, E> Result<T, E> {
|
|||
///
|
||||
/// Converts `self` into an `Option<T>`, consuming `self`,
|
||||
/// and discarding the value, if any.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x: Result<uint, &str> = Ok(2);
|
||||
/// assert_eq!(x.err(), None);
|
||||
///
|
||||
/// let x: Result<uint, &str> = Err("Nothing here");
|
||||
/// assert_eq!(x.err(), Some("Nothing here"));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn err(self) -> Option<E> {
|
||||
|
@ -398,6 +403,14 @@ impl<T, E> Result<T, E> {
|
|||
///
|
||||
/// Produces a new `Result`, containing a reference
|
||||
/// into the original, leaving the original in place.
|
||||
///
|
||||
/// ```
|
||||
/// let x: Result<uint, &str> = Ok(2);
|
||||
/// assert_eq!(x.as_ref(), Ok(&2));
|
||||
///
|
||||
/// let x: Result<uint, &str> = Err("Error");
|
||||
/// assert_eq!(x.as_ref(), Err(&"Error"));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
|
||||
|
@ -408,6 +421,23 @@ impl<T, E> Result<T, E> {
|
|||
}
|
||||
|
||||
/// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
|
||||
///
|
||||
/// ```
|
||||
/// fn mutate(r: &mut Result<int, int>) {
|
||||
/// match r.as_mut() {
|
||||
/// Ok(&ref mut v) => *v = 42,
|
||||
/// Err(&ref mut e) => *e = 0,
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let mut x: Result<int, int> = Ok(2);
|
||||
/// mutate(&mut x);
|
||||
/// assert_eq!(x.unwrap(), 42);
|
||||
///
|
||||
/// let mut x: Result<int, int> = Err(13);
|
||||
/// mutate(&mut x);
|
||||
/// assert_eq!(x.unwrap_err(), 0);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for mut conventions"]
|
||||
pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
|
||||
|
@ -418,6 +448,20 @@ impl<T, E> Result<T, E> {
|
|||
}
|
||||
|
||||
/// Convert from `Result<T, E>` to `&mut [T]` (without copying)
|
||||
///
|
||||
/// ```
|
||||
/// let mut x: Result<&str, uint> = Ok("Gold");
|
||||
/// {
|
||||
/// let v = x.as_mut_slice();
|
||||
/// assert!(v == ["Gold"]);
|
||||
/// v[0] = "Silver";
|
||||
/// assert!(v == ["Silver"]);
|
||||
/// }
|
||||
/// assert_eq!(x, Ok("Silver"));
|
||||
///
|
||||
/// let mut x: Result<&str, uint> = Err(45);
|
||||
/// assert!(x.as_mut_slice() == []);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for mut conventions"]
|
||||
pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
|
||||
|
@ -440,12 +484,12 @@ impl<T, E> Result<T, E> {
|
|||
///
|
||||
/// This function can be used to compose the results of two functions.
|
||||
///
|
||||
/// # Examples
|
||||
/// # Example
|
||||
///
|
||||
/// Sum the lines of a buffer by mapping strings to numbers,
|
||||
/// ignoring I/O and parse errors:
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// use std::io::{BufReader, IoResult};
|
||||
///
|
||||
/// let buffer = "1\n2\n3\n4\n";
|
||||
|
@ -464,7 +508,7 @@ impl<T, E> Result<T, E> {
|
|||
/// }
|
||||
///
|
||||
/// assert!(sum == 10);
|
||||
/// ~~~
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for unboxed closures"]
|
||||
pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
|
||||
|
@ -479,6 +523,18 @@ impl<T, E> Result<T, E> {
|
|||
///
|
||||
/// This function can be used to pass through a successful result while handling
|
||||
/// an error.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// fn stringify(x: uint) -> String { format!("error code: {}", x) }
|
||||
///
|
||||
/// let x: Result<uint, uint> = Ok(2u);
|
||||
/// assert_eq!(x.map_err(stringify), Ok(2u));
|
||||
///
|
||||
/// let x: Result<uint, uint> = Err(13);
|
||||
/// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for unboxed closures"]
|
||||
pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
|
||||
|
@ -494,6 +550,16 @@ impl<T, E> Result<T, E> {
|
|||
/////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Returns an iterator over the possibly contained value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x: Result<uint, &str> = Ok(7);
|
||||
/// assert_eq!(x.iter().next(), Some(&7));
|
||||
///
|
||||
/// let x: Result<uint, &str> = Err("nothing!");
|
||||
/// assert_eq!(x.iter().next(), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for iterator conventions"]
|
||||
pub fn iter<'r>(&'r self) -> Item<&'r T> {
|
||||
|
@ -507,6 +573,20 @@ impl<T, E> Result<T, E> {
|
|||
}
|
||||
|
||||
/// Returns a mutable iterator over the possibly contained value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let mut x: Result<uint, &str> = Ok(7);
|
||||
/// match x.iter_mut().next() {
|
||||
/// Some(&ref mut x) => *x = 40,
|
||||
/// None => {},
|
||||
/// }
|
||||
/// assert_eq!(x, Ok(40));
|
||||
///
|
||||
/// let mut x: Result<uint, &str> = Err("nothing!");
|
||||
/// assert_eq!(x.iter_mut().next(), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for iterator conventions"]
|
||||
pub fn iter_mut<'r>(&'r mut self) -> Item<&'r mut T> {
|
||||
|
@ -520,6 +600,18 @@ impl<T, E> Result<T, E> {
|
|||
}
|
||||
|
||||
/// Returns a consuming iterator over the possibly contained value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x: Result<uint, &str> = Ok(5);
|
||||
/// let v: Vec<uint> = x.into_iter().collect();
|
||||
/// assert_eq!(v, vec![5u]);
|
||||
///
|
||||
/// let x: Result<uint, &str> = Err("nothing!");
|
||||
/// let v: Vec<uint> = x.into_iter().collect();
|
||||
/// assert_eq!(v, vec![]);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for iterator conventions"]
|
||||
pub fn into_iter(self) -> Item<T> {
|
||||
|
@ -531,6 +623,26 @@ impl<T, E> Result<T, E> {
|
|||
/////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x: Result<uint, &str> = Ok(2);
|
||||
/// let y: Result<&str, &str> = Err("late error");
|
||||
/// assert_eq!(x.and(y), Err("late error"));
|
||||
///
|
||||
/// let x: Result<uint, &str> = Err("early error");
|
||||
/// let y: Result<&str, &str> = Ok("foo");
|
||||
/// assert_eq!(x.and(y), Err("early error"));
|
||||
///
|
||||
/// let x: Result<uint, &str> = Err("not a 2");
|
||||
/// let y: Result<&str, &str> = Err("late error");
|
||||
/// assert_eq!(x.and(y), Err("not a 2"));
|
||||
///
|
||||
/// let x: Result<uint, &str> = Ok(2);
|
||||
/// let y: Result<&str, &str> = Ok("different result type");
|
||||
/// assert_eq!(x.and(y), Ok("different result type"));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
|
||||
|
@ -542,7 +654,19 @@ impl<T, E> Result<T, E> {
|
|||
|
||||
/// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
|
||||
///
|
||||
/// This function can be used for control flow based on result values
|
||||
/// This function can be used for control flow based on result values.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// fn sq(x: uint) -> Result<uint, uint> { Ok(x * x) }
|
||||
/// fn err(x: uint) -> Result<uint, uint> { Err(x) }
|
||||
///
|
||||
/// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
|
||||
/// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
|
||||
/// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
|
||||
/// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for unboxed closures"]
|
||||
pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
|
||||
|
@ -553,6 +677,26 @@ impl<T, E> Result<T, E> {
|
|||
}
|
||||
|
||||
/// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x: Result<uint, &str> = Ok(2);
|
||||
/// let y: Result<uint, &str> = Err("late error");
|
||||
/// assert_eq!(x.or(y), Ok(2));
|
||||
///
|
||||
/// let x: Result<uint, &str> = Err("early error");
|
||||
/// let y: Result<uint, &str> = Ok(2);
|
||||
/// assert_eq!(x.or(y), Ok(2));
|
||||
///
|
||||
/// let x: Result<uint, &str> = Err("not a 2");
|
||||
/// let y: Result<uint, &str> = Err("late error");
|
||||
/// assert_eq!(x.or(y), Err("late error"));
|
||||
///
|
||||
/// let x: Result<uint, &str> = Ok(2);
|
||||
/// let y: Result<uint, &str> = Ok(100);
|
||||
/// assert_eq!(x.or(y), Ok(2));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable]
|
||||
pub fn or(self, res: Result<T, E>) -> Result<T, E> {
|
||||
|
@ -564,7 +708,19 @@ impl<T, E> Result<T, E> {
|
|||
|
||||
/// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
|
||||
///
|
||||
/// This function can be used for control flow based on result values
|
||||
/// This function can be used for control flow based on result values.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// fn sq(x: uint) -> Result<uint, uint> { Ok(x * x) }
|
||||
/// fn err(x: uint) -> Result<uint, uint> { Err(x) }
|
||||
///
|
||||
/// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
|
||||
/// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
|
||||
/// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
|
||||
/// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for unboxed closures"]
|
||||
pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
|
||||
|
@ -576,6 +732,17 @@ impl<T, E> Result<T, E> {
|
|||
|
||||
/// Unwraps a result, yielding the content of an `Ok`.
|
||||
/// Else it returns `optb`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let optb = 2u;
|
||||
/// let x: Result<uint, &str> = Ok(9u);
|
||||
/// assert_eq!(x.unwrap_or(optb), 9u);
|
||||
///
|
||||
/// let x: Result<uint, &str> = Err("error");
|
||||
/// assert_eq!(x.unwrap_or(optb), optb);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for conventions"]
|
||||
pub fn unwrap_or(self, optb: T) -> T {
|
||||
|
@ -587,6 +754,15 @@ impl<T, E> Result<T, E> {
|
|||
|
||||
/// Unwraps a result, yielding the content of an `Ok`.
|
||||
/// If the value is an `Err` then it calls `op` with its value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// fn count(x: &str) -> uint { x.len() }
|
||||
///
|
||||
/// assert_eq!(Ok(2u).unwrap_or_else(count), 2u);
|
||||
/// assert_eq!(Err("foo").unwrap_or_else(count), 3u);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for conventions"]
|
||||
pub fn unwrap_or_else(self, op: |E| -> T) -> T {
|
||||
|
@ -611,6 +787,18 @@ impl<T, E: Show> Result<T, E> {
|
|||
///
|
||||
/// Fails if the value is an `Err`, with a custom failure message provided
|
||||
/// by the `Err`'s value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// let x: Result<uint, &str> = Ok(2u);
|
||||
/// assert_eq!(x.unwrap(), 2u);
|
||||
/// ```
|
||||
///
|
||||
/// ```{.should_fail}
|
||||
/// let x: Result<uint, &str> = Err("emergency failure");
|
||||
/// x.unwrap(); // fails with `emergency failure`
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for conventions"]
|
||||
pub fn unwrap(self) -> T {
|
||||
|
@ -629,6 +817,18 @@ impl<T: Show, E> Result<T, E> {
|
|||
///
|
||||
/// Fails if the value is an `Ok`, with a custom failure message provided
|
||||
/// by the `Ok`'s value.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```{.should_fail}
|
||||
/// let x: Result<uint, &str> = Ok(2u);
|
||||
/// x.unwrap_err(); // fails with `2`
|
||||
/// ```
|
||||
///
|
||||
/// ```
|
||||
/// let x: Result<uint, &str> = Err("emergency failure");
|
||||
/// assert_eq!(x.unwrap_err(), "emergency failure");
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable = "waiting for conventions"]
|
||||
pub fn unwrap_err(self) -> E {
|
||||
|
@ -666,7 +866,7 @@ impl<T, E> Slice<T> for Result<T, E> {
|
|||
|
||||
/// A `Result` iterator that yields either one or zero elements
|
||||
///
|
||||
/// The `Item` iterator is returned by the `iter`, `mut_iter` and `move_iter`
|
||||
/// The `Item` iterator is returned by the `iter`, `iter_mut` and `into_iter`
|
||||
/// methods on `Result`.
|
||||
#[deriving(Clone)]
|
||||
#[unstable = "waiting for iterator conventions"]
|
||||
|
|
|
@ -31,7 +31,7 @@
|
|||
//! that requires an input file to be specified, accepts an optional output
|
||||
//! file name following `-o`, and accepts both `-h` and `--help` as optional flags.
|
||||
//!
|
||||
//! ~~~{.rust}
|
||||
//! ```{.rust}
|
||||
//! extern crate getopts;
|
||||
//! use getopts::{optopt,optflag,getopts,OptGroup};
|
||||
//! use std::os;
|
||||
|
@ -76,7 +76,7 @@
|
|||
//! };
|
||||
//! do_work(input.as_slice(), output);
|
||||
//! }
|
||||
//! ~~~
|
||||
//! ```
|
||||
|
||||
#![crate_name = "getopts"]
|
||||
#![experimental]
|
||||
|
|
|
@ -17,7 +17,7 @@ pub trait Integer: Num + PartialOrd
|
|||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// # use num::Integer;
|
||||
/// assert!(( 8i).div_floor(& 3) == 2);
|
||||
/// assert!(( 8i).div_floor(&-3) == -3);
|
||||
|
@ -28,20 +28,20 @@ pub trait Integer: Num + PartialOrd
|
|||
/// assert!(( 1i).div_floor(&-2) == -1);
|
||||
/// assert!((-1i).div_floor(& 2) == -1);
|
||||
/// assert!((-1i).div_floor(&-2) == 0);
|
||||
/// ~~~
|
||||
/// ```
|
||||
fn div_floor(&self, other: &Self) -> Self;
|
||||
|
||||
/// Floored integer modulo, satisfying:
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// # use num::Integer;
|
||||
/// # let n = 1i; let d = 1i;
|
||||
/// assert!(n.div_floor(&d) * d + n.mod_floor(&d) == n)
|
||||
/// ~~~
|
||||
/// ```
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// # use num::Integer;
|
||||
/// assert!(( 8i).mod_floor(& 3) == 2);
|
||||
/// assert!(( 8i).mod_floor(&-3) == -1);
|
||||
|
@ -52,29 +52,29 @@ pub trait Integer: Num + PartialOrd
|
|||
/// assert!(( 1i).mod_floor(&-2) == -1);
|
||||
/// assert!((-1i).mod_floor(& 2) == 1);
|
||||
/// assert!((-1i).mod_floor(&-2) == -1);
|
||||
/// ~~~
|
||||
/// ```
|
||||
fn mod_floor(&self, other: &Self) -> Self;
|
||||
|
||||
/// Greatest Common Divisor (GCD).
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// # use num::Integer;
|
||||
/// assert_eq!(6i.gcd(&8), 2);
|
||||
/// assert_eq!(7i.gcd(&3), 1);
|
||||
/// ~~~
|
||||
/// ```
|
||||
fn gcd(&self, other: &Self) -> Self;
|
||||
|
||||
/// Lowest Common Multiple (LCM).
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// # use num::Integer;
|
||||
/// assert_eq!(7i.lcm(&3), 21);
|
||||
/// assert_eq!(2i.lcm(&4), 4);
|
||||
/// ~~~
|
||||
/// ```
|
||||
fn lcm(&self, other: &Self) -> Self;
|
||||
|
||||
/// Deprecated, use `is_multiple_of` instead.
|
||||
|
@ -85,33 +85,33 @@ pub trait Integer: Num + PartialOrd
|
|||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// # use num::Integer;
|
||||
/// assert_eq!(9i.is_multiple_of(&3), true);
|
||||
/// assert_eq!(3i.is_multiple_of(&9), false);
|
||||
/// ~~~
|
||||
/// ```
|
||||
fn is_multiple_of(&self, other: &Self) -> bool;
|
||||
|
||||
/// Returns `true` if the number is even.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// # use num::Integer;
|
||||
/// assert_eq!(3i.is_even(), false);
|
||||
/// assert_eq!(4i.is_even(), true);
|
||||
/// ~~~
|
||||
/// ```
|
||||
fn is_even(&self) -> bool;
|
||||
|
||||
/// Returns `true` if the number is odd.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// # use num::Integer;
|
||||
/// assert_eq!(3i.is_odd(), true);
|
||||
/// assert_eq!(4i.is_odd(), false);
|
||||
/// ~~~
|
||||
/// ```
|
||||
fn is_odd(&self) -> bool;
|
||||
|
||||
/// Simultaneous truncated integer division and modulus.
|
||||
|
@ -119,7 +119,7 @@ pub trait Integer: Num + PartialOrd
|
|||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// # use num::Integer;
|
||||
/// assert_eq!(( 8i).div_rem( &3), ( 2, 2));
|
||||
/// assert_eq!(( 8i).div_rem(&-3), (-2, 2));
|
||||
|
@ -130,7 +130,7 @@ pub trait Integer: Num + PartialOrd
|
|||
/// assert_eq!(( 1i).div_rem(&-2), ( 0, 1));
|
||||
/// assert_eq!((-1i).div_rem( &2), ( 0, -1));
|
||||
/// assert_eq!((-1i).div_rem(&-2), ( 0, -1));
|
||||
/// ~~~
|
||||
/// ```
|
||||
#[inline]
|
||||
fn div_rem(&self, other: &Self) -> (Self, Self) {
|
||||
(*self / *other, *self % *other)
|
||||
|
@ -141,7 +141,7 @@ pub trait Integer: Num + PartialOrd
|
|||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ~~~
|
||||
/// ```
|
||||
/// # use num::Integer;
|
||||
/// assert_eq!(( 8i).div_mod_floor( &3), ( 2, 2));
|
||||
/// assert_eq!(( 8i).div_mod_floor(&-3), (-3, -1));
|
||||
|
@ -152,7 +152,7 @@ pub trait Integer: Num + PartialOrd
|
|||
/// assert_eq!(( 1i).div_mod_floor(&-2), (-1, -1));
|
||||
/// assert_eq!((-1i).div_mod_floor( &2), (-1, 1));
|
||||
/// assert_eq!((-1i).div_mod_floor(&-2), ( 0, -1));
|
||||
/// ~~~
|
||||
/// ```
|
||||
fn div_mod_floor(&self, other: &Self) -> (Self, Self) {
|
||||
(self.div_floor(other), self.mod_floor(other))
|
||||
}
|
||||
|
|
|
@ -21,7 +21,7 @@
|
|||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ~~~rust
|
||||
/// ```{.rust}
|
||||
/// bitflags! {
|
||||
/// flags Flags: u32 {
|
||||
/// static FlagA = 0x00000001,
|
||||
|
@ -41,11 +41,11 @@
|
|||
/// assert!((e1 - e2) == FlagA); // set difference
|
||||
/// assert!(!e2 == FlagA); // set complement
|
||||
/// }
|
||||
/// ~~~
|
||||
/// ```
|
||||
///
|
||||
/// The generated `struct`s can also be extended with type and trait implementations:
|
||||
///
|
||||
/// ~~~rust
|
||||
/// ```{.rust}
|
||||
/// use std::fmt;
|
||||
///
|
||||
/// bitflags! {
|
||||
|
@ -74,7 +74,7 @@
|
|||
/// assert!(flags.is_empty());
|
||||
/// assert_eq!(format!("{}", flags).as_slice(), "hi!");
|
||||
/// }
|
||||
/// ~~~
|
||||
/// ```
|
||||
///
|
||||
/// # Attributes
|
||||
///
|
||||
|
|
|
@ -192,7 +192,7 @@ macro_rules! debug_assert_eq(
|
|||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ~~~rust
|
||||
/// ```{.rust}
|
||||
/// struct Item { weight: uint }
|
||||
///
|
||||
/// fn choose_weighted_item(v: &[Item]) -> Item {
|
||||
|
@ -208,7 +208,7 @@ macro_rules! debug_assert_eq(
|
|||
/// // type checker that it isn't possible to get down here
|
||||
/// unreachable!();
|
||||
/// }
|
||||
/// ~~~
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! unreachable(
|
||||
() => (fail!("internal error: entered unreachable code"))
|
||||
|
|
|
@ -101,32 +101,32 @@
|
|||
//!
|
||||
//! When generating the `expr` for the `A` impl, the `SubstructureFields` is
|
||||
//!
|
||||
//! ~~~text
|
||||
//! ```{.text}
|
||||
//! Struct(~[FieldInfo {
|
||||
//! span: <span of x>
|
||||
//! name: Some(<ident of x>),
|
||||
//! self_: <expr for &self.x>,
|
||||
//! other: ~[<expr for &other.x]
|
||||
//! }])
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! For the `B` impl, called with `B(a)` and `B(b)`,
|
||||
//!
|
||||
//! ~~~text
|
||||
//! ```{.text}
|
||||
//! Struct(~[FieldInfo {
|
||||
//! span: <span of `int`>,
|
||||
//! name: None,
|
||||
//! <expr for &a>
|
||||
//! ~[<expr for &b>]
|
||||
//! }])
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! ## Enums
|
||||
//!
|
||||
//! When generating the `expr` for a call with `self == C0(a)` and `other
|
||||
//! == C0(b)`, the SubstructureFields is
|
||||
//!
|
||||
//! ~~~text
|
||||
//! ```{.text}
|
||||
//! EnumMatching(0, <ast::Variant for C0>,
|
||||
//! ~[FieldInfo {
|
||||
//! span: <span of int>
|
||||
|
@ -134,11 +134,11 @@
|
|||
//! self_: <expr for &a>,
|
||||
//! other: ~[<expr for &b>]
|
||||
//! }])
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! For `C1 {x}` and `C1 {x}`,
|
||||
//!
|
||||
//! ~~~text
|
||||
//! ```{.text}
|
||||
//! EnumMatching(1, <ast::Variant for C1>,
|
||||
//! ~[FieldInfo {
|
||||
//! span: <span of x>
|
||||
|
@ -146,16 +146,16 @@
|
|||
//! self_: <expr for &self.x>,
|
||||
//! other: ~[<expr for &other.x>]
|
||||
//! }])
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! For `C0(a)` and `C1 {x}` ,
|
||||
//!
|
||||
//! ~~~text
|
||||
//! ```{.text}
|
||||
//! EnumNonMatchingCollapsed(
|
||||
//! ~[<ident of self>, <ident of __arg_1>],
|
||||
//! &[<ast::Variant for C0>, <ast::Variant for C1>],
|
||||
//! &[<ident for self index value>, <ident of __arg_1 index value>])
|
||||
//! ~~~
|
||||
//! ```
|
||||
//!
|
||||
//! It is the same for when the arguments are flipped to `C1 {x}` and
|
||||
//! `C0(a)`; the only difference is what the values of the identifiers
|
||||
|
@ -170,7 +170,7 @@
|
|||
//!
|
||||
//! A static method on the above would result in,
|
||||
//!
|
||||
//! ~~~text
|
||||
//! ```{.text}
|
||||
//! StaticStruct(<ast::StructDef of A>, Named(~[(<ident of x>, <span of x>)]))
|
||||
//!
|
||||
//! StaticStruct(<ast::StructDef of B>, Unnamed(~[<span of x>]))
|
||||
|
@ -178,7 +178,7 @@
|
|||
//! StaticEnum(<ast::EnumDef of C>, ~[(<ident of C0>, <span of C0>, Unnamed(~[<span of int>])),
|
||||
//! (<ident of C1>, <span of C1>,
|
||||
//! Named(~[(<ident of x>, <span of x>)]))])
|
||||
//! ~~~
|
||||
//! ```
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::vec;
|
||||
|
@ -252,7 +252,7 @@ pub struct Substructure<'a> {
|
|||
pub type_ident: Ident,
|
||||
/// ident of the method
|
||||
pub method_ident: Ident,
|
||||
/// dereferenced access to any Self or Ptr(Self, _) arguments
|
||||
/// dereferenced access to any `Self` or `Ptr(Self, _)` arguments
|
||||
pub self_args: &'a [P<Expr>],
|
||||
/// verbatim access to any other arguments
|
||||
pub nonself_args: &'a [P<Expr>],
|
||||
|
@ -269,61 +269,52 @@ pub struct FieldInfo {
|
|||
/// (specifically, a reference to it).
|
||||
pub self_: P<Expr>,
|
||||
/// The expressions corresponding to references to this field in
|
||||
/// the other Self arguments.
|
||||
/// the other `Self` arguments.
|
||||
pub other: Vec<P<Expr>>,
|
||||
}
|
||||
|
||||
/// Fields for a static method
|
||||
pub enum StaticFields {
|
||||
/// Tuple structs/enum variants like this
|
||||
/// Tuple structs/enum variants like this.
|
||||
Unnamed(Vec<Span>),
|
||||
/// Normal structs/struct variants.
|
||||
Named(Vec<(Ident, Span)>),
|
||||
}
|
||||
|
||||
/// A summary of the possible sets of fields. See above for details
|
||||
/// and examples
|
||||
/// A summary of the possible sets of fields.
|
||||
pub enum SubstructureFields<'a> {
|
||||
Struct(Vec<FieldInfo>),
|
||||
/**
|
||||
Matching variants of the enum: variant index, ast::Variant,
|
||||
fields: the field name is only non-`None` in the case of a struct
|
||||
variant.
|
||||
*/
|
||||
/// Matching variants of the enum: variant index, ast::Variant,
|
||||
/// fields: the field name is only non-`None` in the case of a struct
|
||||
/// variant.
|
||||
EnumMatching(uint, &'a ast::Variant, Vec<FieldInfo>),
|
||||
|
||||
/**
|
||||
non-matching variants of the enum, but with all state hidden from
|
||||
the consequent code. The first component holds Idents for all of
|
||||
the Self arguments; the second component is a slice of all of the
|
||||
variants for the enum itself, and the third component is a list of
|
||||
Idents bound to the variant index values for each of the actual
|
||||
input Self arguments.
|
||||
*/
|
||||
/// Non-matching variants of the enum, but with all state hidden from
|
||||
/// the consequent code. The first component holds `Ident`s for all of
|
||||
/// the `Self` arguments; the second component is a slice of all of the
|
||||
/// variants for the enum itself, and the third component is a list of
|
||||
/// `Ident`s bound to the variant index values for each of the actual
|
||||
/// input `Self` arguments.
|
||||
EnumNonMatchingCollapsed(Vec<Ident>, &'a [P<ast::Variant>], &'a [Ident]),
|
||||
|
||||
/// A static method where Self is a struct.
|
||||
/// A static method where `Self` is a struct.
|
||||
StaticStruct(&'a ast::StructDef, StaticFields),
|
||||
/// A static method where Self is an enum.
|
||||
/// A static method where `Self` is an enum.
|
||||
StaticEnum(&'a ast::EnumDef, Vec<(Ident, Span, StaticFields)>),
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
Combine the values of all the fields together. The last argument is
|
||||
all the fields of all the structures, see above for details.
|
||||
*/
|
||||
/// Combine the values of all the fields together. The last argument is
|
||||
/// all the fields of all the structures.
|
||||
pub type CombineSubstructureFunc<'a> =
|
||||
|&mut ExtCtxt, Span, &Substructure|: 'a -> P<Expr>;
|
||||
|
||||
/**
|
||||
Deal with non-matching enum variants. The tuple is a list of
|
||||
identifiers (one for each Self argument, which could be any of the
|
||||
variants since they have been collapsed together) and the identifiers
|
||||
holding the variant index value for each of the Self arguments. The
|
||||
last argument is all the non-Self args of the method being derived.
|
||||
*/
|
||||
/// Deal with non-matching enum variants. The tuple is a list of
|
||||
/// identifiers (one for each `Self` argument, which could be any of the
|
||||
/// variants since they have been collapsed together) and the identifiers
|
||||
/// holding the variant index value for each of the `Self` arguments. The
|
||||
/// last argument is all the non-`Self` args of the method being derived.
|
||||
pub type EnumNonMatchCollapsedFunc<'a> =
|
||||
|&mut ExtCtxt,
|
||||
Span,
|
||||
|
@ -373,18 +364,14 @@ impl<'a> TraitDef<'a> {
|
|||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Given that we are deriving a trait `Tr` for a type `T<'a, ...,
|
||||
* 'z, A, ..., Z>`, creates an impl like:
|
||||
*
|
||||
* ```ignore
|
||||
* impl<'a, ..., 'z, A:Tr B1 B2, ..., Z: Tr B1 B2> Tr for T<A, ..., Z> { ... }
|
||||
* ```
|
||||
*
|
||||
* where B1, B2, ... are the bounds given by `bounds_paths`.'
|
||||
*
|
||||
*/
|
||||
/// Given that we are deriving a trait `Tr` for a type `T<'a, ...,
|
||||
/// 'z, A, ..., Z>`, creates an impl like:
|
||||
///
|
||||
/// ```ignore
|
||||
/// impl<'a, ..., 'z, A:Tr B1 B2, ..., Z: Tr B1 B2> Tr for T<A, ..., Z> { ... }
|
||||
/// ```
|
||||
///
|
||||
/// where B1, B2, ... are the bounds given by `bounds_paths`.'
|
||||
fn create_derived_impl(&self,
|
||||
cx: &mut ExtCtxt,
|
||||
type_ident: Ident,
|
||||
|
@ -693,27 +680,25 @@ impl<'a> MethodDef<'a> {
|
|||
})
|
||||
}
|
||||
|
||||
/**
|
||||
~~~
|
||||
#[deriving(PartialEq)]
|
||||
struct A { x: int, y: int }
|
||||
|
||||
// equivalent to:
|
||||
impl PartialEq for A {
|
||||
fn eq(&self, __arg_1: &A) -> bool {
|
||||
match *self {
|
||||
A {x: ref __self_0_0, y: ref __self_0_1} => {
|
||||
match *__arg_1 {
|
||||
A {x: ref __self_1_0, y: ref __self_1_1} => {
|
||||
__self_0_0.eq(__self_1_0) && __self_0_1.eq(__self_1_1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
~~~
|
||||
*/
|
||||
/// ```
|
||||
/// #[deriving(PartialEq)]
|
||||
/// struct A { x: int, y: int }
|
||||
///
|
||||
/// // equivalent to:
|
||||
/// impl PartialEq for A {
|
||||
/// fn eq(&self, __arg_1: &A) -> bool {
|
||||
/// match *self {
|
||||
/// A {x: ref __self_0_0, y: ref __self_0_1} => {
|
||||
/// match *__arg_1 {
|
||||
/// A {x: ref __self_1_0, y: ref __self_1_1} => {
|
||||
/// __self_0_0.eq(__self_1_0) && __self_0_1.eq(__self_1_1)
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn expand_struct_method_body(&self,
|
||||
cx: &mut ExtCtxt,
|
||||
trait_: &TraitDef,
|
||||
|
@ -798,37 +783,35 @@ impl<'a> MethodDef<'a> {
|
|||
&StaticStruct(struct_def, summary))
|
||||
}
|
||||
|
||||
/**
|
||||
~~~
|
||||
#[deriving(PartialEq)]
|
||||
enum A {
|
||||
A1,
|
||||
A2(int)
|
||||
}
|
||||
|
||||
// is equivalent to
|
||||
|
||||
impl PartialEq for A {
|
||||
fn eq(&self, __arg_1: &A) -> ::bool {
|
||||
match (&*self, &*__arg_1) {
|
||||
(&A1, &A1) => true,
|
||||
(&A2(ref __self_0),
|
||||
&A2(ref __arg_1_0)) => (*__self_0).eq(&(*__arg_1_0)),
|
||||
_ => {
|
||||
let __self_vi = match *self { A1(..) => 0u, A2(..) => 1u };
|
||||
let __arg_1_vi = match *__arg_1 { A1(..) => 0u, A2(..) => 1u };
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
~~~
|
||||
|
||||
(Of course `__self_vi` and `__arg_1_vi` are unused for
|
||||
`PartialEq`, and those subcomputations will hopefully be removed
|
||||
as their results are unused. The point of `__self_vi` and
|
||||
`__arg_1_vi` is for `PartialOrd`; see #15503.)
|
||||
*/
|
||||
/// ```
|
||||
/// #[deriving(PartialEq)]
|
||||
/// enum A {
|
||||
/// A1,
|
||||
/// A2(int)
|
||||
/// }
|
||||
///
|
||||
/// // is equivalent to
|
||||
///
|
||||
/// impl PartialEq for A {
|
||||
/// fn eq(&self, __arg_1: &A) -> ::bool {
|
||||
/// match (&*self, &*__arg_1) {
|
||||
/// (&A1, &A1) => true,
|
||||
/// (&A2(ref __self_0),
|
||||
/// &A2(ref __arg_1_0)) => (*__self_0).eq(&(*__arg_1_0)),
|
||||
/// _ => {
|
||||
/// let __self_vi = match *self { A1(..) => 0u, A2(..) => 1u };
|
||||
/// let __arg_1_vi = match *__arg_1 { A1(..) => 0u, A2(..) => 1u };
|
||||
/// false
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// (Of course `__self_vi` and `__arg_1_vi` are unused for
|
||||
/// `PartialEq`, and those subcomputations will hopefully be removed
|
||||
/// as their results are unused. The point of `__self_vi` and
|
||||
/// `__arg_1_vi` is for `PartialOrd`; see #15503.)
|
||||
fn expand_enum_method_body(&self,
|
||||
cx: &mut ExtCtxt,
|
||||
trait_: &TraitDef,
|
||||
|
@ -842,33 +825,31 @@ impl<'a> MethodDef<'a> {
|
|||
}
|
||||
|
||||
|
||||
/**
|
||||
Creates a match for a tuple of all `self_args`, where either all
|
||||
variants match, or it falls into a catch-all for when one variant
|
||||
does not match.
|
||||
/// Creates a match for a tuple of all `self_args`, where either all
|
||||
/// variants match, or it falls into a catch-all for when one variant
|
||||
/// does not match.
|
||||
|
||||
There are N + 1 cases because is a case for each of the N
|
||||
variants where all of the variants match, and one catch-all for
|
||||
when one does not match.
|
||||
/// There are N + 1 cases because is a case for each of the N
|
||||
/// variants where all of the variants match, and one catch-all for
|
||||
/// when one does not match.
|
||||
|
||||
The catch-all handler is provided access the variant index values
|
||||
for each of the self-args, carried in precomputed variables. (Nota
|
||||
bene: the variant index values are not necessarily the
|
||||
discriminant values. See issue #15523.)
|
||||
/// The catch-all handler is provided access the variant index values
|
||||
/// for each of the self-args, carried in precomputed variables. (Nota
|
||||
/// bene: the variant index values are not necessarily the
|
||||
/// discriminant values. See issue #15523.)
|
||||
|
||||
~~~text
|
||||
match (this, that, ...) {
|
||||
(Variant1, Variant1, Variant1) => ... // delegate Matching on Variant1
|
||||
(Variant2, Variant2, Variant2) => ... // delegate Matching on Variant2
|
||||
...
|
||||
_ => {
|
||||
let __this_vi = match this { Variant1 => 0u, Variant2 => 1u, ... };
|
||||
let __that_vi = match that { Variant1 => 0u, Variant2 => 1u, ... };
|
||||
... // catch-all remainder can inspect above variant index values.
|
||||
}
|
||||
}
|
||||
~~~
|
||||
*/
|
||||
/// ```{.text}
|
||||
/// match (this, that, ...) {
|
||||
/// (Variant1, Variant1, Variant1) => ... // delegate Matching on Variant1
|
||||
/// (Variant2, Variant2, Variant2) => ... // delegate Matching on Variant2
|
||||
/// ...
|
||||
/// _ => {
|
||||
/// let __this_vi = match this { Variant1 => 0u, Variant2 => 1u, ... };
|
||||
/// let __that_vi = match that { Variant1 => 0u, Variant2 => 1u, ... };
|
||||
/// ... // catch-all remainder can inspect above variant index values.
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn build_enum_match_tuple(
|
||||
&self,
|
||||
cx: &mut ExtCtxt,
|
||||
|
@ -1319,10 +1300,8 @@ impl<'a> TraitDef<'a> {
|
|||
|
||||
/* helpful premade recipes */
|
||||
|
||||
/**
|
||||
Fold the fields. `use_foldl` controls whether this is done
|
||||
left-to-right (`true`) or right-to-left (`false`).
|
||||
*/
|
||||
/// Fold the fields. `use_foldl` controls whether this is done
|
||||
/// left-to-right (`true`) or right-to-left (`false`).
|
||||
pub fn cs_fold(use_foldl: bool,
|
||||
f: |&mut ExtCtxt, Span, P<Expr>, P<Expr>, &[P<Expr>]| -> P<Expr>,
|
||||
base: P<Expr>,
|
||||
|
@ -1361,15 +1340,13 @@ pub fn cs_fold(use_foldl: bool,
|
|||
}
|
||||
|
||||
|
||||
/**
|
||||
Call the method that is being derived on all the fields, and then
|
||||
process the collected results. i.e.
|
||||
|
||||
~~~
|
||||
f(cx, span, ~[self_1.method(__arg_1_1, __arg_2_1),
|
||||
self_2.method(__arg_1_2, __arg_2_2)])
|
||||
~~~
|
||||
*/
|
||||
/// Call the method that is being derived on all the fields, and then
|
||||
/// process the collected results. i.e.
|
||||
///
|
||||
/// ```
|
||||
/// f(cx, span, ~[self_1.method(__arg_1_1, __arg_2_1),
|
||||
/// self_2.method(__arg_1_2, __arg_2_2)])
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn cs_same_method(f: |&mut ExtCtxt, Span, Vec<P<Expr>>| -> P<Expr>,
|
||||
enum_nonmatch_f: EnumNonMatchCollapsedFunc,
|
||||
|
@ -1400,11 +1377,9 @@ pub fn cs_same_method(f: |&mut ExtCtxt, Span, Vec<P<Expr>>| -> P<Expr>,
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Fold together the results of calling the derived method on all the
|
||||
fields. `use_foldl` controls whether this is done left-to-right
|
||||
(`true`) or right-to-left (`false`).
|
||||
*/
|
||||
/// Fold together the results of calling the derived method on all the
|
||||
/// fields. `use_foldl` controls whether this is done left-to-right
|
||||
/// (`true`) or right-to-left (`false`).
|
||||
#[inline]
|
||||
pub fn cs_same_method_fold(use_foldl: bool,
|
||||
f: |&mut ExtCtxt, Span, P<Expr>, P<Expr>| -> P<Expr>,
|
||||
|
@ -1430,10 +1405,8 @@ pub fn cs_same_method_fold(use_foldl: bool,
|
|||
cx, trait_span, substructure)
|
||||
}
|
||||
|
||||
/**
|
||||
Use a given binop to combine the result of calling the derived method
|
||||
on all the fields.
|
||||
*/
|
||||
/// Use a given binop to combine the result of calling the derived method
|
||||
/// on all the fields.
|
||||
#[inline]
|
||||
pub fn cs_binop(binop: ast::BinOp, base: P<Expr>,
|
||||
enum_nonmatch_f: EnumNonMatchCollapsedFunc,
|
||||
|
|
|
@ -352,10 +352,9 @@ pub fn write_5_number_summary<T: Float + Show>(w: &mut io::Writer,
|
|||
/// As an example, the summary with 5-number-summary `(min=15, q1=17, med=20, q3=24, max=31)` might
|
||||
/// display as:
|
||||
///
|
||||
/// ~~~~ignore
|
||||
/// ```{.ignore}
|
||||
/// 10 | [--****#******----------] | 40
|
||||
/// ~~~~
|
||||
|
||||
/// ```
|
||||
pub fn write_boxplot<T: Float + Show + FromPrimitive>(
|
||||
w: &mut io::Writer,
|
||||
s: &Summary<T>,
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue