diff --git a/src/doc/book/ffi.md b/src/doc/book/ffi.md index 41457ee67a5fd..50d4d0170fc70 100644 --- a/src/doc/book/ffi.md +++ b/src/doc/book/ffi.md @@ -309,7 +309,7 @@ However it is often desired that the callback is targeted to a special Rust object. This could be the object that represents the wrapper for the respective C object. -This can be achieved by passing an raw pointer to the object down to the +This can be achieved by passing a raw pointer to the object down to the C library. The C library can then include the pointer to the Rust object in the notification. This will allow the callback to unsafely access the referenced Rust object. diff --git a/src/doc/nomicon/dropck.md b/src/doc/nomicon/dropck.md index ad7c65032c769..f54933827b330 100644 --- a/src/doc/nomicon/dropck.md +++ b/src/doc/nomicon/dropck.md @@ -125,7 +125,7 @@ is that some Drop implementations will not access borrowed data even though their type gives them the capability for such access. For example, this variant of the above `Inspector` example will never -accessed borrowed data: +access borrowed data: ```rust,ignore struct Inspector<'a>(&'a u8, &'static str); diff --git a/src/doc/nomicon/unbounded-lifetimes.md b/src/doc/nomicon/unbounded-lifetimes.md index 1f2961b586136..1f3693f542f35 100644 --- a/src/doc/nomicon/unbounded-lifetimes.md +++ b/src/doc/nomicon/unbounded-lifetimes.md @@ -11,7 +11,7 @@ lifetime can be regarded as `'static`. Almost no reference is `'static`, so this is probably wrong. `transmute` and `transmute_copy` are the two other primary offenders. One should endeavor to -bound an unbounded lifetime as quick as possible, especially across function +bound an unbounded lifetime as quickly as possible, especially across function boundaries. Given a function, any output lifetimes that don't derive from inputs are diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index 98c71967f3c39..85e1e133b7d9a 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -1990,11 +1990,11 @@ impl<'a, K: Ord, V> Entry<'a, K, V> { /// use std::collections::BTreeMap; /// /// let mut map: BTreeMap<&str, String> = BTreeMap::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()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn or_insert_with V>(self, default: F) -> &'a mut V { diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index b5e6669220535..805021516db71 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -423,7 +423,7 @@ impl [T] { core_slice::SliceExt::get_unchecked_mut(self, index) } - /// Returns an raw pointer to the slice's buffer. + /// Returns a raw pointer to the slice's buffer. /// /// The caller must ensure that the slice outlives the pointer this /// function returns, or else it will end up pointing to garbage. diff --git a/src/libcompiler_builtins/build.rs b/src/libcompiler_builtins/build.rs index 6a766fc02df3e..ab9a71e1ec6a6 100644 --- a/src/libcompiler_builtins/build.rs +++ b/src/libcompiler_builtins/build.rs @@ -236,10 +236,6 @@ fn main() { "atomic_thread_fence.c"]); } - if !target.contains("redox") && !target.contains("windows") { - sources.extend(&["emutls.c"]); - } - if target.contains("msvc") { if target.contains("x86_64") { sources.extend(&["x86_64/floatdidf.c", "x86_64/floatdisf.c", "x86_64/floatdixf.c"]); diff --git a/src/libcore/any.rs b/src/libcore/any.rs index eb0636e8576be..78f3cd5576e1e 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -101,7 +101,7 @@ pub trait Any: 'static { /// /// fn main() { /// assert_eq!(is_string(&0), false); - /// assert_eq!(is_string(&"cookie monster".to_owned()), true); + /// assert_eq!(is_string(&"cookie monster".to_string()), true); /// } /// ``` #[unstable(feature = "get_type_id", @@ -154,7 +154,7 @@ impl Any { /// /// fn main() { /// is_string(&0); - /// is_string(&"cookie monster".to_owned()); + /// is_string(&"cookie monster".to_string()); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -188,7 +188,7 @@ impl Any { /// /// fn main() { /// print_if_string(&0); - /// print_if_string(&"cookie monster".to_owned()); + /// print_if_string(&"cookie monster".to_string()); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -219,7 +219,7 @@ impl Any { /// /// fn main() { /// let mut x = 10u32; - /// let mut s = "starlord".to_owned(); + /// let mut s = "starlord".to_string(); /// /// modify_if_u32(&mut x); /// modify_if_u32(&mut s); @@ -259,7 +259,7 @@ impl Any+Send { /// /// fn main() { /// is_string(&0); - /// is_string(&"cookie monster".to_owned()); + /// is_string(&"cookie monster".to_string()); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -285,7 +285,7 @@ impl Any+Send { /// /// fn main() { /// print_if_string(&0); - /// print_if_string(&"cookie monster".to_owned()); + /// print_if_string(&"cookie monster".to_string()); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -309,7 +309,7 @@ impl Any+Send { /// /// fn main() { /// let mut x = 10u32; - /// let mut s = "starlord".to_owned(); + /// let mut s = "starlord".to_string(); /// /// modify_if_u32(&mut x); /// modify_if_u32(&mut s); @@ -359,7 +359,7 @@ impl TypeId { /// /// fn main() { /// assert_eq!(is_string(&0), false); - /// assert_eq!(is_string(&"cookie monster".to_owned()), true); + /// assert_eq!(is_string(&"cookie monster".to_string()), true); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/libcore/iter/iterator.rs b/src/libcore/iter/iterator.rs index ec590d2bd06f8..91c09c5530565 100644 --- a/src/libcore/iter/iterator.rs +++ b/src/libcore/iter/iterator.rs @@ -1612,7 +1612,7 @@ pub trait Iterator { /// Returns the maximum element of an iterator. /// - /// If the two elements are equally maximum, the latest element is + /// If several elements are equally maximum, the last element is /// returned. /// /// # Examples @@ -1638,7 +1638,7 @@ pub trait Iterator { /// Returns the minimum element of an iterator. /// - /// If the two elements are equally minimum, the first element is + /// If several elements are equally minimum, the first element is /// returned. /// /// # Examples @@ -1665,8 +1665,8 @@ pub trait Iterator { /// Returns the element that gives the maximum value from the /// specified function. /// - /// Returns the rightmost element if the comparison determines two elements - /// to be equally maximum. + /// If several elements are equally maximum, the last element is + /// returned. /// /// # Examples /// @@ -1690,8 +1690,8 @@ pub trait Iterator { /// Returns the element that gives the maximum value with respect to the /// specified comparison function. /// - /// Returns the rightmost element if the comparison determines two elements - /// to be equally maximum. + /// If several elements are equally maximum, the last element is + /// returned. /// /// # Examples /// @@ -1715,8 +1715,8 @@ pub trait Iterator { /// Returns the element that gives the minimum value from the /// specified function. /// - /// Returns the latest element if the comparison determines two elements - /// to be equally minimum. + /// If several elements are equally minimum, the first element is + /// returned. /// /// # Examples /// @@ -1739,8 +1739,8 @@ pub trait Iterator { /// Returns the element that gives the minimum value with respect to the /// specified comparison function. /// - /// Returns the latest element if the comparison determines two elements - /// to be equally minimum. + /// If several elements are equally minimum, the first element is + /// returned. /// /// # Examples /// diff --git a/src/libcore/iter/traits.rs b/src/libcore/iter/traits.rs index 25406696620c9..1e12714830067 100644 --- a/src/libcore/iter/traits.rs +++ b/src/libcore/iter/traits.rs @@ -260,7 +260,10 @@ impl IntoIterator for I { /// /// Iterators produce a series of values, and collections can also be thought /// of as a series of values. The `Extend` trait bridges this gap, allowing you -/// to extend a collection by including the contents of that iterator. +/// to extend a collection by including the contents of that iterator. When +/// extending a collection with an already existing key, that entry is updated +/// or, in the case of collections that permit multiple entries with equal +/// keys, that entry is inserted. /// /// # Examples /// diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 2fa3a9c4844b5..a314717a8772b 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 V>(self, default: F) -> &'a mut V { match self { diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs index 795c89c000747..434f522cc1ea6 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 f8a5ec0b3791e..a9a19aee5d18d 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 3f9bf70adde22..bf105a50d64ce 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(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::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 { 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 { 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::read_dir(self) diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index f8426e3b5782f..2efddeb4610dd 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 Mutex { /// 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 { let mut m = Mutex { @@ -190,6 +198,21 @@ impl Mutex { /// /// 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> { unsafe { @@ -211,6 +234,26 @@ impl Mutex { /// 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> { unsafe { @@ -225,8 +268,24 @@ impl Mutex { /// 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 Mutex { /// /// 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 where T: Sized { // We know statically that there are no outstanding references to @@ -270,6 +338,16 @@ impl Mutex { /// /// 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 6854f1e14fa13..e4b8d457e2d29 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 { @@ -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 { 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