about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/collections/hash/map.rs4
-rw-r--r--src/libstd/io/error.rs4
-rw-r--r--src/libstd/net/udp.rs20
-rw-r--r--src/libstd/path.rs117
-rw-r--r--src/libstd/sync/mutex.rs80
-rw-r--r--src/libstd/time/mod.rs129
6 files changed, 309 insertions, 45 deletions
diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs
index 2fa3a9c4844..a314717a877 100644
--- a/src/libstd/collections/hash/map.rs
+++ b/src/libstd/collections/hash/map.rs
@@ -1779,11 +1779,11 @@ impl<'a, K, V> Entry<'a, K, V> {
     /// use std::collections::HashMap;
     ///
     /// let mut map: HashMap<&str, String> = HashMap::new();
-    /// let s = "hoho".to_owned();
+    /// let s = "hoho".to_string();
     ///
     /// map.entry("poneyland").or_insert_with(|| s);
     ///
-    /// assert_eq!(map["poneyland"], "hoho".to_owned());
+    /// assert_eq!(map["poneyland"], "hoho".to_string());
     /// ```
     pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
         match self {
diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs
index 795c89c0007..434f522cc1e 100644
--- a/src/libstd/io/error.rs
+++ b/src/libstd/io/error.rs
@@ -388,12 +388,12 @@ impl Error {
     /// impl MyError {
     ///     fn new() -> MyError {
     ///         MyError {
-    ///             v: "oh no!".to_owned()
+    ///             v: "oh no!".to_string()
     ///         }
     ///     }
     ///
     ///     fn change_message(&mut self, new_message: &str) {
-    ///         self.v = new_message.to_owned();
+    ///         self.v = new_message.to_string();
     ///     }
     /// }
     ///
diff --git a/src/libstd/net/udp.rs b/src/libstd/net/udp.rs
index f8a5ec0b379..a9a19aee5d1 100644
--- a/src/libstd/net/udp.rs
+++ b/src/libstd/net/udp.rs
@@ -883,11 +883,23 @@ mod tests {
 
     #[test]
     fn set_nonblocking() {
-        let addr = next_test_ip4();
+        each_ip(&mut |addr, _| {
+            let socket = t!(UdpSocket::bind(&addr));
 
-        let stream = t!(UdpSocket::bind(&addr));
+            t!(socket.set_nonblocking(true));
+            t!(socket.set_nonblocking(false));
+
+            t!(socket.connect(addr));
 
-        t!(stream.set_nonblocking(true));
-        t!(stream.set_nonblocking(false));
+            t!(socket.set_nonblocking(false));
+            t!(socket.set_nonblocking(true));
+
+            let mut buf = [0];
+            match socket.recv(&mut buf) {
+                Ok(_) => panic!("expected error"),
+                Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
+                Err(e) => panic!("unexpected error {}", e),
+            }
+        })
     }
 }
diff --git a/src/libstd/path.rs b/src/libstd/path.rs
index 3f9bf70adde..bf105a50d64 100644
--- a/src/libstd/path.rs
+++ b/src/libstd/path.rs
@@ -10,9 +10,9 @@
 
 //! Cross-platform path manipulation.
 //!
-//! This module provides two types, `PathBuf` and `Path` (akin to `String` and
-//! `str`), for working with paths abstractly. These types are thin wrappers
-//! around `OsString` and `OsStr` respectively, meaning that they work directly
+//! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`]
+//! and [`str`]), for working with paths abstractly. These types are thin wrappers
+//! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly
 //! on strings according to the local platform's path syntax.
 //!
 //! ## Simple usage
@@ -20,10 +20,10 @@
 //! Path manipulation includes both parsing components from slices and building
 //! new owned paths.
 //!
-//! To parse a path, you can create a `Path` slice from a `str`
+//! To parse a path, you can create a [`Path`] slice from a [`str`]
 //! slice and start asking questions:
 //!
-//! ```rust
+//! ```
 //! use std::path::Path;
 //! use std::ffi::OsStr;
 //!
@@ -39,9 +39,9 @@
 //! assert_eq!(extension, Some(OsStr::new("txt")));
 //! ```
 //!
-//! To build or modify paths, use `PathBuf`:
+//! To build or modify paths, use [`PathBuf`]:
 //!
-//! ```rust
+//! ```
 //! use std::path::PathBuf;
 //!
 //! let mut path = PathBuf::from("c:\\");
@@ -103,6 +103,13 @@
 //! that `b` is a symbolic link (so its parent isn't `a`). Further
 //! normalization is possible to build on top of the components APIs,
 //! and will be included in this library in the near future.
+//!
+//! [`PathBuf`]: ../../std/path/struct.PathBuf.html
+//! [`Path`]: ../../std/path/struct.Path.html
+//! [`String`]: ../../std/string/struct.String.html
+//! [`str`]: ../../std/primitive.str.html
+//! [`OsString`]: ../../std/ffi/struct.OsString.html
+//! [`OsStr`]: ../../std/ffi/struct.OsStr.html
 
 #![stable(feature = "rust1", since = "1.0.0")]
 
@@ -527,7 +534,9 @@ pub struct Components<'a> {
     back: State,
 }
 
-/// An iterator over the components of a path, as `OsStr` slices.
+/// An iterator over the components of a path, as [`OsStr`] slices.
+///
+/// [`OsStr`]: ../../std/ffi/struct.OsStr.html
 #[derive(Clone)]
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Iter<'a> {
@@ -1089,10 +1098,11 @@ impl PathBuf {
 
     /// Updates [`self.file_name()`] to `file_name`.
     ///
-    /// If [`self.file_name()`] was `None`, this is equivalent to pushing
+    /// If [`self.file_name()`] was [`None`], this is equivalent to pushing
     /// `file_name`.
     ///
     /// [`self.file_name()`]: struct.PathBuf.html#method.file_name
+    /// [`None`]: ../../std/option/enum.Option.html#variant.None
     ///
     /// # Examples
     ///
@@ -1124,11 +1134,12 @@ impl PathBuf {
     ///
     /// If [`self.file_name()`] is `None`, does nothing and returns `false`.
     ///
-    /// Otherwise, returns `true`; if [`self.extension()`] is `None`, the
+    /// Otherwise, returns `true`; if [`self.extension()`] is [`None`], the
     /// extension is added; otherwise it is replaced.
     ///
     /// [`self.file_name()`]: struct.PathBuf.html#method.file_name
     /// [`self.extension()`]: struct.PathBuf.html#method.extension
+    /// [`None`]: ../../std/option/enum.Option.html#variant.None
     ///
     /// # Examples
     ///
@@ -1356,8 +1367,10 @@ pub struct Path {
     inner: OsStr,
 }
 
-/// An error returned from the `Path::strip_prefix` method indicating that the
+/// An error returned from the [`Path::strip_prefix`] method indicating that the
 /// prefix was not found in `self`.
+///
+/// [`Path::strip_prefix`]: struct.Path.html#method.strip_prefix
 #[derive(Debug, Clone, PartialEq, Eq)]
 #[stable(since = "1.7.0", feature = "strip_prefix")]
 pub struct StripPrefixError(());
@@ -1539,7 +1552,9 @@ impl Path {
 
     /// The path without its final component, if any.
     ///
-    /// Returns `None` if the path terminates in a root or prefix.
+    /// Returns [`None`] if the path terminates in a root or prefix.
+    ///
+    /// [`None`]: ../../std/option/enum.Option.html#variant.None
     ///
     /// # Examples
     ///
@@ -1570,7 +1585,9 @@ impl Path {
 
     /// The final component of the path, if it is a normal file.
     ///
-    /// If the path terminates in `..`, `file_name` will return `None`.
+    /// If the path terminates in `..`, `file_name` will return [`None`].
+    ///
+    /// [`None`]: ../../std/option/enum.Option.html#variant.None
     ///
     /// # Examples
     ///
@@ -1608,8 +1625,11 @@ impl Path {
     ///
     /// # Errors
     ///
-    /// If `base` is not a prefix of `self` (i.e. `starts_with`
-    /// returns `false`), returns `Err`.
+    /// If `base` is not a prefix of `self` (i.e. [`starts_with`]
+    /// returns `false`), returns [`Err`].
+    ///
+    /// [`starts_with`]: #method.starts_with
+    /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
     ///
     /// # Examples
     ///
@@ -1689,11 +1709,13 @@ impl Path {
     ///
     /// The stem is:
     ///
-    /// * None, if there is no file name;
+    /// * [`None`], if there is no file name;
     /// * The entire file name if there is no embedded `.`;
     /// * The entire file name if the file name begins with `.` and has no other `.`s within;
     /// * Otherwise, the portion of the file name before the final `.`
     ///
+    /// [`None`]: ../../std/option/enum.Option.html#variant.None
+    ///
     /// # Examples
     ///
     /// ```
@@ -1710,15 +1732,16 @@ impl Path {
 
     /// Extracts the extension of [`self.file_name()`], if possible.
     ///
-    /// [`self.file_name()`]: struct.Path.html#method.file_name
-    ///
     /// The extension is:
     ///
-    /// * None, if there is no file name;
-    /// * None, if there is no embedded `.`;
-    /// * None, if the file name begins with `.` and has no other `.`s within;
+    /// * [`None`], if there is no file name;
+    /// * [`None`], if there is no embedded `.`;
+    /// * [`None`], if the file name begins with `.` and has no other `.`s within;
     /// * Otherwise, the portion of the file name after the final `.`
     ///
+    /// [`self.file_name()`]: struct.Path.html#method.file_name
+    /// [`None`]: ../../std/option/enum.Option.html#variant.None
+    ///
     /// # Examples
     ///
     /// ```
@@ -1877,7 +1900,6 @@ impl Path {
         Display { path: self }
     }
 
-
     /// Query the file system to get information about a file, directory, etc.
     ///
     /// This function will traverse symbolic links to query information about the
@@ -1886,6 +1908,16 @@ impl Path {
     /// This is an alias to [`fs::metadata`].
     ///
     /// [`fs::metadata`]: ../fs/fn.metadata.html
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// use std::path::Path;
+    ///
+    /// let path = Path::new("/Minas/tirith");
+    /// let metadata = path.metadata().expect("metadata call failed");
+    /// println!("{:?}", metadata.file_type());
+    /// ```
     #[stable(feature = "path_ext", since = "1.5.0")]
     pub fn metadata(&self) -> io::Result<fs::Metadata> {
         fs::metadata(self)
@@ -1896,6 +1928,16 @@ impl Path {
     /// This is an alias to [`fs::symlink_metadata`].
     ///
     /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// use std::path::Path;
+    ///
+    /// let path = Path::new("/Minas/tirith");
+    /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
+    /// println!("{:?}", metadata.file_type());
+    /// ```
     #[stable(feature = "path_ext", since = "1.5.0")]
     pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
         fs::symlink_metadata(self)
@@ -1907,6 +1949,15 @@ impl Path {
     /// This is an alias to [`fs::canonicalize`].
     ///
     /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// use std::path::{Path, PathBuf};
+    ///
+    /// let path = Path::new("/foo/test/../test/bar.rs");
+    /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
+    /// ```
     #[stable(feature = "path_ext", since = "1.5.0")]
     pub fn canonicalize(&self) -> io::Result<PathBuf> {
         fs::canonicalize(self)
@@ -1917,6 +1968,15 @@ impl Path {
     /// This is an alias to [`fs::read_link`].
     ///
     /// [`fs::read_link`]: ../fs/fn.read_link.html
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// use std::path::Path;
+    ///
+    /// let path = Path::new("/laputa/sky_castle.rs");
+    /// let path_link = path.read_link().expect("read_link call failed");
+    /// ```
     #[stable(feature = "path_ext", since = "1.5.0")]
     pub fn read_link(&self) -> io::Result<PathBuf> {
         fs::read_link(self)
@@ -1932,6 +1992,19 @@ impl Path {
     /// [`io::Result`]: ../io/type.Result.html
     /// [`DirEntry`]: ../fs/struct.DirEntry.html
     /// [`fs::read_dir`]: ../fs/fn.read_dir.html
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// use std::path::Path;
+    ///
+    /// let path = Path::new("/laputa");
+    /// for entry in path.read_dir().expect("read_dir call failed") {
+    ///     if let Ok(entry) = entry {
+    ///         println!("{:?}", entry.path());
+    ///     }
+    /// }
+    /// ```
     #[stable(feature = "path_ext", since = "1.5.0")]
     pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
         fs::read_dir(self)
diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs
index f8426e3b578..2efddeb4610 100644
--- a/src/libstd/sync/mutex.rs
+++ b/src/libstd/sync/mutex.rs
@@ -155,6 +155,14 @@ impl<'a, T: ?Sized> !marker::Send for MutexGuard<'a, T> {}
 
 impl<T> Mutex<T> {
     /// Creates a new mutex in an unlocked state ready for use.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::sync::Mutex;
+    ///
+    /// let mutex = Mutex::new(0);
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn new(t: T) -> Mutex<T> {
         let mut m = Mutex {
@@ -190,6 +198,21 @@ impl<T: ?Sized> Mutex<T> {
     ///
     /// This function might panic when called if the lock is already held by
     /// the current thread.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::sync::{Arc, Mutex};
+    /// use std::thread;
+    ///
+    /// let mutex = Arc::new(Mutex::new(0));
+    /// let c_mutex = mutex.clone();
+    ///
+    /// thread::spawn(move || {
+    ///     *c_mutex.lock().unwrap() = 10;
+    /// }).join().expect("thread::spawn failed");
+    /// assert_eq!(*mutex.lock().unwrap(), 10);
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn lock(&self) -> LockResult<MutexGuard<T>> {
         unsafe {
@@ -211,6 +234,26 @@ impl<T: ?Sized> Mutex<T> {
     /// If another user of this mutex panicked while holding the mutex, then
     /// this call will return failure if the mutex would otherwise be
     /// acquired.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::sync::{Arc, Mutex};
+    /// use std::thread;
+    ///
+    /// let mutex = Arc::new(Mutex::new(0));
+    /// let c_mutex = mutex.clone();
+    ///
+    /// thread::spawn(move || {
+    ///     let mut lock = c_mutex.try_lock();
+    ///     if let Ok(ref mut mutex) = lock {
+    ///         **mutex = 10;
+    ///     } else {
+    ///         println!("try_lock failed");
+    ///     }
+    /// }).join().expect("thread::spawn failed");
+    /// assert_eq!(*mutex.lock().unwrap(), 10);
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
         unsafe {
@@ -225,8 +268,24 @@ impl<T: ?Sized> Mutex<T> {
     /// Determines whether the lock is poisoned.
     ///
     /// If another thread is active, the lock can still become poisoned at any
-    /// time.  You should not trust a `false` value for program correctness
+    /// time. You should not trust a `false` value for program correctness
     /// without additional synchronization.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::sync::{Arc, Mutex};
+    /// use std::thread;
+    ///
+    /// let mutex = Arc::new(Mutex::new(0));
+    /// let c_mutex = mutex.clone();
+    ///
+    /// let _ = thread::spawn(move || {
+    ///     let _lock = c_mutex.lock().unwrap();
+    ///     panic!(); // the mutex gets poisoned
+    /// }).join();
+    /// assert_eq!(mutex.is_poisoned(), true);
+    /// ```
     #[inline]
     #[stable(feature = "sync_poison", since = "1.2.0")]
     pub fn is_poisoned(&self) -> bool {
@@ -239,6 +298,15 @@ impl<T: ?Sized> Mutex<T> {
     ///
     /// If another user of this mutex panicked while holding the mutex, then
     /// this call will return an error instead.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::sync::Mutex;
+    ///
+    /// let mutex = Mutex::new(0);
+    /// assert_eq!(mutex.into_inner().unwrap(), 0);
+    /// ```
     #[stable(feature = "mutex_into_inner", since = "1.6.0")]
     pub fn into_inner(self) -> LockResult<T> where T: Sized {
         // We know statically that there are no outstanding references to
@@ -270,6 +338,16 @@ impl<T: ?Sized> Mutex<T> {
     ///
     /// If another user of this mutex panicked while holding the mutex, then
     /// this call will return an error instead.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::sync::Mutex;
+    ///
+    /// let mut mutex = Mutex::new(0);
+    /// *mutex.get_mut().unwrap() = 10;
+    /// assert_eq!(*mutex.lock().unwrap(), 10);
+    /// ```
     #[stable(feature = "mutex_get_mut", since = "1.6.0")]
     pub fn get_mut(&mut self) -> LockResult<&mut T> {
         // We know statically that there are no other references to `self`, so
diff --git a/src/libstd/time/mod.rs b/src/libstd/time/mod.rs
index 6854f1e14fa..e4b8d457e2d 100644
--- a/src/libstd/time/mod.rs
+++ b/src/libstd/time/mod.rs
@@ -34,7 +34,7 @@ pub use self::duration::Duration;
 mod duration;
 
 /// A measurement of a monotonically increasing clock.
-///  Opaque and useful only with `Duration`.
+/// Opaque and useful only with `Duration`.
 ///
 /// Instants are always guaranteed to be greater than any previously measured
 /// instant when created, and are often useful for tasks such as measuring
@@ -73,7 +73,7 @@ pub struct Instant(time::Instant);
 /// A measurement of the system clock, useful for talking to
 /// external entities like the file system or other processes.
 ///
-/// Distinct from the `Instant` type, this time measurement **is not
+/// Distinct from the [`Instant`] type, this time measurement **is not
 /// monotonic**. This means that you can save a file to the file system, then
 /// save another file to the file system, **and the second file has a
 /// `SystemTime` measurement earlier than the first**. In other words, an
@@ -81,15 +81,20 @@ pub struct Instant(time::Instant);
 /// earlier `SystemTime`!
 ///
 /// Consequently, comparing two `SystemTime` instances to learn about the
-/// duration between them returns a `Result` instead of an infallible `Duration`
+/// duration between them returns a [`Result`] instead of an infallible [`Duration`]
 /// to indicate that this sort of time drift may happen and needs to be handled.
 ///
-/// Although a `SystemTime` cannot be directly inspected, the `UNIX_EPOCH`
+/// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
 /// constant is provided in this module as an anchor in time to learn
 /// information about a `SystemTime`. By calculating the duration from this
 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
 /// or perhaps some other string representation.
 ///
+/// [`Instant`]: ../../std/time/struct.Instant.html
+/// [`Result`]: ../../std/result/enum.Result.html
+/// [`Duration`]: ../../std/time/struct.Duration.html
+/// [`UNIX_EPOCH`]: ../../std/time/constant.UNIX_EPOCH.html
+///
 /// Example:
 ///
 /// ```no_run
@@ -117,14 +122,38 @@ pub struct Instant(time::Instant);
 #[stable(feature = "time2", since = "1.8.0")]
 pub struct SystemTime(time::SystemTime);
 
-/// An error returned from the `duration_since` method on `SystemTime`,
-/// used to learn how far in the opposite direction a system time lies.
+/// An error returned from the `duration_since` and `elapsed` methods on
+/// `SystemTime`, used to learn how far in the opposite direction a system time
+/// lies.
+///
+/// # Examples
+///
+/// ```no_run
+/// use std::thread::sleep;
+/// use std::time::{Duration, SystemTime};
+///
+/// let sys_time = SystemTime::now();
+/// sleep(Duration::from_secs(1));
+/// let new_sys_time = SystemTime::now();
+/// match sys_time.duration_since(new_sys_time) {
+///     Ok(_) => {}
+///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
+/// }
+/// ```
 #[derive(Clone, Debug)]
 #[stable(feature = "time2", since = "1.8.0")]
 pub struct SystemTimeError(Duration);
 
 impl Instant {
     /// Returns an instant corresponding to "now".
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::time::Instant;
+    ///
+    /// let now = Instant::now();
+    /// ```
     #[stable(feature = "time2", since = "1.8.0")]
     pub fn now() -> Instant {
         Instant(time::Instant::now())
@@ -138,6 +167,18 @@ impl Instant {
     /// only be possible if `earlier` was created after `self`. Because
     /// `Instant` is monotonic, the only time that this should happen should be
     /// a bug.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// use std::time::{Duration, Instant};
+    /// use std::thread::sleep;
+    ///
+    /// let now = Instant::now();
+    /// sleep(Duration::new(1, 0));
+    /// let new_now = Instant::now();
+    /// println!("{:?}", new_now.duration_since(now));
+    /// ```
     #[stable(feature = "time2", since = "1.8.0")]
     pub fn duration_since(&self, earlier: Instant) -> Duration {
         self.0.sub_instant(&earlier.0)
@@ -218,6 +259,14 @@ impl fmt::Debug for Instant {
 
 impl SystemTime {
     /// Returns the system time corresponding to "now".
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::time::SystemTime;
+    ///
+    /// let sys_time = SystemTime::now();
+    /// ```
     #[stable(feature = "time2", since = "1.8.0")]
     pub fn now() -> SystemTime {
         SystemTime(time::SystemTime::now())
@@ -229,11 +278,26 @@ impl SystemTime {
     /// guaranteed to always be before later measurements (due to anomalies such
     /// as the system clock being adjusted either forwards or backwards).
     ///
-    /// If successful, `Ok(Duration)` is returned where the duration represents
+    /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
     /// the amount of time elapsed from the specified measurement to this one.
     ///
-    /// Returns an `Err` if `earlier` is later than `self`, and the error
+    /// Returns an [`Err`] if `earlier` is later than `self`, and the error
     /// contains how far from `self` the time is.
+    ///
+    /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
+    /// [`Duration`]: ../../std/time/struct.Duration.html
+    /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::time::SystemTime;
+    ///
+    /// let sys_time = SystemTime::now();
+    /// let difference = sys_time.duration_since(sys_time)
+    ///                          .expect("SystemTime::duration_since failed");
+    /// println!("{:?}", difference);
+    /// ```
     #[stable(feature = "time2", since = "1.8.0")]
     pub fn duration_since(&self, earlier: SystemTime)
                           -> Result<Duration, SystemTimeError> {
@@ -244,12 +308,28 @@ impl SystemTime {
     ///
     /// This function may fail as the underlying system clock is susceptible to
     /// drift and updates (e.g. the system clock could go backwards), so this
-    /// function may not always succeed. If successful, `Ok(duration)` is
+    /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
     /// returned where the duration represents the amount of time elapsed from
     /// this time measurement to the current time.
     ///
-    /// Returns an `Err` if `self` is later than the current system time, and
+    /// Returns an [`Err`] if `self` is later than the current system time, and
     /// the error contains how far from the current system time `self` is.
+    ///
+    /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
+    /// [`Duration`]: ../../std/time/struct.Duration.html
+    /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// use std::thread::sleep;
+    /// use std::time::{Duration, SystemTime};
+    ///
+    /// let sys_time = SystemTime::now();
+    /// let one_sec = Duration::from_secs(1);
+    /// sleep(one_sec);
+    /// assert!(sys_time.elapsed().unwrap() >= one_sec);
+    /// ```
     #[stable(feature = "time2", since = "1.8.0")]
     pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
         SystemTime::now().duration_since(*self)
@@ -300,9 +380,11 @@ impl fmt::Debug for SystemTime {
 ///
 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
 /// respect to the system clock. Using `duration_since` on an existing
-/// `SystemTime` instance can tell how far away from this point in time a
+/// [`SystemTime`] instance can tell how far away from this point in time a
 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
-/// `SystemTime` instance to represent another fixed point in time.
+/// [`SystemTime`] instance to represent another fixed point in time.
+///
+/// [`SystemTime`]: ../../std/time/struct.SystemTime.html
 #[stable(feature = "time2", since = "1.8.0")]
 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
 
@@ -310,9 +392,28 @@ impl SystemTimeError {
     /// Returns the positive duration which represents how far forward the
     /// second system time was from the first.
     ///
-    /// A `SystemTimeError` is returned from the `duration_since`
-    /// operation whenever the second system time represents a point later
+    /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
+    /// methods of [`SystemTime`] whenever the second system time represents a point later
     /// in time than the `self` of the method call.
+    ///
+    /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
+    /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
+    /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// use std::thread::sleep;
+    /// use std::time::{Duration, SystemTime};
+    ///
+    /// let sys_time = SystemTime::now();
+    /// sleep(Duration::from_secs(1));
+    /// let new_sys_time = SystemTime::now();
+    /// match sys_time.duration_since(new_sys_time) {
+    ///     Ok(_) => {}
+    ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
+    /// }
+    /// ```
     #[stable(feature = "time2", since = "1.8.0")]
     pub fn duration(&self) -> Duration {
         self.0