Merge branch 'master' into maccoda/env_docs

This commit is contained in:
Dylan Maccora 2017-05-20 09:42:37 +10:00 committed by GitHub
commit 55d75c42ef
241 changed files with 5084 additions and 2478 deletions

View file

@ -50,16 +50,19 @@ use sys::os as os_imp;
/// use std::env;
///
/// // We assume that we are in a valid directory.
/// let p = env::current_dir().unwrap();
/// println!("The current directory is {}", p.display());
/// let path = env::current_dir().unwrap();
/// println!("The current directory is {}", path.display());
/// ```
#[stable(feature = "env", since = "1.0.0")]
pub fn current_dir() -> io::Result<PathBuf> {
os_imp::getcwd()
}
/// Changes the current working directory to the specified path, returning
/// whether the change was completed successfully or not.
/// Changes the current working directory to the specified path.
///
/// Returns an [`Err`] if the operation fails.
///
/// [`Err`]: ../../std/result/enum.Result.html#method.err
///
/// # Examples
///
@ -72,8 +75,8 @@ pub fn current_dir() -> io::Result<PathBuf> {
/// println!("Successfully changed working directory to {}!", root.display());
/// ```
#[stable(feature = "env", since = "1.0.0")]
pub fn set_current_dir<P: AsRef<Path>>(p: P) -> io::Result<()> {
os_imp::chdir(p.as_ref())
pub fn set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
os_imp::chdir(path.as_ref())
}
/// An iterator over a snapshot of the environment variables of this process.
@ -206,7 +209,7 @@ pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
fn _var(key: &OsStr) -> Result<String, VarError> {
match var_os(key) {
Some(s) => s.into_string().map_err(VarError::NotUnicode),
None => Err(VarError::NotPresent)
None => Err(VarError::NotPresent),
}
}

View file

@ -754,6 +754,13 @@ impl fmt::Debug for Stdio {
}
/// Describes the result of a process after it has terminated.
///
/// This `struct` is used to represent the exit status of a child process.
/// Child processes are created via the [`Command`] struct and their exit
/// status is exposed through the [`status`] method.
///
/// [`Command`]: struct.Command.html
/// [`status`]: struct.Command.html#method.status
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
#[stable(feature = "process", since = "1.0.0")]
pub struct ExitStatus(imp::ExitStatus);
@ -788,6 +795,22 @@ impl ExitStatus {
/// On Unix, this will return `None` if the process was terminated
/// by a signal; `std::os::unix` provides an extension trait for
/// extracting the signal and other details from the `ExitStatus`.
///
/// # Examples
///
/// ```no_run
/// use std::process::Command;
///
/// let status = Command::new("mkdir")
/// .arg("projects")
/// .status()
/// .expect("failed to execute mkdir");
///
/// match status.code() {
/// Some(code) => println!("Exited with status code: {}", code),
/// None => println!("Process terminated by signal")
/// }
/// ```
#[stable(feature = "process", since = "1.0.0")]
pub fn code(&self) -> Option<i32> {
self.0.code()

View file

@ -1067,7 +1067,7 @@ impl<T> Receiver<T> {
Receiver { inner: UnsafeCell::new(inner) }
}
/// Attempts to return a pending value on this receiver without blocking
/// Attempts to return a pending value on this receiver without blocking.
///
/// This method will never block the caller in order to wait for data to
/// become available. Instead, this will always return immediately with a

View file

@ -253,7 +253,12 @@ pub fn current_exe() -> io::Result<PathBuf> {
#[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/self/exe")
let selfexe = PathBuf::from("/proc/self/exe");
if selfexe.exists() {
::fs::read_link(selfexe)
} else {
Err(io::Error::new(io::ErrorKind::Other, "no /proc/self/exe available. Is /proc mounted?"))
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]

View file

@ -26,8 +26,22 @@ pub trait OsStringExt {
/// Creates an `OsString` from a potentially ill-formed UTF-16 slice of
/// 16-bit code units.
///
/// This is lossless: calling `.encode_wide()` on the resulting string
/// This is lossless: calling [`encode_wide`] on the resulting string
/// will always return the original code units.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
/// use std::os::windows::prelude::*;
///
/// // UTF-16 encoding for "Unicode".
/// let source = [0x0055, 0x006E, 0x0069, 0x0063, 0x006F, 0x0064, 0x0065];
///
/// let string = OsString::from_wide(&source[..]);
/// ```
///
/// [`encode_wide`]: ./trait.OsStrExt.html#tymethod.encode_wide
#[stable(feature = "rust1", since = "1.0.0")]
fn from_wide(wide: &[u16]) -> Self;
}
@ -42,11 +56,29 @@ impl OsStringExt for OsString {
/// Windows-specific extensions to `OsStr`.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait OsStrExt {
/// Re-encodes an `OsStr` as a wide character sequence,
/// i.e. potentially ill-formed UTF-16.
/// Re-encodes an `OsStr` as a wide character sequence, i.e. potentially
/// ill-formed UTF-16.
///
/// This is lossless. Note that the encoding does not include a final
/// null.
/// This is lossless: calling [`OsString::from_wide`] and then
/// `encode_wide` on the result will yield the original code units.
/// Note that the encoding does not add a final null terminator.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
/// use std::os::windows::prelude::*;
///
/// // UTF-16 encoding for "Unicode".
/// let source = [0x0055, 0x006E, 0x0069, 0x0063, 0x006F, 0x0064, 0x0065];
///
/// let string = OsString::from_wide(&source[..]);
///
/// let result: Vec<u16> = string.encode_wide().collect();
/// assert_eq!(&source[..], &result[..]);
/// ```
///
/// [`OsString::from_wide`]: ./trait.OsStringExt.html#tymethod.from_wide
#[stable(feature = "rust1", since = "1.0.0")]
fn encode_wide(&self) -> EncodeWide;
}

View file

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Windows-specific extensions for the primitives in `std::fs`
//! Windows-specific extensions for the primitives in the `std::fs` module.
#![stable(feature = "rust1", since = "1.0.0")]
@ -18,7 +18,9 @@ use path::Path;
use sys;
use sys_common::{AsInnerMut, AsInner};
/// Windows-specific extensions to `File`
/// Windows-specific extensions to [`File`].
///
/// [`File`]: ../../../fs/struct.File.html
#[stable(feature = "file_offset", since = "1.15.0")]
pub trait FileExt {
/// Seeks to a given position and reads a number of bytes.
@ -35,6 +37,24 @@ pub trait FileExt {
/// Note that similar to `File::read`, it is not an error to return with a
/// short read. When returning from such a short read, the file pointer is
/// still updated.
///
/// # Examples
///
/// ```no_run
/// use std::io;
/// use std::fs::File;
/// use std::os::windows::prelude::*;
///
/// # fn foo() -> io::Result<()> {
/// let mut file = File::open("foo.txt")?;
/// let mut buffer = [0; 10];
///
/// // Read 10 bytes, starting 72 bytes from the
/// // start of the file.
/// file.seek_read(&mut buffer[..], 72)?;
/// # Ok(())
/// # }
/// ```
#[stable(feature = "file_offset", since = "1.15.0")]
fn seek_read(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>;
@ -52,6 +72,22 @@ pub trait FileExt {
/// Note that similar to `File::write`, it is not an error to return a
/// short write. When returning from such a short write, the file pointer
/// is still updated.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::os::windows::prelude::*;
///
/// # fn foo() -> std::io::Result<()> {
/// let mut buffer = File::create("foo.txt")?;
///
/// // Write a byte string starting 72 bytes from
/// // the start of the file.
/// buffer.seek_write(b"some bytes", 72)?;
/// # Ok(())
/// # }
/// ```
#[stable(feature = "file_offset", since = "1.15.0")]
fn seek_write(&self, buf: &[u8], offset: u64) -> io::Result<usize>;
}
@ -67,81 +103,94 @@ impl FileExt for fs::File {
}
}
/// Windows-specific extensions to `OpenOptions`
/// Windows-specific extensions to [`OpenOptions`].
///
/// [`OpenOptions`]: ../../../fs/struct.OpenOptions.html
#[stable(feature = "open_options_ext", since = "1.10.0")]
pub trait OpenOptionsExt {
/// Overrides the `dwDesiredAccess` argument to the call to `CreateFile`
/// Overrides the `dwDesiredAccess` argument to the call to [`CreateFile`]
/// with the specified value.
///
/// This will override the `read`, `write`, and `append` flags on the
/// `OpenOptions` structure. This method provides fine-grained control over
/// the permissions to read, write and append data, attributes (like hidden
/// and system) and extended attributes.
/// and system), and extended attributes.
///
/// # Examples
///
/// ```no_run
/// use std::fs::OpenOptions;
/// use std::os::windows::fs::OpenOptionsExt;
/// use std::os::windows::prelude::*;
///
/// // Open without read and write permission, for example if you only need
/// // to call `stat()` on the file
/// // to call `stat` on the file
/// let file = OpenOptions::new().access_mode(0).open("foo.txt");
/// ```
///
/// [`CreateFile`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx
#[stable(feature = "open_options_ext", since = "1.10.0")]
fn access_mode(&mut self, access: u32) -> &mut Self;
/// Overrides the `dwShareMode` argument to the call to `CreateFile` with
/// Overrides the `dwShareMode` argument to the call to [`CreateFile`] with
/// the specified value.
///
/// By default `share_mode` is set to
/// `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`. Specifying
/// less permissions denies others to read from, write to and/or delete the
/// file while it is open.
/// `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`. This allows
/// other processes to to read, write, and delete/rename the same file
/// while it is open. Removing any of the flags will prevent other
/// processes from performing the corresponding operation until the file
/// handle is closed.
///
/// # Examples
///
/// ```no_run
/// use std::fs::OpenOptions;
/// use std::os::windows::fs::OpenOptionsExt;
/// use std::os::windows::prelude::*;
///
/// // Do not allow others to read or modify this file while we have it open
/// // for writing
/// let file = OpenOptions::new().write(true)
/// .share_mode(0)
/// .open("foo.txt");
/// // for writing.
/// let file = OpenOptions::new()
/// .write(true)
/// .share_mode(0)
/// .open("foo.txt");
/// ```
///
/// [`CreateFile`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx
#[stable(feature = "open_options_ext", since = "1.10.0")]
fn share_mode(&mut self, val: u32) -> &mut Self;
/// Sets extra flags for the `dwFileFlags` argument to the call to
/// `CreateFile2` (or combines it with `attributes` and `security_qos_flags`
/// to set the `dwFlagsAndAttributes` for `CreateFile`).
/// [`CreateFile2`] to the specified value (or combines it with
/// `attributes` and `security_qos_flags` to set the `dwFlagsAndAttributes`
/// for [`CreateFile`]).
///
/// Custom flags can only set flags, not remove flags set by Rusts options.
/// This options overwrites any previously set custom flags.
/// Custom flags can only set flags, not remove flags set by Rust's options.
/// This option overwrites any previously set custom flags.
///
/// # Examples
///
/// ```rust,ignore
/// ```ignore
/// extern crate winapi;
/// use std::fs::OpenOptions;
/// use std::os::windows::fs::OpenOptionsExt;
///
/// let mut options = OpenOptions::new();
/// options.create(true).write(true);
/// if cfg!(windows) {
/// options.custom_flags(winapi::FILE_FLAG_DELETE_ON_CLOSE);
/// }
/// let file = options.open("foo.txt");
/// use std::fs::OpenOptions;
/// use std::os::windows::prelude::*;
///
/// let file = OpenOptions::new()
/// .create(true)
/// .write(true)
/// .custom_flags(winapi::FILE_FLAG_DELETE_ON_CLOSE)
/// .open("foo.txt");
/// ```
///
/// [`CreateFile`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx
/// [`CreateFile2`]: https://msdn.microsoft.com/en-us/library/windows/desktop/hh449422.aspx
#[stable(feature = "open_options_ext", since = "1.10.0")]
fn custom_flags(&mut self, flags: u32) -> &mut Self;
/// Sets the `dwFileAttributes` argument to the call to `CreateFile2` to
/// Sets the `dwFileAttributes` argument to the call to [`CreateFile2`] to
/// the specified value (or combines it with `custom_flags` and
/// `security_qos_flags` to set the `dwFlagsAndAttributes` for
/// `CreateFile`).
/// [`CreateFile`]).
///
/// If a _new_ file is created because it does not yet exist and
/// `.create(true)` or `.create_new(true)` are specified, the new file is
@ -155,21 +204,52 @@ pub trait OpenOptionsExt {
///
/// # Examples
///
/// ```rust,ignore
/// ```ignore
/// extern crate winapi;
/// use std::fs::OpenOptions;
/// use std::os::windows::fs::OpenOptionsExt;
///
/// let file = OpenOptions::new().write(true).create(true)
/// .attributes(winapi::FILE_ATTRIBUTE_HIDDEN)
/// .open("foo.txt");
/// use std::fs::OpenOptions;
/// use std::os::windows::prelude::*;
///
/// let file = OpenOptions::new()
/// .write(true)
/// .create(true)
/// .attributes(winapi::FILE_ATTRIBUTE_HIDDEN)
/// .open("foo.txt");
/// ```
///
/// [`CreateFile`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx
/// [`CreateFile2`]: https://msdn.microsoft.com/en-us/library/windows/desktop/hh449422.aspx
#[stable(feature = "open_options_ext", since = "1.10.0")]
fn attributes(&mut self, val: u32) -> &mut Self;
/// Sets the `dwSecurityQosFlags` argument to the call to `CreateFile2` to
/// Sets the `dwSecurityQosFlags` argument to the call to [`CreateFile2`] to
/// the specified value (or combines it with `custom_flags` and `attributes`
/// to set the `dwFlagsAndAttributes` for `CreateFile`).
/// to set the `dwFlagsAndAttributes` for [`CreateFile`]).
///
/// By default, `security_qos_flags` is set to `SECURITY_ANONYMOUS`. For
/// information about possible values, see [Impersonation Levels] on the
/// Windows Dev Center site.
///
/// # Examples
///
/// ```no_run
/// use std::fs::OpenOptions;
/// use std::os::windows::prelude::*;
///
/// let file = OpenOptions::new()
/// .write(true)
/// .create(true)
///
/// // Sets the flag value to `SecurityIdentification`.
/// .security_qos_flags(1)
///
/// .open("foo.txt");
/// ```
///
/// [`CreateFile`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx
/// [`CreateFile2`]: https://msdn.microsoft.com/en-us/library/windows/desktop/hh449422.aspx
/// [Impersonation Levels]:
/// https://msdn.microsoft.com/en-us/library/windows/desktop/aa379572.aspx
#[stable(feature = "open_options_ext", since = "1.10.0")]
fn security_qos_flags(&mut self, flags: u32) -> &mut OpenOptions;
}
@ -197,35 +277,136 @@ impl OpenOptionsExt for OpenOptions {
}
}
/// Extension methods for `fs::Metadata` to access the raw fields contained
/// Extension methods for [`fs::Metadata`] to access the raw fields contained
/// within.
///
/// The data members that this trait exposes correspond to the members
/// of the [`BY_HANDLE_FILE_INFORMATION`] structure.
///
/// [`fs::Metadata`]: ../../../fs/struct.Metadata.html
/// [`BY_HANDLE_FILE_INFORMATION`]:
/// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363788.aspx
#[stable(feature = "metadata_ext", since = "1.1.0")]
pub trait MetadataExt {
/// Returns the value of the `dwFileAttributes` field of this metadata.
///
/// This field contains the file system attribute information for a file
/// or directory.
/// or directory. For possible values and their descriptions, see
/// [File Attribute Constants] in the Windows Dev Center.
///
/// # Examples
///
/// ```no_run
/// use std::io;
/// use std::fs;
/// use std::os::windows::prelude::*;
///
/// # fn foo() -> io::Result<()> {
/// let metadata = fs::metadata("foo.txt")?;
/// let attributes = metadata.file_attributes();
/// # Ok(())
/// # }
/// ```
///
/// [File Attribute Constants]:
/// https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117.aspx
#[stable(feature = "metadata_ext", since = "1.1.0")]
fn file_attributes(&self) -> u32;
/// Returns the value of the `ftCreationTime` field of this metadata.
///
/// The returned 64-bit value represents the number of 100-nanosecond
/// intervals since January 1, 1601 (UTC).
/// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
/// which represents the number of 100-nanosecond intervals since
/// January 1, 1601 (UTC). The struct is automatically
/// converted to a `u64` value, as that is the recommended way
/// to use it.
///
/// If the underlying filesystem does not support creation time, the
/// returned value is 0.
///
/// # Examples
///
/// ```no_run
/// use std::io;
/// use std::fs;
/// use std::os::windows::prelude::*;
///
/// # fn foo() -> io::Result<()> {
/// let metadata = fs::metadata("foo.txt")?;
/// let creation_time = metadata.creation_time();
/// # Ok(())
/// # }
/// ```
///
/// [`FILETIME`]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx
#[stable(feature = "metadata_ext", since = "1.1.0")]
fn creation_time(&self) -> u64;
/// Returns the value of the `ftLastAccessTime` field of this metadata.
///
/// The returned 64-bit value represents the number of 100-nanosecond
/// intervals since January 1, 1601 (UTC).
/// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
/// which represents the number of 100-nanosecond intervals since
/// January 1, 1601 (UTC). The struct is automatically
/// converted to a `u64` value, as that is the recommended way
/// to use it.
///
/// For a file, the value specifies the last time that a file was read
/// from or written to. For a directory, the value specifies when
/// the directory was created. For both files and directories, the
/// specified date is correct, but the time of day is always set to
/// midnight.
///
/// If the underlying filesystem does not support last access time, the
/// returned value is 0.
///
/// # Examples
///
/// ```no_run
/// use std::io;
/// use std::fs;
/// use std::os::windows::prelude::*;
///
/// # fn foo() -> io::Result<()> {
/// let metadata = fs::metadata("foo.txt")?;
/// let last_access_time = metadata.last_access_time();
/// # Ok(())
/// # }
/// ```
///
/// [`FILETIME`]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx
#[stable(feature = "metadata_ext", since = "1.1.0")]
fn last_access_time(&self) -> u64;
/// Returns the value of the `ftLastWriteTime` field of this metadata.
///
/// The returned 64-bit value represents the number of 100-nanosecond
/// intervals since January 1, 1601 (UTC).
/// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
/// which represents the number of 100-nanosecond intervals since
/// January 1, 1601 (UTC). The struct is automatically
/// converted to a `u64` value, as that is the recommended way
/// to use it.
///
/// For a file, the value specifies the last time that a file was written
/// to. For a directory, the structure specifies when the directory was
/// created.
///
/// If the underlying filesystem does not support the last write time
/// time, the returned value is 0.
///
/// # Examples
///
/// ```no_run
/// use std::io;
/// use std::fs;
/// use std::os::windows::prelude::*;
///
/// # fn foo() -> io::Result<()> {
/// let metadata = fs::metadata("foo.txt")?;
/// let last_write_time = metadata.last_write_time();
/// # Ok(())
/// # }
/// ```
///
/// [`FILETIME`]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx
#[stable(feature = "metadata_ext", since = "1.1.0")]
fn last_write_time(&self) -> u64;
@ -233,6 +414,20 @@ pub trait MetadataExt {
/// metadata.
///
/// The returned value does not have meaning for directories.
///
/// # Examples
///
/// ```no_run
/// use std::io;
/// use std::fs;
/// use std::os::windows::prelude::*;
///
/// # fn foo() -> io::Result<()> {
/// let metadata = fs::metadata("foo.txt")?;
/// let file_size = metadata.file_size();
/// # Ok(())
/// # }
/// ```
#[stable(feature = "metadata_ext", since = "1.1.0")]
fn file_size(&self) -> u64;
}
@ -253,7 +448,7 @@ impl MetadataExt for Metadata {
///
/// # Examples
///
/// ```ignore
/// ```no_run
/// use std::os::windows::fs;
///
/// # fn foo() -> std::io::Result<()> {
@ -274,7 +469,7 @@ pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q)
///
/// # Examples
///
/// ```ignore
/// ```no_run
/// use std::os::windows::fs;
///
/// # fn foo() -> std::io::Result<()> {

View file

@ -8,11 +8,13 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Experimental extensions to `std` for Windows.
//! Platform-specific extensions to `std` for Windows.
//!
//! For now, this module is limited to extracting handles, file
//! descriptors, and sockets, but its functionality will grow over
//! time.
//! Provides access to platform-level information for Windows, and exposes
//! Windows-specific idioms that would otherwise be inappropriate as part
//! the core `std` library. These extensions allow developers to use
//! `std` types and idioms with Windows in a way that the normal
//! platform-agnostic idioms would not normally support.
#![stable(feature = "rust1", since = "1.0.0")]

View file

@ -750,6 +750,7 @@ impl<'a> Iterator for Wtf8CodePoints<'a> {
}
}
/// Generates a wide character sequence for potentially ill-formed UTF-16.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Clone)]
pub struct EncodeWide<'a> {

View file

@ -19,16 +19,16 @@ use mem;
/// A thread local storage key which owns its contents.
///
/// This key uses the fastest possible implementation available to it for the
/// target platform. It is instantiated with the `thread_local!` macro and the
/// primary method is the `with` method.
/// target platform. It is instantiated with the [`thread_local!`] macro and the
/// primary method is the [`with`] method.
///
/// The `with` method yields a reference to the contained value which cannot be
/// The [`with`] method yields a reference to the contained value which cannot be
/// sent across threads or escape the given closure.
///
/// # Initialization and Destruction
///
/// Initialization is dynamically performed on the first call to `with()`
/// within a thread, and values that implement `Drop` get destructed when a
/// Initialization is dynamically performed on the first call to [`with`]
/// within a thread, and values that implement [`Drop`] get destructed when a
/// thread exits. Some caveats apply, which are explained below.
///
/// # Examples
@ -77,6 +77,10 @@ use mem;
/// 3. On macOS, initializing TLS during destruction of other TLS slots can
/// sometimes cancel *all* destructors for the current thread, whether or not
/// the slots have already had their destructors run or not.
///
/// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
/// [`thread_local!`]: ../../std/macro.thread_local.html
/// [`Drop`]: ../../std/ops/trait.Drop.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct LocalKey<T: 'static> {
// This outer `LocalKey<T>` type is what's going to be stored in statics,
@ -106,7 +110,7 @@ impl<T: 'static> fmt::Debug for LocalKey<T> {
}
}
/// Declare a new thread local storage key of type `std::thread::LocalKey`.
/// Declare a new thread local storage key of type [`std::thread::LocalKey`].
///
/// # Syntax
///
@ -124,8 +128,10 @@ impl<T: 'static> fmt::Debug for LocalKey<T> {
/// # fn main() {}
/// ```
///
/// See [LocalKey documentation](thread/struct.LocalKey.html) for more
/// See [LocalKey documentation][`std::thread::LocalKey`] for more
/// information.
///
/// [`std::thread::LocalKey`]: ../std/thread/struct.LocalKey.html
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[allow_internal_unstable]
@ -195,11 +201,13 @@ macro_rules! __thread_local_inner {
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum LocalKeyState {
/// All keys are in this state whenever a thread starts. Keys will
/// transition to the `Valid` state once the first call to `with` happens
/// transition to the `Valid` state once the first call to [`with`] happens
/// and the initialization expression succeeds.
///
/// Keys in the `Uninitialized` state will yield a reference to the closure
/// passed to `with` so long as the initialization routine does not panic.
/// passed to [`with`] so long as the initialization routine does not panic.
///
/// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
Uninitialized,
/// Once a key has been accessed successfully, it will enter the `Valid`
@ -208,7 +216,9 @@ pub enum LocalKeyState {
/// `Destroyed` state.
///
/// Keys in the `Valid` state will be guaranteed to yield a reference to the
/// closure passed to `with`.
/// closure passed to [`with`].
///
/// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
Valid,
/// When a thread exits, the destructors for keys will be run (if
@ -216,7 +226,9 @@ pub enum LocalKeyState {
/// destructor has run, a key is in the `Destroyed` state.
///
/// Keys in the `Destroyed` states will trigger a panic when accessed via
/// `with`.
/// [`with`].
///
/// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
Destroyed,
}
@ -283,23 +295,26 @@ impl<T: 'static> LocalKey<T> {
/// Query the current state of this key.
///
/// A key is initially in the `Uninitialized` state whenever a thread
/// starts. It will remain in this state up until the first call to `with`
/// starts. It will remain in this state up until the first call to [`with`]
/// within a thread has run the initialization expression successfully.
///
/// Once the initialization expression succeeds, the key transitions to the
/// `Valid` state which will guarantee that future calls to `with` will
/// `Valid` state which will guarantee that future calls to [`with`] will
/// succeed within the thread.
///
/// When a thread exits, each key will be destroyed in turn, and as keys are
/// destroyed they will enter the `Destroyed` state just before the
/// destructor starts to run. Keys may remain in the `Destroyed` state after
/// destruction has completed. Keys without destructors (e.g. with types
/// that are `Copy`), may never enter the `Destroyed` state.
/// that are [`Copy`]), may never enter the `Destroyed` state.
///
/// Keys in the `Uninitialized` state can be accessed so long as the
/// initialization does not panic. Keys in the `Valid` state are guaranteed
/// to be able to be accessed. Keys in the `Destroyed` state will panic on
/// any call to `with`.
/// any call to [`with`].
///
/// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
/// [`Copy`]: ../../std/marker/trait.Copy.html
#[unstable(feature = "thread_local_state",
reason = "state querying was recently added",
issue = "27716")]

View file

@ -180,8 +180,33 @@ pub use self::local::{LocalKey, LocalKeyState};
// Builder
////////////////////////////////////////////////////////////////////////////////
/// Thread configuration. Provides detailed control over the properties
/// and behavior of new threads.
/// Thread factory, which can be used in order to configure the properties of
/// a new thread.
///
/// Methods can be chained on it in order to configure it.
///
/// The two configurations available are:
///
/// - [`name`]: allows to give a name to the thread which is currently
/// only used in `panic` messages.
/// - [`stack_size`]: specifies the desired stack size. Note that this can
/// be overriden by the OS.
///
/// If the [`stack_size`] field is not specified, the stack size
/// will be the `RUST_MIN_STACK` environment variable. If it is
/// not specified either, a sensible default will be set.
///
/// If the [`name`] field is not specified, the thread will not be named.
///
/// The [`spawn`] method will take ownership of the builder and create an
/// [`io::Result`] to the thread handle with the given configuration.
///
/// The [`thread::spawn`] free function uses a `Builder` with default
/// configuration and [`unwrap`]s its return value.
///
/// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
/// to recover from a failure to launch a thread, indeed the free function will
/// panick where the `Builder` method will return a [`io::Result`].
///
/// # Examples
///
@ -196,6 +221,13 @@ pub use self::local::{LocalKey, LocalKeyState};
///
/// handler.join().unwrap();
/// ```
///
/// [`thread::spawn`]: ../../std/thread/fn.spawn.html
/// [`stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
/// [`name`]: ../../std/thread/struct.Builder.html#method.name
/// [`spawn`]: ../../std/thread/struct.Builder.html#method.spawn
/// [`io::Result`]: ../../std/io/type.Result.html
/// [`unwrap`]: ../../std/result/enum.Result.html#method.unwrap
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Debug)]
pub struct Builder {
@ -209,11 +241,6 @@ impl Builder {
/// Generates the base configuration for spawning a thread, from which
/// configuration methods can be chained.
///
/// If the [`stack_size`] field is not specified, the stack size
/// will be the `RUST_MIN_STACK` environment variable. If it is
/// not specified either, a sensible default will be set (2MB as
/// of the writting of this doc).
///
/// # Examples
///
/// ```
@ -229,8 +256,6 @@ impl Builder {
///
/// handler.join().unwrap();
/// ```
///
/// [`stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> Builder {
Builder {
@ -280,9 +305,10 @@ impl Builder {
self
}
/// Spawns a new thread, and returns a join handle for it.
/// Spawns a new thread by taking ownership of the `Builder`, and returns an
/// [`io::Result`] to its [`JoinHandle`].
///
/// The child thread may outlive the parent (unless the parent thread
/// The spawned thread may outlive the caller (unless the caller thread
/// is the main thread; the whole process is terminated when the main
/// thread finishes). The join handle can be used to block on
/// termination of the child thread, including recovering its panics.
@ -297,6 +323,7 @@ impl Builder {
///
/// [`spawn`]: ../../std/thread/fn.spawn.html
/// [`io::Result`]: ../../std/io/type.Result.html
/// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
///
/// # Examples
///
@ -468,6 +495,23 @@ pub fn current() -> Thread {
/// Cooperatively gives up a timeslice to the OS scheduler.
///
/// This is used when the programmer knows that the thread will have nothing
/// to do for some time, and thus avoid wasting computing time.
///
/// For example when polling on a resource, it is common to check that it is
/// available, and if not to yield in order to avoid busy waiting.
///
/// Thus the pattern of `yield`ing after a failed poll is rather common when
/// implementing low-level shared resources or synchronization primitives.
///
/// However programmers will usualy prefer to use, [`channel`]s, [`Condvar`]s,
/// [`Mutex`]es or [`join`] for their synchronisation routines, as they avoid
/// thinking about thread schedulling.
///
/// Note that [`channel`]s for example are implemented using this primitive.
/// Indeed when you call `send` or `recv`, which are blocking, they will yield
/// if the channel is not available.
///
/// # Examples
///
/// ```
@ -475,6 +519,12 @@ pub fn current() -> Thread {
///
/// thread::yield_now();
/// ```
///
/// [`channel`]: ../../std/sync/mpsc/index.html
/// [`spawn`]: ../../std/thread/fn.spawn.html
/// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
/// [`Mutex`]: ../../std/sync/struct.Mutex.html
/// [`Condvar`]: ../../std/sync/struct.Condvar.html
#[stable(feature = "rust1", since = "1.0.0")]
pub fn yield_now() {
imp::Thread::yield_now()