diff --git a/src/doc/book/traits.md b/src/doc/book/traits.md index 9cbb514e280..d07fb6b7c45 100644 --- a/src/doc/book/traits.md +++ b/src/doc/book/traits.md @@ -275,7 +275,7 @@ won’t have its methods: [write]: ../std/io/trait.Write.html ```rust,ignore -let mut f = std::fs::File::open("foo.txt").expect("Couldn’t open foo.txt"); +let mut f = std::fs::File::create("foo.txt").expect("Couldn’t create foo.txt"); let buf = b"whatever"; // byte string literal. buf: &[u8; 8] let result = f.write(buf); # result.unwrap(); // ignore the error @@ -294,7 +294,7 @@ We need to `use` the `Write` trait first: ```rust,ignore use std::io::Write; -let mut f = std::fs::File::open("foo.txt").expect("Couldn’t open foo.txt"); +let mut f = std::fs::File::create("foo.txt").expect("Couldn’t create foo.txt"); let buf = b"whatever"; let result = f.write(buf); # result.unwrap(); // ignore the error diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index b54b71cabd1..3d579641b96 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -718,6 +718,7 @@ impl Clone for Weak { #[stable(feature = "downgraded_weak", since = "1.10.0")] impl Default for Weak { + /// Constructs a new `Weak` without an accompanying instance of T. fn default() -> Weak { Weak::new() } @@ -923,6 +924,7 @@ impl fmt::Pointer for Arc { #[stable(feature = "rust1", since = "1.0.0")] impl Default for Arc { + /// Creates a new `Arc`, with the `Default` value for T. fn default() -> Arc { Arc::new(Default::default()) } diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 70c429cc360..bc9b6e805ef 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -290,6 +290,7 @@ impl Box { #[stable(feature = "rust1", since = "1.0.0")] impl Default for Box { + /// Creates a `Box`, with the `Default` value for T. fn default() -> Box { box Default::default() } diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index c24c7ca47ad..dadddbc2cb3 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -870,6 +870,7 @@ impl fmt::Debug for Weak { #[stable(feature = "downgraded_weak", since = "1.10.0")] impl Default for Weak { + /// Creates a new `Weak`. fn default() -> Weak { Weak::new() } diff --git a/src/libcollections/binary_heap.rs b/src/libcollections/binary_heap.rs index 0b923468c74..1fe921543bd 100644 --- a/src/libcollections/binary_heap.rs +++ b/src/libcollections/binary_heap.rs @@ -263,6 +263,7 @@ impl Clone for BinaryHeap { #[stable(feature = "rust1", since = "1.0.0")] impl Default for BinaryHeap { + /// Creates an empty `BinaryHeap`. #[inline] fn default() -> BinaryHeap { BinaryHeap::new() diff --git a/src/libcollections/borrow.rs b/src/libcollections/borrow.rs index 3ad1d082985..700f88dc0f2 100644 --- a/src/libcollections/borrow.rs +++ b/src/libcollections/borrow.rs @@ -249,6 +249,7 @@ impl<'a, B: ?Sized> Default for Cow<'a, B> where B: ToOwned, ::Owned: Default { + /// Creates an owned Cow<'a, B> with the default value for the contained owned value. fn default() -> Cow<'a, B> { Owned(::Owned::default()) } diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index 624083a8eaf..36cb5a1fd9f 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -1667,6 +1667,7 @@ impl Hash for BTreeMap { } impl Default for BTreeMap { + /// Creates an empty `BTreeMap`. fn default() -> BTreeMap { BTreeMap::new() } diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 5d7b00f57c8..fc2a7f82547 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -674,6 +674,7 @@ impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet { #[stable(feature = "rust1", since = "1.0.0")] impl Default for BTreeSet { + /// Makes an empty `BTreeSet` with a reasonable choice of B. fn default() -> BTreeSet { BTreeSet::new() } diff --git a/src/libcollections/linked_list.rs b/src/libcollections/linked_list.rs index 769c5162a45..690c4f4af35 100644 --- a/src/libcollections/linked_list.rs +++ b/src/libcollections/linked_list.rs @@ -164,6 +164,7 @@ impl LinkedList { #[stable(feature = "rust1", since = "1.0.0")] impl Default for LinkedList { + /// Creates an empty `LinkedList`. #[inline] fn default() -> Self { Self::new() diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 3a304c62929..773e94f1b41 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -1567,6 +1567,7 @@ impl_eq! { Cow<'a, str>, String } #[stable(feature = "rust1", since = "1.0.0")] impl Default for String { + /// Creates an empty `String`. #[inline] fn default() -> String { String::new() diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 7388e883434..f8b4a92df2c 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1652,6 +1652,7 @@ impl Drop for Vec { #[stable(feature = "rust1", since = "1.0.0")] impl Default for Vec { + /// Creates an empty `Vec`. fn default() -> Vec { Vec::new() } diff --git a/src/libcollections/vec_deque.rs b/src/libcollections/vec_deque.rs index 96624f121b2..2e561dabb47 100644 --- a/src/libcollections/vec_deque.rs +++ b/src/libcollections/vec_deque.rs @@ -84,6 +84,7 @@ impl Drop for VecDeque { #[stable(feature = "rust1", since = "1.0.0")] impl Default for VecDeque { + /// Creates an empty `VecDeque`. #[inline] fn default() -> VecDeque { VecDeque::new() diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index f0710a1d935..51221f1b9b9 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -317,6 +317,7 @@ impl Clone for Cell { #[stable(feature = "rust1", since = "1.0.0")] impl Default for Cell { + /// Creates a `Cell`, with the `Default` value for T. #[inline] fn default() -> Cell { Cell::new(Default::default()) @@ -758,6 +759,7 @@ impl Clone for RefCell { #[stable(feature = "rust1", since = "1.0.0")] impl Default for RefCell { + /// Creates a `RefCell`, with the `Default` value for T. #[inline] fn default() -> RefCell { RefCell::new(Default::default()) @@ -1139,6 +1141,7 @@ impl UnsafeCell { #[stable(feature = "unsafe_cell_default", since = "1.9.0")] impl Default for UnsafeCell { + /// Creates an `UnsafeCell`, with the `Default` value for T. fn default() -> UnsafeCell { UnsafeCell::new(Default::default()) } diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs index 748bb62a1f3..69355c6c6cc 100644 --- a/src/libcore/clone.rs +++ b/src/libcore/clone.rs @@ -14,10 +14,14 @@ //! assign them or pass them as arguments, the receiver will get a copy, //! leaving the original value in place. These types do not require //! allocation to copy and do not have finalizers (i.e. they do not -//! contain owned boxes or implement `Drop`), so the compiler considers +//! contain owned boxes or implement [`Drop`]), so the compiler considers //! them cheap and safe to copy. For other types copies must be made -//! explicitly, by convention implementing the `Clone` trait and calling -//! the `clone` method. +//! explicitly, by convention implementing the [`Clone`] trait and calling +//! the [`clone`][clone] method. +//! +//! [`Clone`]: trait.Clone.html +//! [clone]: trait.Clone.html#tymethod.clone +//! [`Drop`]: ../../std/ops/trait.Drop.html //! //! Basic usage example: //! @@ -46,22 +50,22 @@ /// A common trait for the ability to explicitly duplicate an object. /// -/// Differs from `Copy` in that `Copy` is implicit and extremely inexpensive, while +/// Differs from [`Copy`] in that [`Copy`] is implicit and extremely inexpensive, while /// `Clone` is always explicit and may or may not be expensive. In order to enforce -/// these characteristics, Rust does not allow you to reimplement `Copy`, but you +/// these characteristics, Rust does not allow you to reimplement [`Copy`], but you /// may reimplement `Clone` and run arbitrary code. /// -/// Since `Clone` is more general than `Copy`, you can automatically make anything -/// `Copy` be `Clone` as well. +/// Since `Clone` is more general than [`Copy`], you can automatically make anything +/// [`Copy`] be `Clone` as well. /// /// ## Derivable /// /// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d -/// implementation of `clone()` calls `clone()` on each field. +/// implementation of [`clone()`] calls [`clone()`] on each field. /// /// ## How can I implement `Clone`? /// -/// Types that are `Copy` should have a trivial implementation of `Clone`. More formally: +/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally: /// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`. /// Manual implementations should be careful to uphold this invariant; however, unsafe code /// must not rely on it to ensure memory safety. @@ -70,6 +74,9 @@ /// library only implements `Clone` up until arrays of size 32. In this case, the implementation of /// `Clone` cannot be `derive`d, but can be implemented as: /// +/// [`Copy`]: ../../std/marker/trait.Copy.html +/// [`clone()`]: trait.Clone.html#tymethod.clone +/// /// ``` /// #[derive(Copy)] /// struct Stats { diff --git a/src/libcore/hash/sip.rs b/src/libcore/hash/sip.rs index bd6cae92b05..dc53683d633 100644 --- a/src/libcore/hash/sip.rs +++ b/src/libcore/hash/sip.rs @@ -333,6 +333,7 @@ impl Clone for Hasher { } impl Default for Hasher { + /// Creates a `Hasher` with the two initial keys set to 0. #[inline] fn default() -> Hasher { Hasher::new_with_keys(0, 0) diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs index 0a46813df7e..c22c9f0d1c7 100644 --- a/src/libcore/marker.rs +++ b/src/libcore/marker.rs @@ -126,7 +126,7 @@ pub trait Unsize { /// } /// ``` /// -/// The `PointList` `struct` cannot implement `Copy`, because `Vec` is not `Copy`. If we +/// The `PointList` `struct` cannot implement `Copy`, because [`Vec`] is not `Copy`. If we /// attempt to derive a `Copy` implementation, we'll get an error: /// /// ```text @@ -136,10 +136,10 @@ pub trait Unsize { /// ## When can my type _not_ be `Copy`? /// /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased -/// mutable reference, and copying `String` would result in two attempts to free the same buffer. +/// mutable reference, and copying [`String`] would result in two attempts to free the same buffer. /// -/// Generalizing the latter case, any type implementing `Drop` can't be `Copy`, because it's -/// managing some resource besides its own `size_of::()` bytes. +/// Generalizing the latter case, any type implementing [`Drop`] can't be `Copy`, because it's +/// managing some resource besides its own [`size_of::()`] bytes. /// /// ## What if I derive `Copy` on a type that can't? /// @@ -156,8 +156,7 @@ pub trait Unsize { /// /// ## Derivable /// -/// This trait can be used with `#[derive]` if all of its components implement `Copy` and the type -/// implements `Clone`. The implementation will copy the bytes of each field using `memcpy`. +/// This trait can be used with `#[derive]` if all of its components implement `Copy` and the type. /// /// ## How can I implement `Copy`? /// @@ -178,6 +177,11 @@ pub trait Unsize { /// /// There is a small difference between the two: the `derive` strategy will also place a `Copy` /// bound on type parameters, which isn't always desired. +/// +/// [`Vec`]: ../../std/vec/struct.Vec.html +/// [`String`]: ../../std/string/struct.String.html +/// [`Drop`]: ../../std/ops/trait.Drop.html +/// [`size_of::()`]: ../../std/mem/fn.size_of.html #[stable(feature = "rust1", since = "1.0.0")] #[lang = "copy"] pub trait Copy : Clone { @@ -190,11 +194,11 @@ pub trait Copy : Clone { /// thread-safe. In other words, there is no possibility of data races /// when passing `&T` references between threads. /// -/// As one would expect, primitive types like `u8` and `f64` are all +/// As one would expect, primitive types like [`u8`] and [`f64`] are all /// `Sync`, and so are simple aggregate types containing them (like /// tuples, structs and enums). More instances of basic `Sync` types /// include "immutable" types like `&T` and those with simple -/// inherited mutability, such as `Box`, `Vec` and most other +/// inherited mutability, such as [`Box`], [`Vec`] and most other /// collection types. (Generic parameters need to be `Sync` for their /// container to be `Sync`.) /// @@ -206,27 +210,42 @@ pub trait Copy : Clone { /// race. /// /// Types that are not `Sync` are those that have "interior -/// mutability" in a non-thread-safe way, such as `Cell` and `RefCell` -/// in `std::cell`. These types allow for mutation of their contents +/// mutability" in a non-thread-safe way, such as [`Cell`] and [`RefCell`] +/// in [`std::cell`]. These types allow for mutation of their contents /// even when in an immutable, aliasable slot, e.g. the contents of -/// `&Cell` can be `.set`, and do not ensure data races are +/// [`&Cell`][`Cell`] can be [`.set`], and do not ensure data races are /// impossible, hence they cannot be `Sync`. A higher level example /// of a non-`Sync` type is the reference counted pointer -/// `std::rc::Rc`, because any reference `&Rc` can clone a new +/// [`std::rc::Rc`][`Rc`], because any reference [`&Rc`][`Rc`] can clone a new /// reference, which modifies the reference counts in a non-atomic /// way. /// /// For cases when one does need thread-safe interior mutability, -/// types like the atomics in `std::sync` and `Mutex` & `RWLock` in -/// the `sync` crate do ensure that any mutation cannot cause data +/// types like the atomics in [`std::sync`][`sync`] and [`Mutex`] / [`RwLock`] in +/// the [`sync`] crate do ensure that any mutation cannot cause data /// races. Hence these types are `Sync`. /// -/// Any types with interior mutability must also use the `std::cell::UnsafeCell` +/// Any types with interior mutability must also use the [`std::cell::UnsafeCell`] /// wrapper around the value(s) which can be mutated when behind a `&` /// reference; not doing this is undefined behavior (for example, -/// `transmute`-ing from `&T` to `&mut T` is invalid). +/// [`transmute`]-ing from `&T` to `&mut T` is invalid). /// /// This trait is automatically derived when the compiler determines it's appropriate. +/// +/// [`u8`]: ../../std/primitive.u8.html +/// [`f64`]: ../../std/primitive.f64.html +/// [`Vec`]: ../../std/vec/struct.Vec.html +/// [`Box`]: ../../std/boxed/struct.Box.html +/// [`Cell`]: ../../std/cell/struct.Cell.html +/// [`RefCell`]: ../../std/cell/struct.RefCell.html +/// [`std::cell`]: ../../std/cell/index.html +/// [`.set`]: ../../std/cell/struct.Cell.html#method.set +/// [`Rc`]: ../../std/rc/struct.Rc.html +/// [`sync`]: ../../std/sync/index.html +/// [`Mutex`]: ../../std/sync/struct.Mutex.html +/// [`RwLock`]: ../../std/sync/struct.RwLock.html +/// [`std::cell::UnsafeCell`]: ../../std/cell/struct.UnsafeCell.html +/// [`transmute`]: ../../std/mem/fn.transmute.html #[stable(feature = "rust1", since = "1.0.0")] #[lang = "sync"] #[rustc_on_unimplemented = "`{Self}` cannot be shared between threads safely"] diff --git a/src/libcore/option.rs b/src/libcore/option.rs index cf52849e019..b9fb2dc90c7 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -10,9 +10,9 @@ //! Optional values. //! -//! Type `Option` represents an optional value: every `Option` -//! is either `Some` and contains a value, or `None`, and -//! does not. `Option` types are very common in Rust code, as +//! Type [`Option`] represents an optional value: every [`Option`] +//! is either [`Some`] and contains a value, or [`None`], and +//! does not. [`Option`] types are very common in Rust code, as //! they have a number of uses: //! //! * Initial values @@ -26,8 +26,8 @@ //! * Nullable pointers //! * Swapping things out of difficult situations //! -//! Options are commonly paired with pattern matching to query the presence -//! of a value and take action, always accounting for the `None` case. +//! [`Option`]s are commonly paired with pattern matching to query the presence +//! of a value and take action, always accounting for the [`None`] case. //! //! ``` //! fn divide(numerator: f64, denominator: f64) -> Option { @@ -57,13 +57,13 @@ //! //! Rust's pointer types must always point to a valid location; there are //! no "null" pointers. Instead, Rust has *optional* pointers, like -//! the optional owned box, `Option>`. +//! the optional owned box, [`Option`]`<`[`Box`]`>`. //! -//! The following example uses `Option` to create an optional box of -//! `i32`. Notice that in order to use the inner `i32` value first the +//! The following example uses [`Option`] to create an optional box of +//! [`i32`]. Notice that in order to use the inner [`i32`] value first the //! `check_optional` function needs to use pattern matching to -//! determine whether the box has a value (i.e. it is `Some(...)`) or -//! not (`None`). +//! determine whether the box has a value (i.e. it is [`Some(...)`][`Some`]) or +//! not ([`None`]). //! //! ``` //! let optional: Option> = None; @@ -80,14 +80,14 @@ //! } //! ``` //! -//! This usage of `Option` to create safe nullable pointers is so +//! This usage of [`Option`] to create safe nullable pointers is so //! common that Rust does special optimizations to make the -//! representation of `Option>` a single pointer. Optional pointers +//! representation of [`Option`]`<`[`Box`]`>` a single pointer. Optional pointers //! in Rust are stored as efficiently as any other pointer type. //! //! # Examples //! -//! Basic pattern matching on `Option`: +//! Basic pattern matching on [`Option`]: //! //! ``` //! let msg = Some("howdy"); @@ -101,7 +101,7 @@ //! let unwrapped_msg = msg.unwrap_or("default message"); //! ``` //! -//! Initialize a result to `None` before a loop: +//! Initialize a result to [`None`] before a loop: //! //! ``` //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) } @@ -136,6 +136,12 @@ //! None => println!("there are no animals :("), //! } //! ``` +//! +//! [`Option`]: enum.Option.html +//! [`Some`]: enum.Option.html#variant.Some +//! [`None`]: enum.Option.html#variant.None +//! [`Box`]: ../../std/boxed/struct.Box.html +//! [`i32`]: ../../std/primitive.i32.html #![stable(feature = "rust1", since = "1.0.0")] @@ -156,7 +162,7 @@ pub enum Option { None, /// Some value `T` #[stable(feature = "rust1", since = "1.0.0")] - Some(#[stable(feature = "rust1", since = "1.0.0")] T) + Some(#[stable(feature = "rust1", since = "1.0.0")] T), } ///////////////////////////////////////////////////////////////////////////// @@ -168,7 +174,7 @@ impl Option { // Querying the contained values ///////////////////////////////////////////////////////////////////////// - /// Returns `true` if the option is a `Some` value + /// Returns `true` if the option is a `Some` value. /// /// # Examples /// @@ -188,7 +194,7 @@ impl Option { } } - /// Returns `true` if the option is a `None` value + /// Returns `true` if the option is a `None` value. /// /// # Examples /// @@ -209,15 +215,17 @@ impl Option { // Adapter for working with references ///////////////////////////////////////////////////////////////////////// - /// Converts from `Option` to `Option<&T>` + /// Converts from `Option` to `Option<&T>`. /// /// # Examples /// /// Convert an `Option` into an `Option`, preserving the original. - /// The `map` method takes the `self` argument by value, consuming the original, + /// The [`map`] method takes the `self` argument by value, consuming the original, /// so this technique uses `as_ref` to first take an `Option` to a reference /// to the value inside the original. /// + /// [`map`]: enum.Option.html#method.map + /// /// ``` /// let num_as_str: Option = Some("10".to_string()); /// // First, cast `Option` to `Option<&String>` with `as_ref`, @@ -234,7 +242,7 @@ impl Option { } } - /// Converts from `Option` to `Option<&mut T>` + /// Converts from `Option` to `Option<&mut T>`. /// /// # Examples /// @@ -357,7 +365,7 @@ impl Option { // Transforming contained values ///////////////////////////////////////////////////////////////////////// - /// Maps an `Option` to `Option` by applying a function to a contained value + /// Maps an `Option` to `Option` by applying a function to a contained value. /// /// # Examples /// @@ -423,8 +431,12 @@ impl Option { } } - /// Transforms the `Option` into a `Result`, mapping `Some(v)` to - /// `Ok(v)` and `None` to `Err(err)`. + /// Transforms the `Option` into a [`Result`], mapping `Some(v)` to + /// [`Ok(v)`] and `None` to [`Err(err)`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err /// /// # Examples /// @@ -444,8 +456,12 @@ impl Option { } } - /// Transforms the `Option` into a `Result`, mapping `Some(v)` to - /// `Ok(v)` and `None` to `Err(err())`. + /// Transforms the `Option` into a [`Result`], mapping `Some(v)` to + /// [`Ok(v)`] and `None` to [`Err(err())`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err /// /// # Examples /// @@ -698,6 +714,7 @@ fn expect_failed(msg: &str) -> ! { #[stable(feature = "rust1", since = "1.0.0")] impl Default for Option { + /// Returns None. #[inline] fn default() -> Option { None } } @@ -789,7 +806,9 @@ impl DoubleEndedIterator for Item { impl ExactSizeIterator for Item {} impl FusedIterator for Item {} -/// An iterator over a reference of the contained item in an Option. +/// An iterator over a reference of the contained item in an [`Option`]. +/// +/// [`Option`]: enum.Option.html #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] pub struct Iter<'a, A: 'a> { inner: Item<&'a A> } @@ -823,7 +842,9 @@ impl<'a, A> Clone for Iter<'a, A> { } } -/// An iterator over a mutable reference of the contained item in an Option. +/// An iterator over a mutable reference of the contained item in an [`Option`]. +/// +/// [`Option`]: enum.Option.html #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> } @@ -850,7 +871,9 @@ impl<'a, A> ExactSizeIterator for IterMut<'a, A> {} #[unstable(feature = "fused", issue = "35602")] impl<'a, A> FusedIterator for IterMut<'a, A> {} -/// An iterator over the item contained inside an Option. +/// An iterator over the item contained inside an [`Option`]. +/// +/// [`Option`]: enum.Option.html #[derive(Clone, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter { inner: Item } diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 94b6d5fa003..96845259299 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -10,9 +10,9 @@ //! Error handling with the `Result` type. //! -//! `Result` is the type used for returning and propagating -//! errors. It is an enum with the variants, `Ok(T)`, representing -//! success and containing a value, and `Err(E)`, representing error +//! [`Result`][`Result`] is the type used for returning and propagating +//! errors. It is an enum with the variants, [`Ok(T)`], representing +//! success and containing a value, and [`Err(E)`], representing error //! and containing an error value. //! //! ``` @@ -23,11 +23,11 @@ //! } //! ``` //! -//! Functions return `Result` whenever errors are expected and -//! recoverable. In the `std` crate `Result` is most prominently used +//! Functions return [`Result`] whenever errors are expected and +//! recoverable. In the `std` crate, [`Result`] is most prominently used //! for [I/O](../../std/io/index.html). //! -//! A simple function returning `Result` might be +//! A simple function returning [`Result`] might be //! defined and used like so: //! //! ``` @@ -50,8 +50,8 @@ //! } //! ``` //! -//! Pattern matching on `Result`s is clear and straightforward for -//! simple cases, but `Result` comes with some convenience methods +//! Pattern matching on [`Result`]s is clear and straightforward for +//! simple cases, but [`Result`] comes with some convenience methods //! that make working with it more succinct. //! //! ``` @@ -80,14 +80,14 @@ //! //! A common problem with using return values to indicate errors is //! that it is easy to ignore the return value, thus failing to handle -//! the error. Result is annotated with the #[must_use] attribute, +//! the error. [`Result`] is annotated with the `#[must_use]` attribute, //! which will cause the compiler to issue a warning when a Result -//! value is ignored. This makes `Result` especially useful with +//! value is ignored. This makes [`Result`] especially useful with //! functions that may encounter errors but don't otherwise return a //! useful value. //! -//! Consider the `write_all` method defined for I/O types -//! by the [`Write`](../../std/io/trait.Write.html) trait: +//! Consider the [`write_all`] method defined for I/O types +//! by the [`Write`] trait: //! //! ``` //! use std::io; @@ -97,8 +97,8 @@ //! } //! ``` //! -//! *Note: The actual definition of `Write` uses `io::Result`, which -//! is just a synonym for `Result`.* +//! *Note: The actual definition of [`Write`] uses [`io::Result`], which +//! is just a synonym for [`Result`]``.* //! //! This method doesn't produce a value, but the write may //! fail. It's crucial to handle the error case, and *not* write @@ -119,7 +119,7 @@ //! warning (by default, controlled by the `unused_must_use` lint). //! //! You might instead, if you don't want to handle the error, simply -//! assert success with `expect`. This will panic if the +//! assert success with [`expect`]. This will panic if the //! write fails, providing a marginally useful message indicating why: //! //! ```{.no_run} @@ -139,7 +139,7 @@ //! assert!(file.write_all(b"important message").is_ok()); //! ``` //! -//! Or propagate the error up the call stack with `try!`: +//! Or propagate the error up the call stack with [`try!`]: //! //! ``` //! # use std::fs::File; @@ -156,7 +156,7 @@ //! # The `try!` macro //! //! When writing code that calls many functions that return the -//! `Result` type, the error handling can be tedious. The `try!` +//! [`Result`] type, the error handling can be tedious. The [`try!`] //! macro hides some of the boilerplate of propagating errors up the //! call stack. //! @@ -219,9 +219,9 @@ //! //! *It's much nicer!* //! -//! Wrapping an expression in `try!` will result in the unwrapped -//! success (`Ok`) value, unless the result is `Err`, in which case -//! `Err` is returned early from the enclosing function. Its simple definition +//! Wrapping an expression in [`try!`] will result in the unwrapped +//! success ([`Ok`]) value, unless the result is [`Err`], in which case +//! [`Err`] is returned early from the enclosing function. Its simple definition //! makes it clear: //! //! ``` @@ -230,9 +230,21 @@ //! } //! ``` //! -//! `try!` is imported by the prelude and is available everywhere, but it can only -//! be used in functions that return `Result` because of the early return of -//! `Err` that it provides. +//! [`try!`] is imported by the prelude and is available everywhere, but it can only +//! be used in functions that return [`Result`] because of the early return of +//! [`Err`] that it provides. +//! +//! [`expect`]: enum.Result.html#method.expect +//! [`Write`]: ../../std/io/trait.Write.html +//! [`write_all`]: ../../std/io/trait.Write.html#method.write_all +//! [`io::Result`]: ../../std/io/type.Result.html +//! [`try!`]: ../../std/macro.try.html +//! [`Result`]: enum.Result.html +//! [`Ok(T)`]: enum.Result.html#variant.Ok +//! [`Err(E)`]: enum.Result.html#variant.Err +//! [`io::Error`]: ../../std/io/struct.Error.html +//! [`Ok`]: enum.Result.html#variant.Ok +//! [`Err`]: enum.Result.html#variant.Err #![stable(feature = "rust1", since = "1.0.0")] @@ -264,7 +276,7 @@ impl Result { // Querying the contained values ///////////////////////////////////////////////////////////////////////// - /// Returns true if the result is `Ok` + /// Returns true if the result is `Ok`. /// /// # Examples /// @@ -286,7 +298,7 @@ impl Result { } } - /// Returns true if the result is `Err` + /// Returns true if the result is `Err`. /// /// # Examples /// @@ -309,11 +321,13 @@ impl Result { // Adapter for each variant ///////////////////////////////////////////////////////////////////////// - /// Converts from `Result` to `Option` + /// Converts from `Result` to [`Option`]. /// - /// Converts `self` into an `Option`, consuming `self`, + /// Converts `self` into an [`Option`], consuming `self`, /// and discarding the error, if any. /// + /// [`Option`]: ../../std/option/enum.Option.html + /// /// # Examples /// /// Basic usage: @@ -334,11 +348,13 @@ impl Result { } } - /// Converts from `Result` to `Option` + /// Converts from `Result` to [`Option`]. /// - /// Converts `self` into an `Option`, consuming `self`, + /// Converts `self` into an [`Option`], consuming `self`, /// and discarding the success value, if any. /// + /// [`Option`]: ../../std/option/enum.Option.html + /// /// # Examples /// /// Basic usage: @@ -363,7 +379,7 @@ impl Result { // Adapter for working with references ///////////////////////////////////////////////////////////////////////// - /// Converts from `Result` to `Result<&T, &E>` + /// Converts from `Result` to `Result<&T, &E>`. /// /// Produces a new `Result`, containing a reference /// into the original, leaving the original in place. @@ -388,7 +404,7 @@ impl Result { } } - /// Converts from `Result` to `Result<&mut T, &mut E>` + /// Converts from `Result` to `Result<&mut T, &mut E>`. /// /// # Examples /// @@ -563,7 +579,7 @@ impl Result { /// 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. /// /// # Examples /// @@ -646,7 +662,7 @@ impl Result { } /// Unwraps a result, yielding the content of an `Ok`. - /// Else it returns `optb`. + /// Else, it returns `optb`. /// /// # Examples /// @@ -837,7 +853,10 @@ impl<'a, T, E> IntoIterator for &'a mut Result { // The Result Iterators ///////////////////////////////////////////////////////////////////////////// -/// An iterator over a reference to the `Ok` variant of a `Result`. +/// An iterator over a reference to the [`Ok`] variant of a [`Result`]. +/// +/// [`Ok`]: enum.Result.html#variant.Ok +/// [`Result`]: enum.Result.html #[derive(Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub struct Iter<'a, T: 'a> { inner: Option<&'a T> } @@ -872,7 +891,10 @@ impl<'a, T> Clone for Iter<'a, T> { fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } } } -/// An iterator over a mutable reference to the `Ok` variant of a `Result`. +/// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`]. +/// +/// [`Ok`]: enum.Result.html#variant.Ok +/// [`Result`]: enum.Result.html #[derive(Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> } @@ -902,10 +924,11 @@ impl<'a, T> ExactSizeIterator for IterMut<'a, T> {} #[unstable(feature = "fused", issue = "35602")] impl<'a, T> FusedIterator for IterMut<'a, T> {} -/// An iterator over the value in a `Ok` variant of a `Result`. This struct is +/// An iterator over the value in a [`Ok`] variant of a [`Result`]. This struct is /// created by the [`into_iter`] method on [`Result`][`Result`] (provided by /// the [`IntoIterator`] trait). /// +/// [`Ok`]: enum.Result.html#variant.Ok /// [`Result`]: enum.Result.html /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter /// [`IntoIterator`]: ../iter/trait.IntoIterator.html diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index b22bdb43414..7b147faccd2 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -755,11 +755,13 @@ impl ops::IndexMut> for [T] { #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> Default for &'a [T] { + /// Creates an empty slice. fn default() -> &'a [T] { &[] } } #[stable(feature = "mut_slice_default", since = "1.5.0")] impl<'a, T> Default for &'a mut [T] { + /// Creates a mutable empty slice. fn default() -> &'a mut [T] { &mut [] } } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 18e43c02c64..1f1ae6f12ab 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1987,5 +1987,6 @@ impl AsRef<[u8]> for str { #[stable(feature = "rust1", since = "1.0.0")] impl<'a> Default for &'a str { + /// Creates an empty str fn default() -> &'a str { "" } } diff --git a/src/libcore/sync/atomic.rs b/src/libcore/sync/atomic.rs index 75ddd2021a8..f5f37be52de 100644 --- a/src/libcore/sync/atomic.rs +++ b/src/libcore/sync/atomic.rs @@ -95,6 +95,7 @@ pub struct AtomicBool { #[cfg(target_has_atomic = "8")] #[stable(feature = "rust1", since = "1.0.0")] impl Default for AtomicBool { + /// Creates an `AtomicBool` initialised as false. fn default() -> Self { Self::new(false) } @@ -117,6 +118,7 @@ pub struct AtomicPtr { #[cfg(target_has_atomic = "ptr")] #[stable(feature = "rust1", since = "1.0.0")] impl Default for AtomicPtr { + /// Creates a null `AtomicPtr`. fn default() -> AtomicPtr { AtomicPtr::new(::ptr::null_mut()) } diff --git a/src/librand/reseeding.rs b/src/librand/reseeding.rs index c7d560eb1f8..48395c12faf 100644 --- a/src/librand/reseeding.rs +++ b/src/librand/reseeding.rs @@ -113,6 +113,7 @@ impl Reseeder for ReseedWithDefault { } #[stable(feature = "rust1", since = "1.0.0")] impl Default for ReseedWithDefault { + /// Creates an instance of `ReseedWithDefault`. fn default() -> ReseedWithDefault { ReseedWithDefault } @@ -137,6 +138,7 @@ mod tests { } } impl Default for Counter { + /// Constructs a `Counter` with initial value zero. fn default() -> Counter { Counter { i: 0 } } diff --git a/src/librustc/ty/layout.rs b/src/librustc/ty/layout.rs index e3f3da916a0..6fec698cfac 100644 --- a/src/librustc/ty/layout.rs +++ b/src/librustc/ty/layout.rs @@ -45,6 +45,7 @@ pub struct TargetDataLayout { } impl Default for TargetDataLayout { + /// Creates an instance of `TargetDataLayout`. fn default() -> TargetDataLayout { TargetDataLayout { endian: Endian::Big, diff --git a/src/librustc_data_structures/fnv.rs b/src/librustc_data_structures/fnv.rs index 47f623266f3..ae90c2fac83 100644 --- a/src/librustc_data_structures/fnv.rs +++ b/src/librustc_data_structures/fnv.rs @@ -35,6 +35,7 @@ pub fn FnvHashSet() -> FnvHashSet { pub struct FnvHasher(u64); impl Default for FnvHasher { + /// Creates a `FnvHasher`, with a 64-bit hex initial value. #[inline] fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs index 74f88433b35..29add1f9b9d 100644 --- a/src/librustc_resolve/resolve_imports.rs +++ b/src/librustc_resolve/resolve_imports.rs @@ -109,6 +109,7 @@ enum SingleImports<'a> { } impl<'a> Default for SingleImports<'a> { + /// Creates a `SingleImports<'a>` of None type. fn default() -> Self { SingleImports::None } diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index 6cb79d6e863..855588a4c3a 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -33,7 +33,8 @@ use syntax::parse; use syntax_pos::Span; /// Highlights `src`, returning the HTML output. -pub fn render_with_highlighting(src: &str, class: Option<&str>, id: Option<&str>) -> String { +pub fn render_with_highlighting(src: &str, class: Option<&str>, id: Option<&str>, + extension: Option<&str>) -> String { debug!("highlighting: ================\n{}\n==============", src); let sess = parse::ParseSess::new(); let fm = sess.codemap().new_filemap("".to_string(), None, src.to_string()); @@ -47,6 +48,9 @@ pub fn render_with_highlighting(src: &str, class: Option<&str>, id: Option<&str> return format!("
{}
", src); } + if let Some(extension) = extension { + write!(out, "{}", extension).unwrap(); + } write_footer(&mut out).unwrap(); String::from_utf8_lossy(&out[..]).into_owned() } diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 139e1033175..aff5a964f75 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -262,9 +262,11 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result { &Default::default()); s.push_str(&format!("{}", Escape(&test))); }); - s.push_str(&highlight::render_with_highlighting(&text, - Some("rust-example-rendered"), - None)); + s.push_str(&highlight::render_with_highlighting( + &text, + Some("rust-example-rendered"), + None, + Some("
Run"))); let output = CString::new(s).unwrap(); hoedown_buffer_puts(ob, output.as_ptr()); }) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index f352e39071c..82ef68745a1 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -2963,7 +2963,7 @@ impl<'a> fmt::Display for Source<'a> { write!(fmt, "{0:1$}\n", i, cols)?; } write!(fmt, "")?; - write!(fmt, "{}", highlight::render_with_highlighting(s, None, None))?; + write!(fmt, "{}", highlight::render_with_highlighting(s, None, None, None))?; Ok(()) } } @@ -2972,6 +2972,7 @@ fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, t: &clean::Macro) -> fmt::Result { w.write_str(&highlight::render_with_highlighting(&t.source, Some("macro"), + None, None))?; render_stability_since_raw(w, it.stable_since(), None)?; document(w, cx, it) diff --git a/src/librustdoc/html/static/playpen.js b/src/librustdoc/html/static/playpen.js index 8f8a753b06c..cad97c04e1a 100644 --- a/src/librustdoc/html/static/playpen.js +++ b/src/librustdoc/html/static/playpen.js @@ -27,9 +27,7 @@ document.addEventListener('DOMContentLoaded', function() { return; } - var a = document.createElement('a'); - a.setAttribute('class', 'test-arrow'); - a.textContent = 'Run'; + var a = el.querySelectorAll('a.test-arrow')[0]; var code = el.previousElementSibling.textContent; @@ -40,17 +38,6 @@ document.addEventListener('DOMContentLoaded', function() { a.setAttribute('href', window.playgroundUrl + '?code=' + encodeURIComponent(code) + channel); - a.setAttribute('target', '_blank'); - - el.appendChild(a); - }; - - el.onmouseout = function(e) { - if (el.contains(e.relatedTarget)) { - return; - } - - el.removeChild(el.querySelectorAll('a.test-arrow')[0]); }; }); }); diff --git a/src/librustdoc/html/static/rustdoc.css b/src/librustdoc/html/static/rustdoc.css index c97cacd10c3..2884320b82e 100644 --- a/src/librustdoc/html/static/rustdoc.css +++ b/src/librustdoc/html/static/rustdoc.css @@ -568,15 +568,18 @@ pre.rust .lifetime { color: #B76514; } .rusttest { display: none; } pre.rust { position: relative; } a.test-arrow { + background-color: rgba(78, 139, 202, 0.2); display: inline-block; position: absolute; - background-color: #4e8bca; padding: 5px 10px 5px 10px; border-radius: 5px; font-size: 130%; top: 5px; right: 5px; } +a.test-arrow:hover{ + background-color: #4e8bca; +} .section-header:hover a:after { content: '\2002\00a7\2002'; diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 4eb2c8f0644..eb1653f18cb 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -1218,6 +1218,7 @@ impl Default for HashMap where K: Eq + Hash, S: BuildHasher + Default, { + /// Creates an empty `HashMap`, with the `Default` value for the hasher. fn default() -> HashMap { HashMap::with_hasher(Default::default()) } @@ -2026,6 +2027,7 @@ impl Hasher for DefaultHasher { #[stable(feature = "rust1", since = "1.0.0")] impl Default for RandomState { + /// Constructs a new `RandomState`. #[inline] fn default() -> RandomState { RandomState::new() diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index ca5137e9573..ff56747fee6 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -665,6 +665,7 @@ impl Default for HashSet where T: Eq + Hash, S: BuildHasher + Default, { + /// Creates an empty `HashSet` with the `Default` value for the hasher. fn default() -> HashSet { HashSet::with_hasher(Default::default()) } diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 2d5e8c04194..1c449712e1f 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -361,6 +361,7 @@ impl<'a> Default for &'a CStr { #[stable(feature = "cstr_default", since = "1.10.0")] impl Default for CString { + /// Creates an empty `CString`. fn default() -> CString { let a: &CStr = Default::default(); a.to_owned() diff --git a/src/libstd/ffi/os_str.rs b/src/libstd/ffi/os_str.rs index 36cf4ef758d..d93d3c73622 100644 --- a/src/libstd/ffi/os_str.rs +++ b/src/libstd/ffi/os_str.rs @@ -170,6 +170,7 @@ impl ops::Deref for OsString { #[stable(feature = "osstring_default", since = "1.9.0")] impl Default for OsString { + /// Constructs an empty `OsString`. #[inline] fn default() -> OsString { OsString::new() @@ -342,6 +343,7 @@ impl OsStr { #[stable(feature = "osstring_default", since = "1.9.0")] impl<'a> Default for &'a OsStr { + /// Creates an empty `OsStr`. #[inline] fn default() -> &'a OsStr { OsStr::new("") diff --git a/src/libstd/net/ip.rs b/src/libstd/net/ip.rs index c6a7a77e68a..05ef559422f 100644 --- a/src/libstd/net/ip.rs +++ b/src/libstd/net/ip.rs @@ -22,6 +22,24 @@ use sys::net::netc as c; use sys_common::{AsInner, FromInner}; /// An IP address, either an IPv4 or IPv6 address. +/// +/// # Examples +/// +/// Constructing an IPv4 address: +/// +/// ``` +/// use std::net::{IpAddr, Ipv4Addr}; +/// +/// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); +/// ``` +/// +/// Constructing an IPv6 address: +/// +/// ``` +/// use std::net::{IpAddr, Ipv6Addr}; +/// +/// IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); +/// ``` #[stable(feature = "ip_addr", since = "1.7.0")] #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)] pub enum IpAddr { diff --git a/src/libstd/sync/condvar.rs b/src/libstd/sync/condvar.rs index 4c946e613ea..3db8b05b954 100644 --- a/src/libstd/sync/condvar.rs +++ b/src/libstd/sync/condvar.rs @@ -241,6 +241,7 @@ impl Condvar { #[stable(feature = "condvar_default", since = "1.9.0")] impl Default for Condvar { + /// Creates a `Condvar` which is ready to be waited on and notified. fn default() -> Condvar { Condvar::new() } diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index c8ae88c2331..098a3e44258 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -287,6 +287,7 @@ impl Drop for Mutex { #[stable(feature = "mutex_default", since = "1.9.0")] impl Default for Mutex { + /// Creates a `Mutex`, with the `Default` value for T. fn default() -> Mutex { Mutex::new(Default::default()) } diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 4801bcffd08..7f053c6704b 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -311,6 +311,7 @@ impl fmt::Debug for RwLock { #[stable(feature = "rw_lock_default", since = "1.9.0")] impl Default for RwLock { + /// Creates a new `RwLock`, with the `Default` value for T. fn default() -> RwLock { RwLock::new(Default::default()) } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 105f911dd57..40c8ba93bd5 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -362,6 +362,7 @@ impl Generics { } impl Default for Generics { + /// Creates an instance of `Generics`. fn default() -> Generics { Generics { lifetimes: Vec::new(), diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index c3f8a977a65..58750158931 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -154,6 +154,7 @@ impl P<[T]> { } impl Default for P<[T]> { + /// Creates an empty `P<[T]>`. fn default() -> P<[T]> { P::new() }