diff options
Diffstat (limited to 'src/libstd/sys/unix')
| -rw-r--r-- | src/libstd/sys/unix/args.rs | 125 | ||||
| -rw-r--r-- | src/libstd/sys/unix/condvar.rs | 64 | ||||
| -rw-r--r-- | src/libstd/sys/unix/ext/mod.rs | 31 | ||||
| -rw-r--r-- | src/libstd/sys/unix/ext/net.rs | 174 | ||||
| -rw-r--r-- | src/libstd/sys/unix/fs.rs | 453 | ||||
| -rw-r--r-- | src/libstd/sys/unix/mod.rs | 68 | ||||
| -rw-r--r-- | src/libstd/sys/unix/mutex.rs | 12 | ||||
| -rw-r--r-- | src/libstd/sys/unix/process/process_unix.rs | 172 | ||||
| -rw-r--r-- | src/libstd/sys/unix/rwlock.rs | 6 | ||||
| -rw-r--r-- | src/libstd/sys/unix/time.rs | 124 |
10 files changed, 638 insertions, 591 deletions
diff --git a/src/libstd/sys/unix/args.rs b/src/libstd/sys/unix/args.rs index 2ed1585395e..09acc3f6e3e 100644 --- a/src/libstd/sys/unix/args.rs +++ b/src/libstd/sys/unix/args.rs @@ -10,10 +10,14 @@ use crate::marker::PhantomData; use crate::vec; /// One-time global initialization. -pub unsafe fn init(argc: isize, argv: *const *const u8) { imp::init(argc, argv) } +pub unsafe fn init(argc: isize, argv: *const *const u8) { + imp::init(argc, argv) +} /// One-time global cleanup. -pub unsafe fn cleanup() { imp::cleanup() } +pub unsafe fn cleanup() { + imp::cleanup() +} /// Returns the command line arguments pub fn args() -> Args { @@ -33,36 +37,46 @@ impl Args { impl Iterator for Args { type Item = OsString; - fn next(&mut self) -> Option<OsString> { self.iter.next() } - fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } + fn next(&mut self) -> Option<OsString> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } } impl ExactSizeIterator for Args { - fn len(&self) -> usize { self.iter.len() } + fn len(&self) -> usize { + self.iter.len() + } } impl DoubleEndedIterator for Args { - fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() } + fn next_back(&mut self) -> Option<OsString> { + self.iter.next_back() + } } -#[cfg(any(target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "dragonfly", - target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris", - target_os = "emscripten", - target_os = "haiku", - target_os = "l4re", - target_os = "fuchsia", - target_os = "redox"))] +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "netbsd", + target_os = "openbsd", + target_os = "solaris", + target_os = "emscripten", + target_os = "haiku", + target_os = "l4re", + target_os = "fuchsia", + target_os = "redox" +))] mod imp { - use crate::os::unix::prelude::*; - use crate::ptr; + use super::Args; use crate::ffi::{CStr, OsString}; use crate::marker::PhantomData; - use super::Args; + use crate::os::unix::prelude::*; + use crate::ptr; use crate::sys_common::mutex::Mutex; @@ -83,10 +97,7 @@ mod imp { // On Linux-GNU, we rely on `ARGV_INIT_ARRAY` below to initialize // `ARGC` and `ARGV`. But in Miri that does not actually happen so we // still initialize here. - #[cfg(any( - miri, - not(all(target_os = "linux", target_env = "gnu")) - ))] + #[cfg(any(miri, not(all(target_os = "linux", target_env = "gnu"))))] really_init(_argc, _argv); } @@ -119,57 +130,52 @@ mod imp { } pub fn args() -> Args { - Args { - iter: clone().into_iter(), - _dont_send_or_sync_me: PhantomData - } + Args { iter: clone().into_iter(), _dont_send_or_sync_me: PhantomData } } fn clone() -> Vec<OsString> { unsafe { let _guard = LOCK.lock(); - (0..ARGC).map(|i| { - let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char); - OsStringExt::from_vec(cstr.to_bytes().to_vec()) - }).collect() + (0..ARGC) + .map(|i| { + let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char); + OsStringExt::from_vec(cstr.to_bytes().to_vec()) + }) + .collect() } } } -#[cfg(any(target_os = "macos", - target_os = "ios"))] +#[cfg(any(target_os = "macos", target_os = "ios"))] mod imp { + use super::Args; use crate::ffi::CStr; use crate::marker::PhantomData; - use super::Args; - pub unsafe fn init(_argc: isize, _argv: *const *const u8) { - } + pub unsafe fn init(_argc: isize, _argv: *const *const u8) {} - pub fn cleanup() { - } + pub fn cleanup() {} #[cfg(target_os = "macos")] pub fn args() -> Args { use crate::os::unix::prelude::*; - extern { + extern "C" { // These functions are in crt_externs.h. fn _NSGetArgc() -> *mut libc::c_int; fn _NSGetArgv() -> *mut *mut *mut libc::c_char; } let vec = unsafe { - let (argc, argv) = (*_NSGetArgc() as isize, - *_NSGetArgv() as *const *const libc::c_char); - (0.. argc as isize).map(|i| { - let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec(); - OsStringExt::from_vec(bytes) - }).collect::<Vec<_>>() + let (argc, argv) = + (*_NSGetArgc() as isize, *_NSGetArgv() as *const *const libc::c_char); + (0..argc as isize) + .map(|i| { + let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec(); + OsStringExt::from_vec(bytes) + }) + .collect::<Vec<_>>() }; - Args { - iter: vec.into_iter(), - _dont_send_or_sync_me: PhantomData, - } + Args { iter: vec.into_iter(), _dont_send_or_sync_me: PhantomData } } // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs @@ -190,22 +196,22 @@ mod imp { use crate::mem; use crate::str; - extern { + extern "C" { fn sel_registerName(name: *const libc::c_uchar) -> Sel; fn objc_getClass(class_name: *const libc::c_uchar) -> NsId; } - #[cfg(target_arch="aarch64")] - extern { + #[cfg(target_arch = "aarch64")] + extern "C" { fn objc_msgSend(obj: NsId, sel: Sel) -> NsId; - #[link_name="objc_msgSend"] + #[link_name = "objc_msgSend"] fn objc_msgSend_ul(obj: NsId, sel: Sel, i: libc::c_ulong) -> NsId; } - #[cfg(not(target_arch="aarch64"))] - extern { + #[cfg(not(target_arch = "aarch64"))] + extern "C" { fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId; - #[link_name="objc_msgSend"] + #[link_name = "objc_msgSend"] fn objc_msgSend_ul(obj: NsId, sel: Sel, ...) -> NsId; } @@ -228,8 +234,7 @@ mod imp { let cnt: usize = mem::transmute(objc_msgSend(args, count_sel)); for i in 0..cnt { let tmp = objc_msgSend_ul(args, object_at_sel, i as libc::c_ulong); - let utf_c_str: *const libc::c_char = - mem::transmute(objc_msgSend(tmp, utf8_sel)); + let utf_c_str: *const libc::c_char = mem::transmute(objc_msgSend(tmp, utf8_sel)); let bytes = CStr::from_ptr(utf_c_str).to_bytes(); res.push(OsString::from(str::from_utf8(bytes).unwrap())) } diff --git a/src/libstd/sys/unix/condvar.rs b/src/libstd/sys/unix/condvar.rs index 6be844ded19..b4896b7ad74 100644 --- a/src/libstd/sys/unix/condvar.rs +++ b/src/libstd/sys/unix/condvar.rs @@ -2,15 +2,15 @@ use crate::cell::UnsafeCell; use crate::sys::mutex::{self, Mutex}; use crate::time::Duration; -pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t> } +pub struct Condvar { + inner: UnsafeCell<libc::pthread_cond_t>, +} unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} -const TIMESPEC_MAX: libc::timespec = libc::timespec { - tv_sec: <libc::time_t>::max_value(), - tv_nsec: 1_000_000_000 - 1, -}; +const TIMESPEC_MAX: libc::timespec = + libc::timespec { tv_sec: <libc::time_t>::max_value(), tv_nsec: 1_000_000_000 - 1 }; fn saturating_cast_to_time_t(value: u64) -> libc::time_t { if value > <libc::time_t>::max_value() as u64 { @@ -27,18 +27,22 @@ impl Condvar { Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) } } - #[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "l4re", - target_os = "android", - target_os = "redox"))] + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "l4re", + target_os = "android", + target_os = "redox" + ))] pub unsafe fn init(&mut self) {} - #[cfg(not(any(target_os = "macos", - target_os = "ios", - target_os = "l4re", - target_os = "android", - target_os = "redox")))] + #[cfg(not(any( + target_os = "macos", + target_os = "ios", + target_os = "l4re", + target_os = "android", + target_os = "redox" + )))] pub unsafe fn init(&mut self) { use crate::mem::MaybeUninit; let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit(); @@ -74,9 +78,7 @@ impl Condvar { // where we configure condition variable to use monotonic clock (instead of // default system clock). This approach avoids all problems that result // from changes made to the system time. - #[cfg(not(any(target_os = "macos", - target_os = "ios", - target_os = "android")))] + #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool { use crate::mem; @@ -92,17 +94,14 @@ impl Condvar { .and_then(|s| s.checked_add(now.tv_sec)); let nsec = nsec % 1_000_000_000; - let timeout = sec.map(|s| { - libc::timespec { tv_sec: s, tv_nsec: nsec as _} - }).unwrap_or(TIMESPEC_MAX); + let timeout = + sec.map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec as _ }).unwrap_or(TIMESPEC_MAX); - let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), - &timeout); + let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout); assert!(r == libc::ETIMEDOUT || r == 0); r == 0 } - // This implementation is modeled after libcxx's condition_variable // https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46 // https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367 @@ -138,21 +137,20 @@ impl Condvar { let r = libc::gettimeofday(&mut sys_now, ptr::null_mut()); debug_assert_eq!(r, 0); - let nsec = dur.subsec_nanos() as libc::c_long + - (sys_now.tv_usec * 1000) as libc::c_long; + let nsec = dur.subsec_nanos() as libc::c_long + (sys_now.tv_usec * 1000) as libc::c_long; let extra = (nsec / 1_000_000_000) as libc::time_t; let nsec = nsec % 1_000_000_000; let seconds = saturating_cast_to_time_t(dur.as_secs()); - let timeout = sys_now.tv_sec.checked_add(extra).and_then(|s| { - s.checked_add(seconds) - }).map(|s| { - libc::timespec { tv_sec: s, tv_nsec: nsec } - }).unwrap_or(TIMESPEC_MAX); + let timeout = sys_now + .tv_sec + .checked_add(extra) + .and_then(|s| s.checked_add(seconds)) + .map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec }) + .unwrap_or(TIMESPEC_MAX); // And wait! - let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), - &timeout); + let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout); debug_assert!(r == libc::ETIMEDOUT || r == 0); // ETIMEDOUT is not a totally reliable method of determining timeout due diff --git a/src/libstd/sys/unix/ext/mod.rs b/src/libstd/sys/unix/ext/mod.rs index 78a3fd05c73..cbdb1c10049 100644 --- a/src/libstd/sys/unix/ext/mod.rs +++ b/src/libstd/sys/unix/ext/mod.rs @@ -29,31 +29,38 @@ #![doc(cfg(unix))] #![allow(missing_docs)] -pub mod io; pub mod ffi; pub mod fs; +pub mod io; +pub mod net; pub mod process; pub mod raw; pub mod thread; -pub mod net; /// A prelude for conveniently writing platform-specific code. /// /// Includes all extension traits, and some important type definitions. #[stable(feature = "rust1", since = "1.0.0")] pub mod prelude { - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] - pub use super::io::{RawFd, AsRawFd, FromRawFd, IntoRawFd}; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] pub use super::ffi::{OsStrExt, OsStringExt}; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] - pub use super::fs::{PermissionsExt, OpenOptionsExt, MetadataExt, FileTypeExt}; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] pub use super::fs::DirEntryExt; - #[doc(no_inline)] #[stable(feature = "file_offset", since = "1.15.0")] + #[doc(no_inline)] + #[stable(feature = "file_offset", since = "1.15.0")] pub use super::fs::FileExt; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] - pub use super::thread::JoinHandleExt; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use super::fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use super::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] pub use super::process::{CommandExt, ExitStatusExt}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use super::thread::JoinHandleExt; } diff --git a/src/libstd/sys/unix/ext/net.rs b/src/libstd/sys/unix/ext/net.rs index 5177cce628c..e0e6e02a443 100644 --- a/src/libstd/sys/unix/ext/net.rs +++ b/src/libstd/sys/unix/ext/net.rs @@ -22,22 +22,32 @@ use crate::io::{self, Initializer, IoSlice, IoSliceMut}; use crate::mem; use crate::net::{self, Shutdown}; use crate::os::unix::ffi::OsStrExt; -use crate::os::unix::io::{RawFd, AsRawFd, FromRawFd, IntoRawFd}; +use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use crate::path::Path; -use crate::time::Duration; -use crate::sys::{self, cvt}; use crate::sys::net::Socket; +use crate::sys::{self, cvt}; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; +use crate::time::Duration; -#[cfg(any(target_os = "linux", target_os = "android", - target_os = "dragonfly", target_os = "freebsd", - target_os = "openbsd", target_os = "netbsd", - target_os = "haiku"))] +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "haiku" +))] use libc::MSG_NOSIGNAL; -#[cfg(not(any(target_os = "linux", target_os = "android", - target_os = "dragonfly", target_os = "freebsd", - target_os = "openbsd", target_os = "netbsd", - target_os = "haiku")))] +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "haiku" +)))] const MSG_NOSIGNAL: libc::c_int = 0x0; fn sun_path_offset(addr: &libc::sockaddr_un) -> usize { @@ -54,13 +64,17 @@ unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::sockl let bytes = path.as_os_str().as_bytes(); if bytes.contains(&0) { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "paths may not contain interior null bytes")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "paths may not contain interior null bytes", + )); } if bytes.len() >= addr.sun_path.len() { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "path must be shorter than SUN_LEN")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "path must be shorter than SUN_LEN", + )); } for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) { *dst = *src as libc::c_char; @@ -107,7 +121,8 @@ pub struct SocketAddr { impl SocketAddr { fn new<F>(f: F) -> io::Result<SocketAddr> - where F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int + where + F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int, { unsafe { let mut addr: libc::sockaddr_un = mem::zeroed(); @@ -121,16 +136,15 @@ impl SocketAddr { if len == 0 { // When there is a datagram from unnamed unix socket // linux returns zero bytes of address - len = sun_path_offset(&addr) as libc::socklen_t; // i.e., zero-length address + len = sun_path_offset(&addr) as libc::socklen_t; // i.e., zero-length address } else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "file descriptor did not correspond to a Unix socket")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "file descriptor did not correspond to a Unix socket", + )); } - Ok(SocketAddr { - addr, - len, - }) + Ok(SocketAddr { addr, len }) } /// Returns `true` if the address is unnamed. @@ -164,11 +178,7 @@ impl SocketAddr { /// ``` #[stable(feature = "unix_socket", since = "1.10.0")] pub fn is_unnamed(&self) -> bool { - if let AddressKind::Unnamed = self.address() { - true - } else { - false - } + if let AddressKind::Unnamed = self.address() { true } else { false } } /// Returns the contents of this address if it is a `pathname` address. @@ -203,11 +213,7 @@ impl SocketAddr { /// ``` #[stable(feature = "unix_socket", since = "1.10.0")] pub fn as_pathname(&self) -> Option<&Path> { - if let AddressKind::Pathname(path) = self.address() { - Some(path) - } else { - None - } + if let AddressKind::Pathname(path) = self.address() { Some(path) } else { None } } fn address(&self) -> AddressKind<'_> { @@ -682,17 +688,23 @@ impl IntoRawFd for UnixStream { #[stable(feature = "rust1", since = "1.0.0")] impl AsRawFd for net::TcpStream { - fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() } + fn as_raw_fd(&self) -> RawFd { + *self.as_inner().socket().as_inner() + } } #[stable(feature = "rust1", since = "1.0.0")] impl AsRawFd for net::TcpListener { - fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() } + fn as_raw_fd(&self) -> RawFd { + *self.as_inner().socket().as_inner() + } } #[stable(feature = "rust1", since = "1.0.0")] impl AsRawFd for net::UdpSocket { - fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() } + fn as_raw_fd(&self) -> RawFd { + *self.as_inner().socket().as_inner() + } } #[stable(feature = "from_raw_os", since = "1.1.0")] @@ -1287,21 +1299,21 @@ impl UnixDatagram { #[stable(feature = "unix_socket", since = "1.10.0")] pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { let mut count = 0; - let addr = SocketAddr::new(|addr, len| { - unsafe { - count = libc::recvfrom(*self.0.as_inner(), - buf.as_mut_ptr() as *mut _, - buf.len(), - 0, - addr, - len); - if count > 0 { - 1 - } else if count == 0 { - 0 - } else { - -1 - } + let addr = SocketAddr::new(|addr, len| unsafe { + count = libc::recvfrom( + *self.0.as_inner(), + buf.as_mut_ptr() as *mut _, + buf.len(), + 0, + addr, + len, + ); + if count > 0 { + 1 + } else if count == 0 { + 0 + } else { + -1 } })?; @@ -1350,12 +1362,14 @@ impl UnixDatagram { unsafe { let (addr, len) = sockaddr_un(path)?; - let count = cvt(libc::sendto(*d.0.as_inner(), - buf.as_ptr() as *const _, - buf.len(), - MSG_NOSIGNAL, - &addr as *const _ as *const _, - len))?; + let count = cvt(libc::sendto( + *d.0.as_inner(), + buf.as_ptr() as *const _, + buf.len(), + MSG_NOSIGNAL, + &addr as *const _ as *const _, + len, + ))?; Ok(count as usize) } } @@ -1606,11 +1620,11 @@ impl IntoRawFd for UnixDatagram { #[cfg(all(test, not(target_os = "emscripten")))] mod test { - use crate::thread; - use crate::io::{self, ErrorKind}; use crate::io::prelude::*; - use crate::time::Duration; + use crate::io::{self, ErrorKind}; use crate::sys_common::io::test::tmpdir; + use crate::thread; + use crate::time::Duration; use super::*; @@ -1620,7 +1634,7 @@ mod test { Ok(e) => e, Err(e) => panic!("{}", e), } - } + }; } #[test] @@ -1640,8 +1654,7 @@ mod test { }); let mut stream = or_panic!(UnixStream::connect(&socket_path)); - assert_eq!(Some(&*socket_path), - stream.peer_addr().unwrap().as_pathname()); + assert_eq!(Some(&*socket_path), stream.peer_addr().unwrap().as_pathname()); or_panic!(stream.write_all(msg1)); let mut buf = vec![]; or_panic!(stream.read_to_end(&mut buf)); @@ -1655,16 +1668,18 @@ mod test { fn vectored() { let (mut s1, mut s2) = or_panic!(UnixStream::pair()); - let len = or_panic!(s1.write_vectored( - &[IoSlice::new(b"hello"), IoSlice::new(b" "), IoSlice::new(b"world!")], - )); + let len = or_panic!(s1.write_vectored(&[ + IoSlice::new(b"hello"), + IoSlice::new(b" "), + IoSlice::new(b"world!") + ],)); assert_eq!(len, 12); let mut buf1 = [0; 6]; let mut buf2 = [0; 7]; - let len = or_panic!(s2.read_vectored( - &mut [IoSliceMut::new(&mut buf1), IoSliceMut::new(&mut buf2)], - )); + let len = or_panic!( + s2.read_vectored(&mut [IoSliceMut::new(&mut buf1), IoSliceMut::new(&mut buf2)],) + ); assert_eq!(len, 12); assert_eq!(&buf1, b"hello "); assert_eq!(&buf2, b"world!\0"); @@ -1744,9 +1759,10 @@ mod test { #[test] fn long_path() { let dir = tmpdir(); - let socket_path = dir.path() - .join("asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfa\ - sasdfasdfasdasdfasdfasdfadfasdfasdfasdfasdfasdf"); + let socket_path = dir.path().join( + "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfa\ + sasdfasdfasdasdfasdfasdfadfasdfasdfasdfasdfasdf", + ); match UnixStream::connect(&socket_path) { Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {} Err(e) => panic!("unexpected error {}", e), @@ -1805,8 +1821,11 @@ mod test { let mut buf = [0; 10]; let kind = stream.read_exact(&mut buf).err().expect("expected error").kind(); - assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, - "unexpected_error: {:?}", kind); + assert!( + kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, + "unexpected_error: {:?}", + kind + ); } #[test] @@ -1827,8 +1846,11 @@ mod test { assert_eq!(b"hello world", &buf[..]); let kind = stream.read_exact(&mut buf).err().expect("expected error").kind(); - assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, - "unexpected_error: {:?}", kind); + assert!( + kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, + "unexpected_error: {:?}", + kind + ); } // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index 8669c48e3bb..26fb0bf10fe 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -1,8 +1,8 @@ use crate::os::unix::prelude::*; -use crate::ffi::{CString, CStr, OsString, OsStr}; +use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; -use crate::io::{self, Error, ErrorKind, SeekFrom, IoSlice, IoSliceMut}; +use crate::io::{self, Error, ErrorKind, IoSlice, IoSliceMut, SeekFrom}; use crate::mem; use crate::path::{Path, PathBuf}; use crate::ptr; @@ -14,28 +14,38 @@ use crate::sys_common::{AsInner, FromInner}; use libc::{c_int, mode_t}; -#[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))] -use libc::{stat64, fstat64, lstat64, off64_t, ftruncate64, lseek64, dirent64, readdir64_r, open64}; -#[cfg(any(target_os = "linux", target_os = "emscripten"))] -use libc::fstatat64; #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))] use libc::dirfd; +#[cfg(any(target_os = "linux", target_os = "emscripten"))] +use libc::fstatat64; +#[cfg(not(any( + target_os = "linux", + target_os = "emscripten", + target_os = "solaris", + target_os = "l4re", + target_os = "fuchsia", + target_os = "redox" +)))] +use libc::readdir_r as readdir64_r; #[cfg(target_os = "android")] -use libc::{stat as stat64, fstat as fstat64, fstatat as fstatat64, lstat as lstat64, lseek64, - dirent as dirent64, open as open64}; -#[cfg(not(any(target_os = "linux", - target_os = "emscripten", - target_os = "l4re", - target_os = "android")))] -use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t, - ftruncate as ftruncate64, lseek as lseek64, dirent as dirent64, open as open64}; -#[cfg(not(any(target_os = "linux", - target_os = "emscripten", - target_os = "solaris", - target_os = "l4re", - target_os = "fuchsia", - target_os = "redox")))] -use libc::{readdir_r as readdir64_r}; +use libc::{ + dirent as dirent64, fstat as fstat64, fstatat as fstatat64, lseek64, lstat as lstat64, + open as open64, stat as stat64, +}; +#[cfg(not(any( + target_os = "linux", + target_os = "emscripten", + target_os = "l4re", + target_os = "android" +)))] +use libc::{ + dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64, + lstat as lstat64, off_t as off64_t, open as open64, stat as stat64, +}; +#[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))] +use libc::{ + dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, readdir64_r, stat64, +}; pub use crate::sys_common::fs::remove_dir_all; @@ -211,7 +221,7 @@ pub struct DirEntry { // array to store the name, b) its lifetime between readdir // calls is not guaranteed. #[cfg(any(target_os = "solaris", target_os = "fuchsia", target_os = "redox"))] - name: Box<[u8]> + name: Box<[u8]>, } #[derive(Clone, Debug)] @@ -229,13 +239,19 @@ pub struct OpenOptions { } #[derive(Clone, PartialEq, Eq, Debug)] -pub struct FilePermissions { mode: mode_t } +pub struct FilePermissions { + mode: mode_t, +} #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct FileType { mode: mode_t } +pub struct FileType { + mode: mode_t, +} #[derive(Debug)] -pub struct DirBuilder { mode: mode_t } +pub struct DirBuilder { + mode: mode_t, +} cfg_has_statx! {{ impl FileAttr { @@ -252,7 +268,9 @@ cfg_has_statx! {{ }} impl FileAttr { - pub fn size(&self) -> u64 { self.stat.st_size as u64 } + pub fn size(&self) -> u64 { + self.stat.st_size as u64 + } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) } } @@ -302,10 +320,12 @@ impl FileAttr { })) } - #[cfg(any(target_os = "freebsd", - target_os = "openbsd", - target_os = "macos", - target_os = "ios"))] + #[cfg(any( + target_os = "freebsd", + target_os = "openbsd", + target_os = "macos", + target_os = "ios" + ))] pub fn created(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(libc::timespec { tv_sec: self.stat.st_birthtime as libc::time_t, @@ -313,10 +333,12 @@ impl FileAttr { })) } - #[cfg(not(any(target_os = "freebsd", - target_os = "openbsd", - target_os = "macos", - target_os = "ios")))] + #[cfg(not(any( + target_os = "freebsd", + target_os = "openbsd", + target_os = "macos", + target_os = "ios" + )))] pub fn created(&self) -> io::Result<SystemTime> { cfg_has_statx! { if let Some(ext) = &self.statx_extra_fields { @@ -334,14 +356,18 @@ impl FileAttr { } } - Err(io::Error::new(io::ErrorKind::Other, - "creation time is not available on this platform \ - currently")) + Err(io::Error::new( + io::ErrorKind::Other, + "creation time is not available on this platform \ + currently", + )) } } impl AsInner<stat64> for FileAttr { - fn as_inner(&self) -> &stat64 { &self.stat } + fn as_inner(&self) -> &stat64 { + &self.stat + } } impl FilePermissions { @@ -359,15 +385,25 @@ impl FilePermissions { self.mode |= 0o222; } } - pub fn mode(&self) -> u32 { self.mode as u32 } + pub fn mode(&self) -> u32 { + self.mode as u32 + } } impl FileType { - pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) } - pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) } - pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) } + pub fn is_dir(&self) -> bool { + self.is(libc::S_IFDIR) + } + pub fn is_file(&self) -> bool { + self.is(libc::S_IFREG) + } + pub fn is_symlink(&self) -> bool { + self.is(libc::S_IFLNK) + } - pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode } + pub fn is(&self, mode: mode_t) -> bool { + self.mode & libc::S_IFMT == mode + } } impl FromInner<u32> for FilePermissions { @@ -405,7 +441,7 @@ impl Iterator for ReadDir { return match super::os::errno() { 0 => None, e => Some(Err(Error::from_raw_os_error(e))), - } + }; } let name = (*entry_ptr).d_name.as_ptr(); @@ -413,12 +449,13 @@ impl Iterator for ReadDir { let ret = DirEntry { entry: *entry_ptr, - name: slice::from_raw_parts(name as *const u8, - namelen as usize).to_owned().into_boxed_slice(), - dir: self.clone() + name: slice::from_raw_parts(name as *const u8, namelen as usize) + .to_owned() + .into_boxed_slice(), + dir: self.clone(), }; if ret.name_bytes() != b"." && ret.name_bytes() != b".." { - return Some(Ok(ret)) + return Some(Ok(ret)); } } } @@ -431,10 +468,7 @@ impl Iterator for ReadDir { } unsafe { - let mut ret = DirEntry { - entry: mem::zeroed(), - dir: self.clone(), - }; + let mut ret = DirEntry { entry: mem::zeroed(), dir: self.clone() }; let mut entry_ptr = ptr::null_mut(); loop { if readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 { @@ -445,13 +479,13 @@ impl Iterator for ReadDir { // (instead of looping forever) self.end_of_stream = true; } - return Some(Err(Error::last_os_error())) + return Some(Err(Error::last_os_error())); } if entry_ptr.is_null() { - return None + return None; } if ret.name_bytes() != b"." && ret.name_bytes() != b".." { - return Some(Ok(ret)) + return Some(Ok(ret)); } } } @@ -491,9 +525,7 @@ impl DirEntry { } let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) - })?; + cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?; Ok(FileAttr::from_stat64(stat)) } @@ -521,54 +553,60 @@ impl DirEntry { } } - #[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "linux", - target_os = "emscripten", - target_os = "android", - target_os = "solaris", - target_os = "haiku", - target_os = "l4re", - target_os = "fuchsia", - target_os = "redox"))] + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "linux", + target_os = "emscripten", + target_os = "android", + target_os = "solaris", + target_os = "haiku", + target_os = "l4re", + target_os = "fuchsia", + target_os = "redox" + ))] pub fn ino(&self) -> u64 { self.entry.d_ino as u64 } - #[cfg(any(target_os = "freebsd", - target_os = "openbsd", - target_os = "netbsd", - target_os = "dragonfly"))] + #[cfg(any( + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "dragonfly" + ))] pub fn ino(&self) -> u64 { self.entry.d_fileno as u64 } - #[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "netbsd", - target_os = "openbsd", - target_os = "freebsd", - target_os = "dragonfly"))] + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "netbsd", + target_os = "openbsd", + target_os = "freebsd", + target_os = "dragonfly" + ))] fn name_bytes(&self) -> &[u8] { use crate::slice; unsafe { - slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8, - self.entry.d_namlen as usize) + slice::from_raw_parts( + self.entry.d_name.as_ptr() as *const u8, + self.entry.d_namlen as usize, + ) } } - #[cfg(any(target_os = "android", - target_os = "linux", - target_os = "emscripten", - target_os = "l4re", - target_os = "haiku"))] + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "emscripten", + target_os = "l4re", + target_os = "haiku" + ))] fn name_bytes(&self) -> &[u8] { - unsafe { - CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes() - } + unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes() } } - #[cfg(any(target_os = "solaris", - target_os = "fuchsia", - target_os = "redox"))] + #[cfg(any(target_os = "solaris", target_os = "fuchsia", target_os = "redox"))] fn name_bytes(&self) -> &[u8] { &*self.name } @@ -590,23 +628,39 @@ impl OpenOptions { } } - pub fn read(&mut self, read: bool) { self.read = read; } - pub fn write(&mut self, write: bool) { self.write = write; } - pub fn append(&mut self, append: bool) { self.append = append; } - pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; } - pub fn create(&mut self, create: bool) { self.create = create; } - pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; } + pub fn read(&mut self, read: bool) { + self.read = read; + } + pub fn write(&mut self, write: bool) { + self.write = write; + } + pub fn append(&mut self, append: bool) { + self.append = append; + } + pub fn truncate(&mut self, truncate: bool) { + self.truncate = truncate; + } + pub fn create(&mut self, create: bool) { + self.create = create; + } + pub fn create_new(&mut self, create_new: bool) { + self.create_new = create_new; + } - pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; } - pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; } + pub fn custom_flags(&mut self, flags: i32) { + self.custom_flags = flags; + } + pub fn mode(&mut self, mode: u32) { + self.mode = mode as mode_t; + } fn get_access_mode(&self) -> io::Result<c_int> { match (self.read, self.write, self.append) { - (true, false, false) => Ok(libc::O_RDONLY), - (false, true, false) => Ok(libc::O_WRONLY), - (true, true, false) => Ok(libc::O_RDWR), - (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND), - (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND), + (true, false, false) => Ok(libc::O_RDONLY), + (false, true, false) => Ok(libc::O_WRONLY), + (true, true, false) => Ok(libc::O_RDWR), + (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND), + (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND), (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)), } } @@ -614,23 +668,25 @@ impl OpenOptions { fn get_creation_mode(&self) -> io::Result<c_int> { match (self.write, self.append) { (true, false) => {} - (false, false) => + (false, false) => { if self.truncate || self.create || self.create_new { return Err(Error::from_raw_os_error(libc::EINVAL)); - }, - (_, true) => + } + } + (_, true) => { if self.truncate && !self.create_new { return Err(Error::from_raw_os_error(libc::EINVAL)); - }, + } + } } Ok(match (self.create, self.truncate, self.create_new) { - (false, false, false) => 0, - (true, false, false) => libc::O_CREAT, - (false, true, false) => libc::O_TRUNC, - (true, true, false) => libc::O_CREAT | libc::O_TRUNC, - (_, _, true) => libc::O_CREAT | libc::O_EXCL, - }) + (false, false, false) => 0, + (true, false, false) => libc::O_CREAT, + (false, true, false) => libc::O_TRUNC, + (true, true, false) => libc::O_CREAT | libc::O_TRUNC, + (_, _, true) => libc::O_CREAT | libc::O_EXCL, + }) } } @@ -641,13 +697,11 @@ impl File { } pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> { - let flags = libc::O_CLOEXEC | - opts.get_access_mode()? | - opts.get_creation_mode()? | - (opts.custom_flags as c_int & !libc::O_ACCMODE); - let fd = cvt_r(|| unsafe { - open64(path.as_ptr(), flags, opts.mode as c_int) - })?; + let flags = libc::O_CLOEXEC + | opts.get_access_mode()? + | opts.get_creation_mode()? + | (opts.custom_flags as c_int & !libc::O_ACCMODE); + let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?; let fd = FileDesc::new(fd); // Currently the standard library supports Linux 2.6.18 which did not @@ -672,12 +726,15 @@ impl File { match OPEN_CLOEXEC.load(Ordering::Relaxed) { OPEN_CLOEXEC_UNKNOWN => { need_to_set = !fd.get_cloexec()?; - OPEN_CLOEXEC.store(if need_to_set { - OPEN_CLOEXEC_NOTSUPPORTED - } else { - OPEN_CLOEXEC_SUPPORTED - }, Ordering::Relaxed); - }, + OPEN_CLOEXEC.store( + if need_to_set { + OPEN_CLOEXEC_NOTSUPPORTED + } else { + OPEN_CLOEXEC_SUPPORTED + }, + Ordering::Relaxed, + ); + } OPEN_CLOEXEC_SUPPORTED => need_to_set = false, OPEN_CLOEXEC_NOTSUPPORTED => need_to_set = true, _ => unreachable!(), @@ -712,9 +769,7 @@ impl File { } let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - fstat64(fd, &mut stat) - })?; + cvt(unsafe { fstat64(fd, &mut stat) })?; Ok(FileAttr::from_stat64(stat)) } @@ -727,7 +782,9 @@ impl File { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(not(any(target_os = "macos", target_os = "ios")))] - unsafe fn os_fsync(fd: c_int) -> c_int { libc::fsync(fd) } + unsafe fn os_fsync(fd: c_int) -> c_int { + libc::fsync(fd) + } } pub fn datasync(&self) -> io::Result<()> { @@ -739,11 +796,13 @@ impl File { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] - unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } - #[cfg(not(any(target_os = "macos", - target_os = "ios", - target_os = "linux")))] - unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } + unsafe fn os_datasync(fd: c_int) -> c_int { + libc::fdatasync(fd) + } + #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] + unsafe fn os_datasync(fd: c_int) -> c_int { + libc::fsync(fd) + } } pub fn truncate(&self, size: u64) -> io::Result<()> { @@ -753,12 +812,9 @@ impl File { #[cfg(not(target_os = "android"))] { use crate::convert::TryInto; - let size: off64_t = size - .try_into() - .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; - cvt_r(|| unsafe { - ftruncate64(self.0.raw(), size) - }).map(|_| ()) + let size: off64_t = + size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + cvt_r(|| unsafe { ftruncate64(self.0.raw(), size) }).map(|_| ()) } } @@ -786,7 +842,9 @@ impl File { self.0.write_at(buf, offset) } - pub fn flush(&self) -> io::Result<()> { Ok(()) } + pub fn flush(&self) -> io::Result<()> { + Ok(()) + } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { @@ -804,9 +862,13 @@ impl File { self.0.duplicate().map(File) } - pub fn fd(&self) -> &FileDesc { &self.0 } + pub fn fd(&self) -> &FileDesc { + &self.0 + } - pub fn into_fd(self) -> FileDesc { self.0 } + pub fn into_fd(self) -> FileDesc { + self.0 + } pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> { cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?; @@ -856,7 +918,7 @@ impl fmt::Debug for File { // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no // alternatives. If a better method is invented, it should be used // instead. - let mut buf = vec![0;libc::PATH_MAX as usize]; + let mut buf = vec![0; libc::PATH_MAX as usize]; let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) }; if n == -1 { return None; @@ -883,7 +945,7 @@ impl fmt::Debug for File { libc::O_RDONLY => Some((true, false)), libc::O_RDWR => Some((true, true)), libc::O_WRONLY => Some((false, true)), - _ => None + _ => None, } } @@ -915,10 +977,7 @@ pub fn readdir(p: &Path) -> io::Result<ReadDir> { Err(Error::last_os_error()) } else { let inner = InnerReadDir { dirp: Dir(ptr), root }; - Ok(ReadDir{ - inner: Arc::new(inner), - end_of_stream: false, - }) + Ok(ReadDir { inner: Arc::new(inner), end_of_stream: false }) } } } @@ -955,11 +1014,12 @@ pub fn readlink(p: &Path) -> io::Result<PathBuf> { let mut buf = Vec::with_capacity(256); loop { - let buf_read = cvt(unsafe { - libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) - })? as usize; + let buf_read = + cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize; - unsafe { buf.set_len(buf_read); } + unsafe { + buf.set_len(buf_read); + } if buf_read != buf.capacity() { buf.shrink_to_fit(); @@ -1003,9 +1063,7 @@ pub fn stat(p: &Path) -> io::Result<FileAttr> { } let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - stat64(p.as_ptr(), &mut stat) - })?; + cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?; Ok(FileAttr::from_stat64(stat)) } @@ -1024,9 +1082,7 @@ pub fn lstat(p: &Path) -> io::Result<FileAttr> { } let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - lstat64(p.as_ptr(), &mut stat) - })?; + cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?; Ok(FileAttr::from_stat64(stat)) } @@ -1036,7 +1092,7 @@ pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { unsafe { let r = libc::realpath(path.as_ptr(), ptr::null_mut()); if r.is_null() { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } buf = CStr::from_ptr(r).to_bytes().to_vec(); libc::free(r as *mut _); @@ -1083,10 +1139,12 @@ fn open_to_and_set_permissions( Ok((writer, writer_metadata)) } -#[cfg(not(any(target_os = "linux", - target_os = "android", - target_os = "macos", - target_os = "ios")))] +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "macos", + target_os = "ios" +)))] pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { let (mut reader, reader_metadata) = open_from(from)?; let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?; @@ -1111,15 +1169,7 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { len: libc::size_t, flags: libc::c_uint, ) -> libc::c_long { - libc::syscall( - libc::SYS_copy_file_range, - fd_in, - off_in, - fd_out, - off_out, - len, - flags, - ) + libc::syscall(libc::SYS_copy_file_range, fd_in, off_in, fd_out, off_out, len, flags) } let (mut reader, reader_metadata) = open_from(from)?; @@ -1160,19 +1210,19 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { Err(err) => { match err.raw_os_error() { Some(os_err) - if os_err == libc::ENOSYS - || os_err == libc::EXDEV - || os_err == libc::EINVAL - || os_err == libc::EPERM => - { - // Try fallback io::copy if either: - // - Kernel version is < 4.5 (ENOSYS) - // - Files are mounted on different fs (EXDEV) - // - copy_file_range is disallowed, for example by seccomp (EPERM) - // - copy_file_range cannot be used with pipes or device nodes (EINVAL) - assert_eq!(written, 0); - return io::copy(&mut reader, &mut writer); - } + if os_err == libc::ENOSYS + || os_err == libc::EXDEV + || os_err == libc::EINVAL + || os_err == libc::EPERM => + { + // Try fallback io::copy if either: + // - Kernel version is < 4.5 (ENOSYS) + // - Files are mounted on different fs (EXDEV) + // - copy_file_range is disallowed, for example by seccomp (EPERM) + // - copy_file_range cannot be used with pipes or device nodes (EINVAL) + assert_eq!(written, 0); + return io::copy(&mut reader, &mut writer); + } _ => return Err(err), } } @@ -1248,14 +1298,8 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { // using `fclonefileat`. if HAS_FCLONEFILEAT.load(Ordering::Relaxed) { let to = cstr(to)?; - let clonefile_result = cvt(unsafe { - fclonefileat( - reader.as_raw_fd(), - libc::AT_FDCWD, - to.as_ptr(), - 0, - ) - }); + let clonefile_result = + cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) }); match clonefile_result { Ok(_) => return Ok(reader_metadata.len()), Err(err) => match err.raw_os_error() { @@ -1266,7 +1310,7 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (), Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed), _ => return Err(err), - } + }, } } @@ -1283,20 +1327,9 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { FreeOnDrop(state) }; - let flags = if writer_metadata.is_file() { - COPYFILE_ALL - } else { - COPYFILE_DATA - }; + let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA }; - cvt(unsafe { - fcopyfile( - reader.as_raw_fd(), - writer.as_raw_fd(), - state.0, - flags, - ) - })?; + cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?; let mut bytes_copied: libc::off_t = 0; cvt(unsafe { diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs index bf0166ceb6f..06876cb0614 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -2,21 +2,35 @@ use crate::io::ErrorKind; -#[cfg(any(doc, target_os = "linux"))] pub use crate::os::linux as platform; - -#[cfg(all(not(doc), target_os = "android"))] pub use crate::os::android as platform; -#[cfg(all(not(doc), target_os = "dragonfly"))] pub use crate::os::dragonfly as platform; -#[cfg(all(not(doc), target_os = "freebsd"))] pub use crate::os::freebsd as platform; -#[cfg(all(not(doc), target_os = "haiku"))] pub use crate::os::haiku as platform; -#[cfg(all(not(doc), target_os = "ios"))] pub use crate::os::ios as platform; -#[cfg(all(not(doc), target_os = "macos"))] pub use crate::os::macos as platform; -#[cfg(all(not(doc), target_os = "netbsd"))] pub use crate::os::netbsd as platform; -#[cfg(all(not(doc), target_os = "openbsd"))] pub use crate::os::openbsd as platform; -#[cfg(all(not(doc), target_os = "solaris"))] pub use crate::os::solaris as platform; -#[cfg(all(not(doc), target_os = "emscripten"))] pub use crate::os::emscripten as platform; -#[cfg(all(not(doc), target_os = "fuchsia"))] pub use crate::os::fuchsia as platform; -#[cfg(all(not(doc), target_os = "l4re"))] pub use crate::os::linux as platform; -#[cfg(all(not(doc), target_os = "redox"))] pub use crate::os::redox as platform; +#[cfg(any(doc, target_os = "linux"))] +pub use crate::os::linux as platform; + +#[cfg(all(not(doc), target_os = "android"))] +pub use crate::os::android as platform; +#[cfg(all(not(doc), target_os = "dragonfly"))] +pub use crate::os::dragonfly as platform; +#[cfg(all(not(doc), target_os = "emscripten"))] +pub use crate::os::emscripten as platform; +#[cfg(all(not(doc), target_os = "freebsd"))] +pub use crate::os::freebsd as platform; +#[cfg(all(not(doc), target_os = "fuchsia"))] +pub use crate::os::fuchsia as platform; +#[cfg(all(not(doc), target_os = "haiku"))] +pub use crate::os::haiku as platform; +#[cfg(all(not(doc), target_os = "ios"))] +pub use crate::os::ios as platform; +#[cfg(all(not(doc), target_os = "l4re"))] +pub use crate::os::linux as platform; +#[cfg(all(not(doc), target_os = "macos"))] +pub use crate::os::macos as platform; +#[cfg(all(not(doc), target_os = "netbsd"))] +pub use crate::os::netbsd as platform; +#[cfg(all(not(doc), target_os = "openbsd"))] +pub use crate::os::openbsd as platform; +#[cfg(all(not(doc), target_os = "redox"))] +pub use crate::os::redox as platform; +#[cfg(all(not(doc), target_os = "solaris"))] +pub use crate::os::solaris as platform; pub use self::rand::hashmap_random_keys; pub use libc::strlen; @@ -25,8 +39,8 @@ pub use libc::strlen; pub mod weak; pub mod alloc; -pub mod args; pub mod android; +pub mod args; pub mod cmath; pub mod condvar; pub mod env; @@ -34,14 +48,14 @@ pub mod ext; pub mod fast_thread_local; pub mod fd; pub mod fs; -pub mod memchr; pub mod io; +#[cfg(target_os = "l4re")] +mod l4re; +pub mod memchr; pub mod mutex; #[cfg(not(target_os = "l4re"))] pub mod net; #[cfg(target_os = "l4re")] -mod l4re; -#[cfg(target_os = "l4re")] pub use self::l4re::net; pub mod os; pub mod path; @@ -50,10 +64,10 @@ pub mod process; pub mod rand; pub mod rwlock; pub mod stack_overflow; +pub mod stdio; pub mod thread; pub mod thread_local; pub mod time; -pub mod stdio; pub use crate::sys_common::os_str_bytes as os_str; @@ -102,8 +116,7 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind { // These two constants can have the same value on some systems, // but different values on others, so we can't use a match // clause - x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => - ErrorKind::WouldBlock, + x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => ErrorKind::WouldBlock, _ => ErrorKind::Other, } @@ -125,16 +138,13 @@ macro_rules! impl_is_minus_one { impl_is_minus_one! { i8 i16 i32 i64 isize } pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> { - if t.is_minus_one() { - Err(crate::io::Error::last_os_error()) - } else { - Ok(t) - } + if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) } } pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T> - where T: IsMinusOne, - F: FnMut() -> T +where + T: IsMinusOne, + F: FnMut() -> T, { loop { match cvt(f()) { diff --git a/src/libstd/sys/unix/mutex.rs b/src/libstd/sys/unix/mutex.rs index b43af8fdcaa..b38375a2e03 100644 --- a/src/libstd/sys/unix/mutex.rs +++ b/src/libstd/sys/unix/mutex.rs @@ -1,7 +1,9 @@ use crate::cell::UnsafeCell; use crate::mem::MaybeUninit; -pub struct Mutex { inner: UnsafeCell<libc::pthread_mutex_t> } +pub struct Mutex { + inner: UnsafeCell<libc::pthread_mutex_t>, +} #[inline] pub unsafe fn raw(m: &Mutex) -> *mut libc::pthread_mutex_t { @@ -82,7 +84,9 @@ impl Mutex { } } -pub struct ReentrantMutex { inner: UnsafeCell<libc::pthread_mutex_t> } +pub struct ReentrantMutex { + inner: UnsafeCell<libc::pthread_mutex_t>, +} unsafe impl Send for ReentrantMutex {} unsafe impl Sync for ReentrantMutex {} @@ -96,8 +100,8 @@ impl ReentrantMutex { let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit(); let result = libc::pthread_mutexattr_init(attr.as_mut_ptr()); debug_assert_eq!(result, 0); - let result = libc::pthread_mutexattr_settype(attr.as_mut_ptr(), - libc::PTHREAD_MUTEX_RECURSIVE); + let result = + libc::pthread_mutexattr_settype(attr.as_mut_ptr(), libc::PTHREAD_MUTEX_RECURSIVE); debug_assert_eq!(result, 0); let result = libc::pthread_mutex_init(self.inner.get(), attr.as_ptr()); debug_assert_eq!(result, 0); diff --git a/src/libstd/sys/unix/process/process_unix.rs b/src/libstd/sys/unix/process/process_unix.rs index 45e4d195f17..85c30abe452 100644 --- a/src/libstd/sys/unix/process/process_unix.rs +++ b/src/libstd/sys/unix/process/process_unix.rs @@ -1,9 +1,9 @@ use crate::fmt; use crate::io::{self, Error, ErrorKind}; use crate::ptr; +use crate::sys; use crate::sys::cvt; use crate::sys::process::process_common::*; -use crate::sys; use libc::{c_int, gid_t, pid_t, uid_t}; @@ -12,21 +12,23 @@ use libc::{c_int, gid_t, pid_t, uid_t}; //////////////////////////////////////////////////////////////////////////////// impl Command { - pub fn spawn(&mut self, default: Stdio, needs_stdin: bool) - -> io::Result<(Process, StdioPipes)> { + pub fn spawn( + &mut self, + default: Stdio, + needs_stdin: bool, + ) -> io::Result<(Process, StdioPipes)> { const CLOEXEC_MSG_FOOTER: &[u8] = b"NOEX"; let envp = self.capture_env(); if self.saw_nul() { - return Err(io::Error::new(ErrorKind::InvalidInput, - "nul byte found in provided data")); + return Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data")); } let (ours, theirs) = self.setup_io(default, needs_stdin)?; if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? { - return Ok((ret, ours)) + return Ok((ret, ours)); } let (input, output) = sys::pipe::anon_pipe()?; @@ -53,10 +55,12 @@ impl Command { let bytes = [ (errno >> 24) as u8, (errno >> 16) as u8, - (errno >> 8) as u8, - (errno >> 0) as u8, - CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1], - CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3] + (errno >> 8) as u8, + (errno >> 0) as u8, + CLOEXEC_MSG_FOOTER[0], + CLOEXEC_MSG_FOOTER[1], + CLOEXEC_MSG_FOOTER[2], + CLOEXEC_MSG_FOOTER[3], ]; // pipe I/O up to PIPE_BUF bytes should be atomic, and then // we want to be sure we *don't* run at_exit destructors as @@ -77,22 +81,23 @@ impl Command { match input.read(&mut bytes) { Ok(0) => return Ok((p, ours)), Ok(8) => { - assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]), - "Validation on the CLOEXEC pipe failed: {:?}", bytes); - let errno = combine(&bytes[0.. 4]); - assert!(p.wait().is_ok(), - "wait() should either return Ok or panic"); - return Err(Error::from_raw_os_error(errno)) + assert!( + combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4..8]), + "Validation on the CLOEXEC pipe failed: {:?}", + bytes + ); + let errno = combine(&bytes[0..4]); + assert!(p.wait().is_ok(), "wait() should either return Ok or panic"); + return Err(Error::from_raw_os_error(errno)); } Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => { - assert!(p.wait().is_ok(), - "wait() should either return Ok or panic"); + assert!(p.wait().is_ok(), "wait() should either return Ok or panic"); panic!("the CLOEXEC pipe failed: {:?}", e) - }, - Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic - assert!(p.wait().is_ok(), - "wait() should either return Ok or panic"); + } + Ok(..) => { + // pipe I/O up to PIPE_BUF bytes should be atomic + assert!(p.wait().is_ok(), "wait() should either return Ok or panic"); panic!("short read on the CLOEXEC pipe") } } @@ -112,8 +117,7 @@ impl Command { let envp = self.capture_env(); if self.saw_nul() { - return io::Error::new(ErrorKind::InvalidInput, - "nul byte found in provided data") + return io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"); } match self.setup_io(default, true) { @@ -165,7 +169,7 @@ impl Command { unsafe fn do_exec( &mut self, stdio: ChildPipes, - maybe_envp: Option<&CStringArray> + maybe_envp: Option<&CStringArray>, ) -> Result<!, io::Error> { use crate::sys::{self, cvt_r}; @@ -215,11 +219,10 @@ impl Command { // we're about to run. let mut set = MaybeUninit::<libc::sigset_t>::uninit(); cvt(sigemptyset(set.as_mut_ptr()))?; - cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), - ptr::null_mut()))?; + cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), ptr::null_mut()))?; let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL); if ret == libc::SIG_ERR { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } } @@ -252,29 +255,40 @@ impl Command { Err(io::Error::last_os_error()) } - #[cfg(not(any(target_os = "macos", target_os = "freebsd", - all(target_os = "linux", target_env = "gnu"))))] - fn posix_spawn(&mut self, _: &ChildPipes, _: Option<&CStringArray>) - -> io::Result<Option<Process>> - { + #[cfg(not(any( + target_os = "macos", + target_os = "freebsd", + all(target_os = "linux", target_env = "gnu") + )))] + fn posix_spawn( + &mut self, + _: &ChildPipes, + _: Option<&CStringArray>, + ) -> io::Result<Option<Process>> { Ok(None) } // Only support platforms for which posix_spawn() can return ENOENT // directly. - #[cfg(any(target_os = "macos", target_os = "freebsd", - all(target_os = "linux", target_env = "gnu")))] - fn posix_spawn(&mut self, stdio: &ChildPipes, envp: Option<&CStringArray>) - -> io::Result<Option<Process>> - { + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + all(target_os = "linux", target_env = "gnu") + ))] + fn posix_spawn( + &mut self, + stdio: &ChildPipes, + envp: Option<&CStringArray>, + ) -> io::Result<Option<Process>> { use crate::mem::MaybeUninit; use crate::sys; - if self.get_gid().is_some() || - self.get_uid().is_some() || - self.env_saw_path() || - !self.get_closures().is_empty() { - return Ok(None) + if self.get_gid().is_some() + || self.get_uid().is_some() + || self.env_saw_path() + || !self.get_closures().is_empty() + { + return Ok(None); } // Only glibc 2.24+ posix_spawn() supports returning ENOENT directly. @@ -282,10 +296,10 @@ impl Command { { if let Some(version) = sys::os::glibc_version() { if version < (2, 24) { - return Ok(None) + return Ok(None); } } else { - return Ok(None) + return Ok(None); } } @@ -337,19 +351,25 @@ impl Command { libc::posix_spawn_file_actions_init(file_actions.0.as_mut_ptr()); if let Some(fd) = stdio.stdin.fd() { - cvt(libc::posix_spawn_file_actions_adddup2(file_actions.0.as_mut_ptr(), - fd, - libc::STDIN_FILENO))?; + cvt(libc::posix_spawn_file_actions_adddup2( + file_actions.0.as_mut_ptr(), + fd, + libc::STDIN_FILENO, + ))?; } if let Some(fd) = stdio.stdout.fd() { - cvt(libc::posix_spawn_file_actions_adddup2(file_actions.0.as_mut_ptr(), - fd, - libc::STDOUT_FILENO))?; + cvt(libc::posix_spawn_file_actions_adddup2( + file_actions.0.as_mut_ptr(), + fd, + libc::STDOUT_FILENO, + ))?; } if let Some(fd) = stdio.stderr.fd() { - cvt(libc::posix_spawn_file_actions_adddup2(file_actions.0.as_mut_ptr(), - fd, - libc::STDERR_FILENO))?; + cvt(libc::posix_spawn_file_actions_adddup2( + file_actions.0.as_mut_ptr(), + fd, + libc::STDERR_FILENO, + ))?; } if let Some((f, cwd)) = addchdir { cvt(f(file_actions.0.as_mut_ptr(), cwd.as_ptr()))?; @@ -357,20 +377,16 @@ impl Command { let mut set = MaybeUninit::<libc::sigset_t>::uninit(); cvt(sigemptyset(set.as_mut_ptr()))?; - cvt(libc::posix_spawnattr_setsigmask(attrs.0.as_mut_ptr(), - set.as_ptr()))?; + cvt(libc::posix_spawnattr_setsigmask(attrs.0.as_mut_ptr(), set.as_ptr()))?; cvt(sigaddset(set.as_mut_ptr(), libc::SIGPIPE))?; - cvt(libc::posix_spawnattr_setsigdefault(attrs.0.as_mut_ptr(), - set.as_ptr()))?; + cvt(libc::posix_spawnattr_setsigdefault(attrs.0.as_mut_ptr(), set.as_ptr()))?; - let flags = libc::POSIX_SPAWN_SETSIGDEF | - libc::POSIX_SPAWN_SETSIGMASK; + let flags = libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETSIGMASK; cvt(libc::posix_spawnattr_setflags(attrs.0.as_mut_ptr(), flags as _))?; // Make sure we synchronize access to the global `environ` resource let _env_lock = sys::os::env_lock(); - let envp = envp.map(|c| c.as_ptr()) - .unwrap_or_else(|| *sys::os::environ() as *const _); + let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::os::environ() as *const _); let ret = libc::posix_spawnp( &mut p.pid, self.get_program().as_ptr(), @@ -379,11 +395,7 @@ impl Command { self.get_argv().as_ptr() as *const _, envp as *const _, ); - if ret == 0 { - Ok(Some(p)) - } else { - Err(io::Error::from_raw_os_error(ret)) - } + if ret == 0 { Ok(Some(p)) } else { Err(io::Error::from_raw_os_error(ret)) } } } } @@ -408,8 +420,10 @@ impl Process { // and used for another process, and we probably shouldn't be killing // random processes, so just return an error. if self.status.is_some() { - Err(Error::new(ErrorKind::InvalidInput, - "invalid argument: can't kill an exited process")) + Err(Error::new( + ErrorKind::InvalidInput, + "invalid argument: can't kill an exited process", + )) } else { cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(|_| ()) } @@ -418,7 +432,7 @@ impl Process { pub fn wait(&mut self) -> io::Result<ExitStatus> { use crate::sys::cvt_r; if let Some(status) = self.status { - return Ok(status) + return Ok(status); } let mut status = 0 as c_int; cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?; @@ -428,12 +442,10 @@ impl Process { pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> { if let Some(status) = self.status { - return Ok(Some(status)) + return Ok(Some(status)); } let mut status = 0 as c_int; - let pid = cvt(unsafe { - libc::waitpid(self.pid, &mut status, libc::WNOHANG) - })?; + let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?; if pid == 0 { Ok(None) } else { @@ -461,19 +473,11 @@ impl ExitStatus { } pub fn code(&self) -> Option<i32> { - if self.exited() { - Some(unsafe { libc::WEXITSTATUS(self.0) }) - } else { - None - } + if self.exited() { Some(unsafe { libc::WEXITSTATUS(self.0) }) } else { None } } pub fn signal(&self) -> Option<i32> { - if !self.exited() { - Some(unsafe { libc::WTERMSIG(self.0) }) - } else { - None - } + if !self.exited() { Some(unsafe { libc::WTERMSIG(self.0) }) } else { None } } } diff --git a/src/libstd/sys/unix/rwlock.rs b/src/libstd/sys/unix/rwlock.rs index e48bfdae610..079dea671ef 100644 --- a/src/libstd/sys/unix/rwlock.rs +++ b/src/libstd/sys/unix/rwlock.rs @@ -71,8 +71,10 @@ impl RWLock { let r = libc::pthread_rwlock_wrlock(self.inner.get()); // See comments above for why we check for EDEADLK and write_locked. We // also need to check that num_readers is 0. - if r == libc::EDEADLK || *self.write_locked.get() || - self.num_readers.load(Ordering::Relaxed) != 0 { + if r == libc::EDEADLK + || *self.write_locked.get() + || self.num_readers.load(Ordering::Relaxed) != 0 + { if r == 0 { self.raw_unlock(); } diff --git a/src/libstd/sys/unix/time.rs b/src/libstd/sys/unix/time.rs index a9122defa55..23104419978 100644 --- a/src/libstd/sys/unix/time.rs +++ b/src/libstd/sys/unix/time.rs @@ -15,20 +15,21 @@ struct Timespec { impl Timespec { const fn zero() -> Timespec { - Timespec { - t: libc::timespec { tv_sec: 0, tv_nsec: 0 }, - } + Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } } } fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> { if self >= other { Ok(if self.t.tv_nsec >= other.t.tv_nsec { - Duration::new((self.t.tv_sec - other.t.tv_sec) as u64, - (self.t.tv_nsec - other.t.tv_nsec) as u32) + Duration::new( + (self.t.tv_sec - other.t.tv_sec) as u64, + (self.t.tv_nsec - other.t.tv_nsec) as u32, + ) } else { - Duration::new((self.t.tv_sec - 1 - other.t.tv_sec) as u64, - self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) - - other.t.tv_nsec as u32) + Duration::new( + (self.t.tv_sec - 1 - other.t.tv_sec) as u64, + self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) - other.t.tv_nsec as u32, + ) }) } else { match other.sub_timespec(self) { @@ -52,12 +53,7 @@ impl Timespec { nsec -= NSEC_PER_SEC as u32; secs = secs.checked_add(1)?; } - Some(Timespec { - t: libc::timespec { - tv_sec: secs, - tv_nsec: nsec as _, - }, - }) + Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } }) } fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> { @@ -73,12 +69,7 @@ impl Timespec { nsec += NSEC_PER_SEC as i32; secs = secs.checked_sub(1)?; } - Some(Timespec { - t: libc::timespec { - tv_sec: secs, - tv_nsec: nsec as _, - }, - }) + Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } }) } } @@ -105,7 +96,7 @@ impl Ord for Timespec { } impl Hash for Timespec { - fn hash<H : Hasher>(&self, state: &mut H) { + fn hash<H: Hasher>(&self, state: &mut H) { self.t.tv_sec.hash(state); self.t.tv_nsec.hash(state); } @@ -120,12 +111,12 @@ mod inner { use crate::sys_common::mul_div_u64; use crate::time::Duration; - use super::NSEC_PER_SEC; use super::Timespec; + use super::NSEC_PER_SEC; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct Instant { - t: u64 + t: u64, } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -133,9 +124,7 @@ mod inner { t: Timespec, } - pub const UNIX_EPOCH: SystemTime = SystemTime { - t: Timespec::zero(), - }; + pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() }; #[repr(C)] #[derive(Copy, Clone)] @@ -170,15 +159,11 @@ mod inner { } pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> { - Some(Instant { - t: self.t.checked_add(checked_dur2intervals(other)?)?, - }) + Some(Instant { t: self.t.checked_add(checked_dur2intervals(other)?)? }) } pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> { - Some(Instant { - t: self.t.checked_sub(checked_dur2intervals(other)?)?, - }) + Some(Instant { t: self.t.checked_sub(checked_dur2intervals(other)?)? }) } } @@ -186,18 +171,12 @@ mod inner { pub fn now() -> SystemTime { use crate::ptr; - let mut s = libc::timeval { - tv_sec: 0, - tv_usec: 0, - }; - cvt(unsafe { - libc::gettimeofday(&mut s, ptr::null_mut()) - }).unwrap(); - return SystemTime::from(s) + let mut s = libc::timeval { tv_sec: 0, tv_usec: 0 }; + cvt(unsafe { libc::gettimeofday(&mut s, ptr::null_mut()) }).unwrap(); + return SystemTime::from(s); } - pub fn sub_time(&self, other: &SystemTime) - -> Result<Duration, Duration> { + pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> { self.t.sub_timespec(&other.t) } @@ -228,25 +207,21 @@ mod inner { impl fmt::Debug for SystemTime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SystemTime") - .field("tv_sec", &self.t.t.tv_sec) - .field("tv_nsec", &self.t.t.tv_nsec) - .finish() + .field("tv_sec", &self.t.t.tv_sec) + .field("tv_nsec", &self.t.t.tv_nsec) + .finish() } } fn checked_dur2intervals(dur: &Duration) -> Option<u64> { - let nanos = dur.as_secs() - .checked_mul(NSEC_PER_SEC)? - .checked_add(dur.subsec_nanos() as u64)?; + let nanos = + dur.as_secs().checked_mul(NSEC_PER_SEC)?.checked_add(dur.subsec_nanos() as u64)?; let info = info(); Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64)) } fn info() -> mach_timebase_info { - static mut INFO: mach_timebase_info = mach_timebase_info { - numer: 0, - denom: 0, - }; + static mut INFO: mach_timebase_info = mach_timebase_info { numer: 0, denom: 0 }; static STATE: AtomicUsize = AtomicUsize::new(0); unsafe { @@ -258,8 +233,7 @@ mod inner { // ... otherwise learn for ourselves ... let mut info = mem::zeroed(); extern "C" { - fn mach_timebase_info(info: mach_timebase_info_t) - -> kern_return_t; + fn mach_timebase_info(info: mach_timebase_info_t) -> kern_return_t; } mach_timebase_info(&mut info); @@ -293,9 +267,7 @@ mod inner { t: Timespec, } - pub const UNIX_EPOCH: SystemTime = SystemTime { - t: Timespec::zero(), - }; + pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() }; impl Instant { pub fn now() -> Instant { @@ -303,16 +275,14 @@ mod inner { } pub const fn zero() -> Instant { - Instant { - t: Timespec::zero(), - } + Instant { t: Timespec::zero() } } pub fn actually_monotonic() -> bool { - (cfg!(target_os = "linux") && cfg!(target_arch = "x86_64")) || - (cfg!(target_os = "linux") && cfg!(target_arch = "x86")) || - cfg!(target_os = "fuchsia") || - false // last clause, used so `||` is always trailing above + (cfg!(target_os = "linux") && cfg!(target_arch = "x86_64")) + || (cfg!(target_os = "linux") && cfg!(target_arch = "x86")) + || cfg!(target_os = "fuchsia") + || false // last clause, used so `||` is always trailing above } pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> { @@ -331,9 +301,9 @@ mod inner { impl fmt::Debug for Instant { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Instant") - .field("tv_sec", &self.t.t.tv_sec) - .field("tv_nsec", &self.t.t.tv_nsec) - .finish() + .field("tv_sec", &self.t.t.tv_sec) + .field("tv_nsec", &self.t.t.tv_nsec) + .finish() } } @@ -342,8 +312,7 @@ mod inner { SystemTime { t: now(libc::CLOCK_REALTIME) } } - pub fn sub_time(&self, other: &SystemTime) - -> Result<Duration, Duration> { + pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> { self.t.sub_timespec(&other.t) } @@ -365,9 +334,9 @@ mod inner { impl fmt::Debug for SystemTime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SystemTime") - .field("tv_sec", &self.t.t.tv_sec) - .field("tv_nsec", &self.t.t.tv_nsec) - .finish() + .field("tv_sec", &self.t.t.tv_sec) + .field("tv_nsec", &self.t.t.tv_nsec) + .finish() } } @@ -377,15 +346,8 @@ mod inner { pub type clock_t = libc::c_ulong; fn now(clock: clock_t) -> Timespec { - let mut t = Timespec { - t: libc::timespec { - tv_sec: 0, - tv_nsec: 0, - } - }; - cvt(unsafe { - libc::clock_gettime(clock, &mut t.t) - }).unwrap(); + let mut t = Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } }; + cvt(unsafe { libc::clock_gettime(clock, &mut t.t) }).unwrap(); t } } |
