From c34fbfaad38cf5829ef5cfe780dc9d58480adeaa Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Wed, 27 Nov 2019 10:28:39 -0800 Subject: [PATCH] Format libstd/sys with rustfmt This commit applies rustfmt with rust-lang/rust's default settings to files in src/libstd/sys *that are not involved in any currently open PR* to minimize merge conflicts. THe list of files involved in open PRs was determined by querying GitHub's GraphQL API with this script: https://gist.github.com/dtolnay/aa9c34993dc051a4f344d1b10e4487e8 With the list of files from the script in outstanding_files, the relevant commands were: $ find src/libstd/sys -name '*.rs' \ | xargs rustfmt --edition=2018 --unstable-features --skip-children $ rg libstd/sys outstanding_files | xargs git checkout -- Repeating this process several months apart should get us coverage of most of the rest of the files. To confirm no funny business: $ git checkout $THIS_COMMIT^ $ git show --pretty= --name-only $THIS_COMMIT \ | xargs rustfmt --edition=2018 --unstable-features --skip-children $ git diff $THIS_COMMIT # there should be no difference --- src/libstd/sys/cloudabi/os.rs | 4 +- src/libstd/sys/cloudabi/shims/fs.rs | 2 +- src/libstd/sys/cloudabi/shims/mod.rs | 7 +- src/libstd/sys/cloudabi/shims/net.rs | 4 +- src/libstd/sys/cloudabi/shims/process.rs | 4 +- src/libstd/sys/cloudabi/thread.rs | 10 +- src/libstd/sys/cloudabi/time.rs | 30 +- src/libstd/sys/hermit/alloc.rs | 6 +- src/libstd/sys/hermit/args.rs | 45 ++- src/libstd/sys/hermit/cmath.rs | 2 +- src/libstd/sys/hermit/condvar.rs | 4 +- src/libstd/sys/hermit/fd.rs | 10 +- src/libstd/sys/hermit/fs.rs | 84 ++-- src/libstd/sys/hermit/mod.rs | 46 +-- src/libstd/sys/hermit/mutex.rs | 6 +- src/libstd/sys/hermit/net.rs | 19 +- src/libstd/sys/hermit/os.rs | 49 +-- src/libstd/sys/hermit/path.rs | 2 +- src/libstd/sys/hermit/pipe.rs | 5 +- src/libstd/sys/hermit/process.rs | 29 +- src/libstd/sys/hermit/rwlock.rs | 6 +- src/libstd/sys/hermit/stack_overflow.rs | 6 +- src/libstd/sys/hermit/stdio.rs | 17 +- src/libstd/sys/hermit/thread.rs | 42 +- src/libstd/sys/hermit/thread_local.rs | 8 +- src/libstd/sys/hermit/time.rs | 45 +-- src/libstd/sys/sgx/abi/mod.rs | 18 +- src/libstd/sys/sgx/abi/panic.rs | 12 +- src/libstd/sys/sgx/abi/reloc.rs | 12 +- src/libstd/sys/sgx/abi/thread.rs | 4 +- src/libstd/sys/sgx/abi/tls.rs | 29 +- src/libstd/sys/sgx/abi/usercalls/alloc.rs | 99 +++-- src/libstd/sys/sgx/abi/usercalls/mod.rs | 67 ++-- src/libstd/sys/sgx/abi/usercalls/raw.rs | 32 +- src/libstd/sys/sgx/args.rs | 13 +- src/libstd/sys/sgx/cmath.rs | 2 +- src/libstd/sys/sgx/ext/io.rs | 10 +- src/libstd/sys/sgx/ext/mod.rs | 2 +- src/libstd/sys/sgx/fd.rs | 10 +- src/libstd/sys/sgx/fs.rs | 28 +- src/libstd/sys/sgx/net.rs | 81 ++-- src/libstd/sys/sgx/os.rs | 27 +- src/libstd/sys/sgx/path.rs | 2 +- src/libstd/sys/sgx/process.rs | 29 +- src/libstd/sys/sgx/stack_overflow.rs | 6 +- src/libstd/sys/sgx/stdio.rs | 14 +- src/libstd/sys/sgx/thread.rs | 16 +- src/libstd/sys/sgx/thread_local.rs | 4 +- src/libstd/sys/sgx/time.rs | 5 +- src/libstd/sys/unix/alloc.rs | 20 +- src/libstd/sys/unix/android.rs | 51 +-- src/libstd/sys/unix/cmath.rs | 4 +- src/libstd/sys/unix/ext/fs.rs | 108 ++++-- src/libstd/sys/unix/ext/io.rs | 26 +- src/libstd/sys/unix/ext/process.rs | 19 +- src/libstd/sys/unix/ext/raw.rs | 25 +- src/libstd/sys/unix/fast_thread_local.rs | 40 +- src/libstd/sys/unix/fd.rs | 131 ++++--- src/libstd/sys/unix/io.rs | 24 +- src/libstd/sys/unix/l4re.rs | 74 ++-- src/libstd/sys/unix/memchr.rs | 23 +- src/libstd/sys/unix/net.rs | 112 +++--- src/libstd/sys/unix/path.rs | 2 +- src/libstd/sys/unix/pipe.rs | 38 +- src/libstd/sys/unix/process/process_common.rs | 64 ++-- .../sys/unix/process/process_fuchsia.rs | 102 +++-- src/libstd/sys/unix/process/zircon.rs | 173 ++++++--- src/libstd/sys/unix/rand.rs | 63 +-- src/libstd/sys/unix/stack_overflow.rs | 87 +++-- src/libstd/sys/unix/stdio.rs | 14 +- src/libstd/sys/unix/thread.rs | 172 +++++---- src/libstd/sys/unix/thread_local.rs | 2 +- src/libstd/sys/unix/weak.rs | 6 +- src/libstd/sys/vxworks/alloc.rs | 10 +- src/libstd/sys/vxworks/args.rs | 47 ++- src/libstd/sys/vxworks/cmath.rs | 4 +- src/libstd/sys/vxworks/condvar.rs | 19 +- src/libstd/sys/vxworks/ext/fs.rs | 94 +++-- src/libstd/sys/vxworks/ext/io.rs | 40 +- src/libstd/sys/vxworks/ext/mod.rs | 17 +- src/libstd/sys/vxworks/ext/process.rs | 13 +- src/libstd/sys/vxworks/fast_thread_local.rs | 2 +- src/libstd/sys/vxworks/fd.rs | 81 ++-- src/libstd/sys/vxworks/fs.rs | 216 ++++++----- src/libstd/sys/vxworks/io.rs | 24 +- src/libstd/sys/vxworks/memchr.rs | 9 +- src/libstd/sys/vxworks/mod.rs | 22 +- src/libstd/sys/vxworks/mutex.rs | 12 +- src/libstd/sys/vxworks/net.rs | 113 +++--- src/libstd/sys/vxworks/path.rs | 2 +- src/libstd/sys/vxworks/pipe.rs | 35 +- src/libstd/sys/vxworks/process/mod.rs | 2 +- .../sys/vxworks/process/process_common.rs | 58 +-- src/libstd/sys/vxworks/rand.rs | 7 +- src/libstd/sys/vxworks/rwlock.rs | 18 +- src/libstd/sys/vxworks/stack_overflow.rs | 13 +- src/libstd/sys/vxworks/stdio.rs | 12 +- src/libstd/sys/vxworks/thread.rs | 43 ++- src/libstd/sys/vxworks/thread_local.rs | 2 +- src/libstd/sys/vxworks/time.rs | 81 ++-- src/libstd/sys/vxworks/weak.rs | 8 +- src/libstd/sys/wasi/alloc.rs | 2 +- src/libstd/sys/wasi/ext/mod.rs | 18 +- src/libstd/sys/wasi/net.rs | 55 +-- src/libstd/sys/wasi/os.rs | 42 +- src/libstd/sys/wasi/path.rs | 2 +- src/libstd/sys/wasi/pipe.rs | 5 +- src/libstd/sys/wasi/process.rs | 31 +- src/libstd/sys/wasm/args.rs | 8 +- src/libstd/sys/wasm/cmath.rs | 2 +- src/libstd/sys/wasm/fs.rs | 28 +- src/libstd/sys/wasm/net.rs | 21 +- src/libstd/sys/wasm/os.rs | 6 +- src/libstd/sys/wasm/path.rs | 2 +- src/libstd/sys/wasm/pipe.rs | 5 +- src/libstd/sys/wasm/process.rs | 29 +- src/libstd/sys/wasm/stack_overflow.rs | 6 +- src/libstd/sys/wasm/thread.rs | 16 +- src/libstd/sys/wasm/thread_local.rs | 2 +- src/libstd/sys/wasm/time.rs | 3 +- src/libstd/sys/windows/alloc.rs | 16 +- src/libstd/sys/windows/args.rs | 56 +-- src/libstd/sys/windows/cmath.rs | 6 +- src/libstd/sys/windows/compat.rs | 3 +- src/libstd/sys/windows/ext/ffi.rs | 4 +- src/libstd/sys/windows/ext/fs.rs | 65 +++- src/libstd/sys/windows/ext/io.rs | 6 +- src/libstd/sys/windows/ext/mod.rs | 23 +- src/libstd/sys/windows/ext/process.rs | 4 +- src/libstd/sys/windows/ext/raw.rs | 9 +- src/libstd/sys/windows/ext/thread.rs | 6 +- src/libstd/sys/windows/fs.rs | 361 ++++++++++-------- src/libstd/sys/windows/handle.rs | 104 ++--- src/libstd/sys/windows/io.rs | 17 +- src/libstd/sys/windows/os.rs | 144 +++---- src/libstd/sys/windows/os_str.rs | 13 +- src/libstd/sys/windows/path.rs | 9 +- src/libstd/sys/windows/pipe.rs | 99 +++-- src/libstd/sys/windows/rand.rs | 23 +- src/libstd/sys/windows/stack_overflow.rs | 5 +- src/libstd/sys/windows/stdio.rs | 72 ++-- src/libstd/sys/windows/stdio_uwp.rs | 7 +- src/libstd/sys/windows/thread.rs | 54 ++- src/libstd/sys/windows/thread_local.rs | 25 +- 144 files changed, 2527 insertions(+), 2285 deletions(-) diff --git a/src/libstd/sys/cloudabi/os.rs b/src/libstd/sys/cloudabi/os.rs index 7db7808a08783..326faaa852afe 100644 --- a/src/libstd/sys/cloudabi/os.rs +++ b/src/libstd/sys/cloudabi/os.rs @@ -18,9 +18,7 @@ pub fn errno() -> i32 { pub fn error_string(errno: i32) -> String { // cloudlibc's strerror() is guaranteed to be thread-safe. There is // thus no need to use strerror_r(). - str::from_utf8(unsafe { CStr::from_ptr(libc::strerror(errno)) }.to_bytes()) - .unwrap() - .to_owned() + str::from_utf8(unsafe { CStr::from_ptr(libc::strerror(errno)) }.to_bytes()).unwrap().to_owned() } pub fn exit(code: i32) -> ! { diff --git a/src/libstd/sys/cloudabi/shims/fs.rs b/src/libstd/sys/cloudabi/shims/fs.rs index 05f91541011e6..e6160d1457d26 100644 --- a/src/libstd/sys/cloudabi/shims/fs.rs +++ b/src/libstd/sys/cloudabi/shims/fs.rs @@ -1,7 +1,7 @@ use crate::ffi::OsString; use crate::fmt; use crate::hash::{Hash, Hasher}; -use crate::io::{self, SeekFrom, IoSlice, IoSliceMut}; +use crate::io::{self, IoSlice, IoSliceMut, SeekFrom}; use crate::path::{Path, PathBuf}; use crate::sys::time::SystemTime; use crate::sys::{unsupported, Void}; diff --git a/src/libstd/sys/cloudabi/shims/mod.rs b/src/libstd/sys/cloudabi/shims/mod.rs index fbb5ff55f2224..b1b5f142f45c2 100644 --- a/src/libstd/sys/cloudabi/shims/mod.rs +++ b/src/libstd/sys/cloudabi/shims/mod.rs @@ -4,19 +4,16 @@ pub mod args; pub mod env; pub mod fs; pub mod net; +pub mod os; #[path = "../../unix/path.rs"] pub mod path; pub mod pipe; pub mod process; -pub mod os; // This enum is used as the storage for a bunch of types which can't actually exist. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub enum Void {} pub fn unsupported() -> io::Result { - Err(io::Error::new( - io::ErrorKind::Other, - "This function is not available on CloudABI.", - )) + Err(io::Error::new(io::ErrorKind::Other, "This function is not available on CloudABI.")) } diff --git a/src/libstd/sys/cloudabi/shims/net.rs b/src/libstd/sys/cloudabi/shims/net.rs index 8d609cdfad5dc..67c436fa7955d 100644 --- a/src/libstd/sys/cloudabi/shims/net.rs +++ b/src/libstd/sys/cloudabi/shims/net.rs @@ -1,9 +1,9 @@ +use crate::convert::TryFrom; use crate::fmt; use crate::io::{self, IoSlice, IoSliceMut}; use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; -use crate::time::Duration; use crate::sys::{unsupported, Void}; -use crate::convert::TryFrom; +use crate::time::Duration; #[allow(unused_extern_crates)] pub extern crate libc as netc; diff --git a/src/libstd/sys/cloudabi/shims/process.rs b/src/libstd/sys/cloudabi/shims/process.rs index 03a59d6d7c832..4702e5c549228 100644 --- a/src/libstd/sys/cloudabi/shims/process.rs +++ b/src/libstd/sys/cloudabi/shims/process.rs @@ -32,9 +32,7 @@ pub enum Stdio { impl Command { pub fn new(_program: &OsStr) -> Command { - Command { - env: Default::default(), - } + Command { env: Default::default() } } pub fn arg(&mut self, _arg: &OsStr) {} diff --git a/src/libstd/sys/cloudabi/thread.rs b/src/libstd/sys/cloudabi/thread.rs index 240b6ea9e57f8..3afcae7ae7516 100644 --- a/src/libstd/sys/cloudabi/thread.rs +++ b/src/libstd/sys/cloudabi/thread.rs @@ -58,8 +58,8 @@ impl Thread { } pub fn sleep(dur: Duration) { - let timeout = checked_dur2intervals(&dur) - .expect("overflow converting duration to nanoseconds"); + let timeout = + checked_dur2intervals(&dur).expect("overflow converting duration to nanoseconds"); unsafe { let subscription = abi::subscription { type_: abi::eventtype::CLOCK, @@ -85,11 +85,7 @@ impl Thread { unsafe { let ret = libc::pthread_join(self.id, ptr::null_mut()); mem::forget(self); - assert!( - ret == 0, - "failed to join thread: {}", - io::Error::from_raw_os_error(ret) - ); + assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); } } } diff --git a/src/libstd/sys/cloudabi/time.rs b/src/libstd/sys/cloudabi/time.rs index 5e502dcb2ba50..c209231cf8c01 100644 --- a/src/libstd/sys/cloudabi/time.rs +++ b/src/libstd/sys/cloudabi/time.rs @@ -10,9 +10,7 @@ pub struct Instant { } pub fn checked_dur2intervals(dur: &Duration) -> Option { - dur.as_secs() - .checked_mul(NSEC_PER_SEC)? - .checked_add(dur.subsec_nanos() as abi::timestamp) + dur.as_secs().checked_mul(NSEC_PER_SEC)?.checked_add(dur.subsec_nanos() as abi::timestamp) } impl Instant { @@ -39,15 +37,11 @@ impl Instant { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - 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 { - Some(Instant { - t: self.t.checked_sub(checked_dur2intervals(other)?)?, - }) + Some(Instant { t: self.t.checked_sub(checked_dur2intervals(other)?)? }) } } @@ -69,29 +63,19 @@ impl SystemTime { pub fn sub_time(&self, other: &SystemTime) -> Result { if self.t >= other.t { let diff = self.t - other.t; - Ok(Duration::new( - diff / NSEC_PER_SEC, - (diff % NSEC_PER_SEC) as u32, - )) + Ok(Duration::new(diff / NSEC_PER_SEC, (diff % NSEC_PER_SEC) as u32)) } else { let diff = other.t - self.t; - Err(Duration::new( - diff / NSEC_PER_SEC, - (diff % NSEC_PER_SEC) as u32, - )) + Err(Duration::new(diff / NSEC_PER_SEC, (diff % NSEC_PER_SEC) as u32)) } } pub fn checked_add_duration(&self, other: &Duration) -> Option { - Some(SystemTime { - t: self.t.checked_add(checked_dur2intervals(other)?)?, - }) + Some(SystemTime { t: self.t.checked_add(checked_dur2intervals(other)?)? }) } pub fn checked_sub_duration(&self, other: &Duration) -> Option { - Some(SystemTime { - t: self.t.checked_sub(checked_dur2intervals(other)?)?, - }) + Some(SystemTime { t: self.t.checked_sub(checked_dur2intervals(other)?)? }) } } diff --git a/src/libstd/sys/hermit/alloc.rs b/src/libstd/sys/hermit/alloc.rs index 86cc446363288..d153914e77e10 100644 --- a/src/libstd/sys/hermit/alloc.rs +++ b/src/libstd/sys/hermit/alloc.rs @@ -13,11 +13,7 @@ unsafe impl GlobalAlloc for System { let addr = abi::malloc(layout.size(), layout.align()); if !addr.is_null() { - ptr::write_bytes( - addr, - 0x00, - layout.size() - ); + ptr::write_bytes(addr, 0x00, layout.size()); } addr diff --git a/src/libstd/sys/hermit/args.rs b/src/libstd/sys/hermit/args.rs index 5b1f3add51fe0..72c1b8511cac8 100644 --- a/src/libstd/sys/hermit/args.rs +++ b/src/libstd/sys/hermit/args.rs @@ -3,10 +3,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 { @@ -26,24 +30,32 @@ impl Args { impl Iterator for Args { type Item = OsString; - fn next(&mut self) -> Option { self.iter.next() } - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + 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 { self.iter.next_back() } + fn next_back(&mut self) -> Option { + self.iter.next_back() + } } mod imp { - use crate::sys_common::os_str_bytes::*; - use crate::ptr; + use super::Args; use crate::ffi::{CStr, OsString}; use crate::marker::PhantomData; - use super::Args; + use crate::ptr; + use crate::sys_common::os_str_bytes::*; use crate::sys_common::mutex::Mutex; @@ -64,19 +76,18 @@ 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 { unsafe { let _guard = LOCK.lock(); - (0..ARGC).map(|i| { - let cstr = CStr::from_ptr(*ARGV.offset(i) as *const i8); - OsStringExt::from_vec(cstr.to_bytes().to_vec()) - }).collect() + (0..ARGC) + .map(|i| { + let cstr = CStr::from_ptr(*ARGV.offset(i) as *const i8); + OsStringExt::from_vec(cstr.to_bytes().to_vec()) + }) + .collect() } } } diff --git a/src/libstd/sys/hermit/cmath.rs b/src/libstd/sys/hermit/cmath.rs index fa7783122c2e9..304cf906b2aea 100644 --- a/src/libstd/sys/hermit/cmath.rs +++ b/src/libstd/sys/hermit/cmath.rs @@ -1,5 +1,5 @@ // These symbols are all defined in `compiler-builtins` -extern { +extern "C" { pub fn acos(n: f64) -> f64; pub fn acosf(n: f32) -> f32; pub fn asin(n: f64) -> f64; diff --git a/src/libstd/sys/hermit/condvar.rs b/src/libstd/sys/hermit/condvar.rs index 8e52b3da1b170..5b7f16ce562b9 100644 --- a/src/libstd/sys/hermit/condvar.rs +++ b/src/libstd/sys/hermit/condvar.rs @@ -18,12 +18,12 @@ impl Condvar { } pub unsafe fn notify_one(&self) { - let _ = abi::notify(self.id(), 1); + let _ = abi::notify(self.id(), 1); } #[inline] pub unsafe fn notify_all(&self) { - let _ = abi::notify(self.id(), -1 /* =all */); + let _ = abi::notify(self.id(), -1 /* =all */); } pub unsafe fn wait(&self, mutex: &Mutex) { diff --git a/src/libstd/sys/hermit/fd.rs b/src/libstd/sys/hermit/fd.rs index 84c547366473a..f2f61fdfb8cc6 100644 --- a/src/libstd/sys/hermit/fd.rs +++ b/src/libstd/sys/hermit/fd.rs @@ -1,6 +1,6 @@ #![unstable(reason = "not public", issue = "0", feature = "fd")] -use crate::io::{self, Read, ErrorKind}; +use crate::io::{self, ErrorKind, Read}; use crate::mem; use crate::sys::cvt; use crate::sys::hermit::abi; @@ -16,7 +16,9 @@ impl FileDesc { FileDesc { fd } } - pub fn raw(&self) -> i32 { self.fd } + pub fn raw(&self) -> i32 { + self.fd + } /// Extracts the actual file descriptor without closing it. pub fn into_raw(self) -> i32 { @@ -67,7 +69,9 @@ impl<'a> Read for &'a FileDesc { } impl AsInner for FileDesc { - fn as_inner(&self) -> &i32 { &self.fd } + fn as_inner(&self) -> &i32 { + &self.fd + } } impl Drop for FileDesc { diff --git a/src/libstd/sys/hermit/fs.rs b/src/libstd/sys/hermit/fs.rs index f8e5844a1678d..37ac5984eeeaf 100644 --- a/src/libstd/sys/hermit/fs.rs +++ b/src/libstd/sys/hermit/fs.rs @@ -1,14 +1,14 @@ -use crate::ffi::{OsString, CString, CStr}; +use crate::ffi::{CStr, CString, OsString}; use crate::fmt; -use crate::io::{self, Error, ErrorKind}; use crate::hash::{Hash, Hasher}; -use crate::io::{SeekFrom, IoSlice, IoSliceMut}; +use crate::io::{self, Error, ErrorKind}; +use crate::io::{IoSlice, IoSliceMut, SeekFrom}; use crate::path::{Path, PathBuf}; -use crate::sys::time::SystemTime; -use crate::sys::{unsupported, Void}; +use crate::sys::cvt; use crate::sys::hermit::abi; use crate::sys::hermit::fd::FileDesc; -use crate::sys::cvt; +use crate::sys::time::SystemTime; +use crate::sys::{unsupported, Void}; use crate::sys_common::os_str_bytes::OsStrExt; pub use crate::sys_common::fs::copy; @@ -45,7 +45,7 @@ pub struct OpenOptions { create: bool, create_new: bool, // system-specific - mode: i32 + mode: i32, } pub struct FilePermissions(Void); @@ -53,7 +53,7 @@ pub struct FilePermissions(Void); pub struct FileType(Void); #[derive(Debug)] -pub struct DirBuilder { } +pub struct DirBuilder {} impl FileAttr { pub fn size(&self) -> u64 { @@ -109,8 +109,7 @@ impl PartialEq for FilePermissions { } } -impl Eq for FilePermissions { -} +impl Eq for FilePermissions {} impl fmt::Debug for FilePermissions { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -146,8 +145,7 @@ impl PartialEq for FileType { } } -impl Eq for FileType { -} +impl Eq for FileType {} impl Hash for FileType { fn hash(&self, _h: &mut H) { @@ -204,50 +202,64 @@ impl OpenOptions { create: false, create_new: false, // system-specific - mode: 0x777 + mode: 0x777, } } - 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; + } fn get_access_mode(&self) -> io::Result { match (self.read, self.write, self.append) { - (true, false, false) => Ok(O_RDONLY), - (false, true, false) => Ok(O_WRONLY), - (true, true, false) => Ok(O_RDWR), - (false, _, true) => Ok(O_WRONLY | O_APPEND), - (true, _, true) => Ok(O_RDWR | O_APPEND), + (true, false, false) => Ok(O_RDONLY), + (false, true, false) => Ok(O_WRONLY), + (true, true, false) => Ok(O_RDWR), + (false, _, true) => Ok(O_WRONLY | O_APPEND), + (true, _, true) => Ok(O_RDWR | O_APPEND), (false, false, false) => { Err(io::Error::new(ErrorKind::InvalidInput, "invalid access mode")) - }, + } } } fn get_creation_mode(&self) -> io::Result { match (self.write, self.append) { (true, false) => {} - (false, false) => + (false, false) => { if self.truncate || self.create || self.create_new { return Err(io::Error::new(ErrorKind::InvalidInput, "invalid creation mode")); - }, - (_, true) => + } + } + (_, true) => { if self.truncate && !self.create_new { return Err(io::Error::new(ErrorKind::InvalidInput, "invalid creation mode")); - }, + } + } } Ok(match (self.create, self.truncate, self.create_new) { - (false, false, false) => 0, - (true, false, false) => O_CREAT, - (false, true, false) => O_TRUNC, - (true, true, false) => O_CREAT | O_TRUNC, - (_, _, true) => O_CREAT | O_EXCL, - }) + (false, false, false) => 0, + (true, false, false) => O_CREAT, + (false, true, false) => O_TRUNC, + (true, true, false) => O_CREAT | O_TRUNC, + (_, _, true) => O_CREAT | O_EXCL, + }) } } @@ -327,7 +339,7 @@ impl File { impl DirBuilder { pub fn new() -> DirBuilder { - DirBuilder { } + DirBuilder {} } pub fn mkdir(&self, _p: &Path) -> io::Result<()> { diff --git a/src/libstd/sys/hermit/mod.rs b/src/libstd/sys/hermit/mod.rs index d4359631769da..1e4a53abdc7bd 100644 --- a/src/libstd/sys/hermit/mod.rs +++ b/src/libstd/sys/hermit/mod.rs @@ -13,34 +13,34 @@ //! compiling for wasm. That way it's a compile time error for something that's //! guaranteed to be a runtime error! -use crate::os::raw::c_char; use crate::intrinsics; +use crate::os::raw::c_char; pub mod alloc; pub mod args; -pub mod condvar; -pub mod stdio; -pub mod memchr; -pub mod io; -pub mod mutex; -pub mod rwlock; -pub mod os; pub mod cmath; -pub mod thread; +pub mod condvar; pub mod env; -pub mod fs; +pub mod fast_thread_local; pub mod fd; +pub mod fs; +pub mod io; +pub mod memchr; +pub mod mutex; pub mod net; +pub mod os; pub mod path; pub mod pipe; pub mod process; +pub mod rwlock; pub mod stack_overflow; -pub mod time; +pub mod stdio; +pub mod thread; pub mod thread_local; -pub mod fast_thread_local; +pub mod time; -pub use crate::sys_common::os_str_bytes as os_str; use crate::io::ErrorKind; +pub use crate::sys_common::os_str_bytes as os_str; #[allow(unused_extern_crates)] pub extern crate hermit_abi as abi; @@ -50,8 +50,7 @@ pub fn unsupported() -> crate::io::Result { } pub fn unsupported_err() -> crate::io::Error { - crate::io::Error::new(crate::io::ErrorKind::Other, - "operation not supported on HermitCore yet") + crate::io::Error::new(crate::io::ErrorKind::Other, "operation not supported on HermitCore yet") } // This enum is used as the storage for a bunch of types which can't actually @@ -71,9 +70,7 @@ pub unsafe fn strlen(start: *const c_char) -> usize { #[no_mangle] pub extern "C" fn floor(x: f64) -> f64 { - unsafe { - intrinsics::floorf64(x) - } + unsafe { intrinsics::floorf64(x) } } pub unsafe fn abort_internal() -> ! { @@ -103,8 +100,11 @@ pub fn init() { #[cfg(not(test))] #[no_mangle] -pub unsafe extern "C" fn runtime_entry(argc: i32, argv: *const *const c_char, - env: *const *const c_char) -> ! { +pub unsafe extern "C" fn runtime_entry( + argc: i32, + argv: *const *const c_char, + env: *const *const c_char, +) -> ! { extern "C" { fn main(argc: isize, argv: *const *const c_char) -> i32; } @@ -139,9 +139,5 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind { } pub fn cvt(result: i32) -> crate::io::Result { - if result < 0 { - Err(crate::io::Error::from_raw_os_error(-result)) - } else { - Ok(result as usize) - } + if result < 0 { Err(crate::io::Error::from_raw_os_error(-result)) } else { Ok(result as usize) } } diff --git a/src/libstd/sys/hermit/mutex.rs b/src/libstd/sys/hermit/mutex.rs index 9414bf8fbbbd4..b5c75f738d228 100644 --- a/src/libstd/sys/hermit/mutex.rs +++ b/src/libstd/sys/hermit/mutex.rs @@ -1,9 +1,9 @@ -use crate::ptr; use crate::ffi::c_void; +use crate::ptr; use crate::sys::hermit::abi; pub struct Mutex { - inner: *const c_void + inner: *const c_void, } unsafe impl Send for Mutex {} @@ -42,7 +42,7 @@ impl Mutex { } pub struct ReentrantMutex { - inner: *const c_void + inner: *const c_void, } impl ReentrantMutex { diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 5b7ff642271c5..82917e71be1f8 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -1,7 +1,7 @@ -use crate::fmt; use crate::convert::TryFrom; +use crate::fmt; use crate::io::{self, IoSlice, IoSliceMut}; -use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr}; +use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; use crate::str; use crate::sys::{unsupported, Void}; use crate::time::Duration; @@ -234,23 +234,19 @@ impl UdpSocket { match self.0 {} } - pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) - -> io::Result<()> { + pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { match self.0 {} } - pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) - -> io::Result<()> { + pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { match self.0 {} } - pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) - -> io::Result<()> { + pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { match self.0 {} } - pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) - -> io::Result<()> { + pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { match self.0 {} } @@ -357,8 +353,7 @@ pub mod netc { } #[derive(Copy, Clone)] - pub struct sockaddr { - } + pub struct sockaddr {} pub type socklen_t = usize; } diff --git a/src/libstd/sys/hermit/os.rs b/src/libstd/sys/hermit/os.rs index 8a25cbcf07b9c..ad63b0e0c1318 100644 --- a/src/libstd/sys/hermit/os.rs +++ b/src/libstd/sys/hermit/os.rs @@ -1,5 +1,6 @@ +use crate::collections::HashMap; use crate::error::Error as StdError; -use crate::ffi::{CStr, OsString, OsStr}; +use crate::ffi::{CStr, OsStr, OsString}; use crate::fmt; use crate::io; use crate::marker::PhantomData; @@ -7,12 +8,11 @@ use crate::memchr; use crate::path::{self, PathBuf}; use crate::ptr; use crate::str; -use crate::sys::{unsupported, Void}; -use crate::collections::HashMap; -use crate::vec; use crate::sync::Mutex; -use crate::sys_common::os_str_bytes::*; use crate::sys::hermit::abi; +use crate::sys::{unsupported, Void}; +use crate::sys_common::os_str_bytes::*; +use crate::vec; pub fn errno() -> i32 { 0 @@ -47,7 +47,9 @@ impl<'a> Iterator for SplitPaths<'a> { pub struct JoinPathsError; pub fn join_paths(_paths: I) -> Result - where I: Iterator, T: AsRef +where + I: Iterator, + T: AsRef, { Err(JoinPathsError) } @@ -77,7 +79,7 @@ pub fn init_environment(env: *const *const i8) { let mut guard = ENV.as_ref().unwrap().lock().unwrap(); let mut environ = env; while environ != ptr::null() && *environ != ptr::null() { - if let Some((key,value)) = parse(CStr::from_ptr(*environ).to_bytes()) { + if let Some((key, value)) = parse(CStr::from_ptr(*environ).to_bytes()) { guard.insert(key, value); } environ = environ.offset(1); @@ -93,10 +95,12 @@ pub fn init_environment(env: *const *const i8) { return None; } let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1); - pos.map(|p| ( - OsStringExt::from_vec(input[..p].to_vec()), - OsStringExt::from_vec(input[p+1..].to_vec()), - )) + pos.map(|p| { + ( + OsStringExt::from_vec(input[..p].to_vec()), + OsStringExt::from_vec(input[p + 1..].to_vec()), + ) + }) } } @@ -107,14 +111,18 @@ pub struct Env { impl Iterator for Env { type Item = (OsString, OsString); - fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() } - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn next(&mut self) -> Option<(OsString, OsString)> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } } /// Returns a vector of (variable, value) byte-vector pairs for all the /// environment variables of the current process. pub fn env() -> Env { - unsafe { + unsafe { let guard = ENV.as_ref().unwrap().lock().unwrap(); let mut result = Vec::new(); @@ -122,18 +130,15 @@ pub fn env() -> Env { result.push((key.clone(), value.clone())); } - return Env { - iter: result.into_iter(), - _dont_send_or_sync_me: PhantomData, - } + return Env { iter: result.into_iter(), _dont_send_or_sync_me: PhantomData }; } } pub fn getenv(k: &OsStr) -> io::Result> { unsafe { match ENV.as_ref().unwrap().lock().unwrap().get_mut(k) { - Some(value) => { Ok(Some(value.clone())) }, - None => { Ok(None) }, + Some(value) => Ok(Some(value.clone())), + None => Ok(None), } } } @@ -168,7 +173,5 @@ pub fn exit(code: i32) -> ! { } pub fn getpid() -> u32 { - unsafe { - abi::getpid() - } + unsafe { abi::getpid() } } diff --git a/src/libstd/sys/hermit/path.rs b/src/libstd/sys/hermit/path.rs index 7a18395610785..840a7ae042625 100644 --- a/src/libstd/sys/hermit/path.rs +++ b/src/libstd/sys/hermit/path.rs @@ -1,5 +1,5 @@ -use crate::path::Prefix; use crate::ffi::OsStr; +use crate::path::Prefix; #[inline] pub fn is_sep_byte(b: u8) -> bool { diff --git a/src/libstd/sys/hermit/pipe.rs b/src/libstd/sys/hermit/pipe.rs index 9f07f054362fe..fb14dc5910181 100644 --- a/src/libstd/sys/hermit/pipe.rs +++ b/src/libstd/sys/hermit/pipe.rs @@ -25,9 +25,6 @@ impl AnonPipe { } } -pub fn read2(p1: AnonPipe, - _v1: &mut Vec, - _p2: AnonPipe, - _v2: &mut Vec) -> io::Result<()> { +pub fn read2(p1: AnonPipe, _v1: &mut Vec, _p2: AnonPipe, _v2: &mut Vec) -> io::Result<()> { match p1.0 {} } diff --git a/src/libstd/sys/hermit/process.rs b/src/libstd/sys/hermit/process.rs index edf933d10e074..4702e5c549228 100644 --- a/src/libstd/sys/hermit/process.rs +++ b/src/libstd/sys/hermit/process.rs @@ -32,32 +32,28 @@ pub enum Stdio { impl Command { pub fn new(_program: &OsStr) -> Command { - Command { - env: Default::default() - } + Command { env: Default::default() } } - pub fn arg(&mut self, _arg: &OsStr) { - } + pub fn arg(&mut self, _arg: &OsStr) {} pub fn env_mut(&mut self) -> &mut CommandEnv { &mut self.env } - pub fn cwd(&mut self, _dir: &OsStr) { - } + pub fn cwd(&mut self, _dir: &OsStr) {} - pub fn stdin(&mut self, _stdin: Stdio) { - } + pub fn stdin(&mut self, _stdin: Stdio) {} - pub fn stdout(&mut self, _stdout: Stdio) { - } + pub fn stdout(&mut self, _stdout: Stdio) {} - pub fn stderr(&mut self, _stderr: Stdio) { - } + pub fn stderr(&mut self, _stderr: Stdio) {} - 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)> { unsupported() } } @@ -106,8 +102,7 @@ impl PartialEq for ExitStatus { } } -impl Eq for ExitStatus { -} +impl Eq for ExitStatus {} impl fmt::Debug for ExitStatus { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/src/libstd/sys/hermit/rwlock.rs b/src/libstd/sys/hermit/rwlock.rs index 990e7551114bb..c19799af3c7ee 100644 --- a/src/libstd/sys/hermit/rwlock.rs +++ b/src/libstd/sys/hermit/rwlock.rs @@ -1,7 +1,7 @@ use super::mutex::Mutex; pub struct RWLock { - mutex: Mutex + mutex: Mutex, } unsafe impl Send for RWLock {} @@ -9,9 +9,7 @@ unsafe impl Sync for RWLock {} impl RWLock { pub const fn new() -> RWLock { - RWLock { - mutex: Mutex::new() - } + RWLock { mutex: Mutex::new() } } #[inline] diff --git a/src/libstd/sys/hermit/stack_overflow.rs b/src/libstd/sys/hermit/stack_overflow.rs index b339e433e77de..65a1b17acce9a 100644 --- a/src/libstd/sys/hermit/stack_overflow.rs +++ b/src/libstd/sys/hermit/stack_overflow.rs @@ -7,9 +7,7 @@ impl Handler { } #[inline] -pub unsafe fn init() { -} +pub unsafe fn init() {} #[inline] -pub unsafe fn cleanup() { -} +pub unsafe fn cleanup() {} diff --git a/src/libstd/sys/hermit/stdio.rs b/src/libstd/sys/hermit/stdio.rs index 9505f02fda83b..2eb011ccb3974 100644 --- a/src/libstd/sys/hermit/stdio.rs +++ b/src/libstd/sys/hermit/stdio.rs @@ -20,7 +20,6 @@ impl Stdin { // .read(data) Ok(0) } - } impl Stdout { @@ -31,9 +30,7 @@ impl Stdout { pub fn write(&self, data: &[u8]) -> io::Result { let len; - unsafe { - len = abi::write(1, data.as_ptr() as *const u8, data.len()) - } + unsafe { len = abi::write(1, data.as_ptr() as *const u8, data.len()) } if len < 0 { Err(io::Error::new(io::ErrorKind::Other, "Stdout is not able to print")) @@ -45,9 +42,7 @@ impl Stdout { pub fn write_vectored(&self, data: &[IoSlice<'_>]) -> io::Result { let len; - unsafe { - len = abi::write(1, data.as_ptr() as *const u8, data.len()) - } + unsafe { len = abi::write(1, data.as_ptr() as *const u8, data.len()) } if len < 0 { Err(io::Error::new(io::ErrorKind::Other, "Stdout is not able to print")) @@ -69,9 +64,7 @@ impl Stderr { pub fn write(&self, data: &[u8]) -> io::Result { let len; - unsafe { - len = abi::write(2, data.as_ptr() as *const u8, data.len()) - } + unsafe { len = abi::write(2, data.as_ptr() as *const u8, data.len()) } if len < 0 { Err(io::Error::new(io::ErrorKind::Other, "Stderr is not able to print")) @@ -83,9 +76,7 @@ impl Stderr { pub fn write_vectored(&self, data: &[IoSlice<'_>]) -> io::Result { let len; - unsafe { - len = abi::write(2, data.as_ptr() as *const u8, data.len()) - } + unsafe { len = abi::write(2, data.as_ptr() as *const u8, data.len()) } if len < 0 { Err(io::Error::new(io::ErrorKind::Other, "Stderr is not able to print")) diff --git a/src/libstd/sys/hermit/thread.rs b/src/libstd/sys/hermit/thread.rs index 99a9c830c9e0a..c3c29c93826de 100644 --- a/src/libstd/sys/hermit/thread.rs +++ b/src/libstd/sys/hermit/thread.rs @@ -1,11 +1,11 @@ #![allow(dead_code)] use crate::ffi::CStr; +use crate::fmt; use crate::io; +use crate::mem; use crate::sys::hermit::abi; use crate::time::Duration; -use crate::mem; -use crate::fmt; use core::u32; use crate::sys_common::thread::*; @@ -35,7 +35,7 @@ impl fmt::Display for Priority { pub const NORMAL_PRIO: Priority = Priority::from(2); pub struct Thread { - tid: Tid + tid: Tid, } unsafe impl Send for Thread {} @@ -44,14 +44,20 @@ unsafe impl Sync for Thread {} pub const DEFAULT_MIN_STACK_SIZE: usize = 262144; impl Thread { - pub unsafe fn new_with_coreid(_stack: usize, p: Box, core_id: isize) - -> io::Result - { + pub unsafe fn new_with_coreid( + _stack: usize, + p: Box, + core_id: isize, + ) -> io::Result { let p = box p; let mut tid: Tid = u32::MAX; - let ret = abi::spawn(&mut tid as *mut Tid, thread_start, - &*p as *const _ as *const u8 as usize, - Priority::into(NORMAL_PRIO), core_id); + let ret = abi::spawn( + &mut tid as *mut Tid, + thread_start, + &*p as *const _ as *const u8 as usize, + Priority::into(NORMAL_PRIO), + core_id, + ); return if ret == 0 { mem::forget(p); // ownership passed to pthread_create @@ -60,16 +66,14 @@ impl Thread { Err(io::Error::new(io::ErrorKind::Other, "Unable to create thread!")) }; - extern fn thread_start(main: usize) { + extern "C" fn thread_start(main: usize) { unsafe { start_thread(main as *mut u8); } } } - pub unsafe fn new(stack: usize, p: Box) - -> io::Result - { + pub unsafe fn new(stack: usize, p: Box) -> io::Result { Thread::new_with_coreid(stack, p, -1 /* = no specific core */) } @@ -99,7 +103,9 @@ impl Thread { } #[inline] - pub fn id(&self) -> Tid { self.tid } + pub fn id(&self) -> Tid { + self.tid + } #[inline] pub fn into_id(self) -> Tid { @@ -111,6 +117,10 @@ impl Thread { pub mod guard { pub type Guard = !; - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + pub unsafe fn current() -> Option { + None + } + pub unsafe fn init() -> Option { + None + } } diff --git a/src/libstd/sys/hermit/thread_local.rs b/src/libstd/sys/hermit/thread_local.rs index 268fb770eae2c..ba967c7676c3f 100644 --- a/src/libstd/sys/hermit/thread_local.rs +++ b/src/libstd/sys/hermit/thread_local.rs @@ -7,7 +7,7 @@ use crate::sys_common::mutex::Mutex; pub type Key = usize; -type Dtor = unsafe extern fn(*mut u8); +type Dtor = unsafe extern "C" fn(*mut u8); static NEXT_KEY: AtomicUsize = AtomicUsize::new(0); @@ -41,11 +41,7 @@ pub unsafe fn create(dtor: Option) -> Key { #[inline] pub unsafe fn get(key: Key) -> *mut u8 { - if let Some(&entry) = locals().get(&key) { - entry - } else { - ptr::null_mut() - } + if let Some(&entry) = locals().get(&key) { entry } else { ptr::null_mut() } } #[inline] diff --git a/src/libstd/sys/hermit/time.rs b/src/libstd/sys/hermit/time.rs index 8372189546d07..c02de17c1fc3a 100644 --- a/src/libstd/sys/hermit/time.rs +++ b/src/libstd/sys/hermit/time.rs @@ -1,34 +1,35 @@ #![allow(dead_code)] -use crate::time::Duration; use crate::cmp::Ordering; use crate::convert::TryInto; -use core::hash::{Hash, Hasher}; use crate::sys::hermit::abi; -use crate::sys::hermit::abi::{CLOCK_REALTIME, CLOCK_MONOTONIC, NSEC_PER_SEC}; use crate::sys::hermit::abi::timespec; +use crate::sys::hermit::abi::{CLOCK_MONOTONIC, CLOCK_REALTIME, NSEC_PER_SEC}; +use crate::time::Duration; +use core::hash::{Hash, Hasher}; #[derive(Copy, Clone, Debug)] struct Timespec { - t: timespec + t: timespec, } impl Timespec { const fn zero() -> Timespec { - Timespec { - t: timespec { tv_sec: 0, tv_nsec: 0 }, - } + Timespec { t: timespec { tv_sec: 0, tv_nsec: 0 } } } fn sub_timespec(&self, other: &Timespec) -> Result { 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: timespec { - tv_sec: secs, - tv_nsec: nsec as _, - }, - }) + Some(Timespec { t: timespec { tv_sec: secs, tv_nsec: nsec as _ } }) } fn checked_sub_duration(&self, other: &Duration) -> Option { @@ -73,12 +69,7 @@ impl Timespec { nsec += NSEC_PER_SEC as i32; secs = secs.checked_sub(1)?; } - Some(Timespec { - t: timespec { - tv_sec: secs, - tv_nsec: nsec as _, - }, - }) + Some(Timespec { t: timespec { tv_sec: secs, tv_nsec: nsec as _ } }) } } @@ -105,7 +96,7 @@ impl Ord for Timespec { } impl Hash for Timespec { - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.t.tv_sec.hash(state); self.t.tv_nsec.hash(state); } @@ -150,9 +141,7 @@ pub struct SystemTime { t: Timespec, } -pub const UNIX_EPOCH: SystemTime = SystemTime { - t: Timespec::zero(), -}; +pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() }; impl SystemTime { pub fn now() -> SystemTime { diff --git a/src/libstd/sys/sgx/abi/mod.rs b/src/libstd/sys/sgx/abi/mod.rs index 0f107de83f062..87e7a5da2b7a9 100644 --- a/src/libstd/sys/sgx/abi/mod.rs +++ b/src/libstd/sys/sgx/abi/mod.rs @@ -1,11 +1,11 @@ #![cfg_attr(test, allow(unused))] // RT initialization logic is not compiled for test -use core::sync::atomic::{AtomicUsize, Ordering}; use crate::io::Write; +use core::sync::atomic::{AtomicUsize, Ordering}; // runtime features -mod reloc; pub(super) mod panic; +mod reloc; // library features pub mod mem; @@ -38,14 +38,16 @@ unsafe extern "C" fn tcs_init(secondary: bool) { UNINIT => { reloc::relocate_elf_rela(); RELOC_STATE.store(DONE, Ordering::Release); - }, + } // We need to wait until the initialization is done. - BUSY => while RELOC_STATE.load(Ordering::Acquire) == BUSY { - core::arch::x86_64::_mm_pause() - }, + BUSY => { + while RELOC_STATE.load(Ordering::Acquire) == BUSY { + core::arch::x86_64::_mm_pause() + } + } // Initialization is done. - DONE => {}, - _ => unreachable!() + DONE => {} + _ => unreachable!(), } } diff --git a/src/libstd/sys/sgx/abi/panic.rs b/src/libstd/sys/sgx/abi/panic.rs index 2401476716f4f..229b3b3291f63 100644 --- a/src/libstd/sys/sgx/abi/panic.rs +++ b/src/libstd/sys/sgx/abi/panic.rs @@ -16,21 +16,13 @@ fn empty_user_slice() -> &'static mut UserRef<[u8]> { impl SgxPanicOutput { pub(crate) fn new() -> Option { - if unsafe { DEBUG == 0 } { - None - } else { - Some(SgxPanicOutput(None)) - } + if unsafe { DEBUG == 0 } { None } else { Some(SgxPanicOutput(None)) } } fn init(&mut self) -> &mut &'static mut UserRef<[u8]> { self.0.get_or_insert_with(|| unsafe { let ptr = take_debug_panic_buf_ptr(); - if ptr.is_null() { - empty_user_slice() - } else { - UserRef::from_raw_parts_mut(ptr, 1024) - } + if ptr.is_null() { empty_user_slice() } else { UserRef::from_raw_parts_mut(ptr, 1024) } }) } } diff --git a/src/libstd/sys/sgx/abi/reloc.rs b/src/libstd/sys/sgx/abi/reloc.rs index 6dd24c524fc30..02dff0ad29fc3 100644 --- a/src/libstd/sys/sgx/abi/reloc.rs +++ b/src/libstd/sys/sgx/abi/reloc.rs @@ -1,5 +1,5 @@ -use crate::slice::from_raw_parts; use super::mem; +use crate::slice::from_raw_parts; const R_X86_64_RELATIVE: u32 = 8; @@ -11,18 +11,20 @@ struct Rela { } pub fn relocate_elf_rela() { - extern { + extern "C" { static RELA: u64; static RELACOUNT: usize; } - if unsafe { RELACOUNT } == 0 { return } // unsafe ok: link-time constant + if unsafe { RELACOUNT } == 0 { + return; + } // unsafe ok: link-time constant let relas = unsafe { - from_raw_parts::>(mem::rel_ptr(RELA), RELACOUNT) // unsafe ok: link-time constant + from_raw_parts::>(mem::rel_ptr(RELA), RELACOUNT) // unsafe ok: link-time constant }; for rela in relas { - if rela.info != (/*0 << 32 |*/ R_X86_64_RELATIVE as u64) { + if rela.info != (/*0 << 32 |*/R_X86_64_RELATIVE as u64) { rtabort!("Invalid relocation"); } unsafe { *mem::rel_ptr_mut::<*const ()>(rela.offset) = mem::rel_ptr(rela.addend) }; diff --git a/src/libstd/sys/sgx/abi/thread.rs b/src/libstd/sys/sgx/abi/thread.rs index c17fa2d00159e..ef55b821a2b65 100644 --- a/src/libstd/sys/sgx/abi/thread.rs +++ b/src/libstd/sys/sgx/abi/thread.rs @@ -6,6 +6,8 @@ use fortanix_sgx_abi::Tcs; /// is a one-to-one correspondence of the ID to the address of the TCS. #[unstable(feature = "sgx_platform", issue = "56975")] pub fn current() -> Tcs { - extern "C" { fn get_tcs_addr() -> Tcs; } + extern "C" { + fn get_tcs_addr() -> Tcs; + } unsafe { get_tcs_addr() } } diff --git a/src/libstd/sys/sgx/abi/tls.rs b/src/libstd/sys/sgx/abi/tls.rs index 03e08ad547d36..81a766e367d6e 100644 --- a/src/libstd/sys/sgx/abi/tls.rs +++ b/src/libstd/sys/sgx/abi/tls.rs @@ -1,11 +1,11 @@ -use crate::sync::atomic::{AtomicUsize, Ordering}; -use crate::ptr; -use crate::mem; +use self::sync_bitset::*; use crate::cell::Cell; +use crate::mem; use crate::num::NonZeroUsize; -use self::sync_bitset::*; +use crate::ptr; +use crate::sync::atomic::{AtomicUsize, Ordering}; -#[cfg(target_pointer_width="64")] +#[cfg(target_pointer_width = "64")] const USIZE_BITS: usize = 64; const TLS_KEYS: usize = 128; // Same as POSIX minimum const TLS_KEYS_BITSET_SIZE: usize = (TLS_KEYS + (USIZE_BITS - 1)) / USIZE_BITS; @@ -50,18 +50,18 @@ impl Key { #[repr(C)] pub struct Tls { - data: [Cell<*mut u8>; TLS_KEYS] + data: [Cell<*mut u8>; TLS_KEYS], } pub struct ActiveTls<'a> { - tls: &'a Tls + tls: &'a Tls, } impl<'a> Drop for ActiveTls<'a> { fn drop(&mut self) { let value_with_destructor = |key: usize| { let ptr = TLS_DESTRUCTOR[key].load(Ordering::Relaxed); - unsafe { mem::transmute::<_,Option>(ptr) } + unsafe { mem::transmute::<_, Option>(ptr) } .map(|dtor| (&self.tls.data[key], dtor)) }; @@ -99,7 +99,7 @@ impl Tls { &*(get_tls_ptr() as *const Tls) } - pub fn create(dtor: Option) -> Key { + pub fn create(dtor: Option) -> Key { let index = if let Some(index) = TLS_KEY_IN_USE.set() { index } else { @@ -127,10 +127,10 @@ impl Tls { } mod sync_bitset { - use crate::sync::atomic::{AtomicUsize, Ordering}; + use super::{TLS_KEYS_BITSET_SIZE, USIZE_BITS}; use crate::iter::{Enumerate, Peekable}; use crate::slice::Iter; - use super::{TLS_KEYS_BITSET_SIZE, USIZE_BITS}; + use crate::sync::atomic::{AtomicUsize, Ordering}; /// A bitset that can be used synchronously. pub(super) struct SyncBitset([AtomicUsize; TLS_KEYS_BITSET_SIZE]); @@ -146,10 +146,7 @@ mod sync_bitset { /// Not atomic. pub fn iter(&self) -> SyncBitsetIter<'_> { - SyncBitsetIter { - iter: self.0.iter().enumerate().peekable(), - elem_idx: 0, - } + SyncBitsetIter { iter: self.0.iter().enumerate().peekable(), elem_idx: 0 } } pub fn clear(&self, index: usize) { @@ -171,7 +168,7 @@ mod sync_bitset { current, current | (1 << trailing_ones), Ordering::AcqRel, - Ordering::Relaxed + Ordering::Relaxed, ) { Ok(_) => return Some(idx * USIZE_BITS + trailing_ones), Err(previous) => current = previous, diff --git a/src/libstd/sys/sgx/abi/usercalls/alloc.rs b/src/libstd/sys/sgx/abi/usercalls/alloc.rs index 75dd0d429c214..b54c115a2b6b6 100644 --- a/src/libstd/sys/sgx/abi/usercalls/alloc.rs +++ b/src/libstd/sys/sgx/abi/usercalls/alloc.rs @@ -1,14 +1,14 @@ #![allow(unused)] -use crate::ptr::{self, NonNull}; -use crate::mem; use crate::cell::UnsafeCell; +use crate::mem; +use crate::ops::{CoerceUnsized, Deref, DerefMut, Index, IndexMut}; +use crate::ptr::{self, NonNull}; use crate::slice; -use crate::ops::{Deref, DerefMut, Index, IndexMut, CoerceUnsized}; use crate::slice::SliceIndex; -use fortanix_sgx_abi::*; use super::super::mem::is_user_range; +use fortanix_sgx_abi::*; /// A type that can be safely read from or written to userspace. /// @@ -109,9 +109,7 @@ pub unsafe trait UserSafe { /// * the pointer is null. /// * the pointed-to range is not in user memory. unsafe fn check_ptr(ptr: *const Self) { - let is_aligned = |p| -> bool { - 0 == (p as usize) & (Self::align_of() - 1) - }; + let is_aligned = |p| -> bool { 0 == (p as usize) & (Self::align_of() - 1) }; assert!(is_aligned(ptr as *const u8)); assert!(is_user_range(ptr as _, mem::size_of_val(&*ptr))); @@ -183,7 +181,10 @@ impl NewUserRef> for NonNull> { } #[unstable(feature = "sgx_platform", issue = "56975")] -impl User where T: UserSafe { +impl User +where + T: UserSafe, +{ // This function returns memory that is practically uninitialized, but is // not considered "unspecified" or "undefined" for purposes of an // optimizing compiler. This is achieved by returning a pointer from @@ -211,7 +212,7 @@ impl User where T: UserSafe { ptr::copy( val as *const T as *const u8, ret.0.as_ptr() as *mut u8, - mem::size_of_val(val) + mem::size_of_val(val), ); ret } @@ -244,7 +245,10 @@ impl User where T: UserSafe { } #[unstable(feature = "sgx_platform", issue = "56975")] -impl User where T: UserSafe { +impl User +where + T: UserSafe, +{ /// Allocate space for `T` in user memory. pub fn uninitialized() -> Self { Self::new_uninit_bytes(mem::size_of::()) @@ -252,7 +256,10 @@ impl User where T: UserSafe { } #[unstable(feature = "sgx_platform", issue = "56975")] -impl User<[T]> where [T]: UserSafe { +impl User<[T]> +where + [T]: UserSafe, +{ /// Allocate space for a `[T]` of `n` elements in user memory. pub fn uninitialized(n: usize) -> Self { Self::new_uninit_bytes(n * mem::size_of::()) @@ -278,7 +285,10 @@ impl User<[T]> where [T]: UserSafe { } #[unstable(feature = "sgx_platform", issue = "56975")] -impl UserRef where T: UserSafe { +impl UserRef +where + T: UserSafe, +{ /// Creates a `&UserRef<[T]>` from a raw pointer. /// /// # Safety @@ -309,7 +319,7 @@ impl UserRef where T: UserSafe { /// * The pointed-to range is not in user memory pub unsafe fn from_mut_ptr<'a>(ptr: *mut T) -> &'a mut Self { T::check_ptr(ptr); - &mut*(ptr as *mut Self) + &mut *(ptr as *mut Self) } /// Copies `val` into user memory. @@ -319,11 +329,11 @@ impl UserRef where T: UserSafe { /// the source. This can happen for dynamically-sized types such as slices. pub fn copy_from_enclave(&mut self, val: &T) { unsafe { - assert_eq!(mem::size_of_val(val), mem::size_of_val( &*self.0.get() )); + assert_eq!(mem::size_of_val(val), mem::size_of_val(&*self.0.get())); ptr::copy( val as *const T as *const u8, self.0.get() as *mut T as *mut u8, - mem::size_of_val(val) + mem::size_of_val(val), ); } } @@ -335,11 +345,11 @@ impl UserRef where T: UserSafe { /// the source. This can happen for dynamically-sized types such as slices. pub fn copy_to_enclave(&self, dest: &mut T) { unsafe { - assert_eq!(mem::size_of_val(dest), mem::size_of_val( &*self.0.get() )); + assert_eq!(mem::size_of_val(dest), mem::size_of_val(&*self.0.get())); ptr::copy( self.0.get() as *const T as *const u8, dest as *mut T as *mut u8, - mem::size_of_val(dest) + mem::size_of_val(dest), ); } } @@ -356,7 +366,10 @@ impl UserRef where T: UserSafe { } #[unstable(feature = "sgx_platform", issue = "56975")] -impl UserRef where T: UserSafe { +impl UserRef +where + T: UserSafe, +{ /// Copies the value from user memory into enclave memory. pub fn to_enclave(&self) -> T { unsafe { ptr::read(self.0.get()) } @@ -364,7 +377,10 @@ impl UserRef where T: UserSafe { } #[unstable(feature = "sgx_platform", issue = "56975")] -impl UserRef<[T]> where [T]: UserSafe { +impl UserRef<[T]> +where + [T]: UserSafe, +{ /// Creates a `&UserRef<[T]>` from a raw thin pointer and a slice length. /// /// # Safety @@ -396,7 +412,7 @@ impl UserRef<[T]> where [T]: UserSafe { /// * The pointed-to range does not fit in the address space /// * The pointed-to range is not in user memory pub unsafe fn from_raw_parts_mut<'a>(ptr: *mut T, len: usize) -> &'a mut Self { - &mut*(<[T]>::from_raw_sized(ptr as _, len * mem::size_of::()).as_ptr() as *mut Self) + &mut *(<[T]>::from_raw_sized(ptr as _, len * mem::size_of::()).as_ptr() as *mut Self) } /// Obtain a raw pointer to the first element of this user slice. @@ -439,20 +455,18 @@ impl UserRef<[T]> where [T]: UserSafe { /// Returns an iterator over the slice. pub fn iter(&self) -> Iter<'_, T> - where T: UserSafe // FIXME: should be implied by [T]: UserSafe? + where + T: UserSafe, // FIXME: should be implied by [T]: UserSafe? { - unsafe { - Iter((&*self.as_raw_ptr()).iter()) - } + unsafe { Iter((&*self.as_raw_ptr()).iter()) } } /// Returns an iterator that allows modifying each value. pub fn iter_mut(&mut self) -> IterMut<'_, T> - where T: UserSafe // FIXME: should be implied by [T]: UserSafe? + where + T: UserSafe, // FIXME: should be implied by [T]: UserSafe? { - unsafe { - IterMut((&mut*self.as_raw_mut_ptr()).iter_mut()) - } + unsafe { IterMut((&mut *self.as_raw_mut_ptr()).iter_mut()) } } } @@ -468,9 +482,7 @@ impl<'a, T: UserSafe> Iterator for Iter<'a, T> { #[inline] fn next(&mut self) -> Option { - unsafe { - self.0.next().map(|e| UserRef::from_ptr(e)) - } + unsafe { self.0.next().map(|e| UserRef::from_ptr(e)) } } } @@ -486,14 +498,15 @@ impl<'a, T: UserSafe> Iterator for IterMut<'a, T> { #[inline] fn next(&mut self) -> Option { - unsafe { - self.0.next().map(|e| UserRef::from_mut_ptr(e)) - } + unsafe { self.0.next().map(|e| UserRef::from_mut_ptr(e)) } } } #[unstable(feature = "sgx_platform", issue = "56975")] -impl Deref for User where T: UserSafe { +impl Deref for User +where + T: UserSafe, +{ type Target = UserRef; fn deref(&self) -> &Self::Target { @@ -502,18 +515,24 @@ impl Deref for User where T: UserSafe { } #[unstable(feature = "sgx_platform", issue = "56975")] -impl DerefMut for User where T: UserSafe { +impl DerefMut for User +where + T: UserSafe, +{ fn deref_mut(&mut self) -> &mut Self::Target { - unsafe { &mut*self.0.as_ptr() } + unsafe { &mut *self.0.as_ptr() } } } #[unstable(feature = "sgx_platform", issue = "56975")] -impl Drop for User where T: UserSafe { +impl Drop for User +where + T: UserSafe, +{ fn drop(&mut self) { unsafe { let ptr = (*self.0.as_ptr()).0.get(); - super::free(ptr as _, mem::size_of_val(&mut*ptr), T::align_of()); + super::free(ptr as _, mem::size_of_val(&mut *ptr), T::align_of()); } } } @@ -550,7 +569,7 @@ where #[inline] fn index_mut(&mut self, index: I) -> &mut UserRef { unsafe { - if let Some(slice) = index.get_mut(&mut*self.as_raw_mut_ptr()) { + if let Some(slice) = index.get_mut(&mut *self.as_raw_mut_ptr()) { UserRef::from_mut_ptr(slice) } else { rtabort!("index out of range for user slice"); diff --git a/src/libstd/sys/sgx/abi/usercalls/mod.rs b/src/libstd/sys/sgx/abi/usercalls/mod.rs index fca62e028deab..ae803ee47a6cb 100644 --- a/src/libstd/sys/sgx/abi/usercalls/mod.rs +++ b/src/libstd/sys/sgx/abi/usercalls/mod.rs @@ -1,5 +1,5 @@ use crate::cmp; -use crate::io::{Error as IoError, Result as IoResult, IoSlice, IoSliceMut}; +use crate::io::{Error as IoError, IoSlice, IoSliceMut, Result as IoResult}; use crate::time::Duration; pub(crate) mod alloc; @@ -26,7 +26,7 @@ pub fn read(fd: Fd, bufs: &mut [IoSliceMut<'_>]) -> IoResult { userbuf[index..end].copy_to_enclave(&mut buf[..buflen]); index += buf.len(); } else { - break + break; } } Ok(userbuf.len()) @@ -60,7 +60,7 @@ pub fn write(fd: Fd, bufs: &[IoSlice<'_>]) -> IoResult { userbuf[index..end].copy_from_enclave(&buf[..buflen]); index += buf.len(); } else { - break + break; } } raw::write(fd, userbuf.as_ptr(), userbuf.len()).from_sgx_result() @@ -90,11 +90,8 @@ pub fn bind_stream(addr: &str) -> IoResult<(Fd, String)> { unsafe { let addr_user = alloc::User::new_from_enclave(addr.as_bytes()); let mut local = alloc::User::::uninitialized(); - let fd = raw::bind_stream( - addr_user.as_ptr(), - addr_user.len(), - local.as_raw_mut_ptr() - ).from_sgx_result()?; + let fd = raw::bind_stream(addr_user.as_ptr(), addr_user.len(), local.as_raw_mut_ptr()) + .from_sgx_result()?; let local = string_from_bytebuffer(&local, "bind_stream", "local_addr"); Ok((fd, local)) } @@ -106,13 +103,10 @@ pub fn accept_stream(fd: Fd) -> IoResult<(Fd, String, String)> { unsafe { let mut bufs = alloc::User::<[ByteBuffer; 2]>::uninitialized(); let mut buf_it = alloc::UserRef::iter_mut(&mut *bufs); // FIXME: can this be done - // without forcing coercion? + // without forcing coercion? let (local, peer) = (buf_it.next().unwrap(), buf_it.next().unwrap()); - let fd = raw::accept_stream( - fd, - local.as_raw_mut_ptr(), - peer.as_raw_mut_ptr() - ).from_sgx_result()?; + let fd = raw::accept_stream(fd, local.as_raw_mut_ptr(), peer.as_raw_mut_ptr()) + .from_sgx_result()?; let local = string_from_bytebuffer(&local, "accept_stream", "local_addr"); let peer = string_from_bytebuffer(&peer, "accept_stream", "peer_addr"); Ok((fd, local, peer)) @@ -126,14 +120,15 @@ pub fn connect_stream(addr: &str) -> IoResult<(Fd, String, String)> { let addr_user = alloc::User::new_from_enclave(addr.as_bytes()); let mut bufs = alloc::User::<[ByteBuffer; 2]>::uninitialized(); let mut buf_it = alloc::UserRef::iter_mut(&mut *bufs); // FIXME: can this be done - // without forcing coercion? + // without forcing coercion? let (local, peer) = (buf_it.next().unwrap(), buf_it.next().unwrap()); let fd = raw::connect_stream( addr_user.as_ptr(), addr_user.len(), local.as_raw_mut_ptr(), - peer.as_raw_mut_ptr() - ).from_sgx_result()?; + peer.as_raw_mut_ptr(), + ) + .from_sgx_result()?; let local = string_from_bytebuffer(&local, "connect_stream", "local_addr"); let peer = string_from_bytebuffer(&peer, "connect_stream", "peer_addr"); Ok((fd, local, peer)) @@ -183,25 +178,25 @@ pub use self::raw::free; fn check_os_error(err: Result) -> i32 { // FIXME: not sure how to make sure all variants of Error are covered - if err == Error::NotFound as _ || - err == Error::PermissionDenied as _ || - err == Error::ConnectionRefused as _ || - err == Error::ConnectionReset as _ || - err == Error::ConnectionAborted as _ || - err == Error::NotConnected as _ || - err == Error::AddrInUse as _ || - err == Error::AddrNotAvailable as _ || - err == Error::BrokenPipe as _ || - err == Error::AlreadyExists as _ || - err == Error::WouldBlock as _ || - err == Error::InvalidInput as _ || - err == Error::InvalidData as _ || - err == Error::TimedOut as _ || - err == Error::WriteZero as _ || - err == Error::Interrupted as _ || - err == Error::Other as _ || - err == Error::UnexpectedEof as _ || - ((Error::UserRangeStart as _)..=(Error::UserRangeEnd as _)).contains(&err) + if err == Error::NotFound as _ + || err == Error::PermissionDenied as _ + || err == Error::ConnectionRefused as _ + || err == Error::ConnectionReset as _ + || err == Error::ConnectionAborted as _ + || err == Error::NotConnected as _ + || err == Error::AddrInUse as _ + || err == Error::AddrNotAvailable as _ + || err == Error::BrokenPipe as _ + || err == Error::AlreadyExists as _ + || err == Error::WouldBlock as _ + || err == Error::InvalidInput as _ + || err == Error::InvalidData as _ + || err == Error::TimedOut as _ + || err == Error::WriteZero as _ + || err == Error::Interrupted as _ + || err == Error::Other as _ + || err == Error::UnexpectedEof as _ + || ((Error::UserRangeStart as _)..=(Error::UserRangeEnd as _)).contains(&err) { err } else { diff --git a/src/libstd/sys/sgx/abi/usercalls/raw.rs b/src/libstd/sys/sgx/abi/usercalls/raw.rs index e4694a8827a0d..e0ebf860618c8 100644 --- a/src/libstd/sys/sgx/abi/usercalls/raw.rs +++ b/src/libstd/sys/sgx/abi/usercalls/raw.rs @@ -3,8 +3,8 @@ #[unstable(feature = "sgx_platform", issue = "56975")] pub use fortanix_sgx_abi::*; -use crate::ptr::NonNull; use crate::num::NonZeroU64; +use crate::ptr::NonNull; #[repr(C)] struct UsercallReturn(u64, u64); @@ -25,9 +25,14 @@ extern "C" { /// Panics if `nr` is `0`. #[unstable(feature = "sgx_platform", issue = "56975")] #[inline] -pub unsafe fn do_usercall(nr: NonZeroU64, p1: u64, p2: u64, p3: u64, p4: u64, abort: bool) - -> (u64, u64) -{ +pub unsafe fn do_usercall( + nr: NonZeroU64, + p1: u64, + p2: u64, + p3: u64, + p4: u64, + abort: bool, +) -> (u64, u64) { let UsercallReturn(a, b) = usercall(nr, p1, p2, abort as _, p3, p4); (a, b) } @@ -109,11 +114,7 @@ define_ra!( *mut T); impl RegisterArgument for bool { fn from_register(a: Register) -> bool { - if a != 0 { - true - } else { - false - } + if a != 0 { true } else { false } } fn into_register(self) -> Register { self as _ @@ -152,16 +153,17 @@ impl ReturnValue for T { impl ReturnValue for (T, U) { fn from_registers(_call: &'static str, regs: (Register, Register)) -> Self { - ( - T::from_register(regs.0), - U::from_register(regs.1) - ) + (T::from_register(regs.0), U::from_register(regs.1)) } } macro_rules! return_type_is_abort { - (!) => { true }; - ($r:ty) => { false }; + (!) => { + true + }; + ($r:ty) => { + false + }; } // In this macro: using `$r:tt` because `$r:ty` doesn't match ! in `return_type_is_abort` diff --git a/src/libstd/sys/sgx/args.rs b/src/libstd/sys/sgx/args.rs index a84ab4138761e..b47a48e752cb7 100644 --- a/src/libstd/sys/sgx/args.rs +++ b/src/libstd/sys/sgx/args.rs @@ -1,9 +1,9 @@ use super::abi::usercalls::{alloc, raw::ByteBuffer}; use crate::ffi::OsString; +use crate::slice; use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sys::os_str::Buf; use crate::sys_common::FromInner; -use crate::slice; #[cfg_attr(test, linkage = "available_externally")] #[export_name = "_ZN16__rust_internals3std3sys3sgx4args4ARGSE"] @@ -14,8 +14,9 @@ type ArgsStore = Vec; pub unsafe fn init(argc: isize, argv: *const *const u8) { if argc != 0 { let args = alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _); - let args = args.iter() - .map( |a| OsString::from_inner(Buf { inner: a.copy_user_buffer() }) ) + let args = args + .iter() + .map(|a| OsString::from_inner(Buf { inner: a.copy_user_buffer() })) .collect::(); ARGS.store(Box::into_raw(Box::new(args)) as _, Ordering::Relaxed); } @@ -30,11 +31,7 @@ pub unsafe fn cleanup() { pub fn args() -> Args { let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() }; - if let Some(args) = args { - Args(args.iter()) - } else { - Args([].iter()) - } + if let Some(args) = args { Args(args.iter()) } else { Args([].iter()) } } pub struct Args(slice::Iter<'static, OsString>); diff --git a/src/libstd/sys/sgx/cmath.rs b/src/libstd/sys/sgx/cmath.rs index 5aabdc1c8d302..b89238f1da8f7 100644 --- a/src/libstd/sys/sgx/cmath.rs +++ b/src/libstd/sys/sgx/cmath.rs @@ -1,7 +1,7 @@ #![cfg(not(test))] // These symbols are all defined in `compiler-builtins` -extern { +extern "C" { pub fn acos(n: f64) -> f64; pub fn acosf(n: f32) -> f32; pub fn asin(n: f64) -> f64; diff --git a/src/libstd/sys/sgx/ext/io.rs b/src/libstd/sys/sgx/ext/io.rs index fc88d10d3eddb..8aa84a550d2ed 100644 --- a/src/libstd/sys/sgx/ext/io.rs +++ b/src/libstd/sys/sgx/ext/io.rs @@ -4,8 +4,8 @@ //! description of [`TryIntoRawFd`](trait.TryIntoRawFd.html) for more details. #![unstable(feature = "sgx_platform", issue = "56975")] -pub use crate::sys::abi::usercalls::raw::Fd as RawFd; use crate::net; +pub use crate::sys::abi::usercalls::raw::Fd as RawFd; use crate::sys::{self, AsInner, FromInner, IntoInner, TryIntoInner}; /// A trait to extract the raw SGX file descriptor from an underlying @@ -60,11 +60,15 @@ pub trait TryIntoRawFd: Sized { } impl AsRawFd for net::TcpStream { - fn as_raw_fd(&self) -> RawFd { *self.as_inner().as_inner().as_inner().as_inner() } + fn as_raw_fd(&self) -> RawFd { + *self.as_inner().as_inner().as_inner().as_inner() + } } impl AsRawFd for net::TcpListener { - fn as_raw_fd(&self) -> RawFd { *self.as_inner().as_inner().as_inner().as_inner() } + fn as_raw_fd(&self) -> RawFd { + *self.as_inner().as_inner().as_inner().as_inner() + } } impl FromRawFd for net::TcpStream { diff --git a/src/libstd/sys/sgx/ext/mod.rs b/src/libstd/sys/sgx/ext/mod.rs index 51b2659da83e3..258ad3cd2180c 100644 --- a/src/libstd/sys/sgx/ext/mod.rs +++ b/src/libstd/sys/sgx/ext/mod.rs @@ -1,5 +1,5 @@ #![unstable(feature = "sgx_platform", issue = "56975")] pub mod arch; -pub mod io; pub mod ffi; +pub mod io; diff --git a/src/libstd/sys/sgx/fd.rs b/src/libstd/sys/sgx/fd.rs index a1c4af81966b2..7da2424a64261 100644 --- a/src/libstd/sys/sgx/fd.rs +++ b/src/libstd/sys/sgx/fd.rs @@ -1,9 +1,9 @@ use fortanix_sgx_abi::Fd; +use super::abi::usercalls; use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; use crate::sys::{AsInner, FromInner, IntoInner}; -use super::abi::usercalls; #[derive(Debug)] pub struct FileDesc { @@ -15,7 +15,9 @@ impl FileDesc { FileDesc { fd: fd } } - pub fn raw(&self) -> Fd { self.fd } + pub fn raw(&self) -> Fd { + self.fd + } /// Extracts the actual filedescriptor without closing it. pub fn into_raw(self) -> Fd { @@ -46,7 +48,9 @@ impl FileDesc { } impl AsInner for FileDesc { - fn as_inner(&self) -> &Fd { &self.fd } + fn as_inner(&self) -> &Fd { + &self.fd + } } impl IntoInner for FileDesc { diff --git a/src/libstd/sys/sgx/fs.rs b/src/libstd/sys/sgx/fs.rs index e9095b375fe5d..e6160d1457d26 100644 --- a/src/libstd/sys/sgx/fs.rs +++ b/src/libstd/sys/sgx/fs.rs @@ -1,7 +1,7 @@ use crate::ffi::OsString; use crate::fmt; use crate::hash::{Hash, Hasher}; -use crate::io::{self, SeekFrom, IoSlice, IoSliceMut}; +use crate::io::{self, IoSlice, IoSliceMut, SeekFrom}; use crate::path::{Path, PathBuf}; use crate::sys::time::SystemTime; use crate::sys::{unsupported, Void}; @@ -15,14 +15,14 @@ pub struct ReadDir(Void); pub struct DirEntry(Void); #[derive(Clone, Debug)] -pub struct OpenOptions { } +pub struct OpenOptions {} pub struct FilePermissions(Void); pub struct FileType(Void); #[derive(Debug)] -pub struct DirBuilder { } +pub struct DirBuilder {} impl FileAttr { pub fn size(&self) -> u64 { @@ -78,8 +78,7 @@ impl PartialEq for FilePermissions { } } -impl Eq for FilePermissions { -} +impl Eq for FilePermissions {} impl fmt::Debug for FilePermissions { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -115,8 +114,7 @@ impl PartialEq for FileType { } } -impl Eq for FileType { -} +impl Eq for FileType {} impl Hash for FileType { fn hash(&self, _h: &mut H) { @@ -164,15 +162,15 @@ impl DirEntry { impl OpenOptions { pub fn new() -> OpenOptions { - OpenOptions { } + OpenOptions {} } - pub fn read(&mut self, _read: bool) { } - pub fn write(&mut self, _write: bool) { } - pub fn append(&mut self, _append: bool) { } - pub fn truncate(&mut self, _truncate: bool) { } - pub fn create(&mut self, _create: bool) { } - pub fn create_new(&mut self, _create_new: bool) { } + pub fn read(&mut self, _read: bool) {} + pub fn write(&mut self, _write: bool) {} + pub fn append(&mut self, _append: bool) {} + pub fn truncate(&mut self, _truncate: bool) {} + pub fn create(&mut self, _create: bool) {} + pub fn create_new(&mut self, _create_new: bool) {} } impl File { @@ -235,7 +233,7 @@ impl File { impl DirBuilder { pub fn new() -> DirBuilder { - DirBuilder { } + DirBuilder {} } pub fn mkdir(&self, _p: &Path) -> io::Result<()> { diff --git a/src/libstd/sys/sgx/net.rs b/src/libstd/sys/sgx/net.rs index f9eca9f4cb3c1..f36687b4d3d58 100644 --- a/src/libstd/sys/sgx/net.rs +++ b/src/libstd/sys/sgx/net.rs @@ -1,12 +1,12 @@ -use crate::fmt; -use crate::io::{self, IoSlice, IoSliceMut}; -use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr, ToSocketAddrs}; -use crate::time::Duration; -use crate::sys::{unsupported, Void, sgx_ineffective, AsInner, FromInner, IntoInner, TryIntoInner}; -use crate::sys::fd::FileDesc; use crate::convert::TryFrom; use crate::error; +use crate::fmt; +use crate::io::{self, IoSlice, IoSliceMut}; +use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, ToSocketAddrs}; use crate::sync::Arc; +use crate::sys::fd::FileDesc; +use crate::sys::{sgx_ineffective, unsupported, AsInner, FromInner, IntoInner, TryIntoInner, Void}; +use crate::time::Duration; use super::abi::usercalls; @@ -25,13 +25,15 @@ impl Socket { } impl AsInner for Socket { - fn as_inner(&self) -> &FileDesc { &self.inner } + fn as_inner(&self) -> &FileDesc { + &self.inner + } } impl TryIntoInner for Socket { fn try_into_inner(self) -> Result { let Socket { inner, local_addr } = self; - Arc::try_unwrap(inner).map_err(|inner| Socket { inner, local_addr } ) + Arc::try_unwrap(inner).map_err(|inner| Socket { inner, local_addr }) } } @@ -59,8 +61,7 @@ impl fmt::Debug for TcpStream { res.field("peer", peer); } - res.field("fd", &self.inner.inner.as_inner()) - .finish() + res.field("fd", &self.inner.inner.as_inner()).finish() } } @@ -69,10 +70,12 @@ fn io_err_to_addr(result: io::Result<&SocketAddr>) -> io::Result { Ok(saddr) => Ok(saddr.to_string()), // need to downcast twice because io::Error::into_inner doesn't return the original // value if the conversion fails - Err(e) => if e.get_ref().and_then(|e| e.downcast_ref::()).is_some() { - Ok(e.into_inner().unwrap().downcast::().unwrap().host) - } else { - Err(e) + Err(e) => { + if e.get_ref().and_then(|e| e.downcast_ref::()).is_some() { + Ok(e.into_inner().unwrap().downcast::().unwrap().host) + } else { + Err(e) + } } } } @@ -94,8 +97,10 @@ impl TcpStream { pub fn connect_timeout(addr: &SocketAddr, dur: Duration) -> io::Result { if dur == Duration::default() { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); } Self::connect(Ok(addr)) // FIXME: ignoring timeout } @@ -103,20 +108,24 @@ impl TcpStream { pub fn set_read_timeout(&self, dur: Option) -> io::Result<()> { match dur { Some(dur) if dur == Duration::default() => { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); } - _ => sgx_ineffective(()) + _ => sgx_ineffective(()), } } pub fn set_write_timeout(&self, dur: Option) -> io::Result<()> { match dur { Some(dur) if dur == Duration::default() => { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); } - _ => sgx_ineffective(()) + _ => sgx_ineffective(()), } } @@ -190,7 +199,9 @@ impl TcpStream { } impl AsInner for TcpStream { - fn as_inner(&self) -> &Socket { &self.inner } + fn as_inner(&self) -> &Socket { + &self.inner + } } // `Inner` includes `peer_addr` so that a `TcpStream` maybe correctly @@ -220,8 +231,7 @@ impl fmt::Debug for TcpListener { res.field("addr", addr); } - res.field("fd", &self.inner.inner.as_inner()) - .finish() + res.field("fd", &self.inner.inner.as_inner()).finish() } } @@ -273,7 +283,9 @@ impl TcpListener { } impl AsInner for TcpListener { - fn as_inner(&self) -> &Socket { &self.inner } + fn as_inner(&self) -> &Socket { + &self.inner + } } impl IntoInner for TcpListener { @@ -367,23 +379,19 @@ impl UdpSocket { match self.0 {} } - pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) - -> io::Result<()> { + pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { match self.0 {} } - pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) - -> io::Result<()> { + pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { match self.0 {} } - pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) - -> io::Result<()> { + pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { match self.0 {} } - pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) - -> io::Result<()> { + pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { match self.0 {} } @@ -428,7 +436,7 @@ impl fmt::Debug for UdpSocket { #[derive(Debug)] pub struct NonIpSockAddr { - host: String + host: String, } impl error::Error for NonIpSockAddr { @@ -511,8 +519,7 @@ pub mod netc { } #[derive(Copy, Clone)] - pub struct sockaddr { - } + pub struct sockaddr {} pub type socklen_t = usize; } diff --git a/src/libstd/sys/sgx/os.rs b/src/libstd/sys/sgx/os.rs index 8b12c49edbaae..2c5b31342199a 100644 --- a/src/libstd/sys/sgx/os.rs +++ b/src/libstd/sys/sgx/os.rs @@ -1,17 +1,17 @@ use fortanix_sgx_abi::{Error, RESULT_SUCCESS}; +use crate::collections::HashMap; use crate::error::Error as StdError; -use crate::ffi::{OsString, OsStr}; +use crate::ffi::{OsStr, OsString}; use crate::fmt; use crate::io; use crate::path::{self, PathBuf}; use crate::str; -use crate::sys::{unsupported, Void, sgx_ineffective, decode_error_kind}; -use crate::collections::HashMap; -use crate::vec; -use crate::sync::Mutex; use crate::sync::atomic::{AtomicUsize, Ordering}; +use crate::sync::Mutex; use crate::sync::Once; +use crate::sys::{decode_error_kind, sgx_ineffective, unsupported, Void}; +use crate::vec; pub fn errno() -> i32 { RESULT_SUCCESS @@ -52,7 +52,9 @@ impl<'a> Iterator for SplitPaths<'a> { pub struct JoinPathsError; pub fn join_paths(_paths: I) -> Result - where I: Iterator, T: AsRef +where + I: Iterator, + T: AsRef, { Err(JoinPathsError) } @@ -89,26 +91,21 @@ fn create_env_store() -> &'static EnvStore { ENV_INIT.call_once(|| { ENV.store(Box::into_raw(Box::new(EnvStore::default())) as _, Ordering::Relaxed) }); - unsafe { - &*(ENV.load(Ordering::Relaxed) as *const EnvStore) - } + unsafe { &*(ENV.load(Ordering::Relaxed) as *const EnvStore) } } pub type Env = vec::IntoIter<(OsString, OsString)>; pub fn env() -> Env { let clone_to_vec = |map: &HashMap| -> Vec<_> { - map.iter().map(|(k, v)| (k.clone(), v.clone()) ).collect() + map.iter().map(|(k, v)| (k.clone(), v.clone())).collect() }; - get_env_store() - .map(|env| clone_to_vec(&env.lock().unwrap()) ) - .unwrap_or_default() - .into_iter() + get_env_store().map(|env| clone_to_vec(&env.lock().unwrap())).unwrap_or_default().into_iter() } pub fn getenv(k: &OsStr) -> io::Result> { - Ok(get_env_store().and_then(|s| s.lock().unwrap().get(k).cloned() )) + Ok(get_env_store().and_then(|s| s.lock().unwrap().get(k).cloned())) } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { diff --git a/src/libstd/sys/sgx/path.rs b/src/libstd/sys/sgx/path.rs index b5fd7e3ae6d1e..06c9df3ff5427 100644 --- a/src/libstd/sys/sgx/path.rs +++ b/src/libstd/sys/sgx/path.rs @@ -1,5 +1,5 @@ -use crate::path::Prefix; use crate::ffi::OsStr; +use crate::path::Prefix; #[inline] pub fn is_sep_byte(b: u8) -> bool { diff --git a/src/libstd/sys/sgx/process.rs b/src/libstd/sys/sgx/process.rs index edf933d10e074..4702e5c549228 100644 --- a/src/libstd/sys/sgx/process.rs +++ b/src/libstd/sys/sgx/process.rs @@ -32,32 +32,28 @@ pub enum Stdio { impl Command { pub fn new(_program: &OsStr) -> Command { - Command { - env: Default::default() - } + Command { env: Default::default() } } - pub fn arg(&mut self, _arg: &OsStr) { - } + pub fn arg(&mut self, _arg: &OsStr) {} pub fn env_mut(&mut self) -> &mut CommandEnv { &mut self.env } - pub fn cwd(&mut self, _dir: &OsStr) { - } + pub fn cwd(&mut self, _dir: &OsStr) {} - pub fn stdin(&mut self, _stdin: Stdio) { - } + pub fn stdin(&mut self, _stdin: Stdio) {} - pub fn stdout(&mut self, _stdout: Stdio) { - } + pub fn stdout(&mut self, _stdout: Stdio) {} - pub fn stderr(&mut self, _stderr: Stdio) { - } + pub fn stderr(&mut self, _stderr: Stdio) {} - 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)> { unsupported() } } @@ -106,8 +102,7 @@ impl PartialEq for ExitStatus { } } -impl Eq for ExitStatus { -} +impl Eq for ExitStatus {} impl fmt::Debug for ExitStatus { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/src/libstd/sys/sgx/stack_overflow.rs b/src/libstd/sys/sgx/stack_overflow.rs index e63fa2bed65d5..a2d13d11849e7 100644 --- a/src/libstd/sys/sgx/stack_overflow.rs +++ b/src/libstd/sys/sgx/stack_overflow.rs @@ -7,8 +7,6 @@ impl Handler { } #[cfg_attr(test, allow(dead_code))] -pub unsafe fn init() { -} +pub unsafe fn init() {} -pub unsafe fn cleanup() { -} +pub unsafe fn cleanup() {} diff --git a/src/libstd/sys/sgx/stdio.rs b/src/libstd/sys/sgx/stdio.rs index a575401f5f60d..716c174bd53b6 100644 --- a/src/libstd/sys/sgx/stdio.rs +++ b/src/libstd/sys/sgx/stdio.rs @@ -1,11 +1,11 @@ use fortanix_sgx_abi as abi; use crate::io; -use crate::sys::fd::FileDesc; #[cfg(not(test))] use crate::slice; #[cfg(not(test))] use crate::str; +use crate::sys::fd::FileDesc; pub struct Stdin(()); pub struct Stdout(()); @@ -19,7 +19,9 @@ fn with_std_fd R, R>(fd: abi::Fd, f: F) -> R { } impl Stdin { - pub fn new() -> io::Result { Ok(Stdin(())) } + pub fn new() -> io::Result { + Ok(Stdin(())) + } } impl io::Read for Stdin { @@ -29,7 +31,9 @@ impl io::Read for Stdin { } impl Stdout { - pub fn new() -> io::Result { Ok(Stdout(())) } + pub fn new() -> io::Result { + Ok(Stdout(())) + } } impl io::Write for Stdout { @@ -43,7 +47,9 @@ impl io::Write for Stdout { } impl Stderr { - pub fn new() -> io::Result { Ok(Stderr(())) } + pub fn new() -> io::Result { + Ok(Stderr(())) + } } impl io::Write for Stderr { diff --git a/src/libstd/sys/sgx/thread.rs b/src/libstd/sys/sgx/thread.rs index b9f42d4ad1c59..9b515eb82de35 100644 --- a/src/libstd/sys/sgx/thread.rs +++ b/src/libstd/sys/sgx/thread.rs @@ -10,8 +10,8 @@ pub struct Thread(task_queue::JoinHandle); pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; mod task_queue { - use crate::sync::{Mutex, MutexGuard, Once}; use crate::sync::mpsc; + use crate::sync::{Mutex, MutexGuard, Once}; pub type JoinHandle = mpsc::Receiver<()>; @@ -41,7 +41,7 @@ mod task_queue { pub(super) fn lock() -> MutexGuard<'static, Vec> { unsafe { - TASK_QUEUE_INIT.call_once(|| TASK_QUEUE = Some(Default::default()) ); + TASK_QUEUE_INIT.call_once(|| TASK_QUEUE = Some(Default::default())); TASK_QUEUE.as_ref().unwrap().lock().unwrap() } } @@ -49,9 +49,7 @@ mod task_queue { impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(_stack: usize, p: Box) - -> io::Result - { + pub unsafe fn new(_stack: usize, p: Box) -> io::Result { let mut queue_lock = task_queue::lock(); usercalls::launch_thread()?; let (task, handle) = task_queue::Task::new(p); @@ -86,6 +84,10 @@ impl Thread { pub mod guard { pub type Guard = !; - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + pub unsafe fn current() -> Option { + None + } + pub unsafe fn init() -> Option { + None + } } diff --git a/src/libstd/sys/sgx/thread_local.rs b/src/libstd/sys/sgx/thread_local.rs index e0d0fe7695722..b21784475f0d2 100644 --- a/src/libstd/sys/sgx/thread_local.rs +++ b/src/libstd/sys/sgx/thread_local.rs @@ -1,9 +1,9 @@ -use super::abi::tls::{Tls, Key as AbiKey}; +use super::abi::tls::{Key as AbiKey, Tls}; pub type Key = usize; #[inline] -pub unsafe fn create(dtor: Option) -> Key { +pub unsafe fn create(dtor: Option) -> Key { Tls::create(dtor).as_usize() } diff --git a/src/libstd/sys/sgx/time.rs b/src/libstd/sys/sgx/time.rs index 4659f7ba71fe0..e2f6e6dba695d 100644 --- a/src/libstd/sys/sgx/time.rs +++ b/src/libstd/sys/sgx/time.rs @@ -1,5 +1,5 @@ -use crate::time::Duration; use super::abi::usercalls; +use crate::time::Duration; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct Instant(Duration); @@ -40,8 +40,7 @@ impl SystemTime { SystemTime(usercalls::insecure_time()) } - pub fn sub_time(&self, other: &SystemTime) - -> Result { + pub fn sub_time(&self, other: &SystemTime) -> Result { self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0) } diff --git a/src/libstd/sys/unix/alloc.rs b/src/libstd/sys/unix/alloc.rs index cf4900b48943e..77417e4133127 100644 --- a/src/libstd/sys/unix/alloc.rs +++ b/src/libstd/sys/unix/alloc.rs @@ -1,6 +1,6 @@ -use crate::ptr; -use crate::sys_common::alloc::{MIN_ALIGN, realloc_fallback}; use crate::alloc::{GlobalAlloc, Layout, System}; +use crate::ptr; +use crate::sys_common::alloc::{realloc_fallback, MIN_ALIGN}; #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { @@ -16,7 +16,7 @@ unsafe impl GlobalAlloc for System { #[cfg(target_os = "macos")] { if layout.align() > (1 << 31) { - return ptr::null_mut() + return ptr::null_mut(); } } aligned_malloc(&layout) @@ -52,9 +52,7 @@ unsafe impl GlobalAlloc for System { } } -#[cfg(any(target_os = "android", - target_os = "redox", - target_os = "solaris"))] +#[cfg(any(target_os = "android", target_os = "redox", target_os = "solaris"))] #[inline] unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { // On android we currently target API level 9 which unfortunately @@ -77,9 +75,7 @@ unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { libc::memalign(layout.align(), layout.size()) as *mut u8 } -#[cfg(not(any(target_os = "android", - target_os = "redox", - target_os = "solaris")))] +#[cfg(not(any(target_os = "android", target_os = "redox", target_os = "solaris")))] #[inline] unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { let mut out = ptr::null_mut(); @@ -87,9 +83,5 @@ unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { // Since these are all powers of 2, we can just use max. let align = layout.align().max(crate::mem::size_of::()); let ret = libc::posix_memalign(&mut out, align, layout.size()); - if ret != 0 { - ptr::null_mut() - } else { - out as *mut u8 - } + if ret != 0 { ptr::null_mut() } else { out as *mut u8 } } diff --git a/src/libstd/sys/unix/android.rs b/src/libstd/sys/unix/android.rs index 6774160bb2561..c5e9d66e85ef9 100644 --- a/src/libstd/sys/unix/android.rs +++ b/src/libstd/sys/unix/android.rs @@ -21,8 +21,8 @@ use libc::{c_int, c_void, sighandler_t, size_t, ssize_t}; use libc::{ftruncate, pread, pwrite}; -use crate::io; use super::{cvt, cvt_r}; +use crate::io; // The `log2` and `log2f` functions apparently appeared in android-18, or at // least you can see they're not present in the android-17 header [1] and they @@ -96,8 +96,7 @@ pub fn ftruncate64(fd: c_int, size: u64) -> io::Result<()> { Some(f) => cvt_r(|| f(fd, size as i64)).map(|_| ()), None => { if size > i32::max_value() as u64 { - Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot truncate >2GB")) + Err(io::Error::new(io::ErrorKind::InvalidInput, "cannot truncate >2GB")) } else { cvt_r(|| ftruncate(fd, size as i32)).map(|_| ()) } @@ -108,53 +107,61 @@ pub fn ftruncate64(fd: c_int, size: u64) -> io::Result<()> { #[cfg(target_pointer_width = "64")] pub fn ftruncate64(fd: c_int, size: u64) -> io::Result<()> { - unsafe { - cvt_r(|| ftruncate(fd, size as i64)).map(|_| ()) - } + unsafe { cvt_r(|| ftruncate(fd, size as i64)).map(|_| ()) } } #[cfg(target_pointer_width = "32")] -pub unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: size_t, offset: i64) - -> io::Result -{ +pub unsafe fn cvt_pread64( + fd: c_int, + buf: *mut c_void, + count: size_t, + offset: i64, +) -> io::Result { use crate::convert::TryInto; weak!(fn pread64(c_int, *mut c_void, size_t, i64) -> ssize_t); pread64.get().map(|f| cvt(f(fd, buf, count, offset))).unwrap_or_else(|| { if let Ok(o) = offset.try_into() { cvt(pread(fd, buf, count, o)) } else { - Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot pread >2GB")) + Err(io::Error::new(io::ErrorKind::InvalidInput, "cannot pread >2GB")) } }) } #[cfg(target_pointer_width = "32")] -pub unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: size_t, offset: i64) - -> io::Result -{ +pub unsafe fn cvt_pwrite64( + fd: c_int, + buf: *const c_void, + count: size_t, + offset: i64, +) -> io::Result { use crate::convert::TryInto; weak!(fn pwrite64(c_int, *const c_void, size_t, i64) -> ssize_t); pwrite64.get().map(|f| cvt(f(fd, buf, count, offset))).unwrap_or_else(|| { if let Ok(o) = offset.try_into() { cvt(pwrite(fd, buf, count, o)) } else { - Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot pwrite >2GB")) + Err(io::Error::new(io::ErrorKind::InvalidInput, "cannot pwrite >2GB")) } }) } #[cfg(target_pointer_width = "64")] -pub unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: size_t, offset: i64) - -> io::Result -{ +pub unsafe fn cvt_pread64( + fd: c_int, + buf: *mut c_void, + count: size_t, + offset: i64, +) -> io::Result { cvt(pread(fd, buf, count, offset)) } #[cfg(target_pointer_width = "64")] -pub unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: size_t, offset: i64) - -> io::Result -{ +pub unsafe fn cvt_pwrite64( + fd: c_int, + buf: *const c_void, + count: size_t, + offset: i64, +) -> io::Result { cvt(pwrite(fd, buf, count, offset)) } diff --git a/src/libstd/sys/unix/cmath.rs b/src/libstd/sys/unix/cmath.rs index f6bb58934fc05..2916ebe444059 100644 --- a/src/libstd/sys/unix/cmath.rs +++ b/src/libstd/sys/unix/cmath.rs @@ -1,9 +1,9 @@ #![cfg(not(test))] -use libc::{c_float, c_double}; +use libc::{c_double, c_float}; #[link_name = "m"] -extern { +extern "C" { pub fn acos(n: c_double) -> c_double; pub fn acosf(n: c_float) -> c_float; pub fn asin(n: c_double) -> c_double; diff --git a/src/libstd/sys/unix/ext/fs.rs b/src/libstd/sys/unix/ext/fs.rs index 0c52dc5b81b0e..732cd677a1859 100644 --- a/src/libstd/sys/unix/ext/fs.rs +++ b/src/libstd/sys/unix/ext/fs.rs @@ -2,12 +2,12 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fs::{self, Permissions, OpenOptions}; +use crate::fs::{self, OpenOptions, Permissions}; use crate::io; use crate::path::Path; use crate::sys; -use crate::sys_common::{FromInner, AsInner, AsInnerMut}; use crate::sys::platform::fs::MetadataExt as UnixMetadataExt; +use crate::sys_common::{AsInner, AsInnerMut, FromInner}; /// Unix-specific extensions to [`File`]. /// @@ -112,8 +112,7 @@ pub trait FileExt { } } if !buf.is_empty() { - Err(io::Error::new(io::ErrorKind::UnexpectedEof, - "failed to fill whole buffer")) + Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer")) } else { Ok(()) } @@ -195,8 +194,12 @@ pub trait FileExt { fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> { while !buf.is_empty() { match self.write_at(buf, offset) { - Ok(0) => return Err(io::Error::new(io::ErrorKind::WriteZero, - "failed to write whole buffer")), + Ok(0) => { + return Err(io::Error::new( + io::ErrorKind::WriteZero, + "failed to write whole buffer", + )); + } Ok(n) => { buf = &buf[n..]; offset += n as u64 @@ -356,11 +359,13 @@ pub trait OpenOptionsExt { #[stable(feature = "fs_ext", since = "1.1.0")] impl OpenOptionsExt for OpenOptions { fn mode(&mut self, mode: u32) -> &mut OpenOptions { - self.as_inner_mut().mode(mode); self + self.as_inner_mut().mode(mode); + self } fn custom_flags(&mut self, flags: i32) -> &mut OpenOptions { - self.as_inner_mut().custom_flags(flags); self + self.as_inner_mut().custom_flags(flags); + self } } @@ -657,22 +662,54 @@ pub trait MetadataExt { #[stable(feature = "metadata_ext", since = "1.1.0")] impl MetadataExt for fs::Metadata { - fn dev(&self) -> u64 { self.st_dev() } - fn ino(&self) -> u64 { self.st_ino() } - fn mode(&self) -> u32 { self.st_mode() } - fn nlink(&self) -> u64 { self.st_nlink() } - fn uid(&self) -> u32 { self.st_uid() } - fn gid(&self) -> u32 { self.st_gid() } - fn rdev(&self) -> u64 { self.st_rdev() } - fn size(&self) -> u64 { self.st_size() } - fn atime(&self) -> i64 { self.st_atime() } - fn atime_nsec(&self) -> i64 { self.st_atime_nsec() } - fn mtime(&self) -> i64 { self.st_mtime() } - fn mtime_nsec(&self) -> i64 { self.st_mtime_nsec() } - fn ctime(&self) -> i64 { self.st_ctime() } - fn ctime_nsec(&self) -> i64 { self.st_ctime_nsec() } - fn blksize(&self) -> u64 { self.st_blksize() } - fn blocks(&self) -> u64 { self.st_blocks() } + fn dev(&self) -> u64 { + self.st_dev() + } + fn ino(&self) -> u64 { + self.st_ino() + } + fn mode(&self) -> u32 { + self.st_mode() + } + fn nlink(&self) -> u64 { + self.st_nlink() + } + fn uid(&self) -> u32 { + self.st_uid() + } + fn gid(&self) -> u32 { + self.st_gid() + } + fn rdev(&self) -> u64 { + self.st_rdev() + } + fn size(&self) -> u64 { + self.st_size() + } + fn atime(&self) -> i64 { + self.st_atime() + } + fn atime_nsec(&self) -> i64 { + self.st_atime_nsec() + } + fn mtime(&self) -> i64 { + self.st_mtime() + } + fn mtime_nsec(&self) -> i64 { + self.st_mtime_nsec() + } + fn ctime(&self) -> i64 { + self.st_ctime() + } + fn ctime_nsec(&self) -> i64 { + self.st_ctime_nsec() + } + fn blksize(&self) -> u64 { + self.st_blksize() + } + fn blocks(&self) -> u64 { + self.st_blocks() + } } /// Unix-specific extensions for [`FileType`]. @@ -759,10 +796,18 @@ pub trait FileTypeExt { #[stable(feature = "file_type_ext", since = "1.5.0")] impl FileTypeExt for fs::FileType { - fn is_block_device(&self) -> bool { self.as_inner().is(libc::S_IFBLK) } - fn is_char_device(&self) -> bool { self.as_inner().is(libc::S_IFCHR) } - fn is_fifo(&self) -> bool { self.as_inner().is(libc::S_IFIFO) } - fn is_socket(&self) -> bool { self.as_inner().is(libc::S_IFSOCK) } + fn is_block_device(&self) -> bool { + self.as_inner().is(libc::S_IFBLK) + } + fn is_char_device(&self) -> bool { + self.as_inner().is(libc::S_IFCHR) + } + fn is_fifo(&self) -> bool { + self.as_inner().is(libc::S_IFIFO) + } + fn is_socket(&self) -> bool { + self.as_inner().is(libc::S_IFSOCK) + } } /// Unix-specific extension methods for [`fs::DirEntry`]. @@ -794,7 +839,9 @@ pub trait DirEntryExt { #[stable(feature = "dir_entry_ext", since = "1.1.0")] impl DirEntryExt for fs::DirEntry { - fn ino(&self) -> u64 { self.as_inner().ino() } + fn ino(&self) -> u64 { + self.as_inner().ino() + } } /// Creates a new symbolic link on the filesystem. @@ -821,8 +868,7 @@ impl DirEntryExt for fs::DirEntry { /// } /// ``` #[stable(feature = "symlink", since = "1.1.0")] -pub fn symlink, Q: AsRef>(src: P, dst: Q) -> io::Result<()> -{ +pub fn symlink, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink(src.as_ref(), dst.as_ref()) } diff --git a/src/libstd/sys/unix/ext/io.rs b/src/libstd/sys/unix/ext/io.rs index 6bcc59495e363..5077e2e28d18b 100644 --- a/src/libstd/sys/unix/ext/io.rs +++ b/src/libstd/sys/unix/ext/io.rs @@ -3,9 +3,9 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::fs; +use crate::io; use crate::os::raw; use crate::sys; -use crate::io; use crate::sys_common::{AsInner, FromInner, IntoInner}; /// Raw file descriptors. @@ -83,30 +83,42 @@ impl IntoRawFd for fs::File { #[stable(feature = "asraw_stdio", since = "1.21.0")] impl AsRawFd for io::Stdin { - fn as_raw_fd(&self) -> RawFd { libc::STDIN_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDIN_FILENO + } } #[stable(feature = "asraw_stdio", since = "1.21.0")] impl AsRawFd for io::Stdout { - fn as_raw_fd(&self) -> RawFd { libc::STDOUT_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDOUT_FILENO + } } #[stable(feature = "asraw_stdio", since = "1.21.0")] impl AsRawFd for io::Stderr { - fn as_raw_fd(&self) -> RawFd { libc::STDERR_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDERR_FILENO + } } #[stable(feature = "asraw_stdio_locks", since = "1.35.0")] impl<'a> AsRawFd for io::StdinLock<'a> { - fn as_raw_fd(&self) -> RawFd { libc::STDIN_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDIN_FILENO + } } #[stable(feature = "asraw_stdio_locks", since = "1.35.0")] impl<'a> AsRawFd for io::StdoutLock<'a> { - fn as_raw_fd(&self) -> RawFd { libc::STDOUT_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDOUT_FILENO + } } #[stable(feature = "asraw_stdio_locks", since = "1.35.0")] impl<'a> AsRawFd for io::StderrLock<'a> { - fn as_raw_fd(&self) -> RawFd { libc::STDERR_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDERR_FILENO + } } diff --git a/src/libstd/sys/unix/ext/process.rs b/src/libstd/sys/unix/ext/process.rs index 0e95f97486b24..fa8670b4aecac 100644 --- a/src/libstd/sys/unix/ext/process.rs +++ b/src/libstd/sys/unix/ext/process.rs @@ -4,10 +4,10 @@ use crate::ffi::OsStr; use crate::io; -use crate::os::unix::io::{FromRawFd, RawFd, AsRawFd, IntoRawFd}; +use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use crate::process; use crate::sys; -use crate::sys_common::{AsInnerMut, AsInner, FromInner, IntoInner}; +use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; /// Unix-specific extensions to the [`process::Command`] builder. /// @@ -56,7 +56,8 @@ pub trait CommandExt { /// locations may not appear where intended. #[stable(feature = "process_pre_exec", since = "1.34.0")] unsafe fn pre_exec(&mut self, f: F) -> &mut process::Command - where F: FnMut() -> io::Result<()> + Send + Sync + 'static; + where + F: FnMut() -> io::Result<()> + Send + Sync + 'static; /// Schedules a closure to be run just before the `exec` function is /// invoked. @@ -68,7 +69,8 @@ pub trait CommandExt { #[stable(feature = "process_exec", since = "1.15.0")] #[rustc_deprecated(since = "1.37.0", reason = "should be unsafe, use `pre_exec` instead")] fn before_exec(&mut self, f: F) -> &mut process::Command - where F: FnMut() -> io::Result<()> + Send + Sync + 'static + where + F: FnMut() -> io::Result<()> + Send + Sync + 'static, { unsafe { self.pre_exec(f) } } @@ -111,7 +113,8 @@ pub trait CommandExt { /// default executable path. #[unstable(feature = "process_set_argv0", issue = "66510")] fn arg0(&mut self, arg: S) -> &mut process::Command - where S: AsRef; + where + S: AsRef; } #[stable(feature = "rust1", since = "1.0.0")] @@ -127,7 +130,8 @@ impl CommandExt for process::Command { } unsafe fn pre_exec(&mut self, f: F) -> &mut process::Command - where F: FnMut() -> io::Result<()> + Send + Sync + 'static + where + F: FnMut() -> io::Result<()> + Send + Sync + 'static, { self.as_inner_mut().pre_exec(Box::new(f)); self @@ -138,7 +142,8 @@ impl CommandExt for process::Command { } fn arg0(&mut self, arg: S) -> &mut process::Command - where S: AsRef + where + S: AsRef, { self.as_inner_mut().set_arg_0(arg.as_ref()); self diff --git a/src/libstd/sys/unix/ext/raw.rs b/src/libstd/sys/unix/ext/raw.rs index 75ae54a919ab3..d81368a18b452 100644 --- a/src/libstd/sys/unix/ext/raw.rs +++ b/src/libstd/sys/unix/ext/raw.rs @@ -1,23 +1,28 @@ //! Unix-specific primitives available on all unix platforms #![stable(feature = "raw_ext", since = "1.1.0")] -#![rustc_deprecated(since = "1.8.0", - reason = "these type aliases are no longer supported by \ - the standard library, the `libc` crate on \ - crates.io should be used instead for the correct \ - definitions")] +#![rustc_deprecated( + since = "1.8.0", + reason = "these type aliases are no longer supported by \ + the standard library, the `libc` crate on \ + crates.io should be used instead for the correct \ + definitions" +)] #![allow(deprecated)] -#[stable(feature = "raw_ext", since = "1.1.0")] pub type uid_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type gid_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type pid_t = i32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type uid_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type gid_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type pid_t = i32; #[doc(inline)] #[stable(feature = "pthread_t", since = "1.8.0")] pub use crate::sys::platform::raw::pthread_t; #[doc(inline)] #[stable(feature = "raw_ext", since = "1.1.0")] -pub use crate::sys::platform::raw::{dev_t, ino_t, mode_t, nlink_t, off_t, blksize_t}; +pub use crate::sys::platform::raw::{blkcnt_t, time_t}; #[doc(inline)] #[stable(feature = "raw_ext", since = "1.1.0")] -pub use crate::sys::platform::raw::{blkcnt_t, time_t}; +pub use crate::sys::platform::raw::{blksize_t, dev_t, ino_t, mode_t, nlink_t, off_t}; diff --git a/src/libstd/sys/unix/fast_thread_local.rs b/src/libstd/sys/unix/fast_thread_local.rs index 7d718032ef6e9..dfb9307daea9f 100644 --- a/src/libstd/sys/unix/fast_thread_local.rs +++ b/src/libstd/sys/unix/fast_thread_local.rs @@ -10,25 +10,34 @@ // fallback implementation to use as well. // // Due to rust-lang/rust#18804, make sure this is not generic! -#[cfg(any(target_os = "linux", target_os = "fuchsia", target_os = "redox", - target_os = "emscripten"))] -pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { +#[cfg(any( + target_os = "linux", + target_os = "fuchsia", + target_os = "redox", + target_os = "emscripten" +))] +pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { use crate::mem; use crate::sys_common::thread_local::register_dtor_fallback; - extern { + extern "C" { #[linkage = "extern_weak"] static __dso_handle: *mut u8; #[linkage = "extern_weak"] static __cxa_thread_atexit_impl: *const libc::c_void; } if !__cxa_thread_atexit_impl.is_null() { - type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8), - arg: *mut u8, - dso_handle: *mut u8) -> libc::c_int; - mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl) - (dtor, t, &__dso_handle as *const _ as *mut _); - return + type F = unsafe extern "C" fn( + dtor: unsafe extern "C" fn(*mut u8), + arg: *mut u8, + dso_handle: *mut u8, + ) -> libc::c_int; + mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl)( + dtor, + t, + &__dso_handle as *const _ as *mut _, + ); + return; } register_dtor_fallback(t, dtor); } @@ -44,7 +53,7 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { // thread. thread_local dtors are pushed to the DTOR list without calling // _tlv_atexit. #[cfg(target_os = "macos")] -pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { +pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { use crate::cell::Cell; use crate::ptr; @@ -55,7 +64,7 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { REGISTERED.set(true); } - type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; + type List = Vec<(*mut u8, unsafe extern "C" fn(*mut u8))>; #[thread_local] static DTORS: Cell<*mut List> = Cell::new(ptr::null_mut()); @@ -64,15 +73,14 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { DTORS.set(Box::into_raw(v)); } - extern { - fn _tlv_atexit(dtor: unsafe extern fn(*mut u8), - arg: *mut u8); + extern "C" { + fn _tlv_atexit(dtor: unsafe extern "C" fn(*mut u8), arg: *mut u8); } let list: &mut List = &mut *DTORS.get(); list.push((t, dtor)); - unsafe extern fn run_dtors(_: *mut u8) { + unsafe extern "C" fn run_dtors(_: *mut u8) { let mut ptr = DTORS.replace(ptr::null_mut()); while !ptr.is_null() { let list = Box::from_raw(ptr); diff --git a/src/libstd/sys/unix/fd.rs b/src/libstd/sys/unix/fd.rs index ba611a6b7e7b9..53b50763fbf2e 100644 --- a/src/libstd/sys/unix/fd.rs +++ b/src/libstd/sys/unix/fd.rs @@ -1,7 +1,7 @@ #![unstable(reason = "not public", issue = "0", feature = "fd")] use crate::cmp; -use crate::io::{self, Read, Initializer, IoSlice, IoSliceMut}; +use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read}; use crate::mem; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sys::cvt; @@ -35,7 +35,9 @@ impl FileDesc { FileDesc { fd } } - pub fn raw(&self) -> c_int { self.fd } + pub fn raw(&self) -> c_int { + self.fd + } /// Extracts the actual file descriptor without closing it. pub fn into_raw(self) -> c_int { @@ -46,18 +48,18 @@ impl FileDesc { pub fn read(&self, buf: &mut [u8]) -> io::Result { let ret = cvt(unsafe { - libc::read(self.fd, - buf.as_mut_ptr() as *mut c_void, - cmp::min(buf.len(), max_len())) + libc::read(self.fd, buf.as_mut_ptr() as *mut c_void, cmp::min(buf.len(), max_len())) })?; Ok(ret as usize) } pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { let ret = cvt(unsafe { - libc::readv(self.fd, - bufs.as_ptr() as *const libc::iovec, - cmp::min(bufs.len(), c_int::max_value() as usize) as c_int) + libc::readv( + self.fd, + bufs.as_ptr() as *const libc::iovec, + cmp::min(bufs.len(), c_int::max_value() as usize) as c_int, + ) })?; Ok(ret as usize) } @@ -72,39 +74,44 @@ impl FileDesc { use super::android::cvt_pread64; #[cfg(not(target_os = "android"))] - unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64) - -> io::Result - { - #[cfg(target_os = "linux")] - use libc::pread64; + unsafe fn cvt_pread64( + fd: c_int, + buf: *mut c_void, + count: usize, + offset: i64, + ) -> io::Result { #[cfg(not(target_os = "linux"))] use libc::pread as pread64; + #[cfg(target_os = "linux")] + use libc::pread64; cvt(pread64(fd, buf, count, offset)) } unsafe { - cvt_pread64(self.fd, - buf.as_mut_ptr() as *mut c_void, - cmp::min(buf.len(), max_len()), - offset as i64) - .map(|n| n as usize) + cvt_pread64( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + offset as i64, + ) + .map(|n| n as usize) } } pub fn write(&self, buf: &[u8]) -> io::Result { let ret = cvt(unsafe { - libc::write(self.fd, - buf.as_ptr() as *const c_void, - cmp::min(buf.len(), max_len())) + libc::write(self.fd, buf.as_ptr() as *const c_void, cmp::min(buf.len(), max_len())) })?; Ok(ret as usize) } pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result { let ret = cvt(unsafe { - libc::writev(self.fd, - bufs.as_ptr() as *const libc::iovec, - cmp::min(bufs.len(), c_int::max_value() as usize) as c_int) + libc::writev( + self.fd, + bufs.as_ptr() as *const libc::iovec, + cmp::min(bufs.len(), c_int::max_value() as usize) as c_int, + ) })?; Ok(ret as usize) } @@ -114,54 +121,61 @@ impl FileDesc { use super::android::cvt_pwrite64; #[cfg(not(target_os = "android"))] - unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64) - -> io::Result - { - #[cfg(target_os = "linux")] - use libc::pwrite64; + unsafe fn cvt_pwrite64( + fd: c_int, + buf: *const c_void, + count: usize, + offset: i64, + ) -> io::Result { #[cfg(not(target_os = "linux"))] use libc::pwrite as pwrite64; + #[cfg(target_os = "linux")] + use libc::pwrite64; cvt(pwrite64(fd, buf, count, offset)) } unsafe { - cvt_pwrite64(self.fd, - buf.as_ptr() as *const c_void, - cmp::min(buf.len(), max_len()), - offset as i64) - .map(|n| n as usize) + cvt_pwrite64( + self.fd, + buf.as_ptr() as *const c_void, + cmp::min(buf.len(), max_len()), + offset as i64, + ) + .map(|n| n as usize) } } #[cfg(target_os = "linux")] pub fn get_cloexec(&self) -> io::Result { - unsafe { - Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0) - } + unsafe { Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0) } } - #[cfg(not(any(target_env = "newlib", - target_os = "solaris", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "l4re", - target_os = "linux", - target_os = "haiku", - target_os = "redox")))] + #[cfg(not(any( + target_env = "newlib", + target_os = "solaris", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "l4re", + target_os = "linux", + target_os = "haiku", + target_os = "redox" + )))] pub fn set_cloexec(&self) -> io::Result<()> { unsafe { cvt(libc::ioctl(self.fd, libc::FIOCLEX))?; Ok(()) } } - #[cfg(any(target_env = "newlib", - target_os = "solaris", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "l4re", - target_os = "linux", - target_os = "haiku", - target_os = "redox"))] + #[cfg(any( + target_env = "newlib", + target_os = "solaris", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "l4re", + target_os = "linux", + target_os = "haiku", + target_os = "redox" + ))] pub fn set_cloexec(&self) -> io::Result<()> { unsafe { let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?; @@ -216,7 +230,7 @@ impl FileDesc { // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963 #[cfg(any(target_os = "android", target_os = "haiku"))] use libc::F_DUPFD as F_DUPFD_CLOEXEC; - #[cfg(not(any(target_os = "android", target_os="haiku")))] + #[cfg(not(any(target_os = "android", target_os = "haiku")))] use libc::F_DUPFD_CLOEXEC; let make_filedesc = |fd| { @@ -224,8 +238,7 @@ impl FileDesc { fd.set_cloexec()?; Ok(fd) }; - static TRY_CLOEXEC: AtomicBool = - AtomicBool::new(!cfg!(target_os = "android")); + static TRY_CLOEXEC: AtomicBool = AtomicBool::new(!cfg!(target_os = "android")); let fd = self.raw(); if TRY_CLOEXEC.load(Ordering::Relaxed) { match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) { @@ -237,7 +250,7 @@ impl FileDesc { make_filedesc(fd)? } else { FileDesc::new(fd) - }) + }); } Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => { TRY_CLOEXEC.store(false, Ordering::Relaxed); @@ -261,7 +274,9 @@ impl<'a> Read for &'a FileDesc { } impl AsInner for FileDesc { - fn as_inner(&self) -> &c_int { &self.fd } + fn as_inner(&self) -> &c_int { + &self.fd + } } impl Drop for FileDesc { diff --git a/src/libstd/sys/unix/io.rs b/src/libstd/sys/unix/io.rs index a3a7291917697..b4a64e93c842b 100644 --- a/src/libstd/sys/unix/io.rs +++ b/src/libstd/sys/unix/io.rs @@ -1,7 +1,7 @@ use crate::marker::PhantomData; use crate::slice; -use libc::{iovec, c_void}; +use libc::{c_void, iovec}; #[repr(transparent)] pub struct IoSlice<'a> { @@ -13,10 +13,7 @@ impl<'a> IoSlice<'a> { #[inline] pub fn new(buf: &'a [u8]) -> IoSlice<'a> { IoSlice { - vec: iovec { - iov_base: buf.as_ptr() as *mut u8 as *mut c_void, - iov_len: buf.len() - }, + vec: iovec { iov_base: buf.as_ptr() as *mut u8 as *mut c_void, iov_len: buf.len() }, _p: PhantomData, } } @@ -35,9 +32,7 @@ impl<'a> IoSlice<'a> { #[inline] pub fn as_slice(&self) -> &[u8] { - unsafe { - slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) - } + unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) } } } @@ -51,10 +46,7 @@ impl<'a> IoSliceMut<'a> { #[inline] pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> { IoSliceMut { - vec: iovec { - iov_base: buf.as_mut_ptr() as *mut c_void, - iov_len: buf.len() - }, + vec: iovec { iov_base: buf.as_mut_ptr() as *mut c_void, iov_len: buf.len() }, _p: PhantomData, } } @@ -73,15 +65,11 @@ impl<'a> IoSliceMut<'a> { #[inline] pub fn as_slice(&self) -> &[u8] { - unsafe { - slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) - } + unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) } } #[inline] pub fn as_mut_slice(&mut self) -> &mut [u8] { - unsafe { - slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len) - } + unsafe { slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len) } } } diff --git a/src/libstd/sys/unix/l4re.rs b/src/libstd/sys/unix/l4re.rs index 2c6f21aa21a3a..c6e4f5693ed5a 100644 --- a/src/libstd/sys/unix/l4re.rs +++ b/src/libstd/sys/unix/l4re.rs @@ -1,16 +1,18 @@ macro_rules! unimpl { - () => (return Err(io::Error::new(io::ErrorKind::Other, "No networking available on L4Re."));) + () => { + return Err(io::Error::new(io::ErrorKind::Other, "No networking available on L4Re.")); + }; } pub mod net { #![allow(warnings)] + use crate::convert::TryFrom; use crate::fmt; use crate::io::{self, IoSlice, IoSliceMut}; - use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr}; - use crate::sys_common::{AsInner, FromInner, IntoInner}; + use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; use crate::sys::fd::FileDesc; + use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; - use crate::convert::TryFrom; #[allow(unused_extern_crates)] pub extern crate libc as netc; @@ -33,8 +35,11 @@ pub mod net { unimpl!(); } - pub fn accept(&self, _: *mut libc::sockaddr, _: *mut libc::socklen_t) - -> io::Result { + pub fn accept( + &self, + _: *mut libc::sockaddr, + _: *mut libc::socklen_t, + ) -> io::Result { unimpl!(); } @@ -100,15 +105,21 @@ pub mod net { } impl AsInner for Socket { - fn as_inner(&self) -> &libc::c_int { self.0.as_inner() } + fn as_inner(&self) -> &libc::c_int { + self.0.as_inner() + } } impl FromInner for Socket { - fn from_inner(fd: libc::c_int) -> Socket { Socket(FileDesc::new(fd)) } + fn from_inner(fd: libc::c_int) -> Socket { + Socket(FileDesc::new(fd)) + } } impl IntoInner for Socket { - fn into_inner(self) -> libc::c_int { self.0.into_raw() } + fn into_inner(self) -> libc::c_int { + self.0.into_raw() + } } pub struct TcpStream { @@ -124,9 +135,13 @@ pub mod net { unimpl!(); } - pub fn socket(&self) -> &Socket { &self.inner } + pub fn socket(&self) -> &Socket { + &self.inner + } - pub fn into_socket(self) -> Socket { self.inner } + pub fn into_socket(self) -> Socket { + self.inner + } pub fn set_read_timeout(&self, _: Option) -> io::Result<()> { unimpl!(); @@ -226,9 +241,13 @@ pub mod net { unimpl!(); } - pub fn socket(&self) -> &Socket { &self.inner } + pub fn socket(&self) -> &Socket { + &self.inner + } - pub fn into_socket(self) -> Socket { self.inner } + pub fn into_socket(self) -> Socket { + self.inner + } pub fn socket_addr(&self) -> io::Result { unimpl!(); @@ -288,9 +307,13 @@ pub mod net { unimpl!(); } - pub fn socket(&self) -> &Socket { &self.inner } + pub fn socket(&self) -> &Socket { + &self.inner + } - pub fn into_socket(self) -> Socket { self.inner } + pub fn into_socket(self) -> Socket { + self.inner + } pub fn peer_addr(&self) -> io::Result { unimpl!(); @@ -364,24 +387,20 @@ pub mod net { unimpl!(); } - pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) - -> io::Result<()> { - unimpl!(); + pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { + unimpl!(); } - pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) - -> io::Result<()> { - unimpl!(); + pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { + unimpl!(); } - pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) - -> io::Result<()> { - unimpl!(); + pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { + unimpl!(); } - pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) - -> io::Result<()> { - unimpl!(); + pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { + unimpl!(); } pub fn set_ttl(&self, _: u32) -> io::Result<()> { @@ -450,7 +469,6 @@ pub mod net { unsafe impl Sync for LookupHost {} unsafe impl Send for LookupHost {} - impl TryFrom<&str> for LookupHost { type Error = io::Error; diff --git a/src/libstd/sys/unix/memchr.rs b/src/libstd/sys/unix/memchr.rs index 1984678bdde4e..a9273ea676cb3 100644 --- a/src/libstd/sys/unix/memchr.rs +++ b/src/libstd/sys/unix/memchr.rs @@ -6,32 +6,27 @@ pub fn memchr(needle: u8, haystack: &[u8]) -> Option { libc::memchr( haystack.as_ptr() as *const libc::c_void, needle as libc::c_int, - haystack.len()) + haystack.len(), + ) }; - if p.is_null() { - None - } else { - Some(p as usize - (haystack.as_ptr() as usize)) - } + if p.is_null() { None } else { Some(p as usize - (haystack.as_ptr() as usize)) } } pub fn memrchr(needle: u8, haystack: &[u8]) -> Option { - #[cfg(target_os = "linux")] fn memrchr_specific(needle: u8, haystack: &[u8]) -> Option { // GNU's memrchr() will - unlike memchr() - error if haystack is empty. - if haystack.is_empty() {return None} + if haystack.is_empty() { + return None; + } let p = unsafe { libc::memrchr( haystack.as_ptr() as *const libc::c_void, needle as libc::c_int, - haystack.len()) + haystack.len(), + ) }; - if p.is_null() { - None - } else { - Some(p as usize - (haystack.as_ptr() as usize)) - } + if p.is_null() { None } else { Some(p as usize - (haystack.as_ptr() as usize)) } } #[cfg(not(target_os = "linux"))] diff --git a/src/libstd/sys/unix/net.rs b/src/libstd/sys/unix/net.rs index 75750b5c4e588..946b2b9d8decf 100644 --- a/src/libstd/sys/unix/net.rs +++ b/src/libstd/sys/unix/net.rs @@ -1,13 +1,13 @@ +use crate::cmp; use crate::ffi::CStr; use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; -use crate::net::{SocketAddr, Shutdown}; +use crate::net::{Shutdown, SocketAddr}; use crate::str; use crate::sys::fd::FileDesc; -use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr}; +use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::{Duration, Instant}; -use crate::cmp; use libc::{c_int, c_void, size_t, sockaddr, socklen_t, EAI_SYSTEM, MSG_PEEK}; @@ -42,23 +42,23 @@ pub fn init() {} pub fn cvt_gai(err: c_int) -> io::Result<()> { if err == 0 { - return Ok(()) + return Ok(()); } // We may need to trigger a glibc workaround. See on_resolver_failure() for details. on_resolver_failure(); if err == EAI_SYSTEM { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } let detail = unsafe { - str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap() - .to_owned() + str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap().to_owned() }; - Err(io::Error::new(io::ErrorKind::Other, - &format!("failed to lookup address information: {}", - detail)[..])) + Err(io::Error::new( + io::ErrorKind::Other, + &format!("failed to lookup address information: {}", detail)[..], + )) } impl Socket { @@ -106,7 +106,7 @@ impl Socket { Ok(_) => { return Ok((Socket(FileDesc::new(fds[0])), Socket(FileDesc::new(fds[1])))); } - Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}, + Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} Err(e) => return Err(e), } } @@ -135,15 +135,13 @@ impl Socket { Err(e) => return Err(e), } - let mut pollfd = libc::pollfd { - fd: self.0.raw(), - events: libc::POLLOUT, - revents: 0, - }; + let mut pollfd = libc::pollfd { fd: self.0.raw(), events: libc::POLLOUT, revents: 0 }; if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); } let start = Instant::now(); @@ -155,7 +153,8 @@ impl Socket { } let timeout = timeout - elapsed; - let mut timeout = timeout.as_secs() + let mut timeout = timeout + .as_secs() .saturating_mul(1_000) .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000); if timeout == 0 { @@ -176,10 +175,9 @@ impl Socket { // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look // for POLLHUP rather than read readiness if pollfd.revents & libc::POLLHUP != 0 { - let e = self.take_error()? - .unwrap_or_else(|| { - io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP") - }); + let e = self.take_error()?.unwrap_or_else(|| { + io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP") + }); return Err(e); } @@ -189,8 +187,7 @@ impl Socket { } } - pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) - -> io::Result { + pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result { // Unfortunately the only known way right now to accept a socket and // atomically set the CLOEXEC flag is to use the `accept4` syscall on // Linux. This was added in 2.6.28, however, and because we support @@ -204,9 +201,7 @@ impl Socket { flags: c_int ) -> c_int } - let res = cvt_r(|| unsafe { - accept4(self.0.raw(), storage, len, SOCK_CLOEXEC) - }); + let res = cvt_r(|| unsafe { accept4(self.0.raw(), storage, len, SOCK_CLOEXEC) }); match res { Ok(fd) => return Ok(Socket(FileDesc::new(fd))), Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {} @@ -214,9 +209,7 @@ impl Socket { } } - let fd = cvt_r(|| unsafe { - libc::accept(self.0.raw(), storage, len) - })?; + let fd = cvt_r(|| unsafe { libc::accept(self.0.raw(), storage, len) })?; let fd = FileDesc::new(fd); fd.set_cloexec()?; Ok(Socket(fd)) @@ -228,10 +221,7 @@ impl Socket { fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result { let ret = cvt(unsafe { - libc::recv(self.0.raw(), - buf.as_mut_ptr() as *mut c_void, - buf.len(), - flags) + libc::recv(self.0.raw(), buf.as_mut_ptr() as *mut c_void, buf.len(), flags) })?; Ok(ret as usize) } @@ -248,18 +238,23 @@ impl Socket { self.0.read_vectored(bufs) } - fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int) - -> io::Result<(usize, SocketAddr)> { + fn recv_from_with_flags( + &self, + buf: &mut [u8], + flags: c_int, + ) -> io::Result<(usize, SocketAddr)> { let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t; let n = cvt(unsafe { - libc::recvfrom(self.0.raw(), - buf.as_mut_ptr() as *mut c_void, - buf.len(), - flags, - &mut storage as *mut _ as *mut _, - &mut addrlen) + libc::recvfrom( + self.0.raw(), + buf.as_mut_ptr() as *mut c_void, + buf.len(), + flags, + &mut storage as *mut _ as *mut _, + &mut addrlen, + ) })?; Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?)) } @@ -284,8 +279,10 @@ impl Socket { let timeout = match dur { Some(dur) => { if dur.as_secs() == 0 && dur.subsec_nanos() == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); } let secs = if dur.as_secs() > libc::time_t::max_value() as u64 { @@ -302,12 +299,7 @@ impl Socket { } timeout } - None => { - libc::timeval { - tv_sec: 0, - tv_usec: 0, - } - } + None => libc::timeval { tv_sec: 0, tv_usec: 0 }, }; setsockopt(self, libc::SOL_SOCKET, kind, timeout) } @@ -349,24 +341,26 @@ impl Socket { pub fn take_error(&self) -> io::Result> { let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?; - if raw == 0 { - Ok(None) - } else { - Ok(Some(io::Error::from_raw_os_error(raw as i32))) - } + if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) } } } impl AsInner for Socket { - fn as_inner(&self) -> &c_int { self.0.as_inner() } + fn as_inner(&self) -> &c_int { + self.0.as_inner() + } } impl FromInner for Socket { - fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) } + fn from_inner(fd: c_int) -> Socket { + Socket(FileDesc::new(fd)) + } } impl IntoInner for Socket { - fn into_inner(self) -> c_int { self.0.into_raw() } + fn into_inner(self) -> c_int { + self.0.into_raw() + } } // In versions of glibc prior to 2.26, there's a bug where the DNS resolver diff --git a/src/libstd/sys/unix/path.rs b/src/libstd/sys/unix/path.rs index 7a18395610785..840a7ae042625 100644 --- a/src/libstd/sys/unix/path.rs +++ b/src/libstd/sys/unix/path.rs @@ -1,5 +1,5 @@ -use crate::path::Prefix; use crate::ffi::OsStr; +use crate::path::Prefix; #[inline] pub fn is_sep_byte(b: u8) -> bool { diff --git a/src/libstd/sys/unix/pipe.rs b/src/libstd/sys/unix/pipe.rs index 029f4216b7e57..77fefef8a1802 100644 --- a/src/libstd/sys/unix/pipe.rs +++ b/src/libstd/sys/unix/pipe.rs @@ -22,15 +22,15 @@ pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { // CLOEXEC flag is to use the `pipe2` syscall on Linux. This was added in // 2.6.27, however, and because we support 2.6.18 we must detect this // support dynamically. - if cfg!(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", - target_os = "redox")) && - !INVALID.load(Ordering::SeqCst) + if cfg!(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd", + target_os = "redox" + )) && !INVALID.load(Ordering::SeqCst) { - // Note that despite calling a glibc function here we may still // get ENOSYS. Glibc has `pipe2` since 2.9 and doesn't try to // emulate on older kernels, so if you happen to be running on @@ -38,8 +38,7 @@ pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { // see the syscall. match cvt(unsafe { pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }) { Ok(_) => { - return Ok((AnonPipe(FileDesc::new(fds[0])), - AnonPipe(FileDesc::new(fds[1])))); + return Ok((AnonPipe(FileDesc::new(fds[0])), AnonPipe(FileDesc::new(fds[1])))); } Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => { INVALID.store(true, Ordering::SeqCst); @@ -73,15 +72,15 @@ impl AnonPipe { self.0.write_vectored(bufs) } - pub fn fd(&self) -> &FileDesc { &self.0 } - pub fn into_fd(self) -> FileDesc { self.0 } + pub fn fd(&self) -> &FileDesc { + &self.0 + } + pub fn into_fd(self) -> FileDesc { + self.0 + } } -pub fn read2(p1: AnonPipe, - v1: &mut Vec, - p2: AnonPipe, - v2: &mut Vec) -> io::Result<()> { - +pub fn read2(p1: AnonPipe, v1: &mut Vec, p2: AnonPipe, v2: &mut Vec) -> io::Result<()> { // Set both pipes into nonblocking mode as we're gonna be reading from both // in the `select` loop below, and we wouldn't want one to block the other! let p1 = p1.into_fd(); @@ -117,8 +116,9 @@ pub fn read2(p1: AnonPipe, match fd.read_to_end(dst) { Ok(_) => Ok(true), Err(e) => { - if e.raw_os_error() == Some(libc::EWOULDBLOCK) || - e.raw_os_error() == Some(libc::EAGAIN) { + if e.raw_os_error() == Some(libc::EWOULDBLOCK) + || e.raw_os_error() == Some(libc::EAGAIN) + { Ok(false) } else { Err(e) diff --git a/src/libstd/sys/unix/process/process_common.rs b/src/libstd/sys/unix/process/process_common.rs index 0e6f96bb22892..c9109b0c9d4d7 100644 --- a/src/libstd/sys/unix/process/process_common.rs +++ b/src/libstd/sys/unix/process/process_common.rs @@ -1,6 +1,7 @@ use crate::os::unix::prelude::*; -use crate::ffi::{OsString, OsStr, CString, CStr}; +use crate::collections::BTreeMap; +use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; use crate::io; use crate::ptr; @@ -8,12 +9,11 @@ use crate::sys::fd::FileDesc; use crate::sys::fs::File; use crate::sys::pipe::{self, AnonPipe}; use crate::sys_common::process::CommandEnv; -use crate::collections::BTreeMap; #[cfg(not(target_os = "fuchsia"))] use crate::sys::fs::OpenOptions; -use libc::{c_int, gid_t, uid_t, c_char, EXIT_SUCCESS, EXIT_FAILURE}; +use libc::{c_char, c_int, gid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS}; cfg_if::cfg_if! { if #[cfg(target_os = "fuchsia")] { @@ -204,10 +204,7 @@ impl Command { &mut self.closures } - pub unsafe fn pre_exec( - &mut self, - f: Box io::Result<()> + Send + Sync>, - ) { + pub unsafe fn pre_exec(&mut self, f: Box io::Result<()> + Send + Sync>) { self.closures.push(f); } @@ -236,26 +233,21 @@ impl Command { self.env.have_changed_path() } - pub fn setup_io(&self, default: Stdio, needs_stdin: bool) - -> io::Result<(StdioPipes, ChildPipes)> { + pub fn setup_io( + &self, + default: Stdio, + needs_stdin: bool, + ) -> io::Result<(StdioPipes, ChildPipes)> { let null = Stdio::Null; - let default_stdin = if needs_stdin {&default} else {&null}; + let default_stdin = if needs_stdin { &default } else { &null }; let stdin = self.stdin.as_ref().unwrap_or(default_stdin); let stdout = self.stdout.as_ref().unwrap_or(&default); let stderr = self.stderr.as_ref().unwrap_or(&default); let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?; let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?; let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?; - let ours = StdioPipes { - stdin: our_stdin, - stdout: our_stdout, - stderr: our_stderr, - }; - let theirs = ChildPipes { - stdin: their_stdin, - stdout: their_stdout, - stderr: their_stderr, - }; + let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr }; + let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr }; Ok((ours, theirs)) } } @@ -270,21 +262,21 @@ fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString { // Helper type to manage ownership of the strings within a C-style array. pub struct CStringArray { items: Vec, - ptrs: Vec<*const c_char> + ptrs: Vec<*const c_char>, } impl CStringArray { pub fn with_capacity(capacity: usize) -> Self { let mut result = CStringArray { items: Vec::with_capacity(capacity), - ptrs: Vec::with_capacity(capacity+1) + ptrs: Vec::with_capacity(capacity + 1), }; result.ptrs.push(ptr::null()); result } pub fn push(&mut self, item: CString) { let l = self.ptrs.len(); - self.ptrs[l-1] = item.as_ptr(); + self.ptrs[l - 1] = item.as_ptr(); self.ptrs.push(ptr::null()); self.items.push(item); } @@ -315,12 +307,9 @@ fn construct_envp(env: BTreeMap, saw_nul: &mut bool) -> CStr } impl Stdio { - pub fn to_child_stdio(&self, readable: bool) - -> io::Result<(ChildStdio, Option)> { + pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option)> { match *self { - Stdio::Inherit => { - Ok((ChildStdio::Inherit, None)) - }, + Stdio::Inherit => Ok((ChildStdio::Inherit, None)), // Make sure that the source descriptors are not an stdio // descriptor, otherwise the order which we set the child's @@ -339,11 +328,7 @@ impl Stdio { Stdio::MakePipe => { let (reader, writer) = pipe::anon_pipe()?; - let (ours, theirs) = if readable { - (writer, reader) - } else { - (reader, writer) - }; + let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) }; Ok((ChildStdio::Owned(theirs.into_fd()), Some(ours))) } @@ -352,17 +337,13 @@ impl Stdio { let mut opts = OpenOptions::new(); opts.read(readable); opts.write(!readable); - let path = unsafe { - CStr::from_ptr(DEV_NULL.as_ptr() as *const _) - }; + let path = unsafe { CStr::from_ptr(DEV_NULL.as_ptr() as *const _) }; let fd = File::open_c(&path, &opts)?; Ok((ChildStdio::Owned(fd.into_fd()), None)) } #[cfg(target_os = "fuchsia")] - Stdio::Null => { - Ok((ChildStdio::Null, None)) - } + Stdio::Null => Ok((ChildStdio::Null, None)), } } } @@ -430,7 +411,7 @@ mod tests { Ok(t) => t, Err(e) => panic!("received error for `{}`: {}", stringify!($e), e), } - } + }; } // See #14232 for more information, but it appears that signal delivery to a @@ -461,8 +442,7 @@ mod tests { let stdin_write = pipes.stdin.take().unwrap(); let stdout_read = pipes.stdout.take().unwrap(); - t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, old_set.as_ptr(), - ptr::null_mut()))); + t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, old_set.as_ptr(), ptr::null_mut()))); t!(cvt(libc::kill(cat.id() as libc::pid_t, libc::SIGINT))); // We need to wait until SIGINT is definitely delivered. The diff --git a/src/libstd/sys/unix/process/process_fuchsia.rs b/src/libstd/sys/unix/process/process_fuchsia.rs index 486c12f9bf88a..f0bd1cdfed52f 100644 --- a/src/libstd/sys/unix/process/process_fuchsia.rs +++ b/src/libstd/sys/unix/process/process_fuchsia.rs @@ -1,11 +1,11 @@ use crate::convert::TryInto; -use crate::io; use crate::fmt; +use crate::io; use crate::mem; use crate::ptr; -use crate::sys::process::zircon::{Handle, zx_handle_t}; use crate::sys::process::process_common::*; +use crate::sys::process::zircon::{zx_handle_t, Handle}; use libc::{c_int, size_t}; @@ -14,13 +14,18 @@ use libc::{c_int, size_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)> { let envp = self.capture_env(); if self.saw_nul() { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "nul byte found in provided data")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "nul byte found in provided data", + )); } let (ours, theirs) = self.setup_io(default, needs_stdin)?; @@ -32,21 +37,23 @@ impl Command { pub fn exec(&mut self, default: Stdio) -> io::Error { if self.saw_nul() { - return io::Error::new(io::ErrorKind::InvalidInput, - "nul byte found in provided data") + return io::Error::new(io::ErrorKind::InvalidInput, "nul byte found in provided data"); } match self.setup_io(default, true) { Ok((_, _)) => { // FIXME: This is tough because we don't support the exec syscalls unimplemented!(); - }, + } Err(e) => e, } } - unsafe fn do_exec(&mut self, stdio: ChildPipes, maybe_envp: Option<&CStringArray>) - -> io::Result { + unsafe fn do_exec( + &mut self, + stdio: ChildPipes, + maybe_envp: Option<&CStringArray>, + ) -> io::Result { use crate::sys::process::zircon::*; let envp = match maybe_envp { @@ -108,10 +115,15 @@ impl Command { let mut process_handle: zx_handle_t = 0; zx_cvt(fdio_spawn_etc( ZX_HANDLE_INVALID, - FDIO_SPAWN_CLONE_JOB | FDIO_SPAWN_CLONE_LDSVC | FDIO_SPAWN_CLONE_NAMESPACE - | FDIO_SPAWN_CLONE_ENVIRON, // this is ignored when envp is non-null - self.get_program().as_ptr(), self.get_argv().as_ptr(), envp, - actions.len() as size_t, actions.as_ptr(), + FDIO_SPAWN_CLONE_JOB + | FDIO_SPAWN_CLONE_LDSVC + | FDIO_SPAWN_CLONE_NAMESPACE + | FDIO_SPAWN_CLONE_ENVIRON, // this is ignored when envp is non-null + self.get_program().as_ptr(), + self.get_argv().as_ptr(), + envp, + actions.len() as size_t, + actions.as_ptr(), &mut process_handle, ptr::null_mut(), ))?; @@ -137,7 +149,9 @@ impl Process { pub fn kill(&mut self) -> io::Result<()> { use crate::sys::process::zircon::*; - unsafe { zx_cvt(zx_task_kill(self.handle.raw()))?; } + unsafe { + zx_cvt(zx_task_kill(self.handle.raw()))?; + } Ok(()) } @@ -151,16 +165,26 @@ impl Process { let mut avail: size_t = 0; unsafe { - zx_cvt(zx_object_wait_one(self.handle.raw(), ZX_TASK_TERMINATED, - ZX_TIME_INFINITE, ptr::null_mut()))?; - zx_cvt(zx_object_get_info(self.handle.raw(), ZX_INFO_PROCESS, - &mut proc_info as *mut _ as *mut libc::c_void, - mem::size_of::(), &mut actual, - &mut avail))?; + zx_cvt(zx_object_wait_one( + self.handle.raw(), + ZX_TASK_TERMINATED, + ZX_TIME_INFINITE, + ptr::null_mut(), + ))?; + zx_cvt(zx_object_get_info( + self.handle.raw(), + ZX_INFO_PROCESS, + &mut proc_info as *mut _ as *mut libc::c_void, + mem::size_of::(), + &mut actual, + &mut avail, + ))?; } if actual != 1 { - return Err(io::Error::new(io::ErrorKind::InvalidData, - "Failed to get exit status of process")); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Failed to get exit status of process", + )); } Ok(ExitStatus(proc_info.return_code)) } @@ -174,23 +198,31 @@ impl Process { let mut avail: size_t = 0; unsafe { - let status = zx_object_wait_one(self.handle.raw(), ZX_TASK_TERMINATED, - 0, ptr::null_mut()); + let status = + zx_object_wait_one(self.handle.raw(), ZX_TASK_TERMINATED, 0, ptr::null_mut()); match status { - 0 => { }, // Success + 0 => {} // Success x if x == ERR_TIMED_OUT => { return Ok(None); - }, - _ => { panic!("Failed to wait on process handle: {}", status); }, + } + _ => { + panic!("Failed to wait on process handle: {}", status); + } } - zx_cvt(zx_object_get_info(self.handle.raw(), ZX_INFO_PROCESS, - &mut proc_info as *mut _ as *mut libc::c_void, - mem::size_of::(), &mut actual, - &mut avail))?; + zx_cvt(zx_object_get_info( + self.handle.raw(), + ZX_INFO_PROCESS, + &mut proc_info as *mut _ as *mut libc::c_void, + mem::size_of::(), + &mut actual, + &mut avail, + ))?; } if actual != 1 { - return Err(io::Error::new(io::ErrorKind::InvalidData, - "Failed to get exit status of process")); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Failed to get exit status of process", + )); } Ok(Some(ExitStatus(proc_info.return_code))) } diff --git a/src/libstd/sys/unix/process/zircon.rs b/src/libstd/sys/unix/process/zircon.rs index 188a6b5f2da4a..750b8f0762ae5 100644 --- a/src/libstd/sys/unix/process/zircon.rs +++ b/src/libstd/sys/unix/process/zircon.rs @@ -1,8 +1,8 @@ #![allow(non_camel_case_types, unused)] use crate::convert::TryInto; -use crate::io; use crate::i64; +use crate::io; use crate::mem::MaybeUninit; use crate::os::raw::c_char; @@ -16,27 +16,26 @@ pub type zx_status_t = i32; pub const ZX_HANDLE_INVALID: zx_handle_t = 0; pub type zx_time_t = i64; -pub const ZX_TIME_INFINITE : zx_time_t = i64::MAX; +pub const ZX_TIME_INFINITE: zx_time_t = i64::MAX; pub type zx_signals_t = u32; -pub const ZX_OBJECT_SIGNAL_3 : zx_signals_t = 1 << 3; +pub const ZX_OBJECT_SIGNAL_3: zx_signals_t = 1 << 3; -pub const ZX_TASK_TERMINATED : zx_signals_t = ZX_OBJECT_SIGNAL_3; +pub const ZX_TASK_TERMINATED: zx_signals_t = ZX_OBJECT_SIGNAL_3; -pub const ZX_RIGHT_SAME_RIGHTS : zx_rights_t = 1 << 31; +pub const ZX_RIGHT_SAME_RIGHTS: zx_rights_t = 1 << 31; pub type zx_object_info_topic_t = u32; -pub const ZX_INFO_PROCESS : zx_object_info_topic_t = 3; +pub const ZX_INFO_PROCESS: zx_object_info_topic_t = 3; -pub fn zx_cvt(t: T) -> io::Result where T: TryInto+Copy { +pub fn zx_cvt(t: T) -> io::Result +where + T: TryInto + Copy, +{ if let Ok(status) = TryInto::try_into(t) { - if status < 0 { - Err(io::Error::from_raw_os_error(status)) - } else { - Ok(t) - } + if status < 0 { Err(io::Error::from_raw_os_error(status)) } else { Ok(t) } } else { Err(io::Error::last_os_error()) } @@ -49,9 +48,7 @@ pub struct Handle { impl Handle { pub fn new(raw: zx_handle_t) -> Handle { - Handle { - raw, - } + Handle { raw } } pub fn raw(&self) -> zx_handle_t { @@ -61,7 +58,9 @@ impl Handle { impl Drop for Handle { fn drop(&mut self) { - unsafe { zx_cvt(zx_handle_close(self.raw)).expect("Failed to close zx_handle_t"); } + unsafe { + zx_cvt(zx_handle_close(self.raw)).expect("Failed to close zx_handle_t"); + } } } @@ -75,22 +74,34 @@ pub struct zx_info_process_t { pub debugger_attached: bool, } -extern { +extern "C" { pub fn zx_job_default() -> zx_handle_t; pub fn zx_task_kill(handle: zx_handle_t) -> zx_status_t; pub fn zx_handle_close(handle: zx_handle_t) -> zx_status_t; - pub fn zx_handle_duplicate(handle: zx_handle_t, rights: zx_rights_t, - out: *const zx_handle_t) -> zx_handle_t; - - pub fn zx_object_wait_one(handle: zx_handle_t, signals: zx_signals_t, timeout: zx_time_t, - pending: *mut zx_signals_t) -> zx_status_t; - - pub fn zx_object_get_info(handle: zx_handle_t, topic: u32, buffer: *mut c_void, - buffer_size: size_t, actual_size: *mut size_t, - avail: *mut size_t) -> zx_status_t; + pub fn zx_handle_duplicate( + handle: zx_handle_t, + rights: zx_rights_t, + out: *const zx_handle_t, + ) -> zx_handle_t; + + pub fn zx_object_wait_one( + handle: zx_handle_t, + signals: zx_signals_t, + timeout: zx_time_t, + pending: *mut zx_signals_t, + ) -> zx_status_t; + + pub fn zx_object_get_info( + handle: zx_handle_t, + topic: u32, + buffer: *mut c_void, + buffer_size: size_t, + actual_size: *mut size_t, + avail: *mut size_t, + ) -> zx_status_t; } #[derive(Default)] @@ -103,11 +114,18 @@ pub struct fdio_spawn_action_t { pub reserved1: u64, } -extern { - pub fn fdio_spawn_etc(job: zx_handle_t, flags: u32, path: *const c_char, - argv: *const *const c_char, envp: *const *const c_char, - action_count: size_t, actions: *const fdio_spawn_action_t, - process: *mut zx_handle_t, err_msg: *mut c_char) -> zx_status_t; +extern "C" { + pub fn fdio_spawn_etc( + job: zx_handle_t, + flags: u32, + path: *const c_char, + argv: *const *const c_char, + envp: *const *const c_char, + action_count: size_t, + actions: *const fdio_spawn_action_t, + process: *mut zx_handle_t, + err_msg: *mut c_char, + ) -> zx_status_t; pub fn fdio_fd_clone(fd: c_int, out_handle: *mut zx_handle_t) -> zx_status_t; pub fn fdio_fd_create(handle: zx_handle_t, fd: *mut c_int) -> zx_status_t; @@ -129,60 +147,74 @@ pub const FDIO_SPAWN_ACTION_TRANSFER_FD: u32 = 0x0002; // Errors -#[allow(unused)] pub const ERR_INTERNAL: zx_status_t = -1; +#[allow(unused)] +pub const ERR_INTERNAL: zx_status_t = -1; // ERR_NOT_SUPPORTED: The operation is not implemented, supported, // or enabled. -#[allow(unused)] pub const ERR_NOT_SUPPORTED: zx_status_t = -2; +#[allow(unused)] +pub const ERR_NOT_SUPPORTED: zx_status_t = -2; // ERR_NO_RESOURCES: The system was not able to allocate some resource // needed for the operation. -#[allow(unused)] pub const ERR_NO_RESOURCES: zx_status_t = -3; +#[allow(unused)] +pub const ERR_NO_RESOURCES: zx_status_t = -3; // ERR_NO_MEMORY: The system was not able to allocate memory needed // for the operation. -#[allow(unused)] pub const ERR_NO_MEMORY: zx_status_t = -4; +#[allow(unused)] +pub const ERR_NO_MEMORY: zx_status_t = -4; // ERR_CALL_FAILED: The second phase of zx_channel_call(; did not complete // successfully. -#[allow(unused)] pub const ERR_CALL_FAILED: zx_status_t = -5; +#[allow(unused)] +pub const ERR_CALL_FAILED: zx_status_t = -5; // ERR_INTERRUPTED_RETRY: The system call was interrupted, but should be // retried. This should not be seen outside of the VDSO. -#[allow(unused)] pub const ERR_INTERRUPTED_RETRY: zx_status_t = -6; +#[allow(unused)] +pub const ERR_INTERRUPTED_RETRY: zx_status_t = -6; // ======= Parameter errors ======= // ERR_INVALID_ARGS: an argument is invalid, ex. null pointer -#[allow(unused)] pub const ERR_INVALID_ARGS: zx_status_t = -10; +#[allow(unused)] +pub const ERR_INVALID_ARGS: zx_status_t = -10; // ERR_BAD_HANDLE: A specified handle value does not refer to a handle. -#[allow(unused)] pub const ERR_BAD_HANDLE: zx_status_t = -11; +#[allow(unused)] +pub const ERR_BAD_HANDLE: zx_status_t = -11; // ERR_WRONG_TYPE: The subject of the operation is the wrong type to // perform the operation. // Example: Attempting a message_read on a thread handle. -#[allow(unused)] pub const ERR_WRONG_TYPE: zx_status_t = -12; +#[allow(unused)] +pub const ERR_WRONG_TYPE: zx_status_t = -12; // ERR_BAD_SYSCALL: The specified syscall number is invalid. -#[allow(unused)] pub const ERR_BAD_SYSCALL: zx_status_t = -13; +#[allow(unused)] +pub const ERR_BAD_SYSCALL: zx_status_t = -13; // ERR_OUT_OF_RANGE: An argument is outside the valid range for this // operation. -#[allow(unused)] pub const ERR_OUT_OF_RANGE: zx_status_t = -14; +#[allow(unused)] +pub const ERR_OUT_OF_RANGE: zx_status_t = -14; // ERR_BUFFER_TOO_SMALL: A caller provided buffer is too small for // this operation. -#[allow(unused)] pub const ERR_BUFFER_TOO_SMALL: zx_status_t = -15; +#[allow(unused)] +pub const ERR_BUFFER_TOO_SMALL: zx_status_t = -15; // ======= Precondition or state errors ======= // ERR_BAD_STATE: operation failed because the current state of the // object does not allow it, or a precondition of the operation is // not satisfied -#[allow(unused)] pub const ERR_BAD_STATE: zx_status_t = -20; +#[allow(unused)] +pub const ERR_BAD_STATE: zx_status_t = -20; // ERR_TIMED_OUT: The time limit for the operation elapsed before // the operation completed. -#[allow(unused)] pub const ERR_TIMED_OUT: zx_status_t = -21; +#[allow(unused)] +pub const ERR_TIMED_OUT: zx_status_t = -21; // ERR_SHOULD_WAIT: The operation cannot be performed currently but // potentially could succeed if the caller waits for a prerequisite @@ -192,67 +224,84 @@ pub const FDIO_SPAWN_ACTION_TRANSFER_FD: u32 = 0x0002; // messages waiting but has an open remote will return ERR_SHOULD_WAIT. // Attempting to read from a message pipe that has no messages waiting // and has a closed remote end will return ERR_REMOTE_CLOSED. -#[allow(unused)] pub const ERR_SHOULD_WAIT: zx_status_t = -22; +#[allow(unused)] +pub const ERR_SHOULD_WAIT: zx_status_t = -22; // ERR_CANCELED: The in-progress operation (e.g., a wait) has been // // canceled. -#[allow(unused)] pub const ERR_CANCELED: zx_status_t = -23; +#[allow(unused)] +pub const ERR_CANCELED: zx_status_t = -23; // ERR_PEER_CLOSED: The operation failed because the remote end // of the subject of the operation was closed. -#[allow(unused)] pub const ERR_PEER_CLOSED: zx_status_t = -24; +#[allow(unused)] +pub const ERR_PEER_CLOSED: zx_status_t = -24; // ERR_NOT_FOUND: The requested entity is not found. -#[allow(unused)] pub const ERR_NOT_FOUND: zx_status_t = -25; +#[allow(unused)] +pub const ERR_NOT_FOUND: zx_status_t = -25; // ERR_ALREADY_EXISTS: An object with the specified identifier // already exists. // Example: Attempting to create a file when a file already exists // with that name. -#[allow(unused)] pub const ERR_ALREADY_EXISTS: zx_status_t = -26; +#[allow(unused)] +pub const ERR_ALREADY_EXISTS: zx_status_t = -26; // ERR_ALREADY_BOUND: The operation failed because the named entity // is already owned or controlled by another entity. The operation // could succeed later if the current owner releases the entity. -#[allow(unused)] pub const ERR_ALREADY_BOUND: zx_status_t = -27; +#[allow(unused)] +pub const ERR_ALREADY_BOUND: zx_status_t = -27; // ERR_UNAVAILABLE: The subject of the operation is currently unable // to perform the operation. // Note: This is used when there's no direct way for the caller to // observe when the subject will be able to perform the operation // and should thus retry. -#[allow(unused)] pub const ERR_UNAVAILABLE: zx_status_t = -28; +#[allow(unused)] +pub const ERR_UNAVAILABLE: zx_status_t = -28; // ======= Permission check errors ======= // ERR_ACCESS_DENIED: The caller did not have permission to perform // the specified operation. -#[allow(unused)] pub const ERR_ACCESS_DENIED: zx_status_t = -30; +#[allow(unused)] +pub const ERR_ACCESS_DENIED: zx_status_t = -30; // ======= Input-output errors ======= // ERR_IO: Otherwise unspecified error occurred during I/O. -#[allow(unused)] pub const ERR_IO: zx_status_t = -40; +#[allow(unused)] +pub const ERR_IO: zx_status_t = -40; // ERR_REFUSED: The entity the I/O operation is being performed on // rejected the operation. // Example: an I2C device NAK'ing a transaction or a disk controller // rejecting an invalid command. -#[allow(unused)] pub const ERR_IO_REFUSED: zx_status_t = -41; +#[allow(unused)] +pub const ERR_IO_REFUSED: zx_status_t = -41; // ERR_IO_DATA_INTEGRITY: The data in the operation failed an integrity // check and is possibly corrupted. // Example: CRC or Parity error. -#[allow(unused)] pub const ERR_IO_DATA_INTEGRITY: zx_status_t = -42; +#[allow(unused)] +pub const ERR_IO_DATA_INTEGRITY: zx_status_t = -42; // ERR_IO_DATA_LOSS: The data in the operation is currently unavailable // and may be permanently lost. // Example: A disk block is irrecoverably damaged. -#[allow(unused)] pub const ERR_IO_DATA_LOSS: zx_status_t = -43; +#[allow(unused)] +pub const ERR_IO_DATA_LOSS: zx_status_t = -43; // Filesystem specific errors -#[allow(unused)] pub const ERR_BAD_PATH: zx_status_t = -50; -#[allow(unused)] pub const ERR_NOT_DIR: zx_status_t = -51; -#[allow(unused)] pub const ERR_NOT_FILE: zx_status_t = -52; +#[allow(unused)] +pub const ERR_BAD_PATH: zx_status_t = -50; +#[allow(unused)] +pub const ERR_NOT_DIR: zx_status_t = -51; +#[allow(unused)] +pub const ERR_NOT_FILE: zx_status_t = -52; // ERR_FILE_BIG: A file exceeds a filesystem-specific size limit. -#[allow(unused)] pub const ERR_FILE_BIG: zx_status_t = -53; +#[allow(unused)] +pub const ERR_FILE_BIG: zx_status_t = -53; // ERR_NO_SPACE: Filesystem or device space is exhausted. -#[allow(unused)] pub const ERR_NO_SPACE: zx_status_t = -54; +#[allow(unused)] +pub const ERR_NO_SPACE: zx_status_t = -54; diff --git a/src/libstd/sys/unix/rand.rs b/src/libstd/sys/unix/rand.rs index bc387544c4cb4..9ce5f3d014cc1 100644 --- a/src/libstd/sys/unix/rand.rs +++ b/src/libstd/sys/unix/rand.rs @@ -4,20 +4,21 @@ use crate::slice; pub fn hashmap_random_keys() -> (u64, u64) { let mut v = (0, 0); unsafe { - let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8, - mem::size_of_val(&v)); + let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8, mem::size_of_val(&v)); imp::fill_bytes(view); } v } -#[cfg(all(unix, - not(target_os = "ios"), - not(target_os = "openbsd"), - not(target_os = "freebsd"), - not(target_os = "netbsd"), - not(target_os = "fuchsia"), - not(target_os = "redox")))] +#[cfg(all( + unix, + not(target_os = "ios"), + not(target_os = "openbsd"), + not(target_os = "freebsd"), + not(target_os = "netbsd"), + not(target_os = "fuchsia"), + not(target_os = "redox") +))] mod imp { use crate::fs::File; use crate::io::Read; @@ -30,7 +31,9 @@ mod imp { } #[cfg(not(any(target_os = "linux", target_os = "android")))] - fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool { false } + fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool { + false + } #[cfg(any(target_os = "linux", target_os = "android"))] fn getrandom_fill_bytes(v: &mut [u8]) -> bool { @@ -96,9 +99,7 @@ mod imp { pub fn fill_bytes(v: &mut [u8]) { // getentropy(2) permits a maximum buffer size of 256 bytes for s in v.chunks_mut(256) { - let ret = unsafe { - libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len()) - }; + let ret = unsafe { libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len()) }; if ret == -1 { panic!("unexpected getentropy error: {}", errno()); } @@ -124,21 +125,14 @@ mod imp { #[allow(non_upper_case_globals)] const kSecRandomDefault: *const SecRandom = ptr::null(); - extern { - fn SecRandomCopyBytes(rnd: *const SecRandom, - count: size_t, - bytes: *mut u8) -> c_int; + extern "C" { + fn SecRandomCopyBytes(rnd: *const SecRandom, count: size_t, bytes: *mut u8) -> c_int; } pub fn fill_bytes(v: &mut [u8]) { - let ret = unsafe { - SecRandomCopyBytes(kSecRandomDefault, - v.len(), - v.as_mut_ptr()) - }; + let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, v.len(), v.as_mut_ptr()) }; if ret == -1 { - panic!("couldn't generate random bytes: {}", - io::Error::last_os_error()); + panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); } } } @@ -153,13 +147,22 @@ mod imp { for s in v.chunks_mut(256) { let mut s_len = s.len(); let ret = unsafe { - libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint, - s.as_mut_ptr() as *mut _, &mut s_len, - ptr::null(), 0) + libc::sysctl( + mib.as_ptr(), + mib.len() as libc::c_uint, + s.as_mut_ptr() as *mut _, + &mut s_len, + ptr::null(), + 0, + ) }; if ret == -1 || s_len != s.len() { - panic!("kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})", - ret, s.len(), s_len); + panic!( + "kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})", + ret, + s.len(), + s_len + ); } } } @@ -168,7 +171,7 @@ mod imp { #[cfg(target_os = "fuchsia")] mod imp { #[link(name = "zircon")] - extern { + extern "C" { fn zx_cprng_draw(buffer: *mut u8, len: usize); } diff --git a/src/libstd/sys/unix/stack_overflow.rs b/src/libstd/sys/unix/stack_overflow.rs index fe1095fa0c2f6..528fe321efbce 100644 --- a/src/libstd/sys/unix/stack_overflow.rs +++ b/src/libstd/sys/unix/stack_overflow.rs @@ -1,12 +1,12 @@ #![cfg_attr(test, allow(dead_code))] -use self::imp::{make_handler, drop_handler}; +use self::imp::{drop_handler, make_handler}; pub use self::imp::cleanup; pub use self::imp::init; pub struct Handler { - _data: *mut libc::c_void + _data: *mut libc::c_void, } impl Handler { @@ -23,28 +23,28 @@ impl Drop for Handler { } } -#[cfg(any(target_os = "linux", - target_os = "macos", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "solaris", - all(target_os = "netbsd", not(target_vendor = "rumprun")), - target_os = "openbsd"))] +#[cfg(any( + target_os = "linux", + target_os = "macos", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "solaris", + all(target_os = "netbsd", not(target_vendor = "rumprun")), + target_os = "openbsd" +))] mod imp { use super::Handler; use crate::mem; use crate::ptr; - use libc::{sigaltstack, SIGSTKSZ, SS_DISABLE}; - use libc::{sigaction, SIGBUS, SIG_DFL, - SA_SIGINFO, SA_ONSTACK, sighandler_t}; - use libc::{mmap, munmap}; - use libc::{SIGSEGV, PROT_READ, PROT_WRITE, MAP_PRIVATE, MAP_ANON}; use libc::MAP_FAILED; + use libc::{mmap, munmap}; + use libc::{sigaction, sighandler_t, SA_ONSTACK, SA_SIGINFO, SIGBUS, SIG_DFL}; + use libc::{sigaltstack, SIGSTKSZ, SS_DISABLE}; + use libc::{MAP_ANON, MAP_PRIVATE, PROT_READ, PROT_WRITE, SIGSEGV}; use crate::sys_common::thread_info; - #[cfg(any(target_os = "linux", target_os = "android"))] unsafe fn siginfo_si_addr(info: *mut libc::siginfo_t) -> usize { #[repr(C)] @@ -82,9 +82,11 @@ mod imp { // out many large systems and all implementations allow returning from a // signal handler to work. For a more detailed explanation see the // comments on #26458. - unsafe extern fn signal_handler(signum: libc::c_int, - info: *mut libc::siginfo_t, - _data: *mut libc::c_void) { + unsafe extern "C" fn signal_handler( + signum: libc::c_int, + info: *mut libc::siginfo_t, + _data: *mut libc::c_void, + ) { use crate::sys_common::util::report_overflow; let guard = thread_info::stack_guard().unwrap_or(0..0); @@ -124,24 +126,22 @@ mod imp { } unsafe fn get_stackp() -> *mut libc::c_void { - let stackp = mmap(ptr::null_mut(), - SIGSTKSZ, - PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANON, - -1, - 0); + let stackp = + mmap(ptr::null_mut(), SIGSTKSZ, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); if stackp == MAP_FAILED { panic!("failed to allocate an alternative stack"); } stackp } - #[cfg(any(target_os = "linux", - target_os = "macos", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris"))] + #[cfg(any( + target_os = "linux", + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + target_os = "solaris" + ))] unsafe fn get_stack() -> libc::stack_t { libc::stack_t { ss_sp: get_stackp(), ss_flags: 0, ss_size: SIGSTKSZ } } @@ -166,7 +166,7 @@ mod imp { pub unsafe fn drop_handler(handler: &mut Handler) { if !handler._data.is_null() { - let stack = libc::stack_t { + let stack = libc::stack_t { ss_sp: ptr::null_mut(), ss_flags: SS_DISABLE, // Workaround for bug in macOS implementation of sigaltstack @@ -181,26 +181,25 @@ mod imp { } } -#[cfg(not(any(target_os = "linux", - target_os = "macos", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "solaris", - all(target_os = "netbsd", not(target_vendor = "rumprun")), - target_os = "openbsd")))] +#[cfg(not(any( + target_os = "linux", + target_os = "macos", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "solaris", + all(target_os = "netbsd", not(target_vendor = "rumprun")), + target_os = "openbsd" +)))] mod imp { use crate::ptr; - pub unsafe fn init() { - } + pub unsafe fn init() {} - pub unsafe fn cleanup() { - } + pub unsafe fn cleanup() {} pub unsafe fn make_handler() -> super::Handler { super::Handler { _data: ptr::null_mut() } } - pub unsafe fn drop_handler(_handler: &mut super::Handler) { - } + pub unsafe fn drop_handler(_handler: &mut super::Handler) {} } diff --git a/src/libstd/sys/unix/stdio.rs b/src/libstd/sys/unix/stdio.rs index f9b017df24088..b9c56963885c0 100644 --- a/src/libstd/sys/unix/stdio.rs +++ b/src/libstd/sys/unix/stdio.rs @@ -1,13 +1,15 @@ use crate::io::{self, IoSlice, IoSliceMut}; -use crate::sys::fd::FileDesc; use crate::mem::ManuallyDrop; +use crate::sys::fd::FileDesc; pub struct Stdin(()); pub struct Stdout(()); pub struct Stderr(()); impl Stdin { - pub fn new() -> io::Result { Ok(Stdin(())) } + pub fn new() -> io::Result { + Ok(Stdin(())) + } } impl io::Read for Stdin { @@ -21,7 +23,9 @@ impl io::Read for Stdin { } impl Stdout { - pub fn new() -> io::Result { Ok(Stdout(())) } + pub fn new() -> io::Result { + Ok(Stdout(())) + } } impl io::Write for Stdout { @@ -39,7 +43,9 @@ impl io::Write for Stdout { } impl Stderr { - pub fn new() -> io::Result { Ok(Stderr(())) } + pub fn new() -> io::Result { + Ok(Stderr(())) + } } impl io::Write for Stderr { diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs index 72b0ac493da15..a5b34eeec289e 100644 --- a/src/libstd/sys/unix/thread.rs +++ b/src/libstd/sys/unix/thread.rs @@ -25,21 +25,24 @@ unsafe impl Sync for Thread {} // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc, // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS. #[cfg(not(target_os = "emscripten"))] -unsafe fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t, - stack_size: libc::size_t) -> libc::c_int { +unsafe fn pthread_attr_setstacksize( + attr: *mut libc::pthread_attr_t, + stack_size: libc::size_t, +) -> libc::c_int { libc::pthread_attr_setstacksize(attr, stack_size) } #[cfg(target_os = "emscripten")] -unsafe fn pthread_attr_setstacksize(_attr: *mut libc::pthread_attr_t, - _stack_size: libc::size_t) -> libc::c_int { +unsafe fn pthread_attr_setstacksize( + _attr: *mut libc::pthread_attr_t, + _stack_size: libc::size_t, +) -> libc::c_int { panic!() } impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(stack: usize, p: Box) - -> io::Result { + pub unsafe fn new(stack: usize, p: Box) -> io::Result { let p = box p; let mut native: libc::pthread_t = mem::zeroed(); let mut attr: libc::pthread_attr_t = mem::zeroed(); @@ -47,8 +50,7 @@ impl Thread { let stack_size = cmp::max(stack, min_stack_size(&attr)); - match pthread_attr_setstacksize(&mut attr, - stack_size) { + match pthread_attr_setstacksize(&mut attr, stack_size) { 0 => {} n => { assert_eq!(n, libc::EINVAL); @@ -57,15 +59,13 @@ impl Thread { // >= PTHREAD_STACK_MIN, it must be an alignment issue. // Round up to the nearest page and try again. let page_size = os::page_size(); - let stack_size = (stack_size + page_size - 1) & - (-(page_size as isize - 1) as usize - 1); - assert_eq!(libc::pthread_attr_setstacksize(&mut attr, - stack_size), 0); + let stack_size = + (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1); + assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0); } }; - let ret = libc::pthread_create(&mut native, &attr, thread_start, - &*p as *const _ as *mut _); + let ret = libc::pthread_create(&mut native, &attr, thread_start, &*p as *const _ as *mut _); assert_eq!(libc::pthread_attr_destroy(&mut attr), 0); return if ret != 0 { @@ -75,8 +75,10 @@ impl Thread { Ok(Thread { id: native }) }; - extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void { - unsafe { start_thread(main as *mut u8); } + extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void { + unsafe { + start_thread(main as *mut u8); + } ptr::null_mut() } } @@ -86,8 +88,7 @@ impl Thread { debug_assert_eq!(ret, 0); } - #[cfg(any(target_os = "linux", - target_os = "android"))] + #[cfg(any(target_os = "linux", target_os = "android"))] pub fn set_name(name: &CStr) { const PR_SET_NAME: libc::c_int = 15; // pthread wrapper only appeared in glibc 2.12, so we use syscall @@ -97,9 +98,7 @@ impl Thread { } } - #[cfg(any(target_os = "freebsd", - target_os = "dragonfly", - target_os = "openbsd"))] + #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))] pub fn set_name(name: &CStr) { unsafe { libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr()); @@ -118,8 +117,11 @@ impl Thread { use crate::ffi::CString; let cname = CString::new(&b"%s"[..]).unwrap(); unsafe { - libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(), - name.as_ptr() as *mut libc::c_void); + libc::pthread_setname_np( + libc::pthread_self(), + cname.as_ptr(), + name.as_ptr() as *mut libc::c_void, + ); } } @@ -132,15 +134,19 @@ impl Thread { } if let Some(f) = pthread_setname_np.get() { - unsafe { f(libc::pthread_self(), name.as_ptr()); } + unsafe { + f(libc::pthread_self(), name.as_ptr()); + } } } - #[cfg(any(target_env = "newlib", - target_os = "haiku", - target_os = "l4re", - target_os = "emscripten", - target_os = "redox"))] + #[cfg(any( + target_env = "newlib", + target_os = "haiku", + target_os = "l4re", + target_os = "emscripten", + target_os = "redox" + ))] pub fn set_name(_name: &CStr) { // Newlib, Illumos, Haiku, and Emscripten have no way to set a thread name. } @@ -177,12 +183,13 @@ impl Thread { unsafe { let ret = libc::pthread_join(self.id, ptr::null_mut()); mem::forget(self); - assert!(ret == 0, - "failed to join thread: {}", io::Error::from_raw_os_error(ret)); + assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); } } - pub fn id(&self) -> libc::pthread_t { self.id } + pub fn id(&self) -> libc::pthread_t { + self.id + } pub fn into_id(self) -> libc::pthread_t { let id = self.id; @@ -198,31 +205,38 @@ impl Drop for Thread { } } -#[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))), - not(target_os = "freebsd"), - not(target_os = "macos"), - not(all(target_os = "netbsd", not(target_vendor = "rumprun"))), - not(target_os = "openbsd"), - not(target_os = "solaris")))] +#[cfg(all( + not(all(target_os = "linux", not(target_env = "musl"))), + not(target_os = "freebsd"), + not(target_os = "macos"), + not(all(target_os = "netbsd", not(target_vendor = "rumprun"))), + not(target_os = "openbsd"), + not(target_os = "solaris") +))] #[cfg_attr(test, allow(dead_code))] pub mod guard { use crate::ops::Range; pub type Guard = Range; - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + pub unsafe fn current() -> Option { + None + } + pub unsafe fn init() -> Option { + None + } } - -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), - target_os = "freebsd", - target_os = "macos", - all(target_os = "netbsd", not(target_vendor = "rumprun")), - target_os = "openbsd", - target_os = "solaris"))] +#[cfg(any( + all(target_os = "linux", not(target_env = "musl")), + target_os = "freebsd", + target_os = "macos", + all(target_os = "netbsd", not(target_vendor = "rumprun")), + target_os = "openbsd", + target_os = "solaris" +))] #[cfg_attr(test, allow(dead_code))] pub mod guard { use libc::{mmap, mprotect}; - use libc::{PROT_NONE, PROT_READ, PROT_WRITE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED}; + use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE}; use crate::ops::Range; use crate::sys::os; @@ -241,16 +255,15 @@ pub mod guard { #[cfg(target_os = "macos")] unsafe fn get_stack_start() -> Option<*mut libc::c_void> { - let stackaddr = libc::pthread_get_stackaddr_np(libc::pthread_self()) as usize - - libc::pthread_get_stacksize_np(libc::pthread_self()); + let stackaddr = libc::pthread_get_stackaddr_np(libc::pthread_self()) as usize + - libc::pthread_get_stacksize_np(libc::pthread_self()); Some(stackaddr as *mut libc::c_void) } #[cfg(target_os = "openbsd")] unsafe fn get_stack_start() -> Option<*mut libc::c_void> { let mut current_stack: libc::stack_t = crate::mem::zeroed(); - assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), - &mut current_stack), 0); + assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0); let stackaddr = if libc::pthread_main_np() == 1 { // main thread @@ -262,21 +275,25 @@ pub mod guard { Some(stackaddr as *mut libc::c_void) } - #[cfg(any(target_os = "android", target_os = "freebsd", - target_os = "linux", target_os = "netbsd", target_os = "l4re"))] + #[cfg(any( + target_os = "android", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd", + target_os = "l4re" + ))] unsafe fn get_stack_start() -> Option<*mut libc::c_void> { let mut ret = None; let mut attr: libc::pthread_attr_t = crate::mem::zeroed(); assert_eq!(libc::pthread_attr_init(&mut attr), 0); #[cfg(target_os = "freebsd")] - let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr); + let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr); #[cfg(not(target_os = "freebsd"))] - let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr); + let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr); if e == 0 { let mut stackaddr = crate::ptr::null_mut(); let mut stacksize = 0; - assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, - &mut stacksize), 0); + assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0); ret = Some(stackaddr); } assert_eq!(libc::pthread_attr_destroy(&mut attr), 0); @@ -329,8 +346,14 @@ pub mod guard { // than the initial mmap() used, so we mmap() here with // read/write permissions and only then mprotect() it to // no permissions at all. See issue #50313. - let result = mmap(stackaddr, PAGE_SIZE, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0); + let result = mmap( + stackaddr, + PAGE_SIZE, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON | MAP_FIXED, + -1, + 0, + ); if result != stackaddr || result == MAP_FAILED { panic!("failed to allocate a guard page"); } @@ -341,34 +364,33 @@ pub mod guard { } let guardaddr = stackaddr as usize; - let offset = if cfg!(target_os = "freebsd") { - 2 - } else { - 1 - }; + let offset = if cfg!(target_os = "freebsd") { 2 } else { 1 }; Some(guardaddr..guardaddr + offset * PAGE_SIZE) } } - #[cfg(any(target_os = "macos", - target_os = "openbsd", - target_os = "solaris"))] + #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))] pub unsafe fn current() -> Option { let stackaddr = get_stack_start()? as usize; Some(stackaddr - PAGE_SIZE..stackaddr) } - #[cfg(any(target_os = "android", target_os = "freebsd", - target_os = "linux", target_os = "netbsd", target_os = "l4re"))] + #[cfg(any( + target_os = "android", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd", + target_os = "l4re" + ))] pub unsafe fn current() -> Option { let mut ret = None; let mut attr: libc::pthread_attr_t = crate::mem::zeroed(); assert_eq!(libc::pthread_attr_init(&mut attr), 0); #[cfg(target_os = "freebsd")] - let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr); + let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr); #[cfg(not(target_os = "freebsd"))] - let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr); + let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr); if e == 0 { let mut guardsize = 0; assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0); @@ -377,8 +399,7 @@ pub mod guard { } let mut stackaddr = crate::ptr::null_mut(); let mut size = 0; - assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, - &mut size), 0); + assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0); let stackaddr = stackaddr as usize; ret = if cfg!(target_os = "freebsd") { @@ -422,8 +443,7 @@ fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize { // No point in looking up __pthread_get_minstack() on non-glibc // platforms. -#[cfg(all(not(target_os = "linux"), - not(target_os = "netbsd")))] +#[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))] fn min_stack_size(_: *const libc::pthread_attr_t) -> usize { libc::PTHREAD_STACK_MIN } diff --git a/src/libstd/sys/unix/thread_local.rs b/src/libstd/sys/unix/thread_local.rs index ac615b76b3624..2c5b94b1e61e5 100644 --- a/src/libstd/sys/unix/thread_local.rs +++ b/src/libstd/sys/unix/thread_local.rs @@ -5,7 +5,7 @@ use crate::mem; pub type Key = libc::pthread_key_t; #[inline] -pub unsafe fn create(dtor: Option) -> Key { +pub unsafe fn create(dtor: Option) -> Key { let mut key = 0; assert_eq!(libc::pthread_key_create(&mut key, mem::transmute(dtor)), 0); key diff --git a/src/libstd/sys/unix/weak.rs b/src/libstd/sys/unix/weak.rs index 9a7691e54bc1a..08cbe59617465 100644 --- a/src/libstd/sys/unix/weak.rs +++ b/src/libstd/sys/unix/weak.rs @@ -36,11 +36,7 @@ pub struct Weak { impl Weak { pub const fn new(name: &'static str) -> Weak { - Weak { - name, - addr: AtomicUsize::new(1), - _marker: marker::PhantomData, - } + Weak { name, addr: AtomicUsize::new(1), _marker: marker::PhantomData } } pub fn get(&self) -> Option { diff --git a/src/libstd/sys/vxworks/alloc.rs b/src/libstd/sys/vxworks/alloc.rs index e0c560b9214ea..97a191d7232e0 100644 --- a/src/libstd/sys/vxworks/alloc.rs +++ b/src/libstd/sys/vxworks/alloc.rs @@ -1,6 +1,6 @@ -use crate::ptr; -use crate::sys_common::alloc::{MIN_ALIGN, realloc_fallback}; use crate::alloc::{GlobalAlloc, Layout, System}; +use crate::ptr; +use crate::sys_common::alloc::{realloc_fallback, MIN_ALIGN}; #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { @@ -45,9 +45,5 @@ unsafe impl GlobalAlloc for System { unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { let mut out = ptr::null_mut(); let ret = libc::posix_memalign(&mut out, layout.align(), layout.size()); - if ret != 0 { - ptr::null_mut() - } else { - out as *mut u8 - } + if ret != 0 { ptr::null_mut() } else { out as *mut u8 } } diff --git a/src/libstd/sys/vxworks/args.rs b/src/libstd/sys/vxworks/args.rs index 11c3cb7881950..efd615f404db6 100644 --- a/src/libstd/sys/vxworks/args.rs +++ b/src/libstd/sys/vxworks/args.rs @@ -4,10 +4,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 { @@ -27,24 +31,32 @@ impl Args { impl Iterator for Args { type Item = OsString; - fn next(&mut self) -> Option { self.iter.next() } - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + 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 { self.iter.next_back() } + fn next_back(&mut self) -> Option { + self.iter.next_back() + } } mod imp { - use crate::ptr; + use super::Args; use crate::ffi::{CStr, OsString}; use crate::marker::PhantomData; + use crate::ptr; use libc; - use super::Args; use crate::sys_common::mutex::Mutex; @@ -65,21 +77,20 @@ 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 { unsafe { let _guard = LOCK.lock(); - let ret = (0..ARGC).map(|i| { - let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char); - use crate::sys::vxworks::ext::ffi::OsStringExt; - OsStringExt::from_vec(cstr.to_bytes().to_vec()) - }).collect(); - return ret + let ret = (0..ARGC) + .map(|i| { + let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char); + use crate::sys::vxworks::ext::ffi::OsStringExt; + OsStringExt::from_vec(cstr.to_bytes().to_vec()) + }) + .collect(); + return ret; } } } diff --git a/src/libstd/sys/vxworks/cmath.rs b/src/libstd/sys/vxworks/cmath.rs index f6bb58934fc05..2916ebe444059 100644 --- a/src/libstd/sys/vxworks/cmath.rs +++ b/src/libstd/sys/vxworks/cmath.rs @@ -1,9 +1,9 @@ #![cfg(not(test))] -use libc::{c_float, c_double}; +use libc::{c_double, c_float}; #[link_name = "m"] -extern { +extern "C" { pub fn acos(n: c_double) -> c_double; pub fn acosf(n: c_float) -> c_float; pub fn asin(n: c_double) -> c_double; diff --git a/src/libstd/sys/vxworks/condvar.rs b/src/libstd/sys/vxworks/condvar.rs index 783c3eb7c766f..f2a1d6815290d 100644 --- a/src/libstd/sys/vxworks/condvar.rs +++ b/src/libstd/sys/vxworks/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 } +pub struct Condvar { + inner: UnsafeCell, +} unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} -const TIMESPEC_MAX: libc::timespec = libc::timespec { - tv_sec: ::max_value(), - tv_nsec: 1_000_000_000 - 1, -}; +const TIMESPEC_MAX: libc::timespec = + libc::timespec { tv_sec: ::max_value(), tv_nsec: 1_000_000_000 - 1 }; fn saturating_cast_to_time_t(value: u64) -> libc::time_t { if value > ::max_value() as u64 { @@ -77,17 +77,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 } - #[inline] pub unsafe fn destroy(&self) { let r = libc::pthread_cond_destroy(self.inner.get()); diff --git a/src/libstd/sys/vxworks/ext/fs.rs b/src/libstd/sys/vxworks/ext/fs.rs index 4a9cc3bd0693c..9864a855df738 100644 --- a/src/libstd/sys/vxworks/ext/fs.rs +++ b/src/libstd/sys/vxworks/ext/fs.rs @@ -2,11 +2,11 @@ use crate::fs::{self, Permissions}; use crate::io; -use libc; use crate::path::Path; use crate::sys; -use crate::sys_common::{FromInner, AsInner, AsInnerMut}; use crate::sys::platform::fs::MetadataExt as UnixMetadataExt; +use crate::sys_common::{AsInner, AsInnerMut, FromInner}; +use libc; /// Unix-specific extensions to [`File`]. /// @@ -112,8 +112,7 @@ pub trait FileExt { } } if !buf.is_empty() { - Err(io::Error::new(io::ErrorKind::UnexpectedEof, - "failed to fill whole buffer")) + Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer")) } else { Ok(()) } @@ -196,8 +195,12 @@ pub trait FileExt { fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> { while !buf.is_empty() { match self.write_at(buf, offset) { - Ok(0) => return Err(io::Error::new(io::ErrorKind::WriteZero, - "failed to write whole buffer")), + Ok(0) => { + return Err(io::Error::new( + io::ErrorKind::WriteZero, + "failed to write whole buffer", + )); + } Ok(n) => { buf = &buf[n..]; offset += n as u64 @@ -604,20 +607,48 @@ pub trait MetadataExt { #[stable(feature = "metadata_ext", since = "1.1.0")] impl MetadataExt for fs::Metadata { - fn dev(&self) -> u64 { self.st_dev() } - fn ino(&self) -> u64 { self.st_ino() } - fn mode(&self) -> u32 { self.st_mode() } - fn nlink(&self) -> u64 { self.st_nlink() } - fn uid(&self) -> u32 { self.st_uid() } - fn gid(&self) -> u32 { self.st_gid() } - fn rdev(&self) -> u64 { self.st_rdev() } - fn size(&self) -> u64 { self.st_size() } - fn atime(&self) -> i64 { self.st_atime() } - fn mtime(&self) -> i64 { self.st_mtime() } - fn ctime(&self) -> i64 { self.st_ctime() } - fn blksize(&self) -> u64 { self.st_blksize() } - fn blocks(&self) -> u64 { self.st_blocks() } - fn attrib(&self) -> u8 {self.st_attrib() } + fn dev(&self) -> u64 { + self.st_dev() + } + fn ino(&self) -> u64 { + self.st_ino() + } + fn mode(&self) -> u32 { + self.st_mode() + } + fn nlink(&self) -> u64 { + self.st_nlink() + } + fn uid(&self) -> u32 { + self.st_uid() + } + fn gid(&self) -> u32 { + self.st_gid() + } + fn rdev(&self) -> u64 { + self.st_rdev() + } + fn size(&self) -> u64 { + self.st_size() + } + fn atime(&self) -> i64 { + self.st_atime() + } + fn mtime(&self) -> i64 { + self.st_mtime() + } + fn ctime(&self) -> i64 { + self.st_ctime() + } + fn blksize(&self) -> u64 { + self.st_blksize() + } + fn blocks(&self) -> u64 { + self.st_blocks() + } + fn attrib(&self) -> u8 { + self.st_attrib() + } } /// Unix-specific extensions for [`FileType`]. @@ -704,10 +735,18 @@ pub trait FileTypeExt { #[stable(feature = "file_type_ext", since = "1.5.0")] impl FileTypeExt for fs::FileType { - fn is_block_device(&self) -> bool { self.as_inner().is(libc::S_IFBLK) } - fn is_char_device(&self) -> bool { self.as_inner().is(libc::S_IFCHR) } - fn is_fifo(&self) -> bool { self.as_inner().is(libc::S_IFIFO) } - fn is_socket(&self) -> bool { self.as_inner().is(libc::S_IFSOCK) } + fn is_block_device(&self) -> bool { + self.as_inner().is(libc::S_IFBLK) + } + fn is_char_device(&self) -> bool { + self.as_inner().is(libc::S_IFCHR) + } + fn is_fifo(&self) -> bool { + self.as_inner().is(libc::S_IFIFO) + } + fn is_socket(&self) -> bool { + self.as_inner().is(libc::S_IFSOCK) + } } /// Unix-specific extension methods for [`fs::DirEntry`]. @@ -739,7 +778,9 @@ pub trait DirEntryExt { #[stable(feature = "dir_entry_ext", since = "1.1.0")] impl DirEntryExt for fs::DirEntry { - fn ino(&self) -> u64 { self.as_inner().ino() } + fn ino(&self) -> u64 { + self.as_inner().ino() + } } /// Creates a new symbolic link on the filesystem. @@ -766,8 +807,7 @@ impl DirEntryExt for fs::DirEntry { /// } /// ``` #[stable(feature = "symlink", since = "1.1.0")] -pub fn symlink, Q: AsRef>(src: P, dst: Q) -> io::Result<()> -{ +pub fn symlink, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink(src.as_ref(), dst.as_ref()) } diff --git a/src/libstd/sys/vxworks/ext/io.rs b/src/libstd/sys/vxworks/ext/io.rs index df6255a3e9e03..25c6e26d96e91 100644 --- a/src/libstd/sys/vxworks/ext/io.rs +++ b/src/libstd/sys/vxworks/ext/io.rs @@ -3,11 +3,11 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::fs; +use crate::io; +use crate::net; use crate::os::raw; use crate::sys; -use crate::io; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; -use crate::net; /// Raw file descriptors. #[stable(feature = "rust1", since = "1.0.0")] @@ -84,47 +84,65 @@ impl IntoRawFd for fs::File { #[stable(feature = "asraw_stdio", since = "1.21.0")] impl AsRawFd for io::Stdin { - fn as_raw_fd(&self) -> RawFd { libc::STDIN_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDIN_FILENO + } } #[stable(feature = "asraw_stdio", since = "1.21.0")] impl AsRawFd for io::Stdout { - fn as_raw_fd(&self) -> RawFd { libc::STDOUT_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDOUT_FILENO + } } #[stable(feature = "asraw_stdio", since = "1.21.0")] impl AsRawFd for io::Stderr { - fn as_raw_fd(&self) -> RawFd { libc::STDERR_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDERR_FILENO + } } #[stable(feature = "asraw_stdio_locks", since = "1.35.0")] impl<'a> AsRawFd for io::StdinLock<'a> { - fn as_raw_fd(&self) -> RawFd { libc::STDIN_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDIN_FILENO + } } #[stable(feature = "asraw_stdio_locks", since = "1.35.0")] impl<'a> AsRawFd for io::StdoutLock<'a> { - fn as_raw_fd(&self) -> RawFd { libc::STDOUT_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDOUT_FILENO + } } #[stable(feature = "asraw_stdio_locks", since = "1.35.0")] impl<'a> AsRawFd for io::StderrLock<'a> { - fn as_raw_fd(&self) -> RawFd { libc::STDERR_FILENO } + fn as_raw_fd(&self) -> RawFd { + libc::STDERR_FILENO + } } #[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")] diff --git a/src/libstd/sys/vxworks/ext/mod.rs b/src/libstd/sys/vxworks/ext/mod.rs index d0f467b303ff9..251a198f821d6 100644 --- a/src/libstd/sys/vxworks/ext/mod.rs +++ b/src/libstd/sys/vxworks/ext/mod.rs @@ -1,18 +1,21 @@ #![stable(feature = "rust1", since = "1.0.0")] #![allow(missing_docs)] -pub mod io; pub mod ffi; pub mod fs; -pub mod raw; +pub mod io; pub mod process; +pub mod raw; #[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")] + 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}; } diff --git a/src/libstd/sys/vxworks/ext/process.rs b/src/libstd/sys/vxworks/ext/process.rs index 4de72fa18167e..e535c4aa122f0 100644 --- a/src/libstd/sys/vxworks/ext/process.rs +++ b/src/libstd/sys/vxworks/ext/process.rs @@ -3,10 +3,10 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::io; -use crate::sys::vxworks::ext::io::{FromRawFd, RawFd, AsRawFd, IntoRawFd}; use crate::process; use crate::sys; -use crate::sys_common::{AsInnerMut, AsInner, FromInner, IntoInner}; +use crate::sys::vxworks::ext::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; +use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; /// Unix-specific extensions to the [`process::Command`] builder. /// @@ -55,7 +55,8 @@ pub trait CommandExt { /// locations may not appear where intended. #[stable(feature = "process_pre_exec", since = "1.34.0")] unsafe fn pre_exec(&mut self, f: F) -> &mut process::Command - where F: FnMut() -> io::Result<()> + Send + Sync + 'static; + where + F: FnMut() -> io::Result<()> + Send + Sync + 'static; /// Schedules a closure to be run just before the `exec` function is /// invoked. @@ -67,7 +68,8 @@ pub trait CommandExt { #[stable(feature = "process_exec", since = "1.15.0")] #[rustc_deprecated(since = "1.37.0", reason = "should be unsafe, use `pre_exec` instead")] fn before_exec(&mut self, f: F) -> &mut process::Command - where F: FnMut() -> io::Result<()> + Send + Sync + 'static + where + F: FnMut() -> io::Result<()> + Send + Sync + 'static, { unsafe { self.pre_exec(f) } } @@ -118,7 +120,8 @@ impl CommandExt for process::Command { } unsafe fn pre_exec(&mut self, f: F) -> &mut process::Command - where F: FnMut() -> io::Result<()> + Send + Sync + 'static + where + F: FnMut() -> io::Result<()> + Send + Sync + 'static, { self.as_inner_mut().pre_exec(Box::new(f)); self diff --git a/src/libstd/sys/vxworks/fast_thread_local.rs b/src/libstd/sys/vxworks/fast_thread_local.rs index 8b55939b8e54a..387ebd0520a71 100644 --- a/src/libstd/sys/vxworks/fast_thread_local.rs +++ b/src/libstd/sys/vxworks/fast_thread_local.rs @@ -1,7 +1,7 @@ #![cfg(target_thread_local)] #![unstable(feature = "thread_local_internals", issue = "0")] -pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { +pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { use crate::sys_common::thread_local::register_dtor_fallback; register_dtor_fallback(t, dtor); } diff --git a/src/libstd/sys/vxworks/fd.rs b/src/libstd/sys/vxworks/fd.rs index db2865d25292c..9b649aa7ef45f 100644 --- a/src/libstd/sys/vxworks/fd.rs +++ b/src/libstd/sys/vxworks/fd.rs @@ -1,7 +1,7 @@ #![unstable(reason = "not public", issue = "0", feature = "fd")] use crate::cmp; -use crate::io::{self, Read, Initializer, IoSlice, IoSliceMut}; +use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read}; use crate::mem; use crate::sys::cvt; use crate::sys_common::AsInner; @@ -25,7 +25,9 @@ impl FileDesc { FileDesc { fd: fd } } - pub fn raw(&self) -> c_int { self.fd } + pub fn raw(&self) -> c_int { + self.fd + } /// Extracts the actual filedescriptor without closing it. pub fn into_raw(self) -> c_int { @@ -36,18 +38,18 @@ impl FileDesc { pub fn read(&self, buf: &mut [u8]) -> io::Result { let ret = cvt(unsafe { - libc::read(self.fd, - buf.as_mut_ptr() as *mut c_void, - cmp::min(buf.len(), max_len())) + libc::read(self.fd, buf.as_mut_ptr() as *mut c_void, cmp::min(buf.len(), max_len())) })?; Ok(ret as usize) } pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { let ret = cvt(unsafe { - libc::readv(self.fd, - bufs.as_ptr() as *const libc::iovec, - cmp::min(bufs.len(), c_int::max_value() as usize) as c_int) + libc::readv( + self.fd, + bufs.as_ptr() as *const libc::iovec, + cmp::min(bufs.len(), c_int::max_value() as usize) as c_int, + ) })?; Ok(ret as usize) } @@ -58,61 +60,69 @@ impl FileDesc { } pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result { - unsafe fn cvt_pread(fd: c_int, buf: *mut c_void, count: usize, offset: i64) - -> io::Result - { + unsafe fn cvt_pread( + fd: c_int, + buf: *mut c_void, + count: usize, + offset: i64, + ) -> io::Result { use libc::pread; cvt(pread(fd, buf, count, offset)) } unsafe { - cvt_pread(self.fd, + cvt_pread( + self.fd, buf.as_mut_ptr() as *mut c_void, cmp::min(buf.len(), max_len()), - offset as i64) + offset as i64, + ) .map(|n| n as usize) } } pub fn write(&self, buf: &[u8]) -> io::Result { let ret = cvt(unsafe { - libc::write(self.fd, - buf.as_ptr() as *const c_void, - cmp::min(buf.len(), max_len())) + libc::write(self.fd, buf.as_ptr() as *const c_void, cmp::min(buf.len(), max_len())) })?; Ok(ret as usize) } pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result { let ret = cvt(unsafe { - libc::writev(self.fd, - bufs.as_ptr() as *const libc::iovec, - cmp::min(bufs.len(), c_int::max_value() as usize) as c_int) + libc::writev( + self.fd, + bufs.as_ptr() as *const libc::iovec, + cmp::min(bufs.len(), c_int::max_value() as usize) as c_int, + ) })?; Ok(ret as usize) } pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result { - unsafe fn cvt_pwrite(fd: c_int, buf: *const c_void, count: usize, offset: i64) - -> io::Result - { + unsafe fn cvt_pwrite( + fd: c_int, + buf: *const c_void, + count: usize, + offset: i64, + ) -> io::Result { use libc::pwrite; cvt(pwrite(fd, buf, count, offset)) } unsafe { - cvt_pwrite(self.fd, + cvt_pwrite( + self.fd, buf.as_ptr() as *const c_void, cmp::min(buf.len(), max_len()), - offset as i64) - .map(|n| n as usize) + offset as i64, + ) + .map(|n| n as usize) } } pub fn get_cloexec(&self) -> io::Result { - unsafe { - Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0) - } + unsafe { Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0) } } pub fn set_cloexec(&self) -> io::Result<()> { @@ -139,23 +149,16 @@ impl FileDesc { pub fn set_nonblocking_pipe(&self, nonblocking: bool) -> io::Result<()> { unsafe { let mut flags = cvt(libc::fcntl(self.fd, libc::F_GETFL, 0))?; - flags = if nonblocking { - flags | libc::O_NONBLOCK - } else { - flags & !libc::O_NONBLOCK - }; + flags = if nonblocking { flags | libc::O_NONBLOCK } else { flags & !libc::O_NONBLOCK }; cvt(libc::fcntl(self.fd, libc::F_SETFL, flags))?; Ok(()) } } - pub fn duplicate(&self) -> io::Result { let fd = self.raw(); match cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) }) { - Ok(newfd) => { - Ok(FileDesc::new(newfd)) - } + Ok(newfd) => Ok(FileDesc::new(newfd)), Err(e) => return Err(e), } } @@ -173,7 +176,9 @@ impl<'a> Read for &'a FileDesc { } impl AsInner for FileDesc { - fn as_inner(&self) -> &c_int { &self.fd } + fn as_inner(&self) -> &c_int { + &self.fd + } } impl Drop for FileDesc { diff --git a/src/libstd/sys/vxworks/fs.rs b/src/libstd/sys/vxworks/fs.rs index adb08d8005ad4..6c2dfb79d6f11 100644 --- a/src/libstd/sys/vxworks/fs.rs +++ b/src/libstd/sys/vxworks/fs.rs @@ -1,19 +1,19 @@ // copies from linuxx -use crate::ffi::{CString, CStr, OsString, OsStr}; -use crate::sys::vxworks::ext::ffi::OsStrExt; +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; use crate::sync::Arc; use crate::sys::fd::FileDesc; use crate::sys::time::SystemTime; +use crate::sys::vxworks::ext::ffi::OsStrExt; +use crate::sys::vxworks::ext::ffi::OsStringExt; use crate::sys::{cvt, cvt_r}; use crate::sys_common::{AsInner, FromInner}; -use libc::{self, c_int, mode_t, stat64, off_t}; -use libc::{ftruncate, lseek, dirent, readdir_r as readdir64_r, open}; -use crate::sys::vxworks::ext::ffi::OsStringExt; +use libc::{self, c_int, mode_t, off_t, stat64}; +use libc::{dirent, ftruncate, lseek, open, readdir_r as readdir64_r}; pub struct File(FileDesc); #[derive(Clone)] @@ -58,16 +58,24 @@ 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, +} 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) } } @@ -85,20 +93,23 @@ impl FileAttr { pub fn accessed(&self) -> io::Result { Ok(SystemTime::from(libc::timespec { - tv_sec: self.stat.st_atime as libc::time_t, - tv_nsec: 0, // hack - a proper fix would be better + tv_sec: self.stat.st_atime as libc::time_t, + tv_nsec: 0, // hack - a proper fix would be better })) } pub fn created(&self) -> io::Result { - 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 for FileAttr { - fn as_inner(&self) -> &stat64 { &self.stat } + fn as_inner(&self) -> &stat64 { + &self.stat + } } impl FilePermissions { @@ -116,15 +127,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 for FilePermissions { @@ -149,10 +170,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 { @@ -163,13 +181,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)); } } } @@ -185,22 +203,20 @@ impl Drop for Dir { impl DirEntry { pub fn path(&self) -> PathBuf { - use crate::sys::vxworks::ext::ffi::OsStrExt; - self.dir.inner.root.join(OsStr::from_bytes(self.name_bytes())) + use crate::sys::vxworks::ext::ffi::OsStrExt; + self.dir.inner.root.join(OsStr::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } - pub fn metadata(&self) -> io::Result { lstat(&self.path()) } pub fn file_type(&self) -> io::Result { lstat(&self.path()).map(|m| m.file_type()) - } pub fn ino(&self) -> u64 { @@ -231,21 +247,35 @@ 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 mode(&mut self, mode: u32) { self.mode = mode as mode_t; } + 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 mode(&mut self, mode: u32) { + self.mode = mode as mode_t; + } fn get_access_mode(&self) -> io::Result { 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)), } } @@ -253,23 +283,25 @@ impl OpenOptions { fn get_creation_mode(&self) -> io::Result { 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, + }) } } @@ -280,21 +312,17 @@ impl File { } pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result { - 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 { - open(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 { open(path.as_ptr(), flags, opts.mode as c_int) })?; Ok(File(FileDesc::new(fd))) } pub fn file_attr(&self) -> io::Result { let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - ::libc::fstat(self.0.raw(), &mut stat) - })?; + cvt(unsafe { ::libc::fstat(self.0.raw(), &mut stat) })?; Ok(FileAttr { stat: stat }) } @@ -306,13 +334,13 @@ impl File { pub fn datasync(&self) -> io::Result<()> { cvt_r(|| unsafe { os_datasync(self.0.raw()) })?; return Ok(()); - unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } //not supported + unsafe fn os_datasync(fd: c_int) -> c_int { + libc::fsync(fd) + } //not supported } pub fn truncate(&self, size: u64) -> io::Result<()> { - return cvt_r(|| unsafe { - ftruncate(self.0.raw(), size as off_t) - }).map(|_| ()); + return cvt_r(|| unsafe { ftruncate(self.0.raw(), size as off_t) }).map(|_| ()); } pub fn read(&self, buf: &mut [u8]) -> io::Result { @@ -339,7 +367,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 { let (whence, pos) = match pos { @@ -357,9 +387,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) })?; @@ -401,7 +435,7 @@ impl FromInner for File { impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn get_path(fd: c_int) -> Option { - let mut buf = vec![0;libc::PATH_MAX as usize]; + let mut buf = vec![0; libc::PATH_MAX as usize]; let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) }; if n == -1 { return None; @@ -419,7 +453,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, } } @@ -445,10 +479,7 @@ pub fn readdir(p: &Path) -> io::Result { 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 }) } } } @@ -480,11 +511,7 @@ pub fn rmdir(p: &Path) -> io::Result<()> { pub fn remove_dir_all(path: &Path) -> io::Result<()> { let filetype = lstat(path)?.file_type(); - if filetype.is_symlink() { - unlink(path) - } else { - remove_dir_all_recursive(path) - } + if filetype.is_symlink() { unlink(path) } else { remove_dir_all_recursive(path) } } fn remove_dir_all_recursive(path: &Path) -> io::Result<()> { @@ -506,11 +533,12 @@ pub fn readlink(p: &Path) -> io::Result { 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(); @@ -542,18 +570,14 @@ pub fn link(src: &Path, dst: &Path) -> io::Result<()> { pub fn stat(p: &Path) -> io::Result { let p = cstr(p)?; let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) - })?; + cvt(unsafe { libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) })?; Ok(FileAttr { stat }) } pub fn lstat(p: &Path) -> io::Result { let p = cstr(p)?; let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - ::libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) - })?; + cvt(unsafe { ::libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) })?; Ok(FileAttr { stat }) } @@ -564,7 +588,7 @@ pub fn canonicalize(p: &Path) -> io::Result { 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 _); @@ -575,8 +599,10 @@ pub fn canonicalize(p: &Path) -> io::Result { pub fn copy(from: &Path, to: &Path) -> io::Result { use crate::fs::File; if !from.is_file() { - return Err(Error::new(ErrorKind::InvalidInput, - "the source path is not an existing regular file")) + return Err(Error::new( + ErrorKind::InvalidInput, + "the source path is not an existing regular file", + )); } let mut reader = File::open(from)?; diff --git a/src/libstd/sys/vxworks/io.rs b/src/libstd/sys/vxworks/io.rs index 8cd11cbf5df4e..f1a2c8446ff8b 100644 --- a/src/libstd/sys/vxworks/io.rs +++ b/src/libstd/sys/vxworks/io.rs @@ -1,7 +1,7 @@ use crate::marker::PhantomData; use crate::slice; -use libc::{iovec, c_void}; +use libc::{c_void, iovec}; #[repr(transparent)] pub struct IoSlice<'a> { @@ -13,10 +13,7 @@ impl<'a> IoSlice<'a> { #[inline] pub fn new(buf: &'a [u8]) -> IoSlice<'a> { IoSlice { - vec: iovec { - iov_base: buf.as_ptr() as *mut u8 as *mut c_void, - iov_len: buf.len() - }, + vec: iovec { iov_base: buf.as_ptr() as *mut u8 as *mut c_void, iov_len: buf.len() }, _p: PhantomData, } } @@ -35,9 +32,7 @@ impl<'a> IoSlice<'a> { #[inline] pub fn as_slice(&self) -> &[u8] { - unsafe { - slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) - } + unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) } } } @@ -50,10 +45,7 @@ impl<'a> IoSliceMut<'a> { #[inline] pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> { IoSliceMut { - vec: iovec { - iov_base: buf.as_mut_ptr() as *mut c_void, - iov_len: buf.len() - }, + vec: iovec { iov_base: buf.as_mut_ptr() as *mut c_void, iov_len: buf.len() }, _p: PhantomData, } } @@ -72,15 +64,11 @@ impl<'a> IoSliceMut<'a> { #[inline] pub fn as_slice(&self) -> &[u8] { - unsafe { - slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) - } + unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) } } #[inline] pub fn as_mut_slice(&mut self) -> &mut [u8] { - unsafe { - slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len) - } + unsafe { slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len) } } } diff --git a/src/libstd/sys/vxworks/memchr.rs b/src/libstd/sys/vxworks/memchr.rs index b5b4e6d9c134e..928100c92ffad 100644 --- a/src/libstd/sys/vxworks/memchr.rs +++ b/src/libstd/sys/vxworks/memchr.rs @@ -6,13 +6,10 @@ pub fn memchr(needle: u8, haystack: &[u8]) -> Option { libc::memchr( haystack.as_ptr() as *const libc::c_void, needle as libc::c_int, - haystack.len()) + haystack.len(), + ) }; - if p.is_null() { - None - } else { - Some(p as usize - (haystack.as_ptr() as usize)) - } + if p.is_null() { None } else { Some(p as usize - (haystack.as_ptr() as usize)) } } pub fn memrchr(needle: u8, haystack: &[u8]) -> Option { diff --git a/src/libstd/sys/vxworks/mod.rs b/src/libstd/sys/vxworks/mod.rs index 1eff4fbcd83b7..f102e4d6adf59 100644 --- a/src/libstd/sys/vxworks/mod.rs +++ b/src/libstd/sys/vxworks/mod.rs @@ -3,8 +3,8 @@ use crate::io::ErrorKind; -pub use crate::os::vxworks as platform; pub use self::rand::hashmap_random_keys; +pub use crate::os::vxworks as platform; pub use libc::strlen; pub mod alloc; @@ -16,8 +16,8 @@ pub mod ext; pub mod fast_thread_local; pub mod fd; pub mod fs; -pub mod memchr; pub mod io; +pub mod memchr; pub mod mutex; pub mod net; pub mod os; @@ -27,10 +27,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; @@ -47,7 +47,7 @@ pub fn init() { reset_sigpipe(); } - unsafe fn reset_sigpipe() { } + unsafe fn reset_sigpipe() {} } pub use libc::signal; @@ -71,8 +71,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, } @@ -94,16 +93,13 @@ macro_rules! impl_is_minus_one { impl_is_minus_one! { i8 i16 i32 i64 isize } pub fn cvt(t: T) -> crate::io::Result { - 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(mut f: F) -> crate::io::Result - where T: IsMinusOne, - F: FnMut() -> T +where + T: IsMinusOne, + F: FnMut() -> T, { loop { match cvt(f()) { diff --git a/src/libstd/sys/vxworks/mutex.rs b/src/libstd/sys/vxworks/mutex.rs index b43af8fdcaaa1..b38375a2e03c5 100644 --- a/src/libstd/sys/vxworks/mutex.rs +++ b/src/libstd/sys/vxworks/mutex.rs @@ -1,7 +1,9 @@ use crate::cell::UnsafeCell; use crate::mem::MaybeUninit; -pub struct Mutex { inner: UnsafeCell } +pub struct Mutex { + inner: UnsafeCell, +} #[inline] pub unsafe fn raw(m: &Mutex) -> *mut libc::pthread_mutex_t { @@ -82,7 +84,9 @@ impl Mutex { } } -pub struct ReentrantMutex { inner: UnsafeCell } +pub struct ReentrantMutex { + inner: UnsafeCell, +} unsafe impl Send for ReentrantMutex {} unsafe impl Sync for ReentrantMutex {} @@ -96,8 +100,8 @@ impl ReentrantMutex { let mut attr = MaybeUninit::::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/vxworks/net.rs b/src/libstd/sys/vxworks/net.rs index 56962e11dcf95..85f5fcff2c259 100644 --- a/src/libstd/sys/vxworks/net.rs +++ b/src/libstd/sys/vxworks/net.rs @@ -1,15 +1,15 @@ +use crate::cmp; use crate::ffi::CStr; use crate::io; use crate::io::{IoSlice, IoSliceMut}; -use libc::{self, c_int, c_void, size_t, sockaddr, socklen_t, EAI_SYSTEM, MSG_PEEK}; use crate::mem; -use crate::net::{SocketAddr, Shutdown}; +use crate::net::{Shutdown, SocketAddr}; use crate::str; use crate::sys::fd::FileDesc; -use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr}; +use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::{Duration, Instant}; -use crate::cmp; +use libc::{self, c_int, c_void, size_t, sockaddr, socklen_t, EAI_SYSTEM, MSG_PEEK}; pub use crate::sys::{cvt, cvt_r}; @@ -18,7 +18,6 @@ pub extern crate libc as netc; pub type wrlen_t = size_t; - const SOCK_CLOEXEC: c_int = 0; const SO_NOSIGPIPE: c_int = 0; @@ -28,23 +27,23 @@ pub fn init() {} pub fn cvt_gai(err: c_int) -> io::Result<()> { if err == 0 { - return Ok(()) + return Ok(()); } // We may need to trigger a glibc workaround. See on_resolver_failure() for details. on_resolver_failure(); if err == EAI_SYSTEM { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } let detail = unsafe { - str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap() - .to_owned() + str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap().to_owned() }; - Err(io::Error::new(io::ErrorKind::Other, - &format!("failed to lookup address information: {}", - detail)[..])) + Err(io::Error::new( + io::ErrorKind::Other, + &format!("failed to lookup address information: {}", detail)[..], + )) } impl Socket { @@ -67,7 +66,7 @@ impl Socket { } pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> { - unimplemented!(); + unimplemented!(); } pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> { @@ -85,15 +84,13 @@ impl Socket { Err(e) => return Err(e), } - let mut pollfd = libc::pollfd { - fd: self.0.raw(), - events: libc::POLLOUT, - revents: 0, - }; + let mut pollfd = libc::pollfd { fd: self.0.raw(), events: libc::POLLOUT, revents: 0 }; if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); } let start = Instant::now(); @@ -105,7 +102,8 @@ impl Socket { } let timeout = timeout - elapsed; - let mut timeout = timeout.as_secs() + let mut timeout = timeout + .as_secs() .saturating_mul(1_000) .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000); if timeout == 0 { @@ -126,10 +124,9 @@ impl Socket { // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look // for POLLHUP rather than read readiness if pollfd.revents & libc::POLLHUP != 0 { - let e = self.take_error()? - .unwrap_or_else(|| { - io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP") - }); + let e = self.take_error()?.unwrap_or_else(|| { + io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP") + }); return Err(e); } @@ -139,11 +136,8 @@ impl Socket { } } - pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) - -> io::Result { - let fd = cvt_r(|| unsafe { - libc::accept(self.0.raw(), storage, len) - })?; + pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result { + let fd = cvt_r(|| unsafe { libc::accept(self.0.raw(), storage, len) })?; let fd = FileDesc::new(fd); fd.set_cloexec()?; Ok(Socket(fd)) @@ -155,10 +149,7 @@ impl Socket { fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result { let ret = cvt(unsafe { - libc::recv(self.0.raw(), - buf.as_mut_ptr() as *mut c_void, - buf.len(), - flags) + libc::recv(self.0.raw(), buf.as_mut_ptr() as *mut c_void, buf.len(), flags) })?; Ok(ret as usize) } @@ -175,18 +166,23 @@ impl Socket { self.0.read_vectored(bufs) } - fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int) - -> io::Result<(usize, SocketAddr)> { + fn recv_from_with_flags( + &self, + buf: &mut [u8], + flags: c_int, + ) -> io::Result<(usize, SocketAddr)> { let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t; let n = cvt(unsafe { - libc::recvfrom(self.0.raw(), - buf.as_mut_ptr() as *mut c_void, - buf.len(), - flags, - &mut storage as *mut _ as *mut _, - &mut addrlen) + libc::recvfrom( + self.0.raw(), + buf.as_mut_ptr() as *mut c_void, + buf.len(), + flags, + &mut storage as *mut _ as *mut _, + &mut addrlen, + ) })?; Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?)) } @@ -211,8 +207,10 @@ impl Socket { let timeout = match dur { Some(dur) => { if dur.as_secs() == 0 && dur.subsec_nanos() == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); } let secs = if dur.as_secs() > libc::time_t::max_value() as u64 { @@ -229,12 +227,7 @@ impl Socket { } timeout } - None => { - libc::timeval { - tv_sec: 0, - tv_usec: 0, - } - } + None => libc::timeval { tv_sec: 0, tv_usec: 0 }, }; setsockopt(self, libc::SOL_SOCKET, kind, timeout) } @@ -276,24 +269,26 @@ impl Socket { pub fn take_error(&self) -> io::Result> { let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?; - if raw == 0 { - Ok(None) - } else { - Ok(Some(io::Error::from_raw_os_error(raw as i32))) - } + if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) } } } impl AsInner for Socket { - fn as_inner(&self) -> &c_int { self.0.as_inner() } + fn as_inner(&self) -> &c_int { + self.0.as_inner() + } } impl FromInner for Socket { - fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) } + fn from_inner(fd: c_int) -> Socket { + Socket(FileDesc::new(fd)) + } } impl IntoInner for Socket { - fn into_inner(self) -> c_int { self.0.into_raw() } + fn into_inner(self) -> c_int { + self.0.into_raw() + } } // In versions of glibc prior to 2.26, there's a bug where the DNS resolver @@ -314,7 +309,7 @@ impl IntoInner for Socket { // believe it's thread-safe). #[cfg(target_env = "gnu")] fn on_resolver_failure() { -/* + /* use crate::sys; // If the version fails to parse, we treat it the same as "not glibc". diff --git a/src/libstd/sys/vxworks/path.rs b/src/libstd/sys/vxworks/path.rs index 7a18395610785..840a7ae042625 100644 --- a/src/libstd/sys/vxworks/path.rs +++ b/src/libstd/sys/vxworks/path.rs @@ -1,5 +1,5 @@ -use crate::path::Prefix; use crate::ffi::OsStr; +use crate::path::Prefix; #[inline] pub fn is_sep_byte(b: u8) -> bool { diff --git a/src/libstd/sys/vxworks/pipe.rs b/src/libstd/sys/vxworks/pipe.rs index e09dbe6e99ba8..b72a655455157 100644 --- a/src/libstd/sys/vxworks/pipe.rs +++ b/src/libstd/sys/vxworks/pipe.rs @@ -1,9 +1,9 @@ use crate::io::{self, IoSlice, IoSliceMut}; -use libc::{self /*, c_int apparently not used? */}; use crate::mem; -use crate::sync::atomic::{AtomicBool}; +use crate::sync::atomic::AtomicBool; use crate::sys::fd::FileDesc; use crate::sys::{cvt, cvt_r}; +use libc::{self /*, c_int apparently not used? */}; pub struct AnonPipe(FileDesc); @@ -25,29 +25,29 @@ impl AnonPipe { self.0.read(buf) } pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { - self.0.read_vectored(bufs) - } + self.0.read_vectored(bufs) + } pub fn write(&self, buf: &[u8]) -> io::Result { self.0.write(buf) } - pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result { - self.0.write_vectored(bufs) - } + pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result { + self.0.write_vectored(bufs) + } - pub fn fd(&self) -> &FileDesc { &self.0 } - pub fn into_fd(self) -> FileDesc { self.0 } + pub fn fd(&self) -> &FileDesc { + &self.0 + } + pub fn into_fd(self) -> FileDesc { + self.0 + } pub fn diverge(&self) -> ! { panic!() - } + } } -pub fn read2(p1: AnonPipe, - v1: &mut Vec, - p2: AnonPipe, - v2: &mut Vec) -> io::Result<()> { - +pub fn read2(p1: AnonPipe, v1: &mut Vec, p2: AnonPipe, v2: &mut Vec) -> io::Result<()> { // Set both pipes into nonblocking mode as we're gonna be reading from both // in the `select` loop below, and we wouldn't want one to block the other! let p1 = p1.into_fd(); @@ -83,8 +83,9 @@ pub fn read2(p1: AnonPipe, match fd.read_to_end(dst) { Ok(_) => Ok(true), Err(e) => { - if e.raw_os_error() == Some(libc::EWOULDBLOCK) || - e.raw_os_error() == Some(libc::EAGAIN) { + if e.raw_os_error() == Some(libc::EWOULDBLOCK) + || e.raw_os_error() == Some(libc::EAGAIN) + { Ok(false) } else { Err(e) diff --git a/src/libstd/sys/vxworks/process/mod.rs b/src/libstd/sys/vxworks/process/mod.rs index 3ecbe4e3b28ba..c59782ff44b0b 100644 --- a/src/libstd/sys/vxworks/process/mod.rs +++ b/src/libstd/sys/vxworks/process/mod.rs @@ -1,4 +1,4 @@ -pub use self::process_common::{Command, ExitStatus, ExitCode, Stdio, StdioPipes}; +pub use self::process_common::{Command, ExitCode, ExitStatus, Stdio, StdioPipes}; pub use self::process_inner::Process; pub use crate::ffi::OsString as EnvKey; diff --git a/src/libstd/sys/vxworks/process/process_common.rs b/src/libstd/sys/vxworks/process/process_common.rs index 13648abd1e447..a8139a27537a9 100644 --- a/src/libstd/sys/vxworks/process/process_common.rs +++ b/src/libstd/sys/vxworks/process/process_common.rs @@ -1,6 +1,7 @@ use crate::os::unix::prelude::*; -use crate::ffi::{OsString, OsStr, CString, CStr}; +use crate::collections::BTreeMap; +use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; use crate::io; use crate::ptr; @@ -8,9 +9,8 @@ use crate::sys::fd::FileDesc; use crate::sys::fs::{File, OpenOptions}; use crate::sys::pipe::{self, AnonPipe}; use crate::sys_common::process::CommandEnv; -use crate::collections::BTreeMap; -use libc::{c_int, gid_t, uid_t, c_char, EXIT_SUCCESS, EXIT_FAILURE}; +use libc::{c_char, c_int, gid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS}; //////////////////////////////////////////////////////////////////////////////// // Command @@ -150,10 +150,7 @@ impl Command { &mut self.closures } - pub unsafe fn pre_exec( - &mut self, - _f: Box io::Result<()> + Send + Sync>, - ) { + pub unsafe fn pre_exec(&mut self, _f: Box io::Result<()> + Send + Sync>) { // Fork() is not supported in vxWorks so no way to run the closure in the new procecss. unimplemented!(); } @@ -183,26 +180,21 @@ impl Command { self.env.have_changed_path() } - pub fn setup_io(&self, default: Stdio, needs_stdin: bool) - -> io::Result<(StdioPipes, ChildPipes)> { + pub fn setup_io( + &self, + default: Stdio, + needs_stdin: bool, + ) -> io::Result<(StdioPipes, ChildPipes)> { let null = Stdio::Null; - let default_stdin = if needs_stdin {&default} else {&null}; + let default_stdin = if needs_stdin { &default } else { &null }; let stdin = self.stdin.as_ref().unwrap_or(default_stdin); let stdout = self.stdout.as_ref().unwrap_or(&default); let stderr = self.stderr.as_ref().unwrap_or(&default); let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?; let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?; let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?; - let ours = StdioPipes { - stdin: our_stdin, - stdout: our_stdout, - stderr: our_stderr, - }; - let theirs = ChildPipes { - stdin: their_stdin, - stdout: their_stdout, - stderr: their_stderr, - }; + let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr }; + let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr }; Ok((ours, theirs)) } } @@ -217,21 +209,21 @@ fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString { // Helper type to manage ownership of the strings within a C-style array. pub struct CStringArray { items: Vec, - ptrs: Vec<*const c_char> + ptrs: Vec<*const c_char>, } impl CStringArray { pub fn with_capacity(capacity: usize) -> Self { let mut result = CStringArray { items: Vec::with_capacity(capacity), - ptrs: Vec::with_capacity(capacity+1) + ptrs: Vec::with_capacity(capacity + 1), }; result.ptrs.push(ptr::null()); result } pub fn push(&mut self, item: CString) { let l = self.ptrs.len(); - self.ptrs[l-1] = item.as_ptr(); + self.ptrs[l - 1] = item.as_ptr(); self.ptrs.push(ptr::null()); self.items.push(item); } @@ -262,12 +254,9 @@ fn construct_envp(env: BTreeMap, saw_nul: &mut bool) -> CStr } impl Stdio { - pub fn to_child_stdio(&self, readable: bool) - -> io::Result<(ChildStdio, Option)> { + pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option)> { match *self { - Stdio::Inherit => { - Ok((ChildStdio::Inherit, None)) - }, + Stdio::Inherit => Ok((ChildStdio::Inherit, None)), // Make sure that the source descriptors are not an stdio // descriptor, otherwise the order which we set the child's @@ -286,11 +275,7 @@ impl Stdio { Stdio::MakePipe => { let (reader, writer) = pipe::anon_pipe()?; - let (ours, theirs) = if readable { - (writer, reader) - } else { - (reader, writer) - }; + let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) }; Ok((ChildStdio::Owned(theirs.into_fd()), Some(ours))) } @@ -298,9 +283,7 @@ impl Stdio { let mut opts = OpenOptions::new(); opts.read(readable); opts.write(!readable); - let path = unsafe { - CStr::from_ptr("/null\0".as_ptr() as *const _) - }; + let path = unsafe { CStr::from_ptr("/null\0".as_ptr() as *const _) }; let fd = File::open_c(&path, &opts)?; Ok((ChildStdio::Owned(fd.into_fd()), None)) } @@ -350,7 +333,8 @@ impl ExitStatus { } fn exited(&self) -> bool { - /*unsafe*/ { libc::WIFEXITED(self.0) } + /*unsafe*/ + { libc::WIFEXITED(self.0) } } pub fn success(&self) -> bool { diff --git a/src/libstd/sys/vxworks/rand.rs b/src/libstd/sys/vxworks/rand.rs index c22880db2bf03..87ebd2c9593fc 100644 --- a/src/libstd/sys/vxworks/rand.rs +++ b/src/libstd/sys/vxworks/rand.rs @@ -4,17 +4,16 @@ use crate::slice; pub fn hashmap_random_keys() -> (u64, u64) { let mut v = (0, 0); unsafe { - let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8, - mem::size_of_val(&v)); + let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8, mem::size_of_val(&v)); imp::fill_bytes(view); } - return v + return v; } mod imp { - use libc; use crate::io; use core::sync::atomic::{AtomicBool, Ordering::Relaxed}; + use libc; pub fn fill_bytes(v: &mut [u8]) { static RNG_INIT: AtomicBool = AtomicBool::new(false); diff --git a/src/libstd/sys/vxworks/rwlock.rs b/src/libstd/sys/vxworks/rwlock.rs index 19b123f2b6131..fd2e1a6e7bcfb 100644 --- a/src/libstd/sys/vxworks/rwlock.rs +++ b/src/libstd/sys/vxworks/rwlock.rs @@ -1,6 +1,6 @@ -use libc; use crate::cell::UnsafeCell; use crate::sync::atomic::{AtomicUsize, Ordering}; +use libc; pub struct RWLock { inner: UnsafeCell, @@ -29,7 +29,7 @@ impl RWLock { if r == 0 { self.raw_unlock(); } - panic!("rwlock read lock would result in deadlock"); + panic!("rwlock read lock would result in deadlock"); } else { debug_assert_eq!(r, 0); self.num_readers.fetch_add(1, Ordering::Relaxed); @@ -57,12 +57,14 @@ 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(); } - panic!("rwlock write lock would result in deadlock"); + panic!("rwlock write lock would result in deadlock"); } else { debug_assert_eq!(r, 0); } @@ -80,8 +82,8 @@ impl RWLock { *self.write_locked.get() = true; true } - } else { - false + } else { + false } } @@ -98,7 +100,7 @@ impl RWLock { self.raw_unlock(); } - #[inline] + #[inline] pub unsafe fn write_unlock(&self) { debug_assert_eq!(self.num_readers.load(Ordering::Relaxed), 0); debug_assert!(*self.write_locked.get()); diff --git a/src/libstd/sys/vxworks/stack_overflow.rs b/src/libstd/sys/vxworks/stack_overflow.rs index 08e7b310ca1b8..7b58c83193bf3 100644 --- a/src/libstd/sys/vxworks/stack_overflow.rs +++ b/src/libstd/sys/vxworks/stack_overflow.rs @@ -1,12 +1,12 @@ #![cfg_attr(test, allow(dead_code))] -use self::imp::{make_handler, drop_handler}; +use self::imp::{drop_handler, make_handler}; pub use self::imp::cleanup; pub use self::imp::init; pub struct Handler { - _data: *mut libc::c_void + _data: *mut libc::c_void, } impl Handler { @@ -26,16 +26,13 @@ impl Drop for Handler { mod imp { use crate::ptr; - pub unsafe fn init() { - } + pub unsafe fn init() {} - pub unsafe fn cleanup() { - } + pub unsafe fn cleanup() {} pub unsafe fn make_handler() -> super::Handler { super::Handler { _data: ptr::null_mut() } } - pub unsafe fn drop_handler(_handler: &mut super::Handler) { - } + pub unsafe fn drop_handler(_handler: &mut super::Handler) {} } diff --git a/src/libstd/sys/vxworks/stdio.rs b/src/libstd/sys/vxworks/stdio.rs index 35f163bbdb10f..622444ccafd3c 100644 --- a/src/libstd/sys/vxworks/stdio.rs +++ b/src/libstd/sys/vxworks/stdio.rs @@ -6,7 +6,9 @@ pub struct Stdout(()); pub struct Stderr(()); impl Stdin { - pub fn new() -> io::Result { Ok(Stdin(())) } + pub fn new() -> io::Result { + Ok(Stdin(())) + } } impl io::Read for Stdin { @@ -19,7 +21,9 @@ impl io::Read for Stdin { } impl Stdout { - pub fn new() -> io::Result { Ok(Stdout(())) } + pub fn new() -> io::Result { + Ok(Stdout(())) + } } impl io::Write for Stdout { @@ -36,7 +40,9 @@ impl io::Write for Stdout { } impl Stderr { - pub fn new() -> io::Result { Ok(Stderr(())) } + pub fn new() -> io::Result { + Ok(Stderr(())) + } } impl io::Write for Stderr { diff --git a/src/libstd/sys/vxworks/thread.rs b/src/libstd/sys/vxworks/thread.rs index e4396b05c0065..e0d104b5f3ec9 100644 --- a/src/libstd/sys/vxworks/thread.rs +++ b/src/libstd/sys/vxworks/thread.rs @@ -21,15 +21,16 @@ unsafe impl Sync for Thread {} // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc, // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS. -unsafe fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t, - stack_size: libc::size_t) -> libc::c_int { +unsafe fn pthread_attr_setstacksize( + attr: *mut libc::pthread_attr_t, + stack_size: libc::size_t, +) -> libc::c_int { libc::pthread_attr_setstacksize(attr, stack_size) } impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(stack: usize, p: Box) - -> io::Result { + pub unsafe fn new(stack: usize, p: Box) -> io::Result { let p = box p; let mut native: libc::pthread_t = mem::zeroed(); let mut attr: libc::pthread_attr_t = mem::zeroed(); @@ -37,8 +38,7 @@ impl Thread { let stack_size = cmp::max(stack, min_stack_size(&attr)); - match pthread_attr_setstacksize(&mut attr, - stack_size) { + match pthread_attr_setstacksize(&mut attr, stack_size) { 0 => {} n => { assert_eq!(n, libc::EINVAL); @@ -47,15 +47,13 @@ impl Thread { // >= PTHREAD_STACK_MIN, it must be an alignment issue. // Round up to the nearest page and try again. let page_size = os::page_size(); - let stack_size = (stack_size + page_size - 1) & - (-(page_size as isize - 1) as usize - 1); - assert_eq!(libc::pthread_attr_setstacksize(&mut attr, - stack_size), 0); + let stack_size = + (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1); + assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0); } }; - let ret = libc::pthread_create(&mut native, &attr, thread_start, - &*p as *const _ as *mut _); + let ret = libc::pthread_create(&mut native, &attr, thread_start, &*p as *const _ as *mut _); assert_eq!(libc::pthread_attr_destroy(&mut attr), 0); return if ret != 0 { @@ -65,8 +63,10 @@ impl Thread { Ok(Thread { id: native }) }; - extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void { - unsafe { start_thread(main as *mut u8); } + extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void { + unsafe { + start_thread(main as *mut u8); + } ptr::null_mut() } } @@ -108,12 +108,13 @@ impl Thread { unsafe { let ret = libc::pthread_join(self.id, ptr::null_mut()); mem::forget(self); - assert!(ret == 0, - "failed to join thread: {}", io::Error::from_raw_os_error(ret)); + assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); } } - pub fn id(&self) -> libc::pthread_t { self.id } + pub fn id(&self) -> libc::pthread_t { + self.id + } pub fn into_id(self) -> libc::pthread_t { let id = self.id; @@ -133,8 +134,12 @@ impl Drop for Thread { pub mod guard { use crate::ops::Range; pub type Guard = Range; - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + pub unsafe fn current() -> Option { + None + } + pub unsafe fn init() -> Option { + None + } pub unsafe fn deinit() {} } diff --git a/src/libstd/sys/vxworks/thread_local.rs b/src/libstd/sys/vxworks/thread_local.rs index ac615b76b3624..2c5b94b1e61e5 100644 --- a/src/libstd/sys/vxworks/thread_local.rs +++ b/src/libstd/sys/vxworks/thread_local.rs @@ -5,7 +5,7 @@ use crate::mem; pub type Key = libc::pthread_key_t; #[inline] -pub unsafe fn create(dtor: Option) -> Key { +pub unsafe fn create(dtor: Option) -> Key { let mut key = 0; assert_eq!(libc::pthread_key_create(&mut key, mem::transmute(dtor)), 0); key diff --git a/src/libstd/sys/vxworks/time.rs b/src/libstd/sys/vxworks/time.rs index cb3a4241ea601..8ebbf89213f32 100644 --- a/src/libstd/sys/vxworks/time.rs +++ b/src/libstd/sys/vxworks/time.rs @@ -1,7 +1,7 @@ use crate::cmp::Ordering; -use libc; use crate::time::Duration; use ::core::hash::{Hash, Hasher}; +use libc; pub use self::inner::{Instant, SystemTime, UNIX_EPOCH}; use crate::convert::TryInto; @@ -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 { 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) - } 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 - 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, + ) + }) } else { match other.sub_timespec(self) { Ok(d) => Err(d), @@ -51,12 +52,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 { @@ -72,12 +68,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 _ } }) } } @@ -104,16 +95,16 @@ impl Ord for Timespec { } impl Hash for Timespec { - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.t.tv_sec.hash(state); self.t.tv_nsec.hash(state); } } mod inner { use crate::fmt; - use libc; use crate::sys::cvt; use crate::time::Duration; + use libc; use super::Timespec; @@ -127,14 +118,8 @@ mod inner { t: Timespec, } - pub const UNIX_EPOCH: SystemTime = SystemTime { - t: Timespec { - t: libc::timespec { - tv_sec: 0, - tv_nsec: 0, - }, - }, - }; + pub const UNIX_EPOCH: SystemTime = + SystemTime { t: Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } } }; impl Instant { pub fn now() -> Instant { @@ -142,9 +127,7 @@ mod inner { } pub const fn zero() -> Instant { - Instant { - t: Timespec::zero(), - } + Instant { t: Timespec::zero() } } pub fn actually_monotonic() -> bool { @@ -167,9 +150,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() } } @@ -178,8 +161,7 @@ mod inner { SystemTime { t: now(libc::CLOCK_REALTIME) } } - pub fn sub_time(&self, other: &SystemTime) - -> Result { + pub fn sub_time(&self, other: &SystemTime) -> Result { self.t.sub_timespec(&other.t) } @@ -201,24 +183,17 @@ 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() } } pub type clock_t = libc::c_int; 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 } } diff --git a/src/libstd/sys/vxworks/weak.rs b/src/libstd/sys/vxworks/weak.rs index 284f21164239a..4c6fddefd3f84 100644 --- a/src/libstd/sys/vxworks/weak.rs +++ b/src/libstd/sys/vxworks/weak.rs @@ -29,11 +29,7 @@ pub struct Weak { impl Weak { pub const fn new(name: &'static str) -> Weak { - Weak { - name, - addr: AtomicUsize::new(1), - _marker: marker::PhantomData, - } + Weak { name, addr: AtomicUsize::new(1), _marker: marker::PhantomData } } pub fn get(&self) -> Option { @@ -56,5 +52,5 @@ unsafe fn fetch(name: &str) -> usize { Err(..) => return 0, }; assert!(false, "FIXME: fetch"); - libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) as usize + libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) as usize } diff --git a/src/libstd/sys/wasi/alloc.rs b/src/libstd/sys/wasi/alloc.rs index c8529937bbde0..e9760d050e105 100644 --- a/src/libstd/sys/wasi/alloc.rs +++ b/src/libstd/sys/wasi/alloc.rs @@ -1,6 +1,6 @@ use crate::alloc::{GlobalAlloc, Layout, System}; use crate::ptr; -use crate::sys_common::alloc::{MIN_ALIGN, realloc_fallback}; +use crate::sys_common::alloc::{realloc_fallback, MIN_ALIGN}; use libc; #[stable(feature = "alloc_system_type", since = "1.28.0")] diff --git a/src/libstd/sys/wasi/ext/mod.rs b/src/libstd/sys/wasi/ext/mod.rs index 1c24b244b8cd0..5f8b1cbfa0b53 100644 --- a/src/libstd/sys/wasi/ext/mod.rs +++ b/src/libstd/sys/wasi/ext/mod.rs @@ -7,12 +7,16 @@ pub mod io; /// 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 crate::sys::ext::ffi::{OsStringExt, OsStrExt}; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] - pub use crate::sys::ext::fs::{FileExt, DirEntryExt, MetadataExt, OpenOptionsExt}; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use crate::sys::ext::ffi::{OsStrExt, OsStringExt}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] pub use crate::sys::ext::fs::FileTypeExt; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] - pub use crate::sys::ext::io::{AsRawFd, IntoRawFd, FromRawFd}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use crate::sys::ext::fs::{DirEntryExt, FileExt, MetadataExt, OpenOptionsExt}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use crate::sys::ext::io::{AsRawFd, FromRawFd, IntoRawFd}; } diff --git a/src/libstd/sys/wasi/net.rs b/src/libstd/sys/wasi/net.rs index 80f633a8e1f2b..8a69028ff1dcf 100644 --- a/src/libstd/sys/wasi/net.rs +++ b/src/libstd/sys/wasi/net.rs @@ -1,11 +1,11 @@ +use crate::convert::TryFrom; use crate::fmt; use crate::io::{self, IoSlice, IoSliceMut}; -use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr}; -use crate::time::Duration; +use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; +use crate::sys::fd::WasiFd; use crate::sys::{unsupported, Void}; -use crate::convert::TryFrom; -use crate::sys::fd::{WasiFd}; use crate::sys_common::FromInner; +use crate::time::Duration; pub struct TcpStream { fd: WasiFd, @@ -107,24 +107,18 @@ impl TcpStream { impl FromInner for TcpStream { fn from_inner(fd: u32) -> TcpStream { - unsafe { - TcpStream { - fd: WasiFd::from_raw(fd), - } - } + unsafe { TcpStream { fd: WasiFd::from_raw(fd) } } } } impl fmt::Debug for TcpStream { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("TcpStream") - .field("fd", &self.fd.as_raw()) - .finish() + f.debug_struct("TcpStream").field("fd", &self.fd.as_raw()).finish() } } pub struct TcpListener { - fd: WasiFd + fd: WasiFd, } impl TcpListener { @@ -179,19 +173,13 @@ impl TcpListener { impl FromInner for TcpListener { fn from_inner(fd: u32) -> TcpListener { - unsafe { - TcpListener { - fd: WasiFd::from_raw(fd), - } - } + unsafe { TcpListener { fd: WasiFd::from_raw(fd) } } } } impl fmt::Debug for TcpListener { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("TcpListener") - .field("fd", &self.fd.as_raw()) - .finish() + f.debug_struct("TcpListener").field("fd", &self.fd.as_raw()).finish() } } @@ -276,23 +264,19 @@ impl UdpSocket { unsupported() } - pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) - -> io::Result<()> { + pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { unsupported() } - pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) - -> io::Result<()> { + pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { unsupported() } - pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) - -> io::Result<()> { + pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { unsupported() } - pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) - -> io::Result<()> { + pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { unsupported() } @@ -339,19 +323,13 @@ impl UdpSocket { impl FromInner for UdpSocket { fn from_inner(fd: u32) -> UdpSocket { - unsafe { - UdpSocket { - fd: WasiFd::from_raw(fd), - } - } + unsafe { UdpSocket { fd: WasiFd::from_raw(fd) } } } } impl fmt::Debug for UdpSocket { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("UdpSocket") - .field("fd", &self.fd.as_raw()) - .finish() + f.debug_struct("UdpSocket").field("fd", &self.fd.as_raw()).finish() } } @@ -419,8 +397,7 @@ pub mod netc { } #[derive(Copy, Clone)] - pub struct sockaddr { - } + pub struct sockaddr {} pub type socklen_t = usize; } diff --git a/src/libstd/sys/wasi/os.rs b/src/libstd/sys/wasi/os.rs index feee840782550..338fbe8976514 100644 --- a/src/libstd/sys/wasi/os.rs +++ b/src/libstd/sys/wasi/os.rs @@ -1,6 +1,6 @@ use crate::any::Any; use crate::error::Error as StdError; -use crate::ffi::{OsString, OsStr, CString, CStr}; +use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; use crate::io; use crate::marker::PhantomData; @@ -19,7 +19,7 @@ pub unsafe fn env_lock() -> impl Any { } pub fn errno() -> i32 { - extern { + extern "C" { #[thread_local] static errno: libc::c_int; } @@ -64,7 +64,9 @@ impl<'a> Iterator for SplitPaths<'a> { pub struct JoinPathsError; pub fn join_paths(_paths: I) -> Result - where I: Iterator, T: AsRef +where + I: Iterator, + T: AsRef, { Err(JoinPathsError) } @@ -91,11 +93,14 @@ pub struct Env { impl Iterator for Env { type Item = (OsString, OsString); - fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() } - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn next(&mut self) -> Option<(OsString, OsString)> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } } - pub fn env() -> Env { unsafe { let _guard = env_lock(); @@ -107,10 +112,7 @@ pub fn env() -> Env { } environ = environ.offset(1); } - return Env { - iter: result.into_iter(), - _dont_send_or_sync_me: PhantomData, - } + return Env { iter: result.into_iter(), _dont_send_or_sync_me: PhantomData }; } // See src/libstd/sys/unix/os.rs, same as that @@ -119,10 +121,12 @@ pub fn env() -> Env { return None; } let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1); - pos.map(|p| ( - OsStringExt::from_vec(input[..p].to_vec()), - OsStringExt::from_vec(input[p+1..].to_vec()), - )) + pos.map(|p| { + ( + OsStringExt::from_vec(input[..p].to_vec()), + OsStringExt::from_vec(input[p + 1..].to_vec()), + ) + }) } } @@ -168,9 +172,7 @@ pub fn home_dir() -> Option { } pub fn exit(code: i32) -> ! { - unsafe { - libc::exit(code) - } + unsafe { libc::exit(code) } } pub fn getpid() -> u32 { @@ -193,9 +195,5 @@ macro_rules! impl_is_minus_one { impl_is_minus_one! { i8 i16 i32 i64 isize } fn cvt(t: T) -> io::Result { - if t.is_minus_one() { - Err(io::Error::last_os_error()) - } else { - Ok(t) - } + if t.is_minus_one() { Err(io::Error::last_os_error()) } else { Ok(t) } } diff --git a/src/libstd/sys/wasi/path.rs b/src/libstd/sys/wasi/path.rs index 7a18395610785..840a7ae042625 100644 --- a/src/libstd/sys/wasi/path.rs +++ b/src/libstd/sys/wasi/path.rs @@ -1,5 +1,5 @@ -use crate::path::Prefix; use crate::ffi::OsStr; +use crate::path::Prefix; #[inline] pub fn is_sep_byte(b: u8) -> bool { diff --git a/src/libstd/sys/wasi/pipe.rs b/src/libstd/sys/wasi/pipe.rs index 9f07f054362fe..fb14dc5910181 100644 --- a/src/libstd/sys/wasi/pipe.rs +++ b/src/libstd/sys/wasi/pipe.rs @@ -25,9 +25,6 @@ impl AnonPipe { } } -pub fn read2(p1: AnonPipe, - _v1: &mut Vec, - _p2: AnonPipe, - _v2: &mut Vec) -> io::Result<()> { +pub fn read2(p1: AnonPipe, _v1: &mut Vec, _p2: AnonPipe, _v2: &mut Vec) -> io::Result<()> { match p1.0 {} } diff --git a/src/libstd/sys/wasi/process.rs b/src/libstd/sys/wasi/process.rs index 1c4d028b7618b..7156c9ab92f2b 100644 --- a/src/libstd/sys/wasi/process.rs +++ b/src/libstd/sys/wasi/process.rs @@ -13,7 +13,7 @@ pub use crate::ffi::OsString as EnvKey; //////////////////////////////////////////////////////////////////////////////// pub struct Command { - env: CommandEnv + env: CommandEnv, } // passed back to std::process with the pipes connected to the child, if any @@ -32,32 +32,28 @@ pub enum Stdio { impl Command { pub fn new(_program: &OsStr) -> Command { - Command { - env: Default::default() - } + Command { env: Default::default() } } - pub fn arg(&mut self, _arg: &OsStr) { - } + pub fn arg(&mut self, _arg: &OsStr) {} pub fn env_mut(&mut self) -> &mut CommandEnv { &mut self.env } - pub fn cwd(&mut self, _dir: &OsStr) { - } + pub fn cwd(&mut self, _dir: &OsStr) {} - pub fn stdin(&mut self, _stdin: Stdio) { - } + pub fn stdin(&mut self, _stdin: Stdio) {} - pub fn stdout(&mut self, _stdout: Stdio) { - } + pub fn stdout(&mut self, _stdout: Stdio) {} - pub fn stderr(&mut self, _stderr: Stdio) { - } + pub fn stderr(&mut self, _stderr: Stdio) {} - 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)> { unsupported() } } @@ -106,8 +102,7 @@ impl PartialEq for ExitStatus { } } -impl Eq for ExitStatus { -} +impl Eq for ExitStatus {} impl fmt::Debug for ExitStatus { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/src/libstd/sys/wasm/args.rs b/src/libstd/sys/wasm/args.rs index 8279e5280e924..3b6557ae3257f 100644 --- a/src/libstd/sys/wasm/args.rs +++ b/src/libstd/sys/wasm/args.rs @@ -6,14 +6,10 @@ pub unsafe fn init(_argc: isize, _argv: *const *const u8) { // On wasm these should always be null, so there's nothing for us to do here } -pub unsafe fn cleanup() { -} +pub unsafe fn cleanup() {} pub fn args() -> Args { - Args { - iter: Vec::new().into_iter(), - _dont_send_or_sync_me: PhantomData, - } + Args { iter: Vec::new().into_iter(), _dont_send_or_sync_me: PhantomData } } pub struct Args { diff --git a/src/libstd/sys/wasm/cmath.rs b/src/libstd/sys/wasm/cmath.rs index fa7783122c2e9..304cf906b2aea 100644 --- a/src/libstd/sys/wasm/cmath.rs +++ b/src/libstd/sys/wasm/cmath.rs @@ -1,5 +1,5 @@ // These symbols are all defined in `compiler-builtins` -extern { +extern "C" { pub fn acos(n: f64) -> f64; pub fn acosf(n: f32) -> f32; pub fn asin(n: f64) -> f64; diff --git a/src/libstd/sys/wasm/fs.rs b/src/libstd/sys/wasm/fs.rs index e9095b375fe5d..e6160d1457d26 100644 --- a/src/libstd/sys/wasm/fs.rs +++ b/src/libstd/sys/wasm/fs.rs @@ -1,7 +1,7 @@ use crate::ffi::OsString; use crate::fmt; use crate::hash::{Hash, Hasher}; -use crate::io::{self, SeekFrom, IoSlice, IoSliceMut}; +use crate::io::{self, IoSlice, IoSliceMut, SeekFrom}; use crate::path::{Path, PathBuf}; use crate::sys::time::SystemTime; use crate::sys::{unsupported, Void}; @@ -15,14 +15,14 @@ pub struct ReadDir(Void); pub struct DirEntry(Void); #[derive(Clone, Debug)] -pub struct OpenOptions { } +pub struct OpenOptions {} pub struct FilePermissions(Void); pub struct FileType(Void); #[derive(Debug)] -pub struct DirBuilder { } +pub struct DirBuilder {} impl FileAttr { pub fn size(&self) -> u64 { @@ -78,8 +78,7 @@ impl PartialEq for FilePermissions { } } -impl Eq for FilePermissions { -} +impl Eq for FilePermissions {} impl fmt::Debug for FilePermissions { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -115,8 +114,7 @@ impl PartialEq for FileType { } } -impl Eq for FileType { -} +impl Eq for FileType {} impl Hash for FileType { fn hash(&self, _h: &mut H) { @@ -164,15 +162,15 @@ impl DirEntry { impl OpenOptions { pub fn new() -> OpenOptions { - OpenOptions { } + OpenOptions {} } - pub fn read(&mut self, _read: bool) { } - pub fn write(&mut self, _write: bool) { } - pub fn append(&mut self, _append: bool) { } - pub fn truncate(&mut self, _truncate: bool) { } - pub fn create(&mut self, _create: bool) { } - pub fn create_new(&mut self, _create_new: bool) { } + pub fn read(&mut self, _read: bool) {} + pub fn write(&mut self, _write: bool) {} + pub fn append(&mut self, _append: bool) {} + pub fn truncate(&mut self, _truncate: bool) {} + pub fn create(&mut self, _create: bool) {} + pub fn create_new(&mut self, _create_new: bool) {} } impl File { @@ -235,7 +233,7 @@ impl File { impl DirBuilder { pub fn new() -> DirBuilder { - DirBuilder { } + DirBuilder {} } pub fn mkdir(&self, _p: &Path) -> io::Result<()> { diff --git a/src/libstd/sys/wasm/net.rs b/src/libstd/sys/wasm/net.rs index d50f989d2bb5f..b7c3108f172f6 100644 --- a/src/libstd/sys/wasm/net.rs +++ b/src/libstd/sys/wasm/net.rs @@ -1,9 +1,9 @@ +use crate::convert::TryFrom; use crate::fmt; use crate::io::{self, IoSlice, IoSliceMut}; -use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr}; -use crate::time::Duration; +use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; use crate::sys::{unsupported, Void}; -use crate::convert::TryFrom; +use crate::time::Duration; pub struct TcpStream(Void); @@ -228,23 +228,19 @@ impl UdpSocket { match self.0 {} } - pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) - -> io::Result<()> { + pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { match self.0 {} } - pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) - -> io::Result<()> { + pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { match self.0 {} } - pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) - -> io::Result<()> { + pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { match self.0 {} } - pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) - -> io::Result<()> { + pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { match self.0 {} } @@ -351,8 +347,7 @@ pub mod netc { } #[derive(Copy, Clone)] - pub struct sockaddr { - } + pub struct sockaddr {} pub type socklen_t = usize; } diff --git a/src/libstd/sys/wasm/os.rs b/src/libstd/sys/wasm/os.rs index 890049e8bfae5..193c3892743c4 100644 --- a/src/libstd/sys/wasm/os.rs +++ b/src/libstd/sys/wasm/os.rs @@ -1,5 +1,5 @@ use crate::error::Error as StdError; -use crate::ffi::{OsString, OsStr}; +use crate::ffi::{OsStr, OsString}; use crate::fmt; use crate::io; use crate::path::{self, PathBuf}; @@ -39,7 +39,9 @@ impl<'a> Iterator for SplitPaths<'a> { pub struct JoinPathsError; pub fn join_paths(_paths: I) -> Result - where I: Iterator, T: AsRef +where + I: Iterator, + T: AsRef, { Err(JoinPathsError) } diff --git a/src/libstd/sys/wasm/path.rs b/src/libstd/sys/wasm/path.rs index 7a18395610785..840a7ae042625 100644 --- a/src/libstd/sys/wasm/path.rs +++ b/src/libstd/sys/wasm/path.rs @@ -1,5 +1,5 @@ -use crate::path::Prefix; use crate::ffi::OsStr; +use crate::path::Prefix; #[inline] pub fn is_sep_byte(b: u8) -> bool { diff --git a/src/libstd/sys/wasm/pipe.rs b/src/libstd/sys/wasm/pipe.rs index 9f07f054362fe..fb14dc5910181 100644 --- a/src/libstd/sys/wasm/pipe.rs +++ b/src/libstd/sys/wasm/pipe.rs @@ -25,9 +25,6 @@ impl AnonPipe { } } -pub fn read2(p1: AnonPipe, - _v1: &mut Vec, - _p2: AnonPipe, - _v2: &mut Vec) -> io::Result<()> { +pub fn read2(p1: AnonPipe, _v1: &mut Vec, _p2: AnonPipe, _v2: &mut Vec) -> io::Result<()> { match p1.0 {} } diff --git a/src/libstd/sys/wasm/process.rs b/src/libstd/sys/wasm/process.rs index edf933d10e074..4702e5c549228 100644 --- a/src/libstd/sys/wasm/process.rs +++ b/src/libstd/sys/wasm/process.rs @@ -32,32 +32,28 @@ pub enum Stdio { impl Command { pub fn new(_program: &OsStr) -> Command { - Command { - env: Default::default() - } + Command { env: Default::default() } } - pub fn arg(&mut self, _arg: &OsStr) { - } + pub fn arg(&mut self, _arg: &OsStr) {} pub fn env_mut(&mut self) -> &mut CommandEnv { &mut self.env } - pub fn cwd(&mut self, _dir: &OsStr) { - } + pub fn cwd(&mut self, _dir: &OsStr) {} - pub fn stdin(&mut self, _stdin: Stdio) { - } + pub fn stdin(&mut self, _stdin: Stdio) {} - pub fn stdout(&mut self, _stdout: Stdio) { - } + pub fn stdout(&mut self, _stdout: Stdio) {} - pub fn stderr(&mut self, _stderr: Stdio) { - } + pub fn stderr(&mut self, _stderr: Stdio) {} - 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)> { unsupported() } } @@ -106,8 +102,7 @@ impl PartialEq for ExitStatus { } } -impl Eq for ExitStatus { -} +impl Eq for ExitStatus {} impl fmt::Debug for ExitStatus { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/src/libstd/sys/wasm/stack_overflow.rs b/src/libstd/sys/wasm/stack_overflow.rs index c0e7c824615c8..cbf62b6e5b7e3 100644 --- a/src/libstd/sys/wasm/stack_overflow.rs +++ b/src/libstd/sys/wasm/stack_overflow.rs @@ -6,8 +6,6 @@ impl Handler { } } -pub unsafe fn init() { -} +pub unsafe fn init() {} -pub unsafe fn cleanup() { -} +pub unsafe fn cleanup() {} diff --git a/src/libstd/sys/wasm/thread.rs b/src/libstd/sys/wasm/thread.rs index d06965f327849..0e0e78a827670 100644 --- a/src/libstd/sys/wasm/thread.rs +++ b/src/libstd/sys/wasm/thread.rs @@ -9,9 +9,7 @@ pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(_stack: usize, _p: Box) - -> io::Result - { + pub unsafe fn new(_stack: usize, _p: Box) -> io::Result { unsupported() } @@ -55,8 +53,12 @@ impl Thread { pub mod guard { pub type Guard = !; - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + pub unsafe fn current() -> Option { + None + } + pub unsafe fn init() -> Option { + None + } } // This is only used by atomics primitives when the `atomics` feature is @@ -84,9 +86,7 @@ pub fn my_id() -> u32 { if MY_ID == 0 { let mut cur = NEXT_ID.load(SeqCst); MY_ID = loop { - let next = cur.checked_add(1).unwrap_or_else(|| { - crate::arch::wasm32::unreachable() - }); + let next = cur.checked_add(1).unwrap_or_else(|| crate::arch::wasm32::unreachable()); match NEXT_ID.compare_exchange(cur, next, SeqCst, SeqCst) { Ok(_) => break next, Err(i) => cur = i, diff --git a/src/libstd/sys/wasm/thread_local.rs b/src/libstd/sys/wasm/thread_local.rs index 8a0ca6f3d25a8..f8be9863ed56f 100644 --- a/src/libstd/sys/wasm/thread_local.rs +++ b/src/libstd/sys/wasm/thread_local.rs @@ -1,7 +1,7 @@ pub type Key = usize; #[inline] -pub unsafe fn create(_dtor: Option) -> Key { +pub unsafe fn create(_dtor: Option) -> Key { panic!("should not be used on the wasm target"); } diff --git a/src/libstd/sys/wasm/time.rs b/src/libstd/sys/wasm/time.rs index dd9ad3760b050..d9edc7fdc4451 100644 --- a/src/libstd/sys/wasm/time.rs +++ b/src/libstd/sys/wasm/time.rs @@ -39,8 +39,7 @@ impl SystemTime { panic!("time not implemented on wasm32-unknown-unknown") } - pub fn sub_time(&self, other: &SystemTime) - -> Result { + pub fn sub_time(&self, other: &SystemTime) -> Result { self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0) } diff --git a/src/libstd/sys/windows/alloc.rs b/src/libstd/sys/windows/alloc.rs index a33c4019a2e6b..99b4d6c72a0e3 100644 --- a/src/libstd/sys/windows/alloc.rs +++ b/src/libstd/sys/windows/alloc.rs @@ -1,6 +1,6 @@ use crate::alloc::{GlobalAlloc, Layout, System}; use crate::sys::c; -use crate::sys_common::alloc::{MIN_ALIGN, realloc_fallback}; +use crate::sys_common::alloc::{realloc_fallback, MIN_ALIGN}; #[repr(C)] struct Header(*mut u8); @@ -18,16 +18,12 @@ unsafe fn align_ptr(ptr: *mut u8, align: usize) -> *mut u8 { #[inline] unsafe fn allocate_with_flags(layout: Layout, flags: c::DWORD) -> *mut u8 { if layout.align() <= MIN_ALIGN { - return c::HeapAlloc(c::GetProcessHeap(), flags, layout.size()) as *mut u8 + return c::HeapAlloc(c::GetProcessHeap(), flags, layout.size()) as *mut u8; } let size = layout.size() + layout.align(); let ptr = c::HeapAlloc(c::GetProcessHeap(), flags, size); - if ptr.is_null() { - ptr as *mut u8 - } else { - align_ptr(ptr as *mut u8, layout.align()) - } + if ptr.is_null() { ptr as *mut u8 } else { align_ptr(ptr as *mut u8, layout.align()) } } #[stable(feature = "alloc_system_type", since = "1.28.0")] @@ -46,13 +42,11 @@ unsafe impl GlobalAlloc for System { unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { if layout.align() <= MIN_ALIGN { let err = c::HeapFree(c::GetProcessHeap(), 0, ptr as c::LPVOID); - debug_assert!(err != 0, "Failed to free heap memory: {}", - c::GetLastError()); + debug_assert!(err != 0, "Failed to free heap memory: {}", c::GetLastError()); } else { let header = get_header(ptr); let err = c::HeapFree(c::GetProcessHeap(), 0, header.0 as c::LPVOID); - debug_assert!(err != 0, "Failed to free heap memory: {}", - c::GetLastError()); + debug_assert!(err != 0, "Failed to free heap memory: {}", c::GetLastError()); } } diff --git a/src/libstd/sys/windows/args.rs b/src/libstd/sys/windows/args.rs index b04bb484eedb9..5fbea2a291017 100644 --- a/src/libstd/sys/windows/args.rs +++ b/src/libstd/sys/windows/args.rs @@ -1,26 +1,26 @@ #![allow(dead_code)] // runtime init functions not used during testing -use crate::os::windows::prelude::*; -use crate::sys::windows::os::current_exe; -use crate::sys::c; use crate::ffi::OsString; use crate::fmt; -use crate::vec; -use crate::slice; +use crate::os::windows::prelude::*; use crate::path::PathBuf; +use crate::slice; +use crate::sys::c; +use crate::sys::windows::os::current_exe; +use crate::vec; use core::iter; -pub unsafe fn init(_argc: isize, _argv: *const *const u8) { } +pub unsafe fn init(_argc: isize, _argv: *const *const u8) {} -pub unsafe fn cleanup() { } +pub unsafe fn cleanup() {} pub fn args() -> Args { unsafe { let lp_cmd_line = c::GetCommandLineW(); - let parsed_args_list = parse_lp_cmd_line( - lp_cmd_line as *const u16, - || current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new())); + let parsed_args_list = parse_lp_cmd_line(lp_cmd_line as *const u16, || { + current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new()) + }); Args { parsed_args_list: parsed_args_list.into_iter() } } @@ -40,8 +40,10 @@ pub fn args() -> Args { /// Windows 10 Pro v1803, using an exhaustive test suite available at /// or /// . -unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_name: F) - -> Vec { +unsafe fn parse_lp_cmd_line OsString>( + lp_cmd_line: *const u16, + exe_name: F, +) -> Vec { const BACKSLASH: u16 = '\\' as u16; const QUOTE: u16 = '"' as u16; const TAB: u16 = '\t' as u16; @@ -84,7 +86,7 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na 0..=SPACE => { ret_val.push(OsString::new()); &cmd_line[1..] - }, + } // The executable name ends at the next whitespace, // no matter what. _ => { @@ -112,7 +114,7 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na BACKSLASH => { backslash_count += 1; was_in_quotes = false; - }, + } QUOTE if backslash_count % 2 == 0 => { cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2)); backslash_count = 0; @@ -171,30 +173,36 @@ impl<'a> fmt::Debug for ArgsInnerDebug<'a> { impl Args { pub fn inner_debug(&self) -> ArgsInnerDebug<'_> { - ArgsInnerDebug { - args: self - } + ArgsInnerDebug { args: self } } } impl Iterator for Args { type Item = OsString; - fn next(&mut self) -> Option { self.parsed_args_list.next() } - fn size_hint(&self) -> (usize, Option) { self.parsed_args_list.size_hint() } + fn next(&mut self) -> Option { + self.parsed_args_list.next() + } + fn size_hint(&self) -> (usize, Option) { + self.parsed_args_list.size_hint() + } } impl DoubleEndedIterator for Args { - fn next_back(&mut self) -> Option { self.parsed_args_list.next_back() } + fn next_back(&mut self) -> Option { + self.parsed_args_list.next_back() + } } impl ExactSizeIterator for Args { - fn len(&self) -> usize { self.parsed_args_list.len() } + fn len(&self) -> usize { + self.parsed_args_list.len() + } } #[cfg(test)] mod tests { - use crate::sys::windows::args::*; use crate::ffi::OsString; + use crate::sys::windows::args::*; fn chk(string: &str, parts: &[&str]) { let mut wide: Vec = OsString::from(string).encode_wide().collect(); @@ -245,7 +253,7 @@ mod tests { chk(r#"EXE "" """"#, &["EXE", "", "\""]); chk( r#"EXE "this is """all""" in the same argument""#, - &["EXE", "this is \"all\" in the same argument"] + &["EXE", "this is \"all\" in the same argument"], ); chk(r#"EXE "a"""#, &["EXE", "a\""]); chk(r#"EXE "a"" a"#, &["EXE", "a\"", "a"]); @@ -253,6 +261,6 @@ mod tests { chk(r#""EXE" check"#, &["EXE", "check"]); chk(r#""EXE check""#, &["EXE check"]); chk(r#""EXE """for""" check"#, &["EXE ", r#"for""#, "check"]); - chk(r#""EXE \"for\" check"#, &[r#"EXE \"#, r#"for""#, "check"]); + chk(r#""EXE \"for\" check"#, &[r#"EXE \"#, r#"for""#, "check"]); } } diff --git a/src/libstd/sys/windows/cmath.rs b/src/libstd/sys/windows/cmath.rs index e744cb219a849..7c5bfa1bd0641 100644 --- a/src/libstd/sys/windows/cmath.rs +++ b/src/libstd/sys/windows/cmath.rs @@ -1,9 +1,9 @@ #![cfg(not(test))] -use libc::{c_float, c_double}; +use libc::{c_double, c_float}; #[link_name = "m"] -extern { +extern "C" { pub fn acos(n: c_double) -> c_double; pub fn asin(n: c_double) -> c_double; pub fn atan(n: c_double) -> c_double; @@ -32,7 +32,7 @@ pub use self::shims::*; mod shims { use libc::c_float; - extern { + extern "C" { pub fn acosf(n: c_float) -> c_float; pub fn asinf(n: c_float) -> c_float; pub fn atan2f(a: c_float, b: c_float) -> c_float; diff --git a/src/libstd/sys/windows/compat.rs b/src/libstd/sys/windows/compat.rs index 544b2087f92e0..d6d433f9d086b 100644 --- a/src/libstd/sys/windows/compat.rs +++ b/src/libstd/sys/windows/compat.rs @@ -28,8 +28,7 @@ pub fn lookup(module: &str, symbol: &str) -> Option { } } -pub fn store_func(ptr: &AtomicUsize, module: &str, symbol: &str, - fallback: usize) -> usize { +pub fn store_func(ptr: &AtomicUsize, module: &str, symbol: &str, fallback: usize) -> usize { let value = lookup(module, symbol).unwrap_or(fallback); ptr.store(value, Ordering::SeqCst); value diff --git a/src/libstd/sys/windows/ext/ffi.rs b/src/libstd/sys/windows/ext/ffi.rs index 1381825806f63..6e78119383f43 100644 --- a/src/libstd/sys/windows/ext/ffi.rs +++ b/src/libstd/sys/windows/ext/ffi.rs @@ -59,10 +59,10 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::ffi::{OsString, OsStr}; +use crate::ffi::{OsStr, OsString}; use crate::sys::os_str::Buf; use crate::sys_common::wtf8::Wtf8Buf; -use crate::sys_common::{FromInner, AsInner}; +use crate::sys_common::{AsInner, FromInner}; #[stable(feature = "rust1", since = "1.0.0")] pub use crate::sys_common::wtf8::EncodeWide; diff --git a/src/libstd/sys/windows/ext/fs.rs b/src/libstd/sys/windows/ext/fs.rs index 23964dc5bd5df..7eaff226a7654 100644 --- a/src/libstd/sys/windows/ext/fs.rs +++ b/src/libstd/sys/windows/ext/fs.rs @@ -2,11 +2,11 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fs::{self, OpenOptions, Metadata}; +use crate::fs::{self, Metadata, OpenOptions}; use crate::io; use crate::path::Path; use crate::sys; -use crate::sys_common::{AsInnerMut, AsInner}; +use crate::sys_common::{AsInner, AsInnerMut}; /// Windows-specific extensions to [`File`]. /// @@ -265,23 +265,28 @@ pub trait OpenOptionsExt { #[stable(feature = "open_options_ext", since = "1.10.0")] impl OpenOptionsExt for OpenOptions { fn access_mode(&mut self, access: u32) -> &mut OpenOptions { - self.as_inner_mut().access_mode(access); self + self.as_inner_mut().access_mode(access); + self } fn share_mode(&mut self, share: u32) -> &mut OpenOptions { - self.as_inner_mut().share_mode(share); self + self.as_inner_mut().share_mode(share); + self } fn custom_flags(&mut self, flags: u32) -> &mut OpenOptions { - self.as_inner_mut().custom_flags(flags); self + self.as_inner_mut().custom_flags(flags); + self } fn attributes(&mut self, attributes: u32) -> &mut OpenOptions { - self.as_inner_mut().attributes(attributes); self + self.as_inner_mut().attributes(attributes); + self } fn security_qos_flags(&mut self, flags: u32) -> &mut OpenOptions { - self.as_inner_mut().security_qos_flags(flags); self + self.as_inner_mut().security_qos_flags(flags); + self } } @@ -468,14 +473,30 @@ pub trait MetadataExt { #[stable(feature = "metadata_ext", since = "1.1.0")] impl MetadataExt for Metadata { - fn file_attributes(&self) -> u32 { self.as_inner().attrs() } - fn creation_time(&self) -> u64 { self.as_inner().created_u64() } - fn last_access_time(&self) -> u64 { self.as_inner().accessed_u64() } - fn last_write_time(&self) -> u64 { self.as_inner().modified_u64() } - fn file_size(&self) -> u64 { self.as_inner().size() } - fn volume_serial_number(&self) -> Option { self.as_inner().volume_serial_number() } - fn number_of_links(&self) -> Option { self.as_inner().number_of_links() } - fn file_index(&self) -> Option { self.as_inner().file_index() } + fn file_attributes(&self) -> u32 { + self.as_inner().attrs() + } + fn creation_time(&self) -> u64 { + self.as_inner().created_u64() + } + fn last_access_time(&self) -> u64 { + self.as_inner().accessed_u64() + } + fn last_write_time(&self) -> u64 { + self.as_inner().modified_u64() + } + fn file_size(&self) -> u64 { + self.as_inner().size() + } + fn volume_serial_number(&self) -> Option { + self.as_inner().volume_serial_number() + } + fn number_of_links(&self) -> Option { + self.as_inner().number_of_links() + } + fn file_index(&self) -> Option { + self.as_inner().file_index() + } } /// Windows-specific extensions to [`FileType`]. @@ -495,8 +516,12 @@ pub trait FileTypeExt { #[unstable(feature = "windows_file_type_ext", issue = "0")] impl FileTypeExt for fs::FileType { - fn is_symlink_dir(&self) -> bool { self.as_inner().is_symlink_dir() } - fn is_symlink_file(&self) -> bool { self.as_inner().is_symlink_file() } + fn is_symlink_dir(&self) -> bool { + self.as_inner().is_symlink_dir() + } + fn is_symlink_file(&self) -> bool { + self.as_inner().is_symlink_file() + } } /// Creates a new file symbolic link on the filesystem. @@ -515,8 +540,7 @@ impl FileTypeExt for fs::FileType { /// } /// ``` #[stable(feature = "symlink", since = "1.1.0")] -pub fn symlink_file, Q: AsRef>(src: P, dst: Q) - -> io::Result<()> { +pub fn symlink_file, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), false) } @@ -536,7 +560,6 @@ pub fn symlink_file, Q: AsRef>(src: P, dst: Q) /// } /// ``` #[stable(feature = "symlink", since = "1.1.0")] -pub fn symlink_dir, Q: AsRef>(src: P, dst: Q) - -> io::Result<()> { +pub fn symlink_dir, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), true) } diff --git a/src/libstd/sys/windows/ext/io.rs b/src/libstd/sys/windows/ext/io.rs index ec47c2e9d5afd..4573ee589321d 100644 --- a/src/libstd/sys/windows/ext/io.rs +++ b/src/libstd/sys/windows/ext/io.rs @@ -1,12 +1,12 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::fs; -use crate::os::windows::raw; +use crate::io; use crate::net; -use crate::sys_common::{self, AsInner, FromInner, IntoInner}; +use crate::os::windows::raw; use crate::sys; use crate::sys::c; -use crate::io; +use crate::sys_common::{self, AsInner, FromInner, IntoInner}; /// Raw HANDLEs. #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/libstd/sys/windows/ext/mod.rs b/src/libstd/sys/windows/ext/mod.rs index 0a6d435d3290e..613d3dc189a43 100644 --- a/src/libstd/sys/windows/ext/mod.rs +++ b/src/libstd/sys/windows/ext/mod.rs @@ -13,8 +13,8 @@ pub mod ffi; pub mod fs; pub mod io; -pub mod raw; pub mod process; +pub mod raw; pub mod thread; /// A prelude for conveniently writing platform-specific code. @@ -22,14 +22,19 @@ pub mod thread; /// 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::{RawSocket, RawHandle, AsRawSocket, AsRawHandle}; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] - pub use super::io::{FromRawSocket, FromRawHandle, IntoRawSocket, IntoRawHandle}; - #[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::{OpenOptionsExt, MetadataExt}; - #[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::fs::{MetadataExt, OpenOptionsExt}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use super::io::{AsRawHandle, AsRawSocket, RawHandle, RawSocket}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use super::io::{FromRawHandle, FromRawSocket, IntoRawHandle, IntoRawSocket}; } diff --git a/src/libstd/sys/windows/ext/process.rs b/src/libstd/sys/windows/ext/process.rs index b2e6cdead4f3b..ed35c5ff19446 100644 --- a/src/libstd/sys/windows/ext/process.rs +++ b/src/libstd/sys/windows/ext/process.rs @@ -2,10 +2,10 @@ #![stable(feature = "process_extensions", since = "1.2.0")] -use crate::os::windows::io::{FromRawHandle, RawHandle, AsRawHandle, IntoRawHandle}; +use crate::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle}; use crate::process; use crate::sys; -use crate::sys_common::{AsInnerMut, AsInner, FromInner, IntoInner}; +use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; #[stable(feature = "process_extensions", since = "1.2.0")] impl FromRawHandle for process::Stdio { diff --git a/src/libstd/sys/windows/ext/raw.rs b/src/libstd/sys/windows/ext/raw.rs index d2bab2720369f..7f2a2877828cf 100644 --- a/src/libstd/sys/windows/ext/raw.rs +++ b/src/libstd/sys/windows/ext/raw.rs @@ -4,8 +4,11 @@ use crate::os::raw::c_void; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type HANDLE = *mut c_void; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type HANDLE = *mut c_void; #[cfg(target_pointer_width = "32")] -#[stable(feature = "raw_ext", since = "1.1.0")] pub type SOCKET = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type SOCKET = u32; #[cfg(target_pointer_width = "64")] -#[stable(feature = "raw_ext", since = "1.1.0")] pub type SOCKET = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type SOCKET = u64; diff --git a/src/libstd/sys/windows/ext/thread.rs b/src/libstd/sys/windows/ext/thread.rs index fdc7e7fa32f0e..41c29f5b950ef 100644 --- a/src/libstd/sys/windows/ext/thread.rs +++ b/src/libstd/sys/windows/ext/thread.rs @@ -2,9 +2,9 @@ #![stable(feature = "thread_extensions", since = "1.9.0")] -use crate::os::windows::io::{RawHandle, AsRawHandle, IntoRawHandle}; -use crate::thread; +use crate::os::windows::io::{AsRawHandle, IntoRawHandle, RawHandle}; use crate::sys_common::{AsInner, IntoInner}; +use crate::thread; #[stable(feature = "thread_extensions", since = "1.9.0")] impl AsRawHandle for thread::JoinHandle { @@ -14,7 +14,7 @@ impl AsRawHandle for thread::JoinHandle { } #[stable(feature = "thread_extensions", since = "1.9.0")] -impl IntoRawHandle for thread::JoinHandle { +impl IntoRawHandle for thread::JoinHandle { fn into_raw_handle(self) -> RawHandle { self.into_inner().into_handle().into_raw() as *mut _ } diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index 4160123c9a2ab..e9c84c4e7c9cb 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -2,7 +2,7 @@ use crate::os::windows::prelude::*; use crate::ffi::OsString; use crate::fmt; -use crate::io::{self, Error, SeekFrom, IoSlice, IoSliceMut}; +use crate::io::{self, Error, IoSlice, IoSliceMut, SeekFrom}; use crate::mem; use crate::path::{Path, PathBuf}; use crate::ptr; @@ -15,7 +15,9 @@ use crate::sys_common::FromInner; use super::to_u16s; -pub struct File { handle: Handle } +pub struct File { + handle: Handle, +} #[derive(Clone)] pub struct FileAttr { @@ -71,7 +73,9 @@ pub struct OpenOptions { } #[derive(Clone, PartialEq, Eq, Debug)] -pub struct FilePermissions { attrs: c::DWORD } +pub struct FilePermissions { + attrs: c::DWORD, +} #[derive(Debug)] pub struct DirBuilder; @@ -97,13 +101,13 @@ impl Iterator for ReadDir { loop { if c::FindNextFileW(self.handle.0, &mut wfd) == 0 { if c::GetLastError() == c::ERROR_NO_MORE_FILES { - return None + return None; } else { - return Some(Err(Error::last_os_error())) + return Some(Err(Error::last_os_error())); } } if let Some(e) = DirEntry::new(&self.root, &wfd) { - return Some(Ok(e)) + return Some(Ok(e)); } } } @@ -121,15 +125,11 @@ impl DirEntry { fn new(root: &Arc, wfd: &c::WIN32_FIND_DATAW) -> Option { match &wfd.cFileName[0..3] { // check for '.' and '..' - &[46, 0, ..] | - &[46, 46, 0, ..] => return None, + &[46, 0, ..] | &[46, 46, 0, ..] => return None, _ => {} } - Some(DirEntry { - root: root.clone(), - data: *wfd, - }) + Some(DirEntry { root: root.clone(), data: *wfd }) } pub fn path(&self) -> PathBuf { @@ -142,8 +142,10 @@ impl DirEntry { } pub fn file_type(&self) -> io::Result { - Ok(FileType::new(self.data.dwFileAttributes, - /* reparse_tag = */ self.data.dwReserved0)) + Ok(FileType::new( + self.data.dwFileAttributes, + /* reparse_tag = */ self.data.dwReserved0, + )) } pub fn metadata(&self) -> io::Result { @@ -154,11 +156,11 @@ impl DirEntry { last_write_time: self.data.ftLastWriteTime, file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64), reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 { - // reserved unless this is a reparse point - self.data.dwReserved0 - } else { - 0 - }, + // reserved unless this is a reparse point + self.data.dwReserved0 + } else { + 0 + }, volume_serial_number: None, number_of_links: None, file_index: None, @@ -186,17 +188,37 @@ 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: u32) { self.custom_flags = flags; } - pub fn access_mode(&mut self, access_mode: u32) { self.access_mode = Some(access_mode); } - pub fn share_mode(&mut self, share_mode: u32) { self.share_mode = share_mode; } - pub fn attributes(&mut self, attrs: u32) { self.attributes = attrs; } + pub fn custom_flags(&mut self, flags: u32) { + self.custom_flags = flags; + } + pub fn access_mode(&mut self, access_mode: u32) { + self.access_mode = Some(access_mode); + } + pub fn share_mode(&mut self, share_mode: u32) { + self.share_mode = share_mode; + } + pub fn attributes(&mut self, attrs: u32) { + self.attributes = attrs; + } pub fn security_qos_flags(&mut self, flags: u32) { // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on. @@ -211,12 +233,13 @@ impl OpenOptions { match (self.read, self.write, self.append, self.access_mode) { (.., Some(mode)) => Ok(mode), - (true, false, false, None) => Ok(c::GENERIC_READ), - (false, true, false, None) => Ok(c::GENERIC_WRITE), - (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE), - (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA), - (true, _, true, None) => Ok(c::GENERIC_READ | - (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)), + (true, false, false, None) => Ok(c::GENERIC_READ), + (false, true, false, None) => Ok(c::GENERIC_WRITE), + (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE), + (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA), + (true, _, true, None) => { + Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)) + } (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)), } } @@ -226,30 +249,32 @@ impl OpenOptions { 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(ERROR_INVALID_PARAMETER)); - }, - (_, true) => + } + } + (_, true) => { if self.truncate && !self.create_new { return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)); - }, + } + } } Ok(match (self.create, self.truncate, self.create_new) { - (false, false, false) => c::OPEN_EXISTING, - (true, false, false) => c::OPEN_ALWAYS, - (false, true, false) => c::TRUNCATE_EXISTING, - (true, true, false) => c::CREATE_ALWAYS, - (_, _, true) => c::CREATE_NEW, - }) + (false, false, false) => c::OPEN_EXISTING, + (true, false, false) => c::OPEN_ALWAYS, + (false, true, false) => c::TRUNCATE_EXISTING, + (true, true, false) => c::CREATE_ALWAYS, + (_, _, true) => c::CREATE_NEW, + }) } fn get_flags_and_attributes(&self) -> c::DWORD { - self.custom_flags | - self.attributes | - self.security_qos_flags | - if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 } + self.custom_flags + | self.attributes + | self.security_qos_flags + | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 } } } @@ -257,13 +282,15 @@ impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result { let path = to_u16s(path)?; let handle = unsafe { - c::CreateFileW(path.as_ptr(), - opts.get_access_mode()?, - opts.share_mode, - opts.security_attributes as *mut _, - opts.get_creation_mode()?, - opts.get_flags_and_attributes(), - ptr::null_mut()) + c::CreateFileW( + path.as_ptr(), + opts.get_access_mode()?, + opts.share_mode, + opts.security_attributes as *mut _, + opts.get_creation_mode()?, + opts.get_flags_and_attributes(), + ptr::null_mut(), + ) }; if handle == c::INVALID_HANDLE_VALUE { Err(Error::last_os_error()) @@ -277,18 +304,20 @@ impl File { Ok(()) } - pub fn datasync(&self) -> io::Result<()> { self.fsync() } + pub fn datasync(&self) -> io::Result<()> { + self.fsync() + } pub fn truncate(&self, size: u64) -> io::Result<()> { - let mut info = c::FILE_END_OF_FILE_INFO { - EndOfFile: size as c::LARGE_INTEGER, - }; + let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER }; let size = mem::size_of_val(&info); cvt(unsafe { - c::SetFileInformationByHandle(self.handle.raw(), - c::FileEndOfFileInfo, - &mut info as *mut _ as *mut _, - size as c::DWORD) + c::SetFileInformationByHandle( + self.handle.raw(), + c::FileEndOfFileInfo, + &mut info as *mut _ as *mut _, + size as c::DWORD, + ) })?; Ok(()) } @@ -314,8 +343,9 @@ impl File { reparse_tag, volume_serial_number: Some(info.dwVolumeSerialNumber), number_of_links: Some(info.nNumberOfLinks), - file_index: Some((info.nFileIndexLow as u64) | - ((info.nFileIndexHigh as u64) << 32)), + file_index: Some( + (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32), + ), }) } } @@ -325,10 +355,12 @@ impl File { unsafe { let mut info: c::FILE_BASIC_INFO = mem::zeroed(); let size = mem::size_of_val(&info); - cvt(c::GetFileInformationByHandleEx(self.handle.raw(), - c::FileBasicInfo, - &mut info as *mut _ as *mut libc::c_void, - size as c::DWORD))?; + cvt(c::GetFileInformationByHandleEx( + self.handle.raw(), + c::FileBasicInfo, + &mut info as *mut _ as *mut libc::c_void, + size as c::DWORD, + ))?; let mut attr = FileAttr { attributes: info.FileAttributes, creation_time: c::FILETIME { @@ -351,10 +383,12 @@ impl File { }; let mut info: c::FILE_STANDARD_INFO = mem::zeroed(); let size = mem::size_of_val(&info); - cvt(c::GetFileInformationByHandleEx(self.handle.raw(), - c::FileStandardInfo, - &mut info as *mut _ as *mut libc::c_void, - size as c::DWORD))?; + cvt(c::GetFileInformationByHandleEx( + self.handle.raw(), + c::FileStandardInfo, + &mut info as *mut _ as *mut libc::c_void, + size as c::DWORD, + ))?; attr.file_size = info.AllocationSize as u64; attr.number_of_links = Some(info.NumberOfLinks); if attr.file_type().is_reparse_point() { @@ -391,7 +425,9 @@ impl File { self.handle.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 { let (whence, pos) = match pos { @@ -403,37 +439,39 @@ impl File { }; let pos = pos as c::LARGE_INTEGER; let mut newpos = 0; - cvt(unsafe { - c::SetFilePointerEx(self.handle.raw(), pos, - &mut newpos, whence) - })?; + cvt(unsafe { c::SetFilePointerEx(self.handle.raw(), pos, &mut newpos, whence) })?; Ok(newpos as u64) } pub fn duplicate(&self) -> io::Result { - Ok(File { - handle: self.handle.duplicate(0, false, c::DUPLICATE_SAME_ACCESS)?, - }) + Ok(File { handle: self.handle.duplicate(0, false, c::DUPLICATE_SAME_ACCESS)? }) } - pub fn handle(&self) -> &Handle { &self.handle } + pub fn handle(&self) -> &Handle { + &self.handle + } - pub fn into_handle(self) -> Handle { self.handle } + pub fn into_handle(self) -> Handle { + self.handle + } - fn reparse_point<'a>(&self, - space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE]) - -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> { + fn reparse_point<'a>( + &self, + space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE], + ) -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> { unsafe { let mut bytes = 0; cvt({ - c::DeviceIoControl(self.handle.raw(), - c::FSCTL_GET_REPARSE_POINT, - ptr::null_mut(), - 0, - space.as_mut_ptr() as *mut _, - space.len() as c::DWORD, - &mut bytes, - ptr::null_mut()) + c::DeviceIoControl( + self.handle.raw(), + c::FSCTL_GET_REPARSE_POINT, + ptr::null_mut(), + 0, + space.as_mut_ptr() as *mut _, + space.len() as c::DWORD, + &mut bytes, + ptr::null_mut(), + ) })?; Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER))) } @@ -447,21 +485,29 @@ impl File { c::IO_REPARSE_TAG_SYMLINK => { let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER = &buf.rest as *const _ as *const _; - (&(*info).PathBuffer as *const _ as *const u16, - (*info).SubstituteNameOffset / 2, - (*info).SubstituteNameLength / 2, - (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0) - }, + ( + &(*info).PathBuffer as *const _ as *const u16, + (*info).SubstituteNameOffset / 2, + (*info).SubstituteNameLength / 2, + (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0, + ) + } c::IO_REPARSE_TAG_MOUNT_POINT => { let info: *const c::MOUNT_POINT_REPARSE_BUFFER = &buf.rest as *const _ as *const _; - (&(*info).PathBuffer as *const _ as *const u16, - (*info).SubstituteNameOffset / 2, - (*info).SubstituteNameLength / 2, - false) - }, - _ => return Err(io::Error::new(io::ErrorKind::Other, - "Unsupported reparse point type")) + ( + &(*info).PathBuffer as *const _ as *const u16, + (*info).SubstituteNameOffset / 2, + (*info).SubstituteNameLength / 2, + false, + ) + } + _ => { + return Err(io::Error::new( + io::ErrorKind::Other, + "Unsupported reparse point type", + )); + } }; let subst_ptr = path_buffer.offset(subst_off as isize); let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize); @@ -484,10 +530,12 @@ impl File { }; let size = mem::size_of_val(&info); cvt(unsafe { - c::SetFileInformationByHandle(self.handle.raw(), - c::FileBasicInfo, - &mut info as *mut _ as *mut _, - size as c::DWORD) + c::SetFileInformationByHandle( + self.handle.raw(), + c::FileBasicInfo, + &mut info as *mut _ as *mut _, + size as c::DWORD, + ) })?; Ok(()) } @@ -585,10 +633,7 @@ impl FilePermissions { impl FileType { fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType { - FileType { - attributes: attrs, - reparse_tag: reparse_tag, - } + FileType { attributes: attrs, reparse_tag: reparse_tag } } pub fn is_dir(&self) -> bool { !self.is_symlink() && self.is_directory() @@ -617,13 +662,13 @@ impl FileType { } impl DirBuilder { - pub fn new() -> DirBuilder { DirBuilder } + pub fn new() -> DirBuilder { + DirBuilder + } pub fn mkdir(&self, p: &Path) -> io::Result<()> { let p = to_u16s(p)?; - cvt(unsafe { - c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) - })?; + cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?; Ok(()) } } @@ -657,9 +702,7 @@ pub fn unlink(p: &Path) -> io::Result<()> { pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = to_u16s(old)?; let new = to_u16s(new)?; - cvt(unsafe { - c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) - })?; + cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?; Ok(()) } @@ -701,8 +744,7 @@ pub fn readlink(path: &Path) -> io::Result { // this is needed for a common case. let mut opts = OpenOptions::new(); opts.access_mode(0); - opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | - c::FILE_FLAG_BACKUP_SEMANTICS); + opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS); let file = File::open(&path, &opts)?; file.readlink() } @@ -720,16 +762,17 @@ pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> { // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be // added to dwFlags to opt into this behaviour. let result = cvt(unsafe { - c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), - flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE) as c::BOOL + c::CreateSymbolicLinkW( + dst.as_ptr(), + src.as_ptr(), + flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE, + ) as c::BOOL }); if let Err(err) = result { if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) { // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE, // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag. - cvt(unsafe { - c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL - })?; + cvt(unsafe { c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL })?; } else { return Err(err); } @@ -741,16 +784,13 @@ pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> { pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = to_u16s(src)?; let dst = to_u16s(dst)?; - cvt(unsafe { - c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut()) - })?; + cvt(unsafe { c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut()) })?; Ok(()) } #[cfg(target_vendor = "uwp")] pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> { - return Err(io::Error::new(io::ErrorKind::Other, - "hard link are not supported on UWP")); + return Err(io::Error::new(io::ErrorKind::Other, "hard link are not supported on UWP")); } pub fn stat(path: &Path) -> io::Result { @@ -781,12 +821,12 @@ pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { } fn get_path(f: &File) -> io::Result { - super::fill_utf16_buf(|buf, sz| unsafe { - c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz, - c::VOLUME_NAME_DOS) - }, |buf| { - PathBuf::from(OsString::from_wide(buf)) - }) + super::fill_utf16_buf( + |buf, sz| unsafe { + c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz, c::VOLUME_NAME_DOS) + }, + |buf| PathBuf::from(OsString::from_wide(buf)), + ) } pub fn canonicalize(p: &Path) -> io::Result { @@ -811,15 +851,23 @@ pub fn copy(from: &Path, to: &Path) -> io::Result { _hDestinationFile: c::HANDLE, lpData: c::LPVOID, ) -> c::DWORD { - if dwStreamNumber == 1 {*(lpData as *mut i64) = StreamBytesTransferred;} + if dwStreamNumber == 1 { + *(lpData as *mut i64) = StreamBytesTransferred; + } c::PROGRESS_CONTINUE } let pfrom = to_u16s(from)?; let pto = to_u16s(to)?; let mut size = 0i64; cvt(unsafe { - c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback), - &mut size as *mut _ as *mut _, ptr::null_mut(), 0) + c::CopyFileExW( + pfrom.as_ptr(), + pto.as_ptr(), + Some(callback), + &mut size as *mut _ as *mut _, + ptr::null_mut(), + 0, + ) })?; Ok(size as u64) } @@ -841,15 +889,13 @@ fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> { let mut opts = OpenOptions::new(); opts.write(true); - opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | - c::FILE_FLAG_BACKUP_SEMANTICS); + opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS); let f = File::open(junction, &opts)?; let h = f.handle().raw(); unsafe { let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; - let db = data.as_mut_ptr() - as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER; + let db = data.as_mut_ptr() as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER; let buf = &mut (*db).ReparseTarget as *mut c::WCHAR; let mut i = 0; // FIXME: this conversion is very hacky @@ -864,16 +910,19 @@ fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> { (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT; (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD; (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD; - (*db).ReparseDataLength = - (*db).ReparseTargetLength as c::DWORD + 12; + (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12; let mut ret = 0; - cvt(c::DeviceIoControl(h as *mut _, - c::FSCTL_SET_REPARSE_POINT, - data.as_ptr() as *mut _, - (*db).ReparseDataLength + 8, - ptr::null_mut(), 0, - &mut ret, - ptr::null_mut())).map(|_| ()) + cvt(c::DeviceIoControl( + h as *mut _, + c::FSCTL_SET_REPARSE_POINT, + data.as_ptr() as *mut _, + (*db).ReparseDataLength + 8, + ptr::null_mut(), + 0, + &mut ret, + ptr::null_mut(), + )) + .map(|_| ()) } } diff --git a/src/libstd/sys/windows/handle.rs b/src/libstd/sys/windows/handle.rs index 3986cda1a5047..ebaa0783d603d 100644 --- a/src/libstd/sys/windows/handle.rs +++ b/src/libstd/sys/windows/handle.rs @@ -1,7 +1,7 @@ #![unstable(issue = "0", feature = "windows_handle")] use crate::cmp; -use crate::io::{self, ErrorKind, Read, IoSlice, IoSliceMut}; +use crate::io::{self, ErrorKind, IoSlice, IoSliceMut, Read}; use crate::mem; use crate::ops::Deref; use crate::ptr; @@ -31,15 +31,9 @@ impl Handle { pub fn new_event(manual: bool, init: bool) -> io::Result { unsafe { - let event = c::CreateEventW(ptr::null_mut(), - manual as c::BOOL, - init as c::BOOL, - ptr::null()); - if event.is_null() { - Err(io::Error::last_os_error()) - } else { - Ok(Handle::new(event)) - } + let event = + c::CreateEventW(ptr::null_mut(), manual as c::BOOL, init as c::BOOL, ptr::null()); + if event.is_null() { Err(io::Error::last_os_error()) } else { Ok(Handle::new(event)) } } } @@ -52,12 +46,16 @@ impl Handle { impl Deref for Handle { type Target = RawHandle; - fn deref(&self) -> &RawHandle { &self.0 } + fn deref(&self) -> &RawHandle { + &self.0 + } } impl Drop for Handle { fn drop(&mut self) { - unsafe { let _ = c::CloseHandle(self.raw()); } + unsafe { + let _ = c::CloseHandle(self.raw()); + } } } @@ -66,14 +64,15 @@ impl RawHandle { RawHandle(handle) } - pub fn raw(&self) -> c::HANDLE { self.0 } + pub fn raw(&self) -> c::HANDLE { + self.0 + } pub fn read(&self, buf: &mut [u8]) -> io::Result { let mut read = 0; let len = cmp::min(buf.len(), ::max_value() as usize) as c::DWORD; let res = cvt(unsafe { - c::ReadFile(self.0, buf.as_mut_ptr() as c::LPVOID, - len, &mut read, ptr::null_mut()) + c::ReadFile(self.0, buf.as_mut_ptr() as c::LPVOID, len, &mut read, ptr::null_mut()) }); match res { @@ -85,7 +84,7 @@ impl RawHandle { // EOF on the pipe. Err(ref e) if e.kind() == ErrorKind::BrokenPipe => Ok(0), - Err(e) => Err(e) + Err(e) => Err(e), } } @@ -100,8 +99,7 @@ impl RawHandle { let mut overlapped: c::OVERLAPPED = mem::zeroed(); overlapped.Offset = offset as u32; overlapped.OffsetHigh = (offset >> 32) as u32; - cvt(c::ReadFile(self.0, buf.as_mut_ptr() as c::LPVOID, - len, &mut read, &mut overlapped)) + cvt(c::ReadFile(self.0, buf.as_mut_ptr() as c::LPVOID, len, &mut read, &mut overlapped)) }; match res { Ok(_) => Ok(read as usize), @@ -110,16 +108,15 @@ impl RawHandle { } } - pub unsafe fn read_overlapped(&self, - buf: &mut [u8], - overlapped: *mut c::OVERLAPPED) - -> io::Result> { + pub unsafe fn read_overlapped( + &self, + buf: &mut [u8], + overlapped: *mut c::OVERLAPPED, + ) -> io::Result> { let len = cmp::min(buf.len(), ::max_value() as usize) as c::DWORD; let mut amt = 0; - let res = cvt({ - c::ReadFile(self.0, buf.as_ptr() as c::LPVOID, - len, &mut amt, overlapped) - }); + let res = + cvt({ c::ReadFile(self.0, buf.as_ptr() as c::LPVOID, len, &mut amt, overlapped) }); match res { Ok(_) => Ok(Some(amt as usize)), Err(e) => { @@ -134,20 +131,21 @@ impl RawHandle { } } - pub fn overlapped_result(&self, - overlapped: *mut c::OVERLAPPED, - wait: bool) -> io::Result { + pub fn overlapped_result( + &self, + overlapped: *mut c::OVERLAPPED, + wait: bool, + ) -> io::Result { unsafe { let mut bytes = 0; - let wait = if wait {c::TRUE} else {c::FALSE}; - let res = cvt({ - c::GetOverlappedResult(self.raw(), overlapped, &mut bytes, wait) - }); + let wait = if wait { c::TRUE } else { c::FALSE }; + let res = cvt({ c::GetOverlappedResult(self.raw(), overlapped, &mut bytes, wait) }); match res { Ok(_) => Ok(bytes as usize), Err(e) => { - if e.raw_os_error() == Some(c::ERROR_HANDLE_EOF as i32) || - e.raw_os_error() == Some(c::ERROR_BROKEN_PIPE as i32) { + if e.raw_os_error() == Some(c::ERROR_HANDLE_EOF as i32) + || e.raw_os_error() == Some(c::ERROR_BROKEN_PIPE as i32) + { Ok(0) } else { Err(e) @@ -158,17 +156,14 @@ impl RawHandle { } pub fn cancel_io(&self) -> io::Result<()> { - unsafe { - cvt(c::CancelIo(self.raw())).map(|_| ()) - } + unsafe { cvt(c::CancelIo(self.raw())).map(|_| ()) } } pub fn write(&self, buf: &[u8]) -> io::Result { let mut amt = 0; let len = cmp::min(buf.len(), ::max_value() as usize) as c::DWORD; cvt(unsafe { - c::WriteFile(self.0, buf.as_ptr() as c::LPVOID, - len, &mut amt, ptr::null_mut()) + c::WriteFile(self.0, buf.as_ptr() as c::LPVOID, len, &mut amt, ptr::null_mut()) })?; Ok(amt as usize) } @@ -184,20 +179,35 @@ impl RawHandle { let mut overlapped: c::OVERLAPPED = mem::zeroed(); overlapped.Offset = offset as u32; overlapped.OffsetHigh = (offset >> 32) as u32; - cvt(c::WriteFile(self.0, buf.as_ptr() as c::LPVOID, - len, &mut written, &mut overlapped))?; + cvt(c::WriteFile( + self.0, + buf.as_ptr() as c::LPVOID, + len, + &mut written, + &mut overlapped, + ))?; } Ok(written as usize) } - pub fn duplicate(&self, access: c::DWORD, inherit: bool, - options: c::DWORD) -> io::Result { + pub fn duplicate( + &self, + access: c::DWORD, + inherit: bool, + options: c::DWORD, + ) -> io::Result { let mut ret = 0 as c::HANDLE; cvt(unsafe { let cur_proc = c::GetCurrentProcess(); - c::DuplicateHandle(cur_proc, self.0, cur_proc, &mut ret, - access, inherit as c::BOOL, - options) + c::DuplicateHandle( + cur_proc, + self.0, + cur_proc, + &mut ret, + access, + inherit as c::BOOL, + options, + ) })?; Ok(Handle::new(ret)) } diff --git a/src/libstd/sys/windows/io.rs b/src/libstd/sys/windows/io.rs index e44dcbe164daf..9d8018fd5e864 100644 --- a/src/libstd/sys/windows/io.rs +++ b/src/libstd/sys/windows/io.rs @@ -35,9 +35,7 @@ impl<'a> IoSlice<'a> { #[inline] pub fn as_slice(&self) -> &[u8] { - unsafe { - slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) - } + unsafe { slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) } } } @@ -52,10 +50,7 @@ impl<'a> IoSliceMut<'a> { pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> { assert!(buf.len() <= c::ULONG::max_value() as usize); IoSliceMut { - vec: c::WSABUF { - len: buf.len() as c::ULONG, - buf: buf.as_mut_ptr() as *mut c::CHAR, - }, + vec: c::WSABUF { len: buf.len() as c::ULONG, buf: buf.as_mut_ptr() as *mut c::CHAR }, _p: PhantomData, } } @@ -74,15 +69,11 @@ impl<'a> IoSliceMut<'a> { #[inline] pub fn as_slice(&self) -> &[u8] { - unsafe { - slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) - } + unsafe { slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) } } #[inline] pub fn as_mut_slice(&mut self) -> &mut [u8] { - unsafe { - slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.len as usize) - } + unsafe { slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.len as usize) } } } diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index 7c400dce686f3..8631e50cf3888 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -5,7 +5,7 @@ use crate::os::windows::prelude::*; use crate::error::Error as StdError; -use crate::ffi::{OsString, OsStr}; +use crate::ffi::{OsStr, OsString}; use crate::fmt; use crate::io; use crate::os::windows::ffi::EncodeWide; @@ -37,8 +37,10 @@ pub fn error_string(mut errnum: i32) -> String { // `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx if (errnum & c::FACILITY_NT_BIT as i32) != 0 { // format according to https://support.microsoft.com/en-us/help/259693 - const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, - '.' as _, 'D' as _, 'L' as _, 'L' as _, 0]; + const NTDLL_DLL: &[u16] = &[ + 'N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, '.' as _, 'D' as _, 'L' as _, + 'L' as _, 0, + ]; module = c::GetModuleHandleW(NTDLL_DLL.as_ptr()); if module != ptr::null_mut() { @@ -47,19 +49,19 @@ pub fn error_string(mut errnum: i32) -> String { } } - let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM | - c::FORMAT_MESSAGE_IGNORE_INSERTS, - module, - errnum as c::DWORD, - langId, - buf.as_mut_ptr(), - buf.len() as c::DWORD, - ptr::null()) as usize; + let res = c::FormatMessageW( + flags | c::FORMAT_MESSAGE_FROM_SYSTEM | c::FORMAT_MESSAGE_IGNORE_INSERTS, + module, + errnum as c::DWORD, + langId, + buf.as_mut_ptr(), + buf.len() as c::DWORD, + ptr::null(), + ) as usize; if res == 0 { // Sometimes FormatMessageW can fail e.g., system doesn't like langId, let fm_err = errno(); - return format!("OS Error {} (FormatMessageW() returned error {})", - errnum, fm_err); + return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err); } match String::from_utf16(&buf[..res]) { @@ -68,9 +70,12 @@ pub fn error_string(mut errnum: i32) -> String { let len = msg.trim_end().len(); msg.truncate(len); msg - }, - Err(..) => format!("OS Error {} (FormatMessageW() returned \ - invalid UTF-16)", errnum), + } + Err(..) => format!( + "OS Error {} (FormatMessageW() returned \ + invalid UTF-16)", + errnum + ), } } } @@ -86,7 +91,9 @@ impl Iterator for Env { fn next(&mut self) -> Option<(OsString, OsString)> { loop { unsafe { - if *self.cur == 0 { return None } + if *self.cur == 0 { + return None; + } let p = &*self.cur as *const u16; let mut len = 0; while *p.offset(len) != 0 { @@ -106,8 +113,8 @@ impl Iterator for Env { }; return Some(( OsStringExt::from_wide(&s[..pos]), - OsStringExt::from_wide(&s[pos+1..]), - )) + OsStringExt::from_wide(&s[pos + 1..]), + )); } } } @@ -115,7 +122,9 @@ impl Iterator for Env { impl Drop for Env { fn drop(&mut self) { - unsafe { c::FreeEnvironmentStringsW(self.base); } + unsafe { + c::FreeEnvironmentStringsW(self.base); + } } } @@ -123,8 +132,7 @@ pub fn env() -> Env { unsafe { let ch = c::GetEnvironmentStringsW(); if ch as usize == 0 { - panic!("failure getting env string from OS: {}", - io::Error::last_os_error()); + panic!("failure getting env string from OS: {}", io::Error::last_os_error()); } Env { base: ch, cur: ch } } @@ -136,10 +144,7 @@ pub struct SplitPaths<'a> { } pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> { - SplitPaths { - data: unparsed.encode_wide(), - must_yield: true, - } + SplitPaths { data: unparsed.encode_wide(), must_yield: true } } impl<'a> Iterator for SplitPaths<'a> { @@ -158,7 +163,6 @@ impl<'a> Iterator for SplitPaths<'a> { // (The above is based on testing; there is no clear reference available // for the grammar.) - let must_yield = self.must_yield; self.must_yield = false; @@ -169,7 +173,7 @@ impl<'a> Iterator for SplitPaths<'a> { in_quote = !in_quote; } else if b == ';' as u16 && !in_quote { self.must_yield = true; - break + break; } else { in_progress.push(b) } @@ -187,17 +191,21 @@ impl<'a> Iterator for SplitPaths<'a> { pub struct JoinPathsError; pub fn join_paths(paths: I) -> Result - where I: Iterator, T: AsRef +where + I: Iterator, + T: AsRef, { let mut joined = Vec::new(); let sep = b';' as u16; for (i, path) in paths.enumerate() { let path = path.as_ref(); - if i > 0 { joined.push(sep) } + if i > 0 { + joined.push(sep) + } let v = path.encode_wide().collect::>(); if v.contains(&(b'"' as u16)) { - return Err(JoinPathsError) + return Err(JoinPathsError); } else if v.contains(&sep) { joined.push(b'"' as u16); joined.extend_from_slice(&v[..]); @@ -217,19 +225,20 @@ impl fmt::Display for JoinPathsError { } impl StdError for JoinPathsError { - fn description(&self) -> &str { "failed to join paths" } + fn description(&self) -> &str { + "failed to join paths" + } } pub fn current_exe() -> io::Result { - super::fill_utf16_buf(|buf, sz| unsafe { - c::GetModuleFileNameW(ptr::null_mut(), buf, sz) - }, super::os2path) + super::fill_utf16_buf( + |buf, sz| unsafe { c::GetModuleFileNameW(ptr::null_mut(), buf, sz) }, + super::os2path, + ) } pub fn getcwd() -> io::Result { - super::fill_utf16_buf(|buf, sz| unsafe { - c::GetCurrentDirectoryW(sz, buf) - }, super::os2path) + super::fill_utf16_buf(|buf, sz| unsafe { c::GetCurrentDirectoryW(sz, buf) }, super::os2path) } pub fn chdir(p: &path::Path) -> io::Result<()> { @@ -237,18 +246,15 @@ pub fn chdir(p: &path::Path) -> io::Result<()> { let mut p = p.encode_wide().collect::>(); p.push(0); - cvt(unsafe { - c::SetCurrentDirectoryW(p.as_ptr()) - }).map(|_| ()) + cvt(unsafe { c::SetCurrentDirectoryW(p.as_ptr()) }).map(|_| ()) } pub fn getenv(k: &OsStr) -> io::Result> { let k = to_u16s(k)?; - let res = super::fill_utf16_buf(|buf, sz| unsafe { - c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) - }, |buf| { - OsStringExt::from_wide(buf) - }); + let res = super::fill_utf16_buf( + |buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) }, + |buf| OsStringExt::from_wide(buf), + ); match res { Ok(value) => Ok(Some(value)), Err(e) => { @@ -265,22 +271,16 @@ pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let k = to_u16s(k)?; let v = to_u16s(v)?; - cvt(unsafe { - c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) - }).map(|_| ()) + cvt(unsafe { c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) }).map(|_| ()) } pub fn unsetenv(n: &OsStr) -> io::Result<()> { let v = to_u16s(n)?; - cvt(unsafe { - c::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) - }).map(|_| ()) + cvt(unsafe { c::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) }).map(|_| ()) } pub fn temp_dir() -> PathBuf { - super::fill_utf16_buf(|buf, sz| unsafe { - c::GetTempPathW(sz, buf) - }, super::os2path).unwrap() + super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPathW(sz, buf) }, super::os2path).unwrap() } #[cfg(not(target_vendor = "uwp"))] @@ -291,16 +291,20 @@ fn home_dir_crt() -> Option { let me = c::GetCurrentProcess(); let mut token = ptr::null_mut(); if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 { - return None + return None; } let _handle = Handle::new(token); - super::fill_utf16_buf(|buf, mut sz| { - match c::GetUserProfileDirectoryW(token, buf, &mut sz) { - 0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0, - 0 => sz, - _ => sz - 1, // sz includes the null terminator - } - }, super::os2path).ok() + super::fill_utf16_buf( + |buf, mut sz| { + match c::GetUserProfileDirectoryW(token, buf, &mut sz) { + 0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0, + 0 => sz, + _ => sz - 1, // sz includes the null terminator + } + }, + super::os2path, + ) + .ok() } } @@ -310,9 +314,10 @@ fn home_dir_crt() -> Option { } pub fn home_dir() -> Option { - crate::env::var_os("HOME").or_else(|| { - crate::env::var_os("USERPROFILE") - }).map(PathBuf::from).or_else(|| home_dir_crt()) + crate::env::var_os("HOME") + .or_else(|| crate::env::var_os("USERPROFILE")) + .map(PathBuf::from) + .or_else(|| home_dir_crt()) } pub fn exit(code: i32) -> ! { @@ -332,7 +337,10 @@ mod tests { #[test] fn ntstatus_error() { const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001; - assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _) - .to_string().contains("FormatMessageW() returned error")); + assert!( + !Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _) + .to_string() + .contains("FormatMessageW() returned error") + ); } } diff --git a/src/libstd/sys/windows/os_str.rs b/src/libstd/sys/windows/os_str.rs index c7a82e092528e..e451e0cfb5bc4 100644 --- a/src/libstd/sys/windows/os_str.rs +++ b/src/libstd/sys/windows/os_str.rs @@ -1,17 +1,16 @@ /// The underlying OsString/OsStr implementation on Windows is a /// wrapper around the "WTF-8" encoding; see the `wtf8` module for more. - use crate::borrow::Cow; use crate::fmt; -use crate::sys_common::wtf8::{Wtf8, Wtf8Buf}; use crate::mem; use crate::rc::Rc; use crate::sync::Arc; -use crate::sys_common::{AsInner, IntoInner, FromInner}; +use crate::sys_common::wtf8::{Wtf8, Wtf8Buf}; +use crate::sys_common::{AsInner, FromInner, IntoInner}; #[derive(Clone, Hash)] pub struct Buf { - pub inner: Wtf8Buf + pub inner: Wtf8Buf, } impl IntoInner for Buf { @@ -45,7 +44,7 @@ impl fmt::Display for Buf { } pub struct Slice { - pub inner: Wtf8 + pub inner: Wtf8, } impl fmt::Debug for Slice { @@ -62,9 +61,7 @@ impl fmt::Display for Slice { impl Buf { pub fn with_capacity(capacity: usize) -> Buf { - Buf { - inner: Wtf8Buf::with_capacity(capacity) - } + Buf { inner: Wtf8Buf::with_capacity(capacity) } } pub fn clear(&mut self) { diff --git a/src/libstd/sys/windows/path.rs b/src/libstd/sys/windows/path.rs index 7eae28cb14fbc..524f21f889bc2 100644 --- a/src/libstd/sys/windows/path.rs +++ b/src/libstd/sys/windows/path.rs @@ -1,6 +1,6 @@ -use crate::path::Prefix; use crate::ffi::OsStr; use crate::mem; +use crate::path::Prefix; fn os_str_as_u8_slice(s: &OsStr) -> &[u8] { unsafe { mem::transmute(s) } @@ -38,8 +38,9 @@ pub fn parse_prefix(path: &OsStr) -> Option> { // \\?\UNC\server\share path = &path[4..]; let (server, share) = match parse_two_comps(path, is_verbatim_sep) { - Some((server, share)) => - (u8_slice_as_os_str(server), u8_slice_as_os_str(share)), + Some((server, share)) => { + (u8_slice_as_os_str(server), u8_slice_as_os_str(share)) + } None => (u8_slice_as_os_str(path), u8_slice_as_os_str(&[])), }; return Some(VerbatimUNC(server, share)); @@ -70,7 +71,7 @@ pub fn parse_prefix(path: &OsStr) -> Option> { } _ => (), } - } else if path.get(1) == Some(& b':') { + } else if path.get(1) == Some(&b':') { // C: let c = path[0]; if c.is_ascii() && (c as char).is_alphabetic() { diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs index 041d5385eb69b..992e634dea510 100644 --- a/src/libstd/sys/windows/pipe.rs +++ b/src/libstd/sys/windows/pipe.rs @@ -6,8 +6,8 @@ use crate::mem; use crate::path::Path; use crate::ptr; use crate::slice; -use crate::sync::atomic::Ordering::SeqCst; use crate::sync::atomic::AtomicUsize; +use crate::sync::atomic::Ordering::SeqCst; use crate::sys::c; use crate::sys::fs::{File, OpenOptions}; use crate::sys::handle::Handle; @@ -63,32 +63,32 @@ pub fn anon_pipe(ours_readable: bool, their_handle_inheritable: bool) -> io::Res let mut reject_remote_clients_flag = c::PIPE_REJECT_REMOTE_CLIENTS; loop { tries += 1; - name = format!(r"\\.\pipe\__rust_anonymous_pipe1__.{}.{}", - c::GetCurrentProcessId(), - random_number()); - let wide_name = OsStr::new(&name) - .encode_wide() - .chain(Some(0)) - .collect::>(); - let mut flags = c::FILE_FLAG_FIRST_PIPE_INSTANCE | - c::FILE_FLAG_OVERLAPPED; + name = format!( + r"\\.\pipe\__rust_anonymous_pipe1__.{}.{}", + c::GetCurrentProcessId(), + random_number() + ); + let wide_name = OsStr::new(&name).encode_wide().chain(Some(0)).collect::>(); + let mut flags = c::FILE_FLAG_FIRST_PIPE_INSTANCE | c::FILE_FLAG_OVERLAPPED; if ours_readable { flags |= c::PIPE_ACCESS_INBOUND; } else { flags |= c::PIPE_ACCESS_OUTBOUND; } - let handle = c::CreateNamedPipeW(wide_name.as_ptr(), - flags, - c::PIPE_TYPE_BYTE | - c::PIPE_READMODE_BYTE | - c::PIPE_WAIT | - reject_remote_clients_flag, - 1, - 4096, - 4096, - 0, - ptr::null_mut()); + let handle = c::CreateNamedPipeW( + wide_name.as_ptr(), + flags, + c::PIPE_TYPE_BYTE + | c::PIPE_READMODE_BYTE + | c::PIPE_WAIT + | reject_remote_clients_flag, + 1, + 4096, + 4096, + 0, + ptr::null_mut(), + ); // We pass the `FILE_FLAG_FIRST_PIPE_INSTANCE` flag above, and we're // also just doing a best effort at selecting a unique name. If @@ -112,18 +112,19 @@ pub fn anon_pipe(ours_readable: bool, their_handle_inheritable: bool) -> io::Res let raw_os_err = err.raw_os_error(); if tries < 10 { if raw_os_err == Some(c::ERROR_ACCESS_DENIED as i32) { - continue - } else if reject_remote_clients_flag != 0 && - raw_os_err == Some(c::ERROR_INVALID_PARAMETER as i32) { + continue; + } else if reject_remote_clients_flag != 0 + && raw_os_err == Some(c::ERROR_INVALID_PARAMETER as i32) + { reject_remote_clients_flag = 0; tries -= 1; - continue + continue; } } - return Err(err) + return Err(err); } ours = Handle::new(handle); - break + break; } // Connect to the named pipe we just created. This handle is going to be @@ -158,7 +159,7 @@ fn random_number() -> usize { static N: AtomicUsize = AtomicUsize::new(0); loop { if N.load(SeqCst) != 0 { - return N.fetch_add(1, SeqCst) + return N.fetch_add(1, SeqCst); } N.store(hashmap_random_keys().0 as usize, SeqCst); @@ -166,8 +167,12 @@ fn random_number() -> usize { } impl AnonPipe { - pub fn handle(&self) -> &Handle { &self.inner } - pub fn into_handle(self) -> Handle { self.inner } + pub fn handle(&self) -> &Handle { + &self.inner + } + pub fn into_handle(self) -> Handle { + self.inner + } pub fn read(&self, buf: &mut [u8]) -> io::Result { self.inner.read(buf) @@ -186,10 +191,7 @@ impl AnonPipe { } } -pub fn read2(p1: AnonPipe, - v1: &mut Vec, - p2: AnonPipe, - v2: &mut Vec) -> io::Result<()> { +pub fn read2(p1: AnonPipe, v1: &mut Vec, p2: AnonPipe, v2: &mut Vec) -> io::Result<()> { let p1 = p1.into_handle(); let p2 = p2.into_handle(); @@ -206,19 +208,17 @@ pub fn read2(p1: AnonPipe, // duration of the I/O operation (where tons of operations can also fail). // The destructor for `AsyncPipe` ends up taking care of most of this. loop { - let res = unsafe { - c::WaitForMultipleObjects(2, objs.as_ptr(), c::FALSE, c::INFINITE) - }; + let res = unsafe { c::WaitForMultipleObjects(2, objs.as_ptr(), c::FALSE, c::INFINITE) }; if res == c::WAIT_OBJECT_0 { if !p1.result()? || !p1.schedule_read()? { - return p2.finish() + return p2.finish(); } } else if res == c::WAIT_OBJECT_0 + 1 { if !p2.result()? || !p2.schedule_read()? { - return p1.finish() + return p1.finish(); } } else { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } } } @@ -251,17 +251,9 @@ impl<'a> AsyncPipe<'a> { // and the only time an even will go back to "unset" will be once an // I/O operation is successfully scheduled (what we want). let event = Handle::new_event(true, true)?; - let mut overlapped: Box = unsafe { - Box::new(mem::zeroed()) - }; + let mut overlapped: Box = unsafe { Box::new(mem::zeroed()) }; overlapped.hEvent = event.raw(); - Ok(AsyncPipe { - pipe, - overlapped, - event, - dst, - state: State::NotReading, - }) + Ok(AsyncPipe { pipe, overlapped, event, dst, state: State::NotReading }) } /// Executes an overlapped read operation. @@ -306,9 +298,7 @@ impl<'a> AsyncPipe<'a> { fn result(&mut self) -> io::Result { let amt = match self.state { State::NotReading => return Ok(true), - State::Reading => { - self.pipe.overlapped_result(&mut *self.overlapped, true)? - } + State::Reading => self.pipe.overlapped_result(&mut *self.overlapped, true)?, State::Read(amt) => amt, }; self.state = State::NotReading; @@ -364,6 +354,5 @@ unsafe fn slice_to_end(v: &mut Vec) -> &mut [u8] { if v.capacity() == v.len() { v.reserve(1); } - slice::from_raw_parts_mut(v.as_mut_ptr().add(v.len()), - v.capacity() - v.len()) + slice::from_raw_parts_mut(v.as_mut_ptr().add(v.len()), v.capacity() - v.len()) } diff --git a/src/libstd/sys/windows/rand.rs b/src/libstd/sys/windows/rand.rs index 993831bec1886..87ea416bf675a 100644 --- a/src/libstd/sys/windows/rand.rs +++ b/src/libstd/sys/windows/rand.rs @@ -5,13 +5,10 @@ use crate::sys::c; #[cfg(not(target_vendor = "uwp"))] pub fn hashmap_random_keys() -> (u64, u64) { let mut v = (0, 0); - let ret = unsafe { - c::RtlGenRandom(&mut v as *mut _ as *mut u8, - mem::size_of_val(&v) as c::ULONG) - }; + let ret = + unsafe { c::RtlGenRandom(&mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG) }; if ret == 0 { - panic!("couldn't generate random bytes: {}", - io::Error::last_os_error()); + panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); } v } @@ -22,13 +19,15 @@ pub fn hashmap_random_keys() -> (u64, u64) { let mut v = (0, 0); let ret = unsafe { - c::BCryptGenRandom(ptr::null_mut(), &mut v as *mut _ as *mut u8, - mem::size_of_val(&v) as c::ULONG, - c::BCRYPT_USE_SYSTEM_PREFERRED_RNG) + c::BCryptGenRandom( + ptr::null_mut(), + &mut v as *mut _ as *mut u8, + mem::size_of_val(&v) as c::ULONG, + c::BCRYPT_USE_SYSTEM_PREFERRED_RNG, + ) }; if ret != 0 { - panic!("couldn't generate random bytes: {}", - io::Error::last_os_error()); + panic!("couldn't generate random bytes: {}", io::Error::last_os_error()); } - return v + return v; } diff --git a/src/libstd/sys/windows/stack_overflow.rs b/src/libstd/sys/windows/stack_overflow.rs index d5b7765f9ff5f..187ad4e66c3ef 100644 --- a/src/libstd/sys/windows/stack_overflow.rs +++ b/src/libstd/sys/windows/stack_overflow.rs @@ -1,7 +1,7 @@ #![cfg_attr(test, allow(dead_code))] -use crate::sys_common::util::report_overflow; use crate::sys::c; +use crate::sys_common::util::report_overflow; pub struct Handler; @@ -18,8 +18,7 @@ impl Handler { } } -extern "system" fn vectored_handler(ExceptionInfo: *mut c::EXCEPTION_POINTERS) - -> c::LONG { +extern "system" fn vectored_handler(ExceptionInfo: *mut c::EXCEPTION_POINTERS) -> c::LONG { unsafe { let rec = &(*(*ExceptionInfo).ExceptionRecord); let code = rec.ExceptionCode; diff --git a/src/libstd/sys/windows/stdio.rs b/src/libstd/sys/windows/stdio.rs index b1e76b3b755da..f322c2b1d96c9 100644 --- a/src/libstd/sys/windows/stdio.rs +++ b/src/libstd/sys/windows/stdio.rs @@ -68,9 +68,11 @@ fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result { let utf8 = match str::from_utf8(&data[..len]) { Ok(s) => s, Err(ref e) if e.valid_up_to() == 0 => { - return Err(io::Error::new(io::ErrorKind::InvalidData, - "Windows stdio in console mode does not support writing non-UTF-8 byte sequences")) - }, + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Windows stdio in console mode does not support writing non-UTF-8 byte sequences", + )); + } Err(e) => str::from_utf8(&data[..e.valid_up_to()]).unwrap(), }; let mut utf16 = [0u16; MAX_BUFFER_SIZE / 2]; @@ -93,18 +95,19 @@ fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result { // write the missing surrogate out now. // Buffering it would mean we have to lie about the number of bytes written. let first_char_remaining = utf16[written]; - if first_char_remaining >= 0xDCEE && first_char_remaining <= 0xDFFF { // low surrogate + if first_char_remaining >= 0xDCEE && first_char_remaining <= 0xDFFF { + // low surrogate // We just hope this works, and give up otherwise - let _ = write_u16s(handle, &utf16[written..written+1]); + let _ = write_u16s(handle, &utf16[written..written + 1]); written += 1; } // Calculate the number of bytes of `utf8` that were actually written. let mut count = 0; for ch in utf16[..written].iter() { count += match ch { - 0x0000 ..= 0x007F => 1, - 0x0080 ..= 0x07FF => 2, - 0xDCEE ..= 0xDFFF => 1, // Low surrogate. We already counted 3 bytes for the other. + 0x0000..=0x007F => 1, + 0x0080..=0x07FF => 2, + 0xDCEE..=0xDFFF => 1, // Low surrogate. We already counted 3 bytes for the other. _ => 3, }; } @@ -116,11 +119,13 @@ fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result { fn write_u16s(handle: c::HANDLE, data: &[u16]) -> io::Result { let mut written = 0; cvt(unsafe { - c::WriteConsoleW(handle, - data.as_ptr() as c::LPCVOID, - data.len() as u32, - &mut written, - ptr::null_mut()) + c::WriteConsoleW( + handle, + data.as_ptr() as c::LPCVOID, + data.len() as u32, + &mut written, + ptr::null_mut(), + ) })?; Ok(written as usize) } @@ -144,9 +149,11 @@ impl io::Read for Stdin { if buf.len() == 0 { return Ok(0); } else if buf.len() < 4 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "Windows stdin in console mode does not support a buffer too small to \ - guarantee holding one arbitrary UTF-8 character (4 bytes)")) + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Windows stdin in console mode does not support a buffer too small to \ + guarantee holding one arbitrary UTF-8 character (4 bytes)", + )); } let mut utf16_buf = [0u16; MAX_BUFFER_SIZE / 2]; @@ -160,15 +167,15 @@ impl io::Read for Stdin { } } - // We assume that if the last `u16` is an unpaired surrogate they got sliced apart by our // buffer size, and keep it around for the next read hoping to put them together. // This is a best effort, and may not work if we are not the only reader on Stdin. -fn read_u16s_fixup_surrogates(handle: c::HANDLE, - buf: &mut [u16], - mut amount: usize, - surrogate: &mut u16) -> io::Result -{ +fn read_u16s_fixup_surrogates( + handle: c::HANDLE, + buf: &mut [u16], + mut amount: usize, + surrogate: &mut u16, +) -> io::Result { // Insert possibly remaining unpaired surrogate from last read. let mut start = 0; if *surrogate != 0 { @@ -186,7 +193,8 @@ fn read_u16s_fixup_surrogates(handle: c::HANDLE, if amount > 0 { let last_char = buf[amount - 1]; - if last_char >= 0xD800 && last_char <= 0xDBFF { // high surrogate + if last_char >= 0xD800 && last_char <= 0xDBFF { + // high surrogate *surrogate = last_char; amount -= 1; } @@ -209,11 +217,13 @@ fn read_u16s(handle: c::HANDLE, buf: &mut [u16]) -> io::Result { let mut amount = 0; cvt(unsafe { - c::ReadConsoleW(handle, - buf.as_mut_ptr() as c::LPVOID, - buf.len() as u32, - &mut amount, - &mut input_control as c::PCONSOLE_READCONSOLE_CONTROL) + c::ReadConsoleW( + handle, + buf.as_mut_ptr() as c::LPVOID, + buf.len() as u32, + &mut amount, + &mut input_control as c::PCONSOLE_READCONSOLE_CONTROL, + ) })?; if amount > 0 && buf[amount as usize - 1] == CTRL_Z { @@ -233,9 +243,11 @@ fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result { } Err(_) => { // We can't really do any better than forget all data and return an error. - return Err(io::Error::new(io::ErrorKind::InvalidData, + return Err(io::Error::new( + io::ErrorKind::InvalidData, "Windows stdin in console mode does not support non-UTF-16 input; \ - encountered unpaired surrogate")) + encountered unpaired surrogate", + )); } } } diff --git a/src/libstd/sys/windows/stdio_uwp.rs b/src/libstd/sys/windows/stdio_uwp.rs index 489d3df28600b..0f2178f73532f 100644 --- a/src/libstd/sys/windows/stdio_uwp.rs +++ b/src/libstd/sys/windows/stdio_uwp.rs @@ -1,12 +1,11 @@ #![unstable(issue = "0", feature = "windows_stdio")] use crate::io; +use crate::mem::ManuallyDrop; use crate::sys::c; use crate::sys::handle::Handle; -use crate::mem::ManuallyDrop; -pub struct Stdin { -} +pub struct Stdin {} pub struct Stdout; pub struct Stderr; @@ -32,7 +31,7 @@ fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result { impl Stdin { pub fn new() -> io::Result { - Ok(Stdin { }) + Ok(Stdin {}) } } diff --git a/src/libstd/sys/windows/thread.rs b/src/libstd/sys/windows/thread.rs index ebdf3612e0602..c828243a59b11 100644 --- a/src/libstd/sys/windows/thread.rs +++ b/src/libstd/sys/windows/thread.rs @@ -1,5 +1,5 @@ -use crate::io; use crate::ffi::CStr; +use crate::io; use crate::mem; use crate::ptr; use crate::sys::c; @@ -14,13 +14,12 @@ use super::to_u16s; pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024; pub struct Thread { - handle: Handle + handle: Handle, } impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(stack: usize, p: Box) - -> io::Result { + pub unsafe fn new(stack: usize, p: Box) -> io::Result { let p = box p; // FIXME On UNIX, we guard against stack sizes that are too small but @@ -31,10 +30,14 @@ impl Thread { // Round up to the next 64 kB because that's what the NT kernel does, // might as well make it explicit. let stack_size = (stack + 0xfffe) & (!0xfffe); - let ret = c::CreateThread(ptr::null_mut(), stack_size, - thread_start, &*p as *const _ as *mut _, - c::STACK_SIZE_PARAM_IS_A_RESERVATION, - ptr::null_mut()); + let ret = c::CreateThread( + ptr::null_mut(), + stack_size, + thread_start, + &*p as *const _ as *mut _, + c::STACK_SIZE_PARAM_IS_A_RESERVATION, + ptr::null_mut(), + ); return if ret as usize == 0 { Err(io::Error::last_os_error()) @@ -44,7 +47,9 @@ impl Thread { }; extern "system" fn thread_start(main: *mut c_void) -> c::DWORD { - unsafe { start_thread(main as *mut u8); } + unsafe { + start_thread(main as *mut u8); + } 0 } } @@ -52,7 +57,9 @@ impl Thread { pub fn set_name(name: &CStr) { if let Ok(utf8) = name.to_str() { if let Ok(utf16) = to_u16s(utf8) { - unsafe { c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr()); }; + unsafe { + c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr()); + }; }; }; } @@ -60,8 +67,7 @@ impl Thread { pub fn join(self) { let rc = unsafe { c::WaitForSingleObject(self.handle.raw(), c::INFINITE) }; if rc == c::WAIT_FAILED { - panic!("failed to join on thread: {}", - io::Error::last_os_error()); + panic!("failed to join on thread: {}", io::Error::last_os_error()); } } @@ -69,23 +75,31 @@ impl Thread { // This function will return 0 if there are no other threads to execute, // but this also means that the yield was useless so this isn't really a // case that needs to be worried about. - unsafe { c::SwitchToThread(); } + unsafe { + c::SwitchToThread(); + } } pub fn sleep(dur: Duration) { - unsafe { - c::Sleep(super::dur2timeout(dur)) - } + unsafe { c::Sleep(super::dur2timeout(dur)) } } - pub fn handle(&self) -> &Handle { &self.handle } + pub fn handle(&self) -> &Handle { + &self.handle + } - pub fn into_handle(self) -> Handle { self.handle } + pub fn into_handle(self) -> Handle { + self.handle + } } #[cfg_attr(test, allow(dead_code))] pub mod guard { pub type Guard = !; - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + pub unsafe fn current() -> Option { + None + } + pub unsafe fn init() -> Option { + None + } } diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs index 728257cdd4bb1..e0bb102b3afe5 100644 --- a/src/libstd/sys/windows/thread_local.rs +++ b/src/libstd/sys/windows/thread_local.rs @@ -5,7 +5,7 @@ use crate::sync::atomic::Ordering::SeqCst; use crate::sys::c; pub type Key = c::DWORD; -pub type Dtor = unsafe extern fn(*mut u8); +pub type Dtor = unsafe extern "C" fn(*mut u8); // Turns out, like pretty much everything, Windows is pretty close the // functionality that Unix provides, but slightly different! In the case of @@ -111,11 +111,7 @@ struct Node { } unsafe fn register_dtor(key: Key, dtor: Dtor) { - let mut node = Box::new(Node { - key, - dtor, - next: ptr::null_mut(), - }); + let mut node = Box::new(Node { key, dtor, next: ptr::null_mut() }); let mut head = DTORS.load(SeqCst); loop { @@ -192,15 +188,12 @@ unsafe fn register_dtor(key: Key, dtor: Dtor) { #[link_section = ".CRT$XLB"] #[allow(dead_code, unused_variables)] #[used] // we don't want LLVM eliminating this symbol for any reason, and - // when the symbol makes it to the linker the linker will take over -pub static p_thread_callback: unsafe extern "system" fn(c::LPVOID, c::DWORD, - c::LPVOID) = - on_tls_callback; +// when the symbol makes it to the linker the linker will take over +pub static p_thread_callback: unsafe extern "system" fn(c::LPVOID, c::DWORD, c::LPVOID) = + on_tls_callback; #[allow(dead_code, unused_variables)] -unsafe extern "system" fn on_tls_callback(h: c::LPVOID, - dwReason: c::DWORD, - pv: c::LPVOID) { +unsafe extern "system" fn on_tls_callback(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID) { if dwReason == c::DLL_THREAD_DETACH || dwReason == c::DLL_PROCESS_DETACH { run_dtors(); } @@ -210,7 +203,9 @@ unsafe extern "system" fn on_tls_callback(h: c::LPVOID, reference_tls_used(); #[cfg(target_env = "msvc")] unsafe fn reference_tls_used() { - extern { static _tls_used: u8; } + extern "C" { + static _tls_used: u8; + } crate::intrinsics::volatile_load(&_tls_used); } #[cfg(not(target_env = "msvc"))] @@ -222,7 +217,7 @@ unsafe fn run_dtors() { let mut any_run = true; for _ in 0..5 { if !any_run { - break + break; } any_run = false; let mut cur = DTORS.load(SeqCst);