1
Fork 0

Rollup merge of #90431 - jkugelman:must-use-std-o-through-z, r=joshtriplett

Add #[must_use] to remaining std functions (O-Z)

I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is half of the remaining items from the `std` crate, from O-Z.

`panicking::take_hook` has a side effect: it unregisters the current panic hook, returning it. I almost ignored it, but the documentation example shows `let _ = panic::take_hook();`, so following suit I went ahead and added a `#[must_use]`.

```rust
std::panicking   fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>;
```

I added these functions that clippy did not flag:

```rust
std::path::Path   fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool;
std::path::Path   fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool;
std::path::Path   fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf;
std::path::Path   fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf;
```

Parent issue: #89692

r? `@joshtriplett`
This commit is contained in:
Matthias Krüger 2021-10-31 13:20:07 +01:00 committed by GitHub
commit 455a79acab
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 57 additions and 2 deletions

View file

@ -201,6 +201,7 @@ impl SocketCred {
} }
/// Get the current PID. /// Get the current PID.
#[must_use]
#[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
pub fn get_pid(&self) -> libc::pid_t { pub fn get_pid(&self) -> libc::pid_t {
self.0.pid self.0.pid
@ -213,6 +214,7 @@ impl SocketCred {
} }
/// Get the current UID. /// Get the current UID.
#[must_use]
#[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
pub fn get_uid(&self) -> libc::uid_t { pub fn get_uid(&self) -> libc::uid_t {
self.0.uid self.0.uid
@ -225,6 +227,7 @@ impl SocketCred {
} }
/// Get the current GID. /// Get the current GID.
#[must_use]
#[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
pub fn get_gid(&self) -> libc::gid_t { pub fn get_gid(&self) -> libc::gid_t {
self.0.gid self.0.gid
@ -330,6 +333,7 @@ impl<'a> AncillaryData<'a> {
} }
/// This struct is used to iterate through the control messages. /// This struct is used to iterate through the control messages.
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
pub struct Messages<'a> { pub struct Messages<'a> {
buffer: &'a [u8], buffer: &'a [u8],
@ -425,6 +429,7 @@ impl<'a> SocketAncillary<'a> {
} }
/// Returns the capacity of the buffer. /// Returns the capacity of the buffer.
#[must_use]
#[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
pub fn capacity(&self) -> usize { pub fn capacity(&self) -> usize {
self.buffer.len() self.buffer.len()
@ -473,6 +478,7 @@ impl<'a> SocketAncillary<'a> {
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
#[must_use]
#[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")]
pub fn truncated(&self) -> bool { pub fn truncated(&self) -> bool {
self.truncated self.truncated

View file

@ -365,6 +365,7 @@ impl<'a> IntoIterator for &'a UnixListener {
/// } /// }
/// ``` /// ```
#[derive(Debug)] #[derive(Debug)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "unix_socket", since = "1.10.0")] #[stable(feature = "unix_socket", since = "1.10.0")]
pub struct Incoming<'a> { pub struct Incoming<'a> {
listener: &'a UnixListener, listener: &'a UnixListener,

View file

@ -436,6 +436,7 @@ impl From<crate::process::ChildStderr> for OwnedFd {
} }
/// Returns the OS-assigned process identifier associated with this process's parent. /// Returns the OS-assigned process identifier associated with this process's parent.
#[must_use]
#[stable(feature = "unix_ppid", since = "1.27.0")] #[stable(feature = "unix_ppid", since = "1.27.0")]
pub fn parent_id() -> u32 { pub fn parent_id() -> u32 {
crate::sys::os::getppid() crate::sys::os::getppid()

View file

@ -160,6 +160,7 @@ pub fn set_hook(hook: Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>) {
/// ///
/// panic!("Normal panic"); /// panic!("Normal panic");
/// ``` /// ```
#[must_use]
#[stable(feature = "panic_hooks", since = "1.10.0")] #[stable(feature = "panic_hooks", since = "1.10.0")]
pub fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> { pub fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
if thread::panicking() { if thread::panicking() {
@ -284,11 +285,13 @@ pub mod panic_count {
} }
// Disregards ALWAYS_ABORT_FLAG // Disregards ALWAYS_ABORT_FLAG
#[must_use]
pub fn get_count() -> usize { pub fn get_count() -> usize {
LOCAL_PANIC_COUNT.with(|c| c.get()) LOCAL_PANIC_COUNT.with(|c| c.get())
} }
// Disregards ALWAYS_ABORT_FLAG // Disregards ALWAYS_ABORT_FLAG
#[must_use]
#[inline] #[inline]
pub fn count_is_zero() -> bool { pub fn count_is_zero() -> bool {
if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) & !ALWAYS_ABORT_FLAG == 0 { if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) & !ALWAYS_ABORT_FLAG == 0 {

View file

@ -422,6 +422,7 @@ impl<'a> PrefixComponent<'a> {
/// See [`Prefix`]'s documentation for more information on the different /// See [`Prefix`]'s documentation for more information on the different
/// kinds of prefixes. /// kinds of prefixes.
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[inline] #[inline]
pub fn kind(&self) -> Prefix<'a> { pub fn kind(&self) -> Prefix<'a> {
self.parsed self.parsed
@ -583,6 +584,7 @@ impl AsRef<Path> for Component<'_> {
/// ///
/// [`components`]: Path::components /// [`components`]: Path::components
#[derive(Clone)] #[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub struct Components<'a> { pub struct Components<'a> {
// The path left to parse components from // The path left to parse components from
@ -609,6 +611,7 @@ pub struct Components<'a> {
/// ///
/// [`iter`]: Path::iter /// [`iter`]: Path::iter
#[derive(Clone)] #[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub struct Iter<'a> { pub struct Iter<'a> {
inner: Components<'a>, inner: Components<'a>,
@ -1051,6 +1054,7 @@ fn compare_components(mut left: Components<'_>, mut right: Components<'_>) -> cm
/// ///
/// [`ancestors`]: Path::ancestors /// [`ancestors`]: Path::ancestors
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "path_ancestors", since = "1.28.0")] #[stable(feature = "path_ancestors", since = "1.28.0")]
pub struct Ancestors<'a> { pub struct Ancestors<'a> {
next: Option<&'a Path>, next: Option<&'a Path>,
@ -1459,6 +1463,7 @@ impl PathBuf {
/// ///
/// [`capacity`]: OsString::capacity /// [`capacity`]: OsString::capacity
#[stable(feature = "path_buf_capacity", since = "1.44.0")] #[stable(feature = "path_buf_capacity", since = "1.44.0")]
#[must_use]
#[inline] #[inline]
pub fn capacity(&self) -> usize { pub fn capacity(&self) -> usize {
self.inner.capacity() self.inner.capacity()
@ -2103,6 +2108,7 @@ impl Path {
/// assert_eq!(grand_parent.parent(), None); /// assert_eq!(grand_parent.parent(), None);
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn parent(&self) -> Option<&Path> { pub fn parent(&self) -> Option<&Path> {
let mut comps = self.components(); let mut comps = self.components();
let comp = comps.next_back(); let comp = comps.next_back();
@ -2169,6 +2175,7 @@ impl Path {
/// assert_eq!(None, Path::new("/").file_name()); /// assert_eq!(None, Path::new("/").file_name());
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn file_name(&self) -> Option<&OsStr> { pub fn file_name(&self) -> Option<&OsStr> {
self.components().next_back().and_then(|p| match p { self.components().next_back().and_then(|p| match p {
Component::Normal(p) => Some(p), Component::Normal(p) => Some(p),
@ -2241,6 +2248,7 @@ impl Path {
/// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo")); /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool { pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
self._starts_with(base.as_ref()) self._starts_with(base.as_ref())
} }
@ -2268,6 +2276,7 @@ impl Path {
/// assert!(!path.ends_with("conf")); // use .extension() instead /// assert!(!path.ends_with("conf")); // use .extension() instead
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool { pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
self._ends_with(child.as_ref()) self._ends_with(child.as_ref())
} }
@ -2303,6 +2312,7 @@ impl Path {
/// [`Path::file_prefix`]: Path::file_prefix /// [`Path::file_prefix`]: Path::file_prefix
/// ///
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn file_stem(&self) -> Option<&OsStr> { pub fn file_stem(&self) -> Option<&OsStr> {
self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after)) self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after))
} }
@ -2336,6 +2346,7 @@ impl Path {
/// [`Path::file_stem`]: Path::file_stem /// [`Path::file_stem`]: Path::file_stem
/// ///
#[unstable(feature = "path_file_prefix", issue = "86319")] #[unstable(feature = "path_file_prefix", issue = "86319")]
#[must_use]
pub fn file_prefix(&self) -> Option<&OsStr> { pub fn file_prefix(&self) -> Option<&OsStr> {
self.file_name().map(split_file_at_dot).and_then(|(before, _after)| Some(before)) self.file_name().map(split_file_at_dot).and_then(|(before, _after)| Some(before))
} }
@ -2360,6 +2371,7 @@ impl Path {
/// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap()); /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn extension(&self) -> Option<&OsStr> { pub fn extension(&self) -> Option<&OsStr> {
self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.and(after)) self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.and(after))
} }
@ -2403,6 +2415,7 @@ impl Path {
/// assert_eq!(path.with_file_name("var"), PathBuf::from("/var")); /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf { pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
self._with_file_name(file_name.as_ref()) self._with_file_name(file_name.as_ref())
} }
@ -2660,6 +2673,7 @@ impl Path {
/// This is a convenience function that coerces errors to false. If you want to /// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`fs::metadata`]. /// check errors, call [`fs::metadata`].
#[stable(feature = "path_ext", since = "1.5.0")] #[stable(feature = "path_ext", since = "1.5.0")]
#[must_use]
#[inline] #[inline]
pub fn exists(&self) -> bool { pub fn exists(&self) -> bool {
fs::metadata(self).is_ok() fs::metadata(self).is_ok()
@ -2786,6 +2800,7 @@ impl Path {
/// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or
/// allocating. /// allocating.
#[stable(feature = "into_boxed_path", since = "1.20.0")] #[stable(feature = "into_boxed_path", since = "1.20.0")]
#[must_use = "`self` will be dropped if the result is not used"]
pub fn into_path_buf(self: Box<Path>) -> PathBuf { pub fn into_path_buf(self: Box<Path>) -> PathBuf {
let rw = Box::into_raw(self) as *mut OsStr; let rw = Box::into_raw(self) as *mut OsStr;
let inner = unsafe { Box::from_raw(rw) }; let inner = unsafe { Box::from_raw(rw) };

View file

@ -948,6 +948,7 @@ impl Command {
/// let cmd = Command::new("echo"); /// let cmd = Command::new("echo");
/// assert_eq!(cmd.get_program(), "echo"); /// assert_eq!(cmd.get_program(), "echo");
/// ``` /// ```
#[must_use]
#[stable(feature = "command_access", since = "1.57.0")] #[stable(feature = "command_access", since = "1.57.0")]
pub fn get_program(&self) -> &OsStr { pub fn get_program(&self) -> &OsStr {
self.inner.get_program() self.inner.get_program()
@ -1021,6 +1022,7 @@ impl Command {
/// cmd.current_dir("/bin"); /// cmd.current_dir("/bin");
/// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin"))); /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
/// ``` /// ```
#[must_use]
#[stable(feature = "command_access", since = "1.57.0")] #[stable(feature = "command_access", since = "1.57.0")]
pub fn get_current_dir(&self) -> Option<&Path> { pub fn get_current_dir(&self) -> Option<&Path> {
self.inner.get_current_dir() self.inner.get_current_dir()
@ -1053,6 +1055,7 @@ impl AsInnerMut<imp::Command> for Command {
/// ///
/// This struct is created by [`Command::get_args`]. See its documentation for /// This struct is created by [`Command::get_args`]. See its documentation for
/// more. /// more.
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "command_access", since = "1.57.0")] #[stable(feature = "command_access", since = "1.57.0")]
#[derive(Debug)] #[derive(Debug)]
pub struct CommandArgs<'a> { pub struct CommandArgs<'a> {
@ -1183,6 +1186,7 @@ impl Stdio {
/// its entire stdin before writing more than a pipe buffer's worth of output. /// its entire stdin before writing more than a pipe buffer's worth of output.
/// The size of a pipe buffer varies on different targets. /// The size of a pipe buffer varies on different targets.
/// ///
#[must_use]
#[stable(feature = "process", since = "1.0.0")] #[stable(feature = "process", since = "1.0.0")]
pub fn piped() -> Stdio { pub fn piped() -> Stdio {
Stdio(imp::Stdio::MakePipe) Stdio(imp::Stdio::MakePipe)
@ -1222,6 +1226,7 @@ impl Stdio {
/// print!("You piped in the reverse of: "); /// print!("You piped in the reverse of: ");
/// io::stdout().write_all(&output.stdout).unwrap(); /// io::stdout().write_all(&output.stdout).unwrap();
/// ``` /// ```
#[must_use]
#[stable(feature = "process", since = "1.0.0")] #[stable(feature = "process", since = "1.0.0")]
pub fn inherit() -> Stdio { pub fn inherit() -> Stdio {
Stdio(imp::Stdio::Inherit) Stdio(imp::Stdio::Inherit)
@ -1261,6 +1266,7 @@ impl Stdio {
/// assert_eq!(String::from_utf8_lossy(&output.stdout), ""); /// assert_eq!(String::from_utf8_lossy(&output.stdout), "");
/// // Ignores any piped-in input /// // Ignores any piped-in input
/// ``` /// ```
#[must_use]
#[stable(feature = "process", since = "1.0.0")] #[stable(feature = "process", since = "1.0.0")]
pub fn null() -> Stdio { pub fn null() -> Stdio {
Stdio(imp::Stdio::Null) Stdio(imp::Stdio::Null)
@ -1462,6 +1468,7 @@ impl ExitStatus {
/// println!("failed to create 'projects/' directory: {}", status); /// println!("failed to create 'projects/' directory: {}", status);
/// } /// }
/// ``` /// ```
#[must_use]
#[stable(feature = "process", since = "1.0.0")] #[stable(feature = "process", since = "1.0.0")]
pub fn success(&self) -> bool { pub fn success(&self) -> bool {
self.0.exit_ok().is_ok() self.0.exit_ok().is_ok()
@ -1493,6 +1500,7 @@ impl ExitStatus {
/// None => println!("Process terminated by signal") /// None => println!("Process terminated by signal")
/// } /// }
/// ``` /// ```
#[must_use]
#[stable(feature = "process", since = "1.0.0")] #[stable(feature = "process", since = "1.0.0")]
pub fn code(&self) -> Option<i32> { pub fn code(&self) -> Option<i32> {
self.0.code() self.0.code()
@ -1580,6 +1588,7 @@ impl ExitStatusError {
/// assert_eq!(bad.code(), Some(1)); /// assert_eq!(bad.code(), Some(1));
/// # } // #[cfg(unix)] /// # } // #[cfg(unix)]
/// ``` /// ```
#[must_use]
pub fn code(&self) -> Option<i32> { pub fn code(&self) -> Option<i32> {
self.code_nonzero().map(Into::into) self.code_nonzero().map(Into::into)
} }
@ -1605,11 +1614,13 @@ impl ExitStatusError {
/// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap()); /// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
/// # } // cfg!(unix) /// # } // cfg!(unix)
/// ``` /// ```
#[must_use]
pub fn code_nonzero(&self) -> Option<NonZeroI32> { pub fn code_nonzero(&self) -> Option<NonZeroI32> {
self.0.code() self.0.code()
} }
/// Converts an `ExitStatusError` (back) to an `ExitStatus`. /// Converts an `ExitStatusError` (back) to an `ExitStatus`.
#[must_use]
pub fn into_status(&self) -> ExitStatus { pub fn into_status(&self) -> ExitStatus {
ExitStatus(self.0.into()) ExitStatus(self.0.into())
} }
@ -1718,6 +1729,7 @@ impl Child {
/// println!("ls command didn't start"); /// println!("ls command didn't start");
/// } /// }
/// ``` /// ```
#[must_use]
#[stable(feature = "process_id", since = "1.3.0")] #[stable(feature = "process_id", since = "1.3.0")]
pub fn id(&self) -> u32 { pub fn id(&self) -> u32 {
self.handle.id() self.handle.id()
@ -1988,6 +2000,7 @@ pub fn abort() -> ! {
/// ``` /// ```
/// ///
/// ///
#[must_use]
#[stable(feature = "getpid", since = "1.26.0")] #[stable(feature = "getpid", since = "1.26.0")]
pub fn id() -> u32 { pub fn id() -> u32 {
crate::sys::os::getpid() crate::sys::os::getpid()

View file

@ -61,6 +61,7 @@ impl WaitTimeoutResult {
/// } /// }
/// } /// }
/// ``` /// ```
#[must_use]
#[stable(feature = "wait_timeout", since = "1.5.0")] #[stable(feature = "wait_timeout", since = "1.5.0")]
pub fn timed_out(&self) -> bool { pub fn timed_out(&self) -> bool {
self.0 self.0

View file

@ -707,6 +707,7 @@ impl<T> UnsafeFlavor<T> for Receiver<T> {
/// // Let's see what that answer was /// // Let's see what that answer was
/// println!("{:?}", receiver.recv().unwrap()); /// println!("{:?}", receiver.recv().unwrap());
/// ``` /// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub fn channel<T>() -> (Sender<T>, Receiver<T>) { pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let a = Arc::new(oneshot::Packet::new()); let a = Arc::new(oneshot::Packet::new());
@ -755,6 +756,7 @@ pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
/// assert_eq!(receiver.recv().unwrap(), 1); /// assert_eq!(receiver.recv().unwrap(), 1);
/// assert_eq!(receiver.recv().unwrap(), 2); /// assert_eq!(receiver.recv().unwrap(), 2);
/// ``` /// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Receiver<T>) { pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Receiver<T>) {
let a = Arc::new(sync::Packet::new(bound)); let a = Arc::new(sync::Packet::new(bound));

View file

@ -106,6 +106,7 @@ impl CommandEnv {
/// This struct is created by /// This struct is created by
/// [`Command::get_envs`][crate::process::Command::get_envs]. See its /// [`Command::get_envs`][crate::process::Command::get_envs]. See its
/// documentation for more. /// documentation for more.
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "command_access", since = "1.57.0")] #[stable(feature = "command_access", since = "1.57.0")]
#[derive(Debug)] #[derive(Debug)]
pub struct CommandEnvs<'a> { pub struct CommandEnvs<'a> {

View file

@ -650,6 +650,7 @@ where
/// ///
/// handler.join().unwrap(); /// handler.join().unwrap();
/// ``` /// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub fn current() -> Thread { pub fn current() -> Thread {
thread_info::current_thread().expect( thread_info::current_thread().expect(
@ -738,6 +739,7 @@ pub fn yield_now() {
/// ///
/// [Mutex]: crate::sync::Mutex /// [Mutex]: crate::sync::Mutex
#[inline] #[inline]
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub fn panicking() -> bool { pub fn panicking() -> bool {
panicking::panicking() panicking::panicking()
@ -1132,6 +1134,7 @@ impl Thread {
/// assert!(thread::current().id() != other_thread_id); /// assert!(thread::current().id() != other_thread_id);
/// ``` /// ```
#[stable(feature = "thread_id", since = "1.19.0")] #[stable(feature = "thread_id", since = "1.19.0")]
#[must_use]
pub fn id(&self) -> ThreadId { pub fn id(&self) -> ThreadId {
self.inner.id self.inner.id
} }
@ -1174,6 +1177,7 @@ impl Thread {
/// ///
/// [naming-threads]: ./index.html#naming-threads /// [naming-threads]: ./index.html#naming-threads
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn name(&self) -> Option<&str> { pub fn name(&self) -> Option<&str> {
self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) }) self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
} }
@ -1361,6 +1365,7 @@ impl<T> JoinHandle<T> {
/// println!("thread id: {:?}", thread.id()); /// println!("thread id: {:?}", thread.id());
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn thread(&self) -> &Thread { pub fn thread(&self) -> &Thread {
&self.0.thread &self.0.thread
} }

View file

@ -239,6 +239,7 @@ impl Instant {
/// ///
/// let now = Instant::now(); /// let now = Instant::now();
/// ``` /// ```
#[must_use]
#[stable(feature = "time2", since = "1.8.0")] #[stable(feature = "time2", since = "1.8.0")]
pub fn now() -> Instant { pub fn now() -> Instant {
let os_now = time::Instant::now(); let os_now = time::Instant::now();
@ -306,6 +307,7 @@ impl Instant {
/// let new_now = Instant::now(); /// let new_now = Instant::now();
/// println!("{:?}", new_now.duration_since(now)); /// println!("{:?}", new_now.duration_since(now));
/// ``` /// ```
#[must_use]
#[stable(feature = "time2", since = "1.8.0")] #[stable(feature = "time2", since = "1.8.0")]
pub fn duration_since(&self, earlier: Instant) -> Duration { pub fn duration_since(&self, earlier: Instant) -> Duration {
self.0.checked_sub_instant(&earlier.0).expect("supplied instant is later than self") self.0.checked_sub_instant(&earlier.0).expect("supplied instant is later than self")
@ -326,6 +328,7 @@ impl Instant {
/// println!("{:?}", new_now.checked_duration_since(now)); /// println!("{:?}", new_now.checked_duration_since(now));
/// println!("{:?}", now.checked_duration_since(new_now)); // None /// println!("{:?}", now.checked_duration_since(new_now)); // None
/// ``` /// ```
#[must_use]
#[stable(feature = "checked_duration_since", since = "1.39.0")] #[stable(feature = "checked_duration_since", since = "1.39.0")]
pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> { pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
self.0.checked_sub_instant(&earlier.0) self.0.checked_sub_instant(&earlier.0)
@ -346,6 +349,7 @@ impl Instant {
/// println!("{:?}", new_now.saturating_duration_since(now)); /// println!("{:?}", new_now.saturating_duration_since(now));
/// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
/// ``` /// ```
#[must_use]
#[stable(feature = "checked_duration_since", since = "1.39.0")] #[stable(feature = "checked_duration_since", since = "1.39.0")]
pub fn saturating_duration_since(&self, earlier: Instant) -> Duration { pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
self.checked_duration_since(earlier).unwrap_or_default() self.checked_duration_since(earlier).unwrap_or_default()
@ -370,6 +374,7 @@ impl Instant {
/// sleep(three_secs); /// sleep(three_secs);
/// assert!(instant.elapsed() >= three_secs); /// assert!(instant.elapsed() >= three_secs);
/// ``` /// ```
#[must_use]
#[stable(feature = "time2", since = "1.8.0")] #[stable(feature = "time2", since = "1.8.0")]
pub fn elapsed(&self) -> Duration { pub fn elapsed(&self) -> Duration {
Instant::now() - *self Instant::now() - *self
@ -476,6 +481,7 @@ impl SystemTime {
/// ///
/// let sys_time = SystemTime::now(); /// let sys_time = SystemTime::now();
/// ``` /// ```
#[must_use]
#[stable(feature = "time2", since = "1.8.0")] #[stable(feature = "time2", since = "1.8.0")]
pub fn now() -> SystemTime { pub fn now() -> SystemTime {
SystemTime(time::SystemTime::now()) SystemTime(time::SystemTime::now())
@ -644,6 +650,7 @@ impl SystemTimeError {
/// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()), /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
/// } /// }
/// ``` /// ```
#[must_use]
#[stable(feature = "time2", since = "1.8.0")] #[stable(feature = "time2", since = "1.8.0")]
pub fn duration(&self) -> Duration { pub fn duration(&self) -> Duration {
self.0 self.0

View file

@ -48,7 +48,7 @@ fn instant_monotonic_concurrent() -> crate::thread::Result<()> {
#[test] #[test]
fn instant_elapsed() { fn instant_elapsed() {
let a = Instant::now(); let a = Instant::now();
a.elapsed(); let _ = a.elapsed();
} }
#[test] #[test]
@ -93,7 +93,7 @@ fn instant_math_is_associative() {
#[should_panic] #[should_panic]
fn instant_duration_since_panic() { fn instant_duration_since_panic() {
let a = Instant::now(); let a = Instant::now();
(a - Duration::SECOND).duration_since(a); let _ = (a - Duration::SECOND).duration_since(a);
} }
#[test] #[test]