1
Fork 0

auto merge of #17339 : treeman/rust/doc-things, r=alexcrichton

Also some cleanup to conform to documentation style.
This commit is contained in:
bors 2014-09-22 09:05:29 +00:00
commit 8a458181dd
10 changed files with 633 additions and 245 deletions

View file

@ -138,10 +138,10 @@ pub struct RadixFmt<T, R>(T, R);
/// ///
/// # Example /// # Example
/// ///
/// ~~~ /// ```
/// use std::fmt::radix; /// use std::fmt::radix;
/// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string()); /// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
/// ~~~ /// ```
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> { pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base)) RadixFmt(x, Radix::new(base))
} }

View file

@ -61,10 +61,10 @@ pub trait Zero: Add<Self, Self> {
/// ///
/// # Laws /// # Laws
/// ///
/// ~~~text /// ```{.text}
/// a + 0 = a ∀ a ∈ Self /// a + 0 = a ∀ a ∈ Self
/// 0 + a = a ∀ a ∈ Self /// 0 + a = a ∀ a ∈ Self
/// ~~~ /// ```
/// ///
/// # Purity /// # Purity
/// ///
@ -114,10 +114,10 @@ pub trait One: Mul<Self, Self> {
/// ///
/// # Laws /// # Laws
/// ///
/// ~~~text /// ```{.text}
/// a * 1 = a ∀ a ∈ Self /// a * 1 = a ∀ a ∈ Self
/// 1 * a = a ∀ a ∈ Self /// 1 * a = a ∀ a ∈ Self
/// ~~~ /// ```
/// ///
/// # Purity /// # Purity
/// ///

View file

@ -175,6 +175,16 @@ impl<T> Option<T> {
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
/// Returns `true` if the option is a `Some` value /// 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] #[inline]
#[stable] #[stable]
pub fn is_some(&self) -> bool { pub fn is_some(&self) -> bool {
@ -185,6 +195,16 @@ impl<T> Option<T> {
} }
/// Returns `true` if the option is a `None` value /// 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] #[inline]
#[stable] #[stable]
pub fn is_none(&self) -> bool { pub fn is_none(&self) -> bool {
@ -218,6 +238,17 @@ impl<T> Option<T> {
} }
/// Convert from `Option<T>` to `Option<&mut 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] #[inline]
#[unstable = "waiting for mut conventions"] #[unstable = "waiting for mut conventions"]
pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> { 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) /// 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] #[inline]
#[unstable = "waiting for mut conventions"] #[unstable = "waiting for mut conventions"]
pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] { 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 /// Fails if the value is a `None` with a custom failure message provided by
/// `msg`. /// `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] #[inline]
#[unstable = "waiting for conventions"] #[unstable = "waiting for conventions"]
pub fn expect(self, msg: &str) -> T { 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. /// In general, because this function may fail, its use is discouraged.
/// Instead, prefer to use pattern matching and handle the `None` /// Instead, prefer to use pattern matching and handle the `None`
/// case explicitly. /// 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] #[inline]
#[unstable = "waiting for conventions"] #[unstable = "waiting for conventions"]
pub fn unwrap(self) -> T { pub fn unwrap(self) -> T {
@ -280,6 +348,13 @@ impl<T> Option<T> {
} }
/// Returns the contained value or a default. /// Returns the contained value or a default.
///
/// # Example
///
/// ```
/// assert_eq!(Some("car").unwrap_or("bike"), "car");
/// assert_eq!(None.unwrap_or("bike"), "bike");
/// ```
#[inline] #[inline]
#[unstable = "waiting for conventions"] #[unstable = "waiting for conventions"]
pub fn unwrap_or(self, def: T) -> T { 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. /// 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] #[inline]
#[unstable = "waiting for conventions"] #[unstable = "waiting for conventions"]
pub fn unwrap_or_else(self, f: || -> T) -> T { 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. /// 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] #[inline]
#[unstable = "waiting for unboxed closures"] #[unstable = "waiting for unboxed closures"]
pub fn map_or<U>(self, def: U, f: |T| -> U) -> U { 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. /// 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] #[inline]
#[unstable = "waiting for unboxed closures"] #[unstable = "waiting for unboxed closures"]
pub fn map_or_else<U>(self, def: || -> U, f: |T| -> U) -> U { 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. /// 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] #[inline]
#[unstable = "waiting for iterator conventions"] #[unstable = "waiting for iterator conventions"]
pub fn iter<'r>(&'r self) -> Item<&'r T> { 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. /// 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] #[inline]
#[unstable = "waiting for iterator conventions"] #[unstable = "waiting for iterator conventions"]
pub fn iter_mut<'r>(&'r mut self) -> Item<&'r mut T> { 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. /// 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] #[inline]
#[unstable = "waiting for iterator conventions"] #[unstable = "waiting for iterator conventions"]
pub fn into_iter(self) -> Item<T> { 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`. /// 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] #[inline]
#[stable] #[stable]
pub fn and<U>(self, optb: Option<U>) -> Option<U> { 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 /// Returns `None` if the option is `None`, otherwise calls `f` with the
/// wrapped value and returns the result. /// 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] #[inline]
#[unstable = "waiting for unboxed closures"] #[unstable = "waiting for unboxed closures"]
pub fn and_then<U>(self, f: |T| -> Option<U>) -> Option<U> { 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`. /// 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] #[inline]
#[stable] #[stable]
pub fn or(self, optb: Option<T>) -> Option<T> { 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 option if it contains a value, otherwise calls `f` and
/// returns the result. /// 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] #[inline]
#[unstable = "waiting for unboxed closures"] #[unstable = "waiting for unboxed closures"]
pub fn or_else(self, f: || -> Option<T>) -> Option<T> { 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. /// 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] #[inline]
#[stable] #[stable]
pub fn take(&mut self) -> Option<T> { 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 /// 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`. /// methods on `Option`.
#[deriving(Clone)] #[deriving(Clone)]
#[unstable = "waiting for iterator conventions"] #[unstable = "waiting for iterator conventions"]

View file

@ -15,12 +15,12 @@
//! success and containing a value, and `Err(E)`, representing error //! success and containing a value, and `Err(E)`, representing error
//! and containing an error value. //! and containing an error value.
//! //!
//! ~~~ //! ```
//! enum Result<T, E> { //! enum Result<T, E> {
//! Ok(T), //! Ok(T),
//! Err(E) //! Err(E)
//! } //! }
//! ~~~ //! ```
//! //!
//! Functions return `Result` whenever errors are expected and //! Functions return `Result` whenever errors are expected and
//! recoverable. In the `std` crate `Result` is most prominently used //! recoverable. In the `std` crate `Result` is most prominently used
@ -29,7 +29,7 @@
//! A simple function returning `Result` might be //! A simple function returning `Result` might be
//! defined and used like so: //! defined and used like so:
//! //!
//! ~~~ //! ```
//! #[deriving(Show)] //! #[deriving(Show)]
//! enum Version { Version1, Version2 } //! enum Version { Version1, Version2 }
//! //!
@ -53,13 +53,13 @@
//! println!("error parsing header: {}", e); //! println!("error parsing header: {}", e);
//! } //! }
//! } //! }
//! ~~~ //! ```
//! //!
//! Pattern matching on `Result`s is clear and straightforward for //! Pattern matching on `Result`s is clear and straightforward for
//! simple cases, but `Result` comes with some convenience methods //! simple cases, but `Result` comes with some convenience methods
//! that make working it more succinct. //! that make working it more succinct.
//! //!
//! ~~~ //! ```
//! let good_result: Result<int, int> = Ok(10); //! let good_result: Result<int, int> = Ok(10);
//! let bad_result: Result<int, int> = Err(10); //! let bad_result: Result<int, int> = Err(10);
//! //!
@ -79,7 +79,7 @@
//! //!
//! // Consume the result and return the contents with `unwrap`. //! // Consume the result and return the contents with `unwrap`.
//! let final_awesome_result = good_result.ok().unwrap(); //! let final_awesome_result = good_result.ok().unwrap();
//! ~~~ //! ```
//! //!
//! # Results must be used //! # Results must be used
//! //!
@ -94,13 +94,13 @@
//! Consider the `write_line` method defined for I/O types //! Consider the `write_line` method defined for I/O types
//! by the [`Writer`](../io/trait.Writer.html) trait: //! by the [`Writer`](../io/trait.Writer.html) trait:
//! //!
//! ~~~ //! ```
//! use std::io::IoError; //! use std::io::IoError;
//! //!
//! trait Writer { //! trait Writer {
//! fn write_line(&mut self, s: &str) -> Result<(), IoError>; //! fn write_line(&mut self, s: &str) -> Result<(), IoError>;
//! } //! }
//! ~~~ //! ```
//! //!
//! *Note: The actual definition of `Writer` uses `IoResult`, which //! *Note: The actual definition of `Writer` uses `IoResult`, which
//! is just a synonym for `Result<T, IoError>`.* //! is just a synonym for `Result<T, IoError>`.*
@ -109,7 +109,7 @@
//! fail. It's crucial to handle the error case, and *not* write //! fail. It's crucial to handle the error case, and *not* write
//! something like this: //! something like this:
//! //!
//! ~~~ignore //! ```{.ignore}
//! use std::io::{File, Open, Write}; //! use std::io::{File, Open, Write};
//! //!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write); //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
@ -117,7 +117,7 @@
//! // value is ignored. //! // value is ignored.
//! file.write_line("important message"); //! file.write_line("important message");
//! drop(file); //! drop(file);
//! ~~~ //! ```
//! //!
//! If you *do* write that in Rust, the compiler will by give you a //! If you *do* write that in Rust, the compiler will by give you a
//! warning (by default, controlled by the `unused_must_use` lint). //! 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 //! success with `expect`. This will fail if the write fails, proving
//! a marginally useful message indicating why: //! a marginally useful message indicating why:
//! //!
//! ~~~no_run //! ```{.no_run}
//! use std::io::{File, Open, Write}; //! use std::io::{File, Open, Write};
//! //!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), 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"); //! file.write_line("important message").ok().expect("failed to write message");
//! drop(file); //! drop(file);
//! ~~~ //! ```
//! //!
//! You might also simply assert success: //! You might also simply assert success:
//! //!
//! ~~~no_run //! ```{.no_run}
//! # use std::io::{File, Open, Write}; //! # use std::io::{File, Open, Write};
//! //!
//! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write); //! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! assert!(file.write_line("important message").is_ok()); //! assert!(file.write_line("important message").is_ok());
//! # drop(file); //! # drop(file);
//! ~~~ //! ```
//! //!
//! Or propagate the error up the call stack with `try!`: //! Or propagate the error up the call stack with `try!`:
//! //!
//! ~~~ //! ```
//! # use std::io::{File, Open, Write, IoError}; //! # use std::io::{File, Open, Write, IoError};
//! fn write_message() -> Result<(), IoError> { //! fn write_message() -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write); //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
@ -155,7 +155,7 @@
//! drop(file); //! drop(file);
//! return Ok(()); //! return Ok(());
//! } //! }
//! ~~~ //! ```
//! //!
//! # The `try!` macro //! # The `try!` macro
//! //!
@ -166,7 +166,7 @@
//! //!
//! It replaces this: //! It replaces this:
//! //!
//! ~~~ //! ```
//! use std::io::{File, Open, Write, IoError}; //! use std::io::{File, Open, Write, IoError};
//! //!
//! struct Info { //! struct Info {
@ -188,11 +188,11 @@
//! } //! }
//! return file.write_line(format!("rating: {}", info.rating).as_slice()); //! return file.write_line(format!("rating: {}", info.rating).as_slice());
//! } //! }
//! ~~~ //! ```
//! //!
//! With this: //! With this:
//! //!
//! ~~~ //! ```
//! use std::io::{File, Open, Write, IoError}; //! use std::io::{File, Open, Write, IoError};
//! //!
//! struct Info { //! struct Info {
@ -209,7 +209,7 @@
//! try!(file.write_line(format!("rating: {}", info.rating).as_slice())); //! try!(file.write_line(format!("rating: {}", info.rating).as_slice()));
//! return Ok(()); //! return Ok(());
//! } //! }
//! ~~~ //! ```
//! //!
//! *It's much nicer!* //! *It's much nicer!*
//! //!
@ -218,13 +218,13 @@
//! `Err` is returned early from the enclosing function. Its simple definition //! `Err` is returned early from the enclosing function. Its simple definition
//! makes it clear: //! makes it clear:
//! //!
//! ~~~ //! ```
//! # #![feature(macro_rules)] //! # #![feature(macro_rules)]
//! macro_rules! try( //! macro_rules! try(
//! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) }) //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
//! ) //! )
//! # fn main() { } //! # fn main() { }
//! ~~~ //! ```
//! //!
//! `try!` is imported by the prelude, and is available everywhere. //! `try!` is imported by the prelude, and is available everywhere.
//! //!
@ -245,10 +245,10 @@
//! //!
//! Converting to an `Option` with `ok()` to handle an error: //! Converting to an `Option` with `ok()` to handle an error:
//! //!
//! ~~~ //! ```
//! use std::io::Timer; //! use std::io::Timer;
//! let mut t = Timer::new().ok().expect("failed to create timer!"); //! let mut t = Timer::new().ok().expect("failed to create timer!");
//! ~~~ //! ```
//! //!
//! # `Result` vs. `fail!` //! # `Result` vs. `fail!`
//! //!
@ -311,14 +311,13 @@ impl<T, E> Result<T, E> {
/// ///
/// # Example /// # 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 x: Result<int, &str> = Err("Some error message");
/// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write); /// assert_eq!(x.is_ok(), false);
/// assert!(file.write_line("it's cold in here").is_ok()); /// ```
/// # }
/// ~~~
#[inline] #[inline]
#[stable] #[stable]
pub fn is_ok(&self) -> bool { pub fn is_ok(&self) -> bool {
@ -332,14 +331,13 @@ impl<T, E> Result<T, E> {
/// ///
/// # Example /// # 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 /// let x: Result<int, &str> = Err("Some error message");
/// // then `open_mode` returns an error. /// assert_eq!(x.is_err(), true);
/// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read); /// ```
/// assert!(bogus.is_err());
/// ~~~
#[inline] #[inline]
#[stable] #[stable]
pub fn is_err(&self) -> bool { pub fn is_err(&self) -> bool {
@ -356,18 +354,15 @@ impl<T, E> Result<T, E> {
/// Converts `self` into an `Option<T>`, consuming `self`, /// Converts `self` into an `Option<T>`, consuming `self`,
/// and discarding the error, if any. /// and discarding the error, if any.
/// ///
/// To convert to an `Option` without discarding the error value, /// # Example
/// use `as_ref` to first convert the `Result<T, E>` into a
/// `Result<&T, &E>`.
/// ///
/// # Examples /// ```
/// let x: Result<uint, &str> = Ok(2);
/// assert_eq!(x.ok(), Some(2));
/// ///
/// ~~~{.should_fail} /// let x: Result<uint, &str> = Err("Nothing here");
/// use std::io::{File, IoResult}; /// assert_eq!(x.ok(), None);
/// /// ```
/// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
/// let bdays: File = bdays.ok().expect("unable to open birthday file");
/// ~~~
#[inline] #[inline]
#[stable] #[stable]
pub fn ok(self) -> Option<T> { pub fn ok(self) -> Option<T> {
@ -381,6 +376,16 @@ impl<T, E> Result<T, E> {
/// ///
/// Converts `self` into an `Option<T>`, consuming `self`, /// Converts `self` into an `Option<T>`, consuming `self`,
/// and discarding the value, if any. /// 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] #[inline]
#[stable] #[stable]
pub fn err(self) -> Option<E> { pub fn err(self) -> Option<E> {
@ -398,6 +403,14 @@ impl<T, E> Result<T, E> {
/// ///
/// Produces a new `Result`, containing a reference /// Produces a new `Result`, containing a reference
/// into the original, leaving the original in place. /// 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] #[inline]
#[stable] #[stable]
pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> { 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>` /// 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] #[inline]
#[unstable = "waiting for mut conventions"] #[unstable = "waiting for mut conventions"]
pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> { 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) /// 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] #[inline]
#[unstable = "waiting for mut conventions"] #[unstable = "waiting for mut conventions"]
pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] { 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. /// 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, /// Sum the lines of a buffer by mapping strings to numbers,
/// ignoring I/O and parse errors: /// ignoring I/O and parse errors:
/// ///
/// ~~~ /// ```
/// use std::io::{BufReader, IoResult}; /// use std::io::{BufReader, IoResult};
/// ///
/// let buffer = "1\n2\n3\n4\n"; /// let buffer = "1\n2\n3\n4\n";
@ -464,7 +508,7 @@ impl<T, E> Result<T, E> {
/// } /// }
/// ///
/// assert!(sum == 10); /// assert!(sum == 10);
/// ~~~ /// ```
#[inline] #[inline]
#[unstable = "waiting for unboxed closures"] #[unstable = "waiting for unboxed closures"]
pub fn map<U>(self, op: |T| -> U) -> Result<U,E> { 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 /// This function can be used to pass through a successful result while handling
/// an error. /// 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] #[inline]
#[unstable = "waiting for unboxed closures"] #[unstable = "waiting for unboxed closures"]
pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> { 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. /// 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] #[inline]
#[unstable = "waiting for iterator conventions"] #[unstable = "waiting for iterator conventions"]
pub fn iter<'r>(&'r self) -> Item<&'r T> { 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. /// 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] #[inline]
#[unstable = "waiting for iterator conventions"] #[unstable = "waiting for iterator conventions"]
pub fn iter_mut<'r>(&'r mut self) -> Item<&'r mut T> { 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. /// 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] #[inline]
#[unstable = "waiting for iterator conventions"] #[unstable = "waiting for iterator conventions"]
pub fn into_iter(self) -> Item<T> { 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`. /// 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] #[inline]
#[stable] #[stable]
pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> { 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`. /// 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] #[inline]
#[unstable = "waiting for unboxed closures"] #[unstable = "waiting for unboxed closures"]
pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> { 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`. /// 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] #[inline]
#[stable] #[stable]
pub fn or(self, res: Result<T, E>) -> Result<T, E> { 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`. /// 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] #[inline]
#[unstable = "waiting for unboxed closures"] #[unstable = "waiting for unboxed closures"]
pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> { 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`. /// Unwraps a result, yielding the content of an `Ok`.
/// Else it returns `optb`. /// 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] #[inline]
#[unstable = "waiting for conventions"] #[unstable = "waiting for conventions"]
pub fn unwrap_or(self, optb: T) -> T { 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`. /// Unwraps a result, yielding the content of an `Ok`.
/// If the value is an `Err` then it calls `op` with its value. /// 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] #[inline]
#[unstable = "waiting for conventions"] #[unstable = "waiting for conventions"]
pub fn unwrap_or_else(self, op: |E| -> T) -> T { 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 /// Fails if the value is an `Err`, with a custom failure message provided
/// by the `Err`'s value. /// 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] #[inline]
#[unstable = "waiting for conventions"] #[unstable = "waiting for conventions"]
pub fn unwrap(self) -> T { 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 /// Fails if the value is an `Ok`, with a custom failure message provided
/// by the `Ok`'s value. /// 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] #[inline]
#[unstable = "waiting for conventions"] #[unstable = "waiting for conventions"]
pub fn unwrap_err(self) -> E { 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 /// 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`. /// methods on `Result`.
#[deriving(Clone)] #[deriving(Clone)]
#[unstable = "waiting for iterator conventions"] #[unstable = "waiting for iterator conventions"]

View file

@ -31,7 +31,7 @@
//! that requires an input file to be specified, accepts an optional output //! 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. //! file name following `-o`, and accepts both `-h` and `--help` as optional flags.
//! //!
//! ~~~{.rust} //! ```{.rust}
//! extern crate getopts; //! extern crate getopts;
//! use getopts::{optopt,optflag,getopts,OptGroup}; //! use getopts::{optopt,optflag,getopts,OptGroup};
//! use std::os; //! use std::os;
@ -76,7 +76,7 @@
//! }; //! };
//! do_work(input.as_slice(), output); //! do_work(input.as_slice(), output);
//! } //! }
//! ~~~ //! ```
#![crate_name = "getopts"] #![crate_name = "getopts"]
#![experimental] #![experimental]

View file

@ -17,7 +17,7 @@ pub trait Integer: Num + PartialOrd
/// ///
/// # Examples /// # Examples
/// ///
/// ~~~ /// ```
/// # use num::Integer; /// # use num::Integer;
/// assert!(( 8i).div_floor(& 3) == 2); /// assert!(( 8i).div_floor(& 3) == 2);
/// assert!(( 8i).div_floor(&-3) == -3); /// 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) == -1); /// assert!((-1i).div_floor(& 2) == -1);
/// assert!((-1i).div_floor(&-2) == 0); /// assert!((-1i).div_floor(&-2) == 0);
/// ~~~ /// ```
fn div_floor(&self, other: &Self) -> Self; fn div_floor(&self, other: &Self) -> Self;
/// Floored integer modulo, satisfying: /// Floored integer modulo, satisfying:
/// ///
/// ~~~ /// ```
/// # use num::Integer; /// # use num::Integer;
/// # let n = 1i; let d = 1i; /// # let n = 1i; let d = 1i;
/// assert!(n.div_floor(&d) * d + n.mod_floor(&d) == n) /// assert!(n.div_floor(&d) * d + n.mod_floor(&d) == n)
/// ~~~ /// ```
/// ///
/// # Examples /// # Examples
/// ///
/// ~~~ /// ```
/// # use num::Integer; /// # use num::Integer;
/// assert!(( 8i).mod_floor(& 3) == 2); /// assert!(( 8i).mod_floor(& 3) == 2);
/// assert!(( 8i).mod_floor(&-3) == -1); /// 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); /// 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; fn mod_floor(&self, other: &Self) -> Self;
/// Greatest Common Divisor (GCD). /// Greatest Common Divisor (GCD).
/// ///
/// # Examples /// # Examples
/// ///
/// ~~~ /// ```
/// # use num::Integer; /// # use num::Integer;
/// assert_eq!(6i.gcd(&8), 2); /// assert_eq!(6i.gcd(&8), 2);
/// assert_eq!(7i.gcd(&3), 1); /// assert_eq!(7i.gcd(&3), 1);
/// ~~~ /// ```
fn gcd(&self, other: &Self) -> Self; fn gcd(&self, other: &Self) -> Self;
/// Lowest Common Multiple (LCM). /// Lowest Common Multiple (LCM).
/// ///
/// # Examples /// # Examples
/// ///
/// ~~~ /// ```
/// # use num::Integer; /// # use num::Integer;
/// assert_eq!(7i.lcm(&3), 21); /// assert_eq!(7i.lcm(&3), 21);
/// assert_eq!(2i.lcm(&4), 4); /// assert_eq!(2i.lcm(&4), 4);
/// ~~~ /// ```
fn lcm(&self, other: &Self) -> Self; fn lcm(&self, other: &Self) -> Self;
/// Deprecated, use `is_multiple_of` instead. /// Deprecated, use `is_multiple_of` instead.
@ -85,33 +85,33 @@ pub trait Integer: Num + PartialOrd
/// ///
/// # Examples /// # Examples
/// ///
/// ~~~ /// ```
/// # use num::Integer; /// # use num::Integer;
/// assert_eq!(9i.is_multiple_of(&3), true); /// assert_eq!(9i.is_multiple_of(&3), true);
/// assert_eq!(3i.is_multiple_of(&9), false); /// assert_eq!(3i.is_multiple_of(&9), false);
/// ~~~ /// ```
fn is_multiple_of(&self, other: &Self) -> bool; fn is_multiple_of(&self, other: &Self) -> bool;
/// Returns `true` if the number is even. /// Returns `true` if the number is even.
/// ///
/// # Examples /// # Examples
/// ///
/// ~~~ /// ```
/// # use num::Integer; /// # use num::Integer;
/// assert_eq!(3i.is_even(), false); /// assert_eq!(3i.is_even(), false);
/// assert_eq!(4i.is_even(), true); /// assert_eq!(4i.is_even(), true);
/// ~~~ /// ```
fn is_even(&self) -> bool; fn is_even(&self) -> bool;
/// Returns `true` if the number is odd. /// Returns `true` if the number is odd.
/// ///
/// # Examples /// # Examples
/// ///
/// ~~~ /// ```
/// # use num::Integer; /// # use num::Integer;
/// assert_eq!(3i.is_odd(), true); /// assert_eq!(3i.is_odd(), true);
/// assert_eq!(4i.is_odd(), false); /// assert_eq!(4i.is_odd(), false);
/// ~~~ /// ```
fn is_odd(&self) -> bool; fn is_odd(&self) -> bool;
/// Simultaneous truncated integer division and modulus. /// Simultaneous truncated integer division and modulus.
@ -119,7 +119,7 @@ pub trait Integer: Num + PartialOrd
/// ///
/// # Examples /// # Examples
/// ///
/// ~~~ /// ```
/// # use num::Integer; /// # use num::Integer;
/// assert_eq!(( 8i).div_rem( &3), ( 2, 2)); /// assert_eq!(( 8i).div_rem( &3), ( 2, 2));
/// 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)); /// 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] #[inline]
fn div_rem(&self, other: &Self) -> (Self, Self) { fn div_rem(&self, other: &Self) -> (Self, Self) {
(*self / *other, *self % *other) (*self / *other, *self % *other)
@ -141,7 +141,7 @@ pub trait Integer: Num + PartialOrd
/// ///
/// # Examples /// # Examples
/// ///
/// ~~~ /// ```
/// # use num::Integer; /// # use num::Integer;
/// assert_eq!(( 8i).div_mod_floor( &3), ( 2, 2)); /// assert_eq!(( 8i).div_mod_floor( &3), ( 2, 2));
/// assert_eq!(( 8i).div_mod_floor(&-3), (-3, -1)); /// 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), (-1, 1)); /// assert_eq!((-1i).div_mod_floor( &2), (-1, 1));
/// assert_eq!((-1i).div_mod_floor(&-2), ( 0, -1)); /// assert_eq!((-1i).div_mod_floor(&-2), ( 0, -1));
/// ~~~ /// ```
fn div_mod_floor(&self, other: &Self) -> (Self, Self) { fn div_mod_floor(&self, other: &Self) -> (Self, Self) {
(self.div_floor(other), self.mod_floor(other)) (self.div_floor(other), self.mod_floor(other))
} }

View file

@ -21,7 +21,7 @@
/// ///
/// # Example /// # Example
/// ///
/// ~~~rust /// ```{.rust}
/// bitflags! { /// bitflags! {
/// flags Flags: u32 { /// flags Flags: u32 {
/// static FlagA = 0x00000001, /// static FlagA = 0x00000001,
@ -41,11 +41,11 @@
/// assert!((e1 - e2) == FlagA); // set difference /// assert!((e1 - e2) == FlagA); // set difference
/// assert!(!e2 == FlagA); // set complement /// assert!(!e2 == FlagA); // set complement
/// } /// }
/// ~~~ /// ```
/// ///
/// The generated `struct`s can also be extended with type and trait implementations: /// The generated `struct`s can also be extended with type and trait implementations:
/// ///
/// ~~~rust /// ```{.rust}
/// use std::fmt; /// use std::fmt;
/// ///
/// bitflags! { /// bitflags! {
@ -74,7 +74,7 @@
/// assert!(flags.is_empty()); /// assert!(flags.is_empty());
/// assert_eq!(format!("{}", flags).as_slice(), "hi!"); /// assert_eq!(format!("{}", flags).as_slice(), "hi!");
/// } /// }
/// ~~~ /// ```
/// ///
/// # Attributes /// # Attributes
/// ///

View file

@ -192,7 +192,7 @@ macro_rules! debug_assert_eq(
/// ///
/// # Example /// # Example
/// ///
/// ~~~rust /// ```{.rust}
/// struct Item { weight: uint } /// struct Item { weight: uint }
/// ///
/// fn choose_weighted_item(v: &[Item]) -> Item { /// 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 /// // type checker that it isn't possible to get down here
/// unreachable!(); /// unreachable!();
/// } /// }
/// ~~~ /// ```
#[macro_export] #[macro_export]
macro_rules! unreachable( macro_rules! unreachable(
() => (fail!("internal error: entered unreachable code")) () => (fail!("internal error: entered unreachable code"))

View file

@ -101,32 +101,32 @@
//! //!
//! When generating the `expr` for the `A` impl, the `SubstructureFields` is //! When generating the `expr` for the `A` impl, the `SubstructureFields` is
//! //!
//! ~~~text //! ```{.text}
//! Struct(~[FieldInfo { //! Struct(~[FieldInfo {
//! span: <span of x> //! span: <span of x>
//! name: Some(<ident of x>), //! name: Some(<ident of x>),
//! self_: <expr for &self.x>, //! self_: <expr for &self.x>,
//! other: ~[<expr for &other.x] //! other: ~[<expr for &other.x]
//! }]) //! }])
//! ~~~ //! ```
//! //!
//! For the `B` impl, called with `B(a)` and `B(b)`, //! For the `B` impl, called with `B(a)` and `B(b)`,
//! //!
//! ~~~text //! ```{.text}
//! Struct(~[FieldInfo { //! Struct(~[FieldInfo {
//! span: <span of `int`>, //! span: <span of `int`>,
//! name: None, //! name: None,
//! <expr for &a> //! <expr for &a>
//! ~[<expr for &b>] //! ~[<expr for &b>]
//! }]) //! }])
//! ~~~ //! ```
//! //!
//! ## Enums //! ## Enums
//! //!
//! When generating the `expr` for a call with `self == C0(a)` and `other //! When generating the `expr` for a call with `self == C0(a)` and `other
//! == C0(b)`, the SubstructureFields is //! == C0(b)`, the SubstructureFields is
//! //!
//! ~~~text //! ```{.text}
//! EnumMatching(0, <ast::Variant for C0>, //! EnumMatching(0, <ast::Variant for C0>,
//! ~[FieldInfo { //! ~[FieldInfo {
//! span: <span of int> //! span: <span of int>
@ -134,11 +134,11 @@
//! self_: <expr for &a>, //! self_: <expr for &a>,
//! other: ~[<expr for &b>] //! other: ~[<expr for &b>]
//! }]) //! }])
//! ~~~ //! ```
//! //!
//! For `C1 {x}` and `C1 {x}`, //! For `C1 {x}` and `C1 {x}`,
//! //!
//! ~~~text //! ```{.text}
//! EnumMatching(1, <ast::Variant for C1>, //! EnumMatching(1, <ast::Variant for C1>,
//! ~[FieldInfo { //! ~[FieldInfo {
//! span: <span of x> //! span: <span of x>
@ -146,16 +146,16 @@
//! self_: <expr for &self.x>, //! self_: <expr for &self.x>,
//! other: ~[<expr for &other.x>] //! other: ~[<expr for &other.x>]
//! }]) //! }])
//! ~~~ //! ```
//! //!
//! For `C0(a)` and `C1 {x}` , //! For `C0(a)` and `C1 {x}` ,
//! //!
//! ~~~text //! ```{.text}
//! EnumNonMatchingCollapsed( //! EnumNonMatchingCollapsed(
//! ~[<ident of self>, <ident of __arg_1>], //! ~[<ident of self>, <ident of __arg_1>],
//! &[<ast::Variant for C0>, <ast::Variant for C1>], //! &[<ast::Variant for C0>, <ast::Variant for C1>],
//! &[<ident for self index value>, <ident of __arg_1 index value>]) //! &[<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 //! 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 //! `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, //! 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 A>, Named(~[(<ident of x>, <span of x>)]))
//! //!
//! StaticStruct(<ast::StructDef of B>, Unnamed(~[<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>])), //! StaticEnum(<ast::EnumDef of C>, ~[(<ident of C0>, <span of C0>, Unnamed(~[<span of int>])),
//! (<ident of C1>, <span of C1>, //! (<ident of C1>, <span of C1>,
//! Named(~[(<ident of x>, <span of x>)]))]) //! Named(~[(<ident of x>, <span of x>)]))])
//! ~~~ //! ```
use std::cell::RefCell; use std::cell::RefCell;
use std::vec; use std::vec;
@ -252,7 +252,7 @@ pub struct Substructure<'a> {
pub type_ident: Ident, pub type_ident: Ident,
/// ident of the method /// ident of the method
pub method_ident: Ident, 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>], pub self_args: &'a [P<Expr>],
/// verbatim access to any other arguments /// verbatim access to any other arguments
pub nonself_args: &'a [P<Expr>], pub nonself_args: &'a [P<Expr>],
@ -269,61 +269,52 @@ pub struct FieldInfo {
/// (specifically, a reference to it). /// (specifically, a reference to it).
pub self_: P<Expr>, pub self_: P<Expr>,
/// The expressions corresponding to references to this field in /// The expressions corresponding to references to this field in
/// the other Self arguments. /// the other `Self` arguments.
pub other: Vec<P<Expr>>, pub other: Vec<P<Expr>>,
} }
/// Fields for a static method /// Fields for a static method
pub enum StaticFields { pub enum StaticFields {
/// Tuple structs/enum variants like this /// Tuple structs/enum variants like this.
Unnamed(Vec<Span>), Unnamed(Vec<Span>),
/// Normal structs/struct variants. /// Normal structs/struct variants.
Named(Vec<(Ident, Span)>), Named(Vec<(Ident, Span)>),
} }
/// A summary of the possible sets of fields. See above for details /// A summary of the possible sets of fields.
/// and examples
pub enum SubstructureFields<'a> { pub enum SubstructureFields<'a> {
Struct(Vec<FieldInfo>), Struct(Vec<FieldInfo>),
/** /// Matching variants of the enum: variant index, ast::Variant,
Matching variants of the enum: variant index, ast::Variant, /// fields: the field name is only non-`None` in the case of a struct
fields: the field name is only non-`None` in the case of a struct /// variant.
variant.
*/
EnumMatching(uint, &'a ast::Variant, Vec<FieldInfo>), EnumMatching(uint, &'a ast::Variant, Vec<FieldInfo>),
/** /// Non-matching variants of the enum, but with all state hidden from
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 consequent code. The first component holds Idents for all of /// the `Self` arguments; the second component is a slice of all of the
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
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
Idents bound to the variant index values for each of the actual /// input `Self` arguments.
input Self arguments.
*/
EnumNonMatchingCollapsed(Vec<Ident>, &'a [P<ast::Variant>], &'a [Ident]), 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), 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)>), StaticEnum(&'a ast::EnumDef, Vec<(Ident, Span, StaticFields)>),
} }
/** /// Combine the values of all the fields together. The last argument is
Combine the values of all the fields together. The last argument is /// all the fields of all the structures.
all the fields of all the structures, see above for details.
*/
pub type CombineSubstructureFunc<'a> = pub type CombineSubstructureFunc<'a> =
|&mut ExtCtxt, Span, &Substructure|: 'a -> P<Expr>; |&mut ExtCtxt, Span, &Substructure|: 'a -> P<Expr>;
/** /// Deal with non-matching enum variants. The tuple is a list of
Deal with non-matching enum variants. The tuple is a list of /// identifiers (one for each `Self` argument, which could be any of the
identifiers (one for each Self argument, which could be any of the /// variants since they have been collapsed together) and the identifiers
variants since they have been collapsed together) and the identifiers /// holding the variant index value for each of the `Self` arguments. The
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.
last argument is all the non-Self args of the method being derived.
*/
pub type EnumNonMatchCollapsedFunc<'a> = pub type EnumNonMatchCollapsedFunc<'a> =
|&mut ExtCtxt, |&mut ExtCtxt,
Span, 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:
* 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> { ... }
* ```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`.'
*
* where B1, B2, ... are the bounds given by `bounds_paths`.'
*
*/
fn create_derived_impl(&self, fn create_derived_impl(&self,
cx: &mut ExtCtxt, cx: &mut ExtCtxt,
type_ident: Ident, type_ident: Ident,
@ -693,27 +680,25 @@ impl<'a> MethodDef<'a> {
}) })
} }
/** /// ```
~~~ /// #[deriving(PartialEq)]
#[deriving(PartialEq)] /// struct A { x: int, y: int }
struct A { x: int, y: int } ///
/// // equivalent to:
// equivalent to: /// impl PartialEq for A {
impl PartialEq for A { /// fn eq(&self, __arg_1: &A) -> bool {
fn eq(&self, __arg_1: &A) -> bool { /// match *self {
match *self { /// A {x: ref __self_0_0, y: ref __self_0_1} => {
A {x: ref __self_0_0, y: ref __self_0_1} => { /// match *__arg_1 {
match *__arg_1 { /// A {x: ref __self_1_0, y: ref __self_1_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)
__self_0_0.eq(__self_1_0) && __self_0_1.eq(__self_1_1) /// }
} /// }
} /// }
} /// }
} /// }
} /// }
} /// ```
~~~
*/
fn expand_struct_method_body(&self, fn expand_struct_method_body(&self,
cx: &mut ExtCtxt, cx: &mut ExtCtxt,
trait_: &TraitDef, trait_: &TraitDef,
@ -798,37 +783,35 @@ impl<'a> MethodDef<'a> {
&StaticStruct(struct_def, summary)) &StaticStruct(struct_def, summary))
} }
/** /// ```
~~~ /// #[deriving(PartialEq)]
#[deriving(PartialEq)] /// enum A {
enum A { /// A1,
A1, /// A2(int)
A2(int) /// }
} ///
/// // is equivalent to
// is equivalent to ///
/// impl PartialEq for A {
impl PartialEq for A { /// fn eq(&self, __arg_1: &A) -> ::bool {
fn eq(&self, __arg_1: &A) -> ::bool { /// match (&*self, &*__arg_1) {
match (&*self, &*__arg_1) { /// (&A1, &A1) => true,
(&A1, &A1) => true, /// (&A2(ref __self_0),
(&A2(ref __self_0), /// &A2(ref __arg_1_0)) => (*__self_0).eq(&(*__arg_1_0)),
&A2(ref __arg_1_0)) => (*__self_0).eq(&(*__arg_1_0)), /// _ => {
_ => { /// let __self_vi = match *self { A1(..) => 0u, A2(..) => 1u };
let __self_vi = match *self { A1(..) => 0u, A2(..) => 1u }; /// let __arg_1_vi = match *__arg_1 { A1(..) => 0u, A2(..) => 1u };
let __arg_1_vi = match *__arg_1 { A1(..) => 0u, A2(..) => 1u }; /// false
false /// }
} /// }
} /// }
} /// }
} /// ```
~~~ ///
/// (Of course `__self_vi` and `__arg_1_vi` are unused for
(Of course `__self_vi` and `__arg_1_vi` are unused for /// `PartialEq`, and those subcomputations will hopefully be removed
`PartialEq`, and those subcomputations will hopefully be removed /// as their results are unused. The point of `__self_vi` and
as their results are unused. The point of `__self_vi` and /// `__arg_1_vi` is for `PartialOrd`; see #15503.)
`__arg_1_vi` is for `PartialOrd`; see #15503.)
*/
fn expand_enum_method_body(&self, fn expand_enum_method_body(&self,
cx: &mut ExtCtxt, cx: &mut ExtCtxt,
trait_: &TraitDef, trait_: &TraitDef,
@ -842,33 +825,31 @@ impl<'a> MethodDef<'a> {
} }
/** /// Creates a match for a tuple of all `self_args`, where either all
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
variants match, or it falls into a catch-all for when one variant /// does not match.
does not match.
There are N + 1 cases because is a case for each of the N /// 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 /// variants where all of the variants match, and one catch-all for
when one does not match. /// when one does not match.
The catch-all handler is provided access the variant index values /// The catch-all handler is provided access the variant index values
for each of the self-args, carried in precomputed variables. (Nota /// for each of the self-args, carried in precomputed variables. (Nota
bene: the variant index values are not necessarily the /// bene: the variant index values are not necessarily the
discriminant values. See issue #15523.) /// discriminant values. See issue #15523.)
~~~text /// ```{.text}
match (this, that, ...) { /// match (this, that, ...) {
(Variant1, Variant1, Variant1) => ... // delegate Matching on Variant1 /// (Variant1, Variant1, Variant1) => ... // delegate Matching on Variant1
(Variant2, Variant2, Variant2) => ... // delegate Matching on Variant2 /// (Variant2, Variant2, Variant2) => ... // delegate Matching on Variant2
... /// ...
_ => { /// _ => {
let __this_vi = match this { Variant1 => 0u, Variant2 => 1u, ... }; /// let __this_vi = match this { Variant1 => 0u, Variant2 => 1u, ... };
let __that_vi = match that { Variant1 => 0u, Variant2 => 1u, ... }; /// let __that_vi = match that { Variant1 => 0u, Variant2 => 1u, ... };
... // catch-all remainder can inspect above variant index values. /// ... // catch-all remainder can inspect above variant index values.
} /// }
} /// }
~~~ /// ```
*/
fn build_enum_match_tuple( fn build_enum_match_tuple(
&self, &self,
cx: &mut ExtCtxt, cx: &mut ExtCtxt,
@ -1319,10 +1300,8 @@ impl<'a> TraitDef<'a> {
/* helpful premade recipes */ /* helpful premade recipes */
/** /// Fold the fields. `use_foldl` controls whether this is done
Fold the fields. `use_foldl` controls whether this is done /// left-to-right (`true`) or right-to-left (`false`).
left-to-right (`true`) or right-to-left (`false`).
*/
pub fn cs_fold(use_foldl: bool, pub fn cs_fold(use_foldl: bool,
f: |&mut ExtCtxt, Span, P<Expr>, P<Expr>, &[P<Expr>]| -> P<Expr>, f: |&mut ExtCtxt, Span, P<Expr>, P<Expr>, &[P<Expr>]| -> P<Expr>,
base: 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
Call the method that is being derived on all the fields, and then /// process the collected results. i.e.
process the collected results. i.e. ///
/// ```
~~~ /// f(cx, span, ~[self_1.method(__arg_1_1, __arg_2_1),
f(cx, span, ~[self_1.method(__arg_1_1, __arg_2_1), /// self_2.method(__arg_1_2, __arg_2_2)])
self_2.method(__arg_1_2, __arg_2_2)]) /// ```
~~~
*/
#[inline] #[inline]
pub fn cs_same_method(f: |&mut ExtCtxt, Span, Vec<P<Expr>>| -> P<Expr>, pub fn cs_same_method(f: |&mut ExtCtxt, Span, Vec<P<Expr>>| -> P<Expr>,
enum_nonmatch_f: EnumNonMatchCollapsedFunc, 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
Fold together the results of calling the derived method on all the /// fields. `use_foldl` controls whether this is done left-to-right
fields. `use_foldl` controls whether this is done left-to-right /// (`true`) or right-to-left (`false`).
(`true`) or right-to-left (`false`).
*/
#[inline] #[inline]
pub fn cs_same_method_fold(use_foldl: bool, pub fn cs_same_method_fold(use_foldl: bool,
f: |&mut ExtCtxt, Span, P<Expr>, P<Expr>| -> P<Expr>, 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) cx, trait_span, substructure)
} }
/** /// Use a given binop to combine the result of calling the derived method
Use a given binop to combine the result of calling the derived method /// on all the fields.
on all the fields.
*/
#[inline] #[inline]
pub fn cs_binop(binop: ast::BinOp, base: P<Expr>, pub fn cs_binop(binop: ast::BinOp, base: P<Expr>,
enum_nonmatch_f: EnumNonMatchCollapsedFunc, enum_nonmatch_f: EnumNonMatchCollapsedFunc,

View file

@ -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 /// As an example, the summary with 5-number-summary `(min=15, q1=17, med=20, q3=24, max=31)` might
/// display as: /// display as:
/// ///
/// ~~~~ignore /// ```{.ignore}
/// 10 | [--****#******----------] | 40 /// 10 | [--****#******----------] | 40
/// ~~~~ /// ```
pub fn write_boxplot<T: Float + Show + FromPrimitive>( pub fn write_boxplot<T: Float + Show + FromPrimitive>(
w: &mut io::Writer, w: &mut io::Writer,
s: &Summary<T>, s: &Summary<T>,