diff --git a/src/libfmt_macros/lib.rs b/src/libfmt_macros/lib.rs index 24b19028ac117..900c6ed5ff322 100644 --- a/src/libfmt_macros/lib.rs +++ b/src/libfmt_macros/lib.rs @@ -442,20 +442,9 @@ impl<'a> Parser<'a> { Some(ArgumentIs(i)) } else { match self.cur.peek() { - Some(&(_, c)) if c.is_alphabetic() => { + Some(&(_, c)) if rustc_lexer::is_id_start(c) => { Some(ArgumentNamed(Symbol::intern(self.word()))) } - Some(&(pos, c)) if c == '_' => { - let invalid_name = self.string(pos); - self.err_with_note(format!("invalid argument name `{}`", invalid_name), - "invalid argument name", - "argument names cannot start with an underscore", - self.to_span_index(pos).to( - self.to_span_index(pos + invalid_name.len()) - ), - ); - Some(ArgumentNamed(Symbol::intern(invalid_name))) - }, // This is an `ArgumentNext`. // Record the fact and do the resolution after parsing the @@ -611,22 +600,34 @@ impl<'a> Parser<'a> { /// Rust identifier, except that it can't start with `_` character. fn word(&mut self) -> &'a str { let start = match self.cur.peek() { - Some(&(pos, c)) if c != '_' && rustc_lexer::is_id_start(c) => { + Some(&(pos, c)) if rustc_lexer::is_id_start(c) => { self.cur.next(); pos } _ => { - return &self.input[..0]; + return ""; } }; + let mut end = None; while let Some(&(pos, c)) = self.cur.peek() { if rustc_lexer::is_id_continue(c) { self.cur.next(); } else { - return &self.input[start..pos]; + end = Some(pos); + break; } } - &self.input[start..self.input.len()] + let end = end.unwrap_or(self.input.len()); + let word = &self.input[start..end]; + if word == "_" { + self.err_with_note( + "invalid argument name `_`", + "invalid argument name", + "argument name cannot be a single underscore", + self.to_span_index(start).to(self.to_span_index(end)), + ); + } + word } /// Optionally parses an integer at the current position. This doesn't deal diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 7db0aad390960..41bdfea53e559 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -17,7 +17,7 @@ #![stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")] -pub use core::ascii::{EscapeDefault, escape_default}; +pub use core::ascii::{escape_default, EscapeDefault}; /// Extension methods for ASCII-subset only operations. /// diff --git a/src/libstd/backtrace.rs b/src/libstd/backtrace.rs index 9f400713a86d4..5ba1c940251dc 100644 --- a/src/libstd/backtrace.rs +++ b/src/libstd/backtrace.rs @@ -95,10 +95,10 @@ use crate::env; use crate::fmt; use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use crate::sync::Mutex; -use crate::sys_common::backtrace::{output_filename, lock}; +use crate::sys_common::backtrace::{lock, output_filename}; use crate::vec::Vec; -use backtrace_rs as backtrace; use backtrace::BytesOrWideString; +use backtrace_rs as backtrace; /// A captured OS thread stack backtrace. /// diff --git a/src/libstd/benches/hash/map.rs b/src/libstd/benches/hash/map.rs index 25425c5968e25..bf646cbae47db 100644 --- a/src/libstd/benches/hash/map.rs +++ b/src/libstd/benches/hash/map.rs @@ -1,7 +1,7 @@ #![cfg(test)] -use test::Bencher; use std::collections::HashMap; +use test::Bencher; #[bench] fn new_drop(b: &mut Bencher) { diff --git a/src/libstd/collections/mod.rs b/src/libstd/collections/mod.rs index f5957466be841..522b8b25144f4 100644 --- a/src/libstd/collections/mod.rs +++ b/src/libstd/collections/mod.rs @@ -413,20 +413,20 @@ #[doc(hidden)] pub use crate::ops::Bound; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::collections::{BinaryHeap, BTreeMap, BTreeSet}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::collections::{LinkedList, VecDeque}; -#[stable(feature = "rust1", since = "1.0.0")] pub use alloc_crate::collections::{binary_heap, btree_map, btree_set}; #[stable(feature = "rust1", since = "1.0.0")] pub use alloc_crate::collections::{linked_list, vec_deque}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::collections::{BTreeMap, BTreeSet, BinaryHeap}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::collections::{LinkedList, VecDeque}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::hash_map::HashMap; #[stable(feature = "rust1", since = "1.0.0")] pub use self::hash_set::HashSet; -#[unstable(feature = "try_reserve", reason = "new API", issue="48043")] +#[unstable(feature = "try_reserve", reason = "new API", issue = "48043")] pub use alloc_crate::collections::TryReserveError; mod hash; diff --git a/src/libstd/env.rs b/src/libstd/env.rs index 651010d136611..cf71b61b917a7 100644 --- a/src/libstd/env.rs +++ b/src/libstd/env.rs @@ -78,7 +78,9 @@ pub fn set_current_dir>(path: P) -> io::Result<()> { /// /// [`std::env::vars`]: fn.vars.html #[stable(feature = "env", since = "1.0.0")] -pub struct Vars { inner: VarsOs } +pub struct Vars { + inner: VarsOs, +} /// An iterator over a snapshot of the environment variables of this process. /// @@ -87,7 +89,9 @@ pub struct Vars { inner: VarsOs } /// /// [`std::env::vars_os`]: fn.vars_os.html #[stable(feature = "env", since = "1.0.0")] -pub struct VarsOs { inner: os_imp::Env } +pub struct VarsOs { + inner: os_imp::Env, +} /// Returns an iterator of (variable, value) pairs of strings, for all the /// environment variables of the current process. @@ -147,11 +151,11 @@ pub fn vars_os() -> VarsOs { impl Iterator for Vars { type Item = (String, String); fn next(&mut self) -> Option<(String, String)> { - self.inner.next().map(|(a, b)| { - (a.into_string().unwrap(), b.into_string().unwrap()) - }) + self.inner.next().map(|(a, b)| (a.into_string().unwrap(), b.into_string().unwrap())) + } + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() } - fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } #[stable(feature = "std_debug", since = "1.16.0")] @@ -164,8 +168,12 @@ impl fmt::Debug for Vars { #[stable(feature = "env", since = "1.0.0")] impl Iterator for VarsOs { type Item = (OsString, OsString); - fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() } - fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } + fn next(&mut self) -> Option<(OsString, OsString)> { + self.inner.next() + } + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } } #[stable(feature = "std_debug", since = "1.16.0")] @@ -239,9 +247,8 @@ pub fn var_os>(key: K) -> Option { } fn _var_os(key: &OsStr) -> Option { - os_imp::getenv(key).unwrap_or_else(|e| { - panic!("failed to get environment variable `{:?}`: {}", key, e) - }) + os_imp::getenv(key) + .unwrap_or_else(|e| panic!("failed to get environment variable `{:?}`: {}", key, e)) } /// The error type for operations interacting with environment variables. @@ -321,8 +328,7 @@ pub fn set_var, V: AsRef>(k: K, v: V) { fn _set_var(k: &OsStr, v: &OsStr) { os_imp::setenv(k, v).unwrap_or_else(|e| { - panic!("failed to set environment variable `{:?}` to `{:?}`: {}", - k, v, e) + panic!("failed to set environment variable `{:?}` to `{:?}`: {}", k, v, e) }) } @@ -363,9 +369,8 @@ pub fn remove_var>(k: K) { } fn _remove_var(k: &OsStr) { - os_imp::unsetenv(k).unwrap_or_else(|e| { - panic!("failed to remove environment variable `{:?}`: {}", k, e) - }) + os_imp::unsetenv(k) + .unwrap_or_else(|e| panic!("failed to remove environment variable `{:?}`: {}", k, e)) } /// An iterator that splits an environment variable into paths according to @@ -379,7 +384,9 @@ fn _remove_var(k: &OsStr) { /// [`PathBuf`]: ../../std/path/struct.PathBuf.html /// [`std::env::split_paths`]: fn.split_paths.html #[stable(feature = "env", since = "1.0.0")] -pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> } +pub struct SplitPaths<'a> { + inner: os_imp::SplitPaths<'a>, +} /// Parses input according to platform conventions for the `PATH` /// environment variable. @@ -412,8 +419,12 @@ pub fn split_paths + ?Sized>(unparsed: &T) -> SplitPaths<'_> { #[stable(feature = "env", since = "1.0.0")] impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; - fn next(&mut self) -> Option { self.inner.next() } - fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } + fn next(&mut self) -> Option { + self.inner.next() + } + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } } #[stable(feature = "std_debug", since = "1.16.0")] @@ -430,7 +441,7 @@ impl fmt::Debug for SplitPaths<'_> { #[derive(Debug)] #[stable(feature = "env", since = "1.0.0")] pub struct JoinPathsError { - inner: os_imp::JoinPathsError + inner: os_imp::JoinPathsError, } /// Joins a collection of [`Path`]s appropriately for the `PATH` @@ -499,11 +510,11 @@ pub struct JoinPathsError { /// [`env::split_paths`]: fn.split_paths.html #[stable(feature = "env", since = "1.0.0")] pub fn join_paths(paths: I) -> Result - where I: IntoIterator, T: AsRef +where + I: IntoIterator, + T: AsRef, { - os_imp::join_paths(paths.into_iter()).map_err(|e| { - JoinPathsError { inner: e } - }) + os_imp::join_paths(paths.into_iter()).map_err(|e| JoinPathsError { inner: e }) } #[stable(feature = "env", since = "1.0.0")] @@ -515,7 +526,9 @@ impl fmt::Display for JoinPathsError { #[stable(feature = "env", since = "1.0.0")] impl Error for JoinPathsError { - fn description(&self) -> &str { self.inner.description() } + fn description(&self) -> &str { + self.inner.description() + } } /// Returns the path of the current user's home directory if known. @@ -549,9 +562,11 @@ impl Error for JoinPathsError { /// None => println!("Impossible to get your home dir!"), /// } /// ``` -#[rustc_deprecated(since = "1.29.0", +#[rustc_deprecated( + since = "1.29.0", reason = "This function's behavior is unexpected and probably not what you want. \ - Consider using the home_dir function from https://crates.io/crates/dirs instead.")] + Consider using the home_dir function from https://crates.io/crates/dirs instead." +)] #[stable(feature = "env", since = "1.0.0")] pub fn home_dir() -> Option { os_imp::home_dir() @@ -674,7 +689,9 @@ pub fn current_exe() -> io::Result { /// [`String`]: ../string/struct.String.html /// [`std::env::args`]: ./fn.args.html #[stable(feature = "env", since = "1.0.0")] -pub struct Args { inner: ArgsOs } +pub struct Args { + inner: ArgsOs, +} /// An iterator over the arguments of a process, yielding an [`OsString`] value /// for each argument. @@ -689,7 +706,9 @@ pub struct Args { inner: ArgsOs } /// [`OsString`]: ../ffi/struct.OsString.html /// [`std::env::args_os`]: ./fn.args_os.html #[stable(feature = "env", since = "1.0.0")] -pub struct ArgsOs { inner: sys::args::Args } +pub struct ArgsOs { + inner: sys::args::Args, +} /// Returns the arguments which this program was started with (normally passed /// via the command line). @@ -769,13 +788,19 @@ impl Iterator for Args { fn next(&mut self) -> Option { self.inner.next().map(|s| s.into_string().unwrap()) } - fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } } #[stable(feature = "env", since = "1.0.0")] impl ExactSizeIterator for Args { - fn len(&self) -> usize { self.inner.len() } - fn is_empty(&self) -> bool { self.inner.is_empty() } + fn len(&self) -> usize { + self.inner.len() + } + fn is_empty(&self) -> bool { + self.inner.is_empty() + } } #[stable(feature = "env_iterators", since = "1.12.0")] @@ -788,9 +813,7 @@ impl DoubleEndedIterator for Args { #[stable(feature = "std_debug", since = "1.16.0")] impl fmt::Debug for Args { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Args") - .field("inner", &self.inner.inner.inner_debug()) - .finish() + f.debug_struct("Args").field("inner", &self.inner.inner.inner_debug()).finish() } } @@ -803,27 +826,35 @@ impl !Sync for ArgsOs {} #[stable(feature = "env", since = "1.0.0")] impl Iterator for ArgsOs { type Item = OsString; - fn next(&mut self) -> Option { self.inner.next() } - fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } + fn next(&mut self) -> Option { + self.inner.next() + } + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } } #[stable(feature = "env", since = "1.0.0")] impl ExactSizeIterator for ArgsOs { - fn len(&self) -> usize { self.inner.len() } - fn is_empty(&self) -> bool { self.inner.is_empty() } + fn len(&self) -> usize { + self.inner.len() + } + fn is_empty(&self) -> bool { + self.inner.is_empty() + } } #[stable(feature = "env_iterators", since = "1.12.0")] impl DoubleEndedIterator for ArgsOs { - fn next_back(&mut self) -> Option { self.inner.next_back() } + fn next_back(&mut self) -> Option { + self.inner.next_back() + } } #[stable(feature = "std_debug", since = "1.16.0")] impl fmt::Debug for ArgsOs { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("ArgsOs") - .field("inner", &self.inner.inner_debug()) - .finish() + f.debug_struct("ArgsOs").field("inner", &self.inner.inner_debug()).finish() } } @@ -1033,8 +1064,8 @@ mod tests { use crate::path::PathBuf; fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { - split_paths(unparsed).collect::>() == - parsed.iter().map(|s| PathBuf::from(*s)).collect::>() + split_paths(unparsed).collect::>() + == parsed.iter().map(|s| PathBuf::from(*s)).collect::>() } assert!(check_parse("", &mut [""])); @@ -1042,11 +1073,12 @@ mod tests { assert!(check_parse(";;", &mut ["", "", ""])); assert!(check_parse(r"c:\", &mut [r"c:\"])); assert!(check_parse(r"c:\;", &mut [r"c:\", ""])); - assert!(check_parse(r"c:\;c:\Program Files\", - &mut [r"c:\", r"c:\Program Files\"])); + assert!(check_parse(r"c:\;c:\Program Files\", &mut [r"c:\", r"c:\Program Files\"])); assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"])); - assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#, - &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"])); + assert!(check_parse( + r#"c:\;c:\"foo;bar"\;c:\baz"#, + &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"] + )); } #[test] @@ -1055,8 +1087,8 @@ mod tests { use crate::path::PathBuf; fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { - split_paths(unparsed).collect::>() == - parsed.iter().map(|s| PathBuf::from(*s)).collect::>() + split_paths(unparsed).collect::>() + == parsed.iter().map(|s| PathBuf::from(*s)).collect::>() } assert!(check_parse("", &mut [""])); @@ -1072,15 +1104,12 @@ mod tests { use crate::ffi::OsStr; fn test_eq(input: &[&str], output: &str) -> bool { - &*join_paths(input.iter().cloned()).unwrap() == - OsStr::new(output) + &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output) } assert!(test_eq(&[], "")); - assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"], - "/bin:/usr/bin:/usr/local/bin")); - assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""], - ":/bin:::/usr/bin:")); + assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"], "/bin:/usr/bin:/usr/local/bin")); + assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""], ":/bin:::/usr/bin:")); assert!(join_paths(["/te:st"].iter().cloned()).is_err()); } @@ -1090,17 +1119,13 @@ mod tests { use crate::ffi::OsStr; fn test_eq(input: &[&str], output: &str) -> bool { - &*join_paths(input.iter().cloned()).unwrap() == - OsStr::new(output) + &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output) } assert!(test_eq(&[], "")); - assert!(test_eq(&[r"c:\windows", r"c:\"], - r"c:\windows;c:\")); - assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""], - r";c:\windows;;;c:\;")); - assert!(test_eq(&[r"c:\te;st", r"c:\"], - r#""c:\te;st";c:\"#)); + assert!(test_eq(&[r"c:\windows", r"c:\"], r"c:\windows;c:\")); + assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""], r";c:\windows;;;c:\;")); + assert!(test_eq(&[r"c:\te;st", r"c:\"], r#""c:\te;st";c:\"#)); assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err()); } @@ -1108,9 +1133,11 @@ mod tests { fn args_debug() { assert_eq!( format!("Args {{ inner: {:?} }}", args().collect::>()), - format!("{:?}", args())); + format!("{:?}", args()) + ); assert_eq!( format!("ArgsOs {{ inner: {:?} }}", args_os().collect::>()), - format!("{:?}", args_os())); + format!("{:?}", args_os()) + ); } } diff --git a/src/libstd/f32.rs b/src/libstd/f32.rs index 4b672a4c78810..54e0caeddaa0b 100644 --- a/src/libstd/f32.rs +++ b/src/libstd/f32.rs @@ -14,15 +14,15 @@ use crate::intrinsics; use crate::sys::cmath; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::f32::{RADIX, MANTISSA_DIGITS, DIGITS, EPSILON}; +pub use core::f32::consts; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::f32::{MIN_EXP, MAX_EXP, MIN_10_EXP}; +pub use core::f32::{DIGITS, EPSILON, MANTISSA_DIGITS, RADIX}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::f32::{MAX_10_EXP, NAN, INFINITY, NEG_INFINITY}; +pub use core::f32::{INFINITY, MAX_10_EXP, NAN, NEG_INFINITY}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::f32::{MIN, MIN_POSITIVE, MAX}; +pub use core::f32::{MAX, MIN, MIN_POSITIVE}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::f32::consts; +pub use core::f32::{MAX_EXP, MIN_10_EXP, MIN_EXP}; #[cfg(not(test))] #[lang = "f32_runtime"] @@ -142,7 +142,9 @@ impl f32 { #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn fract(self) -> f32 { self - self.trunc() } + pub fn fract(self) -> f32 { + self - self.trunc() + } /// Computes the absolute value of `self`. Returns `NAN` if the /// number is `NAN`. @@ -192,11 +194,7 @@ impl f32 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn signum(self) -> f32 { - if self.is_nan() { - NAN - } else { - 1.0_f32.copysign(self) - } + if self.is_nan() { NAN } else { 1.0_f32.copysign(self) } } /// Returns a number composed of the magnitude of `self` and the sign of @@ -277,7 +275,7 @@ impl f32 { pub fn div_euclid(self, rhs: f32) -> f32 { let q = (self / rhs).trunc(); if self % rhs < 0.0 { - return if rhs > 0.0 { q - 1.0 } else { q + 1.0 } + return if rhs > 0.0 { q - 1.0 } else { q + 1.0 }; } q } @@ -310,14 +308,9 @@ impl f32 { #[stable(feature = "euclidean_division", since = "1.38.0")] pub fn rem_euclid(self, rhs: f32) -> f32 { let r = self % rhs; - if r < 0.0 { - r + rhs.abs() - } else { - r - } + if r < 0.0 { r + rhs.abs() } else { r } } - /// Raises a number to an integer power. /// /// Using this function is generally faster than using `powf` @@ -383,11 +376,7 @@ impl f32 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn sqrt(self) -> f32 { - if self < 0.0 { - NAN - } else { - unsafe { intrinsics::sqrtf32(self) } - } + if self < 0.0 { NAN } else { unsafe { intrinsics::sqrtf32(self) } } } /// Returns `e^(self)`, (the exponential function). @@ -486,7 +475,9 @@ impl f32 { #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn log(self, base: f32) -> f32 { self.ln() / base.ln() } + pub fn log(self, base: f32) -> f32 { + self.ln() / base.ln() + } /// Returns the base 2 logarithm of the number. /// @@ -559,14 +550,16 @@ impl f32 { #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] #[inline] - #[rustc_deprecated(since = "1.10.0", - reason = "you probably meant `(self - other).abs()`: \ - this operation is `(self - other).max(0.0)` \ - except that `abs_sub` also propagates NaNs (also \ - known as `fdimf` in C). If you truly need the positive \ - difference, consider using that expression or the C function \ - `fdimf`, depending on how you wish to handle NaN (please consider \ - filing an issue describing your use-case too).")] + #[rustc_deprecated( + since = "1.10.0", + reason = "you probably meant `(self - other).abs()`: \ + this operation is `(self - other).max(0.0)` \ + except that `abs_sub` also propagates NaNs (also \ + known as `fdimf` in C). If you truly need the positive \ + difference, consider using that expression or the C function \ + `fdimf`, depending on how you wish to handle NaN (please consider \ + filing an issue describing your use-case too)." + )] pub fn abs_sub(self, other: f32) -> f32 { unsafe { cmath::fdimf(self, other) } } @@ -967,11 +960,7 @@ impl f32 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn acosh(self) -> f32 { - if self < 1.0 { - crate::f32::NAN - } else { - (self + ((self * self) - 1.0).sqrt()).ln() - } + if self < 1.0 { crate::f32::NAN } else { (self + ((self * self) - 1.0).sqrt()).ln() } } /// Inverse hyperbolic tangent function. @@ -1022,19 +1011,22 @@ impl f32 { pub fn clamp(self, min: f32, max: f32) -> f32 { assert!(min <= max); let mut x = self; - if x < min { x = min; } - if x > max { x = max; } + if x < min { + x = min; + } + if x > max { + x = max; + } x } - } #[cfg(test)] mod tests { use crate::f32; use crate::f32::*; - use crate::num::*; use crate::num::FpCategory as Fp; + use crate::num::*; #[test] fn test_num_f32() { @@ -1279,7 +1271,7 @@ mod tests { assert_eq!((-0f32).abs(), 0f32); assert_eq!((-1f32).abs(), 1f32); assert_eq!(NEG_INFINITY.abs(), INFINITY); - assert_eq!((1f32/NEG_INFINITY).abs(), 0f32); + assert_eq!((1f32 / NEG_INFINITY).abs(), 0f32); assert!(NAN.abs().is_nan()); } @@ -1291,7 +1283,7 @@ mod tests { assert_eq!((-0f32).signum(), -1f32); assert_eq!((-1f32).signum(), -1f32); assert_eq!(NEG_INFINITY.signum(), -1f32); - assert_eq!((1f32/NEG_INFINITY).signum(), -1f32); + assert_eq!((1f32 / NEG_INFINITY).signum(), -1f32); assert!(NAN.signum().is_nan()); } @@ -1303,7 +1295,7 @@ mod tests { assert!(!(-0f32).is_sign_positive()); assert!(!(-1f32).is_sign_positive()); assert!(!NEG_INFINITY.is_sign_positive()); - assert!(!(1f32/NEG_INFINITY).is_sign_positive()); + assert!(!(1f32 / NEG_INFINITY).is_sign_positive()); assert!(NAN.is_sign_positive()); assert!(!(-NAN).is_sign_positive()); } @@ -1316,7 +1308,7 @@ mod tests { assert!((-0f32).is_sign_negative()); assert!((-1f32).is_sign_negative()); assert!(NEG_INFINITY.is_sign_negative()); - assert!((1f32/NEG_INFINITY).is_sign_negative()); + assert!((1f32 / NEG_INFINITY).is_sign_negative()); assert!(!NAN.is_sign_negative()); assert!((-NAN).is_sign_negative()); } diff --git a/src/libstd/f64.rs b/src/libstd/f64.rs index b16038ee1f8ca..aa32e5fb998bc 100644 --- a/src/libstd/f64.rs +++ b/src/libstd/f64.rs @@ -14,15 +14,15 @@ use crate::intrinsics; use crate::sys::cmath; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::f64::{RADIX, MANTISSA_DIGITS, DIGITS, EPSILON}; +pub use core::f64::consts; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::f64::{MIN_EXP, MAX_EXP, MIN_10_EXP}; +pub use core::f64::{DIGITS, EPSILON, MANTISSA_DIGITS, RADIX}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::f64::{MAX_10_EXP, NAN, INFINITY, NEG_INFINITY}; +pub use core::f64::{INFINITY, MAX_10_EXP, NAN, NEG_INFINITY}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::f64::{MIN, MIN_POSITIVE, MAX}; +pub use core::f64::{MAX, MIN, MIN_POSITIVE}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::f64::consts; +pub use core::f64::{MAX_EXP, MIN_10_EXP, MIN_EXP}; #[cfg(not(test))] #[lang = "f64_runtime"] @@ -120,7 +120,9 @@ impl f64 { #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn fract(self) -> f64 { self - self.trunc() } + pub fn fract(self) -> f64 { + self - self.trunc() + } /// Computes the absolute value of `self`. Returns `NAN` if the /// number is `NAN`. @@ -170,11 +172,7 @@ impl f64 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn signum(self) -> f64 { - if self.is_nan() { - NAN - } else { - 1.0_f64.copysign(self) - } + if self.is_nan() { NAN } else { 1.0_f64.copysign(self) } } /// Returns a number composed of the magnitude of `self` and the sign of @@ -286,11 +284,7 @@ impl f64 { #[stable(feature = "euclidean_division", since = "1.38.0")] pub fn rem_euclid(self, rhs: f64) -> f64 { let r = self % rhs; - if r < 0.0 { - r + rhs.abs() - } else { - r - } + if r < 0.0 { r + rhs.abs() } else { r } } /// Raises a number to an integer power. @@ -348,11 +342,7 @@ impl f64 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn sqrt(self) -> f64 { - if self < 0.0 { - NAN - } else { - unsafe { intrinsics::sqrtf64(self) } - } + if self < 0.0 { NAN } else { unsafe { intrinsics::sqrtf64(self) } } } /// Returns `e^(self)`, (the exponential function). @@ -413,7 +403,7 @@ impl f64 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn ln(self) -> f64 { - self.log_wrapper(|n| { unsafe { intrinsics::logf64(n) } }) + self.log_wrapper(|n| unsafe { intrinsics::logf64(n) }) } /// Returns the logarithm of the number with respect to an arbitrary base. @@ -435,7 +425,9 @@ impl f64 { #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn log(self, base: f64) -> f64 { self.ln() / base.ln() } + pub fn log(self, base: f64) -> f64 { + self.ln() / base.ln() + } /// Returns the base 2 logarithm of the number. /// @@ -455,9 +447,9 @@ impl f64 { pub fn log2(self) -> f64 { self.log_wrapper(|n| { #[cfg(target_os = "android")] - return crate::sys::android::log2f64(n); + return crate::sys::android::log2f64(n); #[cfg(not(target_os = "android"))] - return unsafe { intrinsics::log2f64(n) }; + return unsafe { intrinsics::log2f64(n) }; }) } @@ -477,7 +469,7 @@ impl f64 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn log10(self) -> f64 { - self.log_wrapper(|n| { unsafe { intrinsics::log10f64(n) } }) + self.log_wrapper(|n| unsafe { intrinsics::log10f64(n) }) } /// The positive difference of two numbers. @@ -500,14 +492,16 @@ impl f64 { #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] #[inline] - #[rustc_deprecated(since = "1.10.0", - reason = "you probably meant `(self - other).abs()`: \ - this operation is `(self - other).max(0.0)` \ - except that `abs_sub` also propagates NaNs (also \ - known as `fdim` in C). If you truly need the positive \ - difference, consider using that expression or the C function \ - `fdim`, depending on how you wish to handle NaN (please consider \ - filing an issue describing your use-case too).")] + #[rustc_deprecated( + since = "1.10.0", + reason = "you probably meant `(self - other).abs()`: \ + this operation is `(self - other).max(0.0)` \ + except that `abs_sub` also propagates NaNs (also \ + known as `fdim` in C). If you truly need the positive \ + difference, consider using that expression or the C function \ + `fdim`, depending on how you wish to handle NaN (please consider \ + filing an issue describing your use-case too)." + )] pub fn abs_sub(self, other: f64) -> f64 { unsafe { cmath::fdim(self, other) } } @@ -888,11 +882,7 @@ impl f64 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn acosh(self) -> f64 { - if self < 1.0 { - NAN - } else { - (self + ((self * self) - 1.0).sqrt()).ln() - } + if self < 1.0 { NAN } else { (self + ((self * self) - 1.0).sqrt()).ln() } } /// Inverse hyperbolic tangent function. @@ -943,8 +933,12 @@ impl f64 { pub fn clamp(self, min: f64, max: f64) -> f64 { assert!(min <= max); let mut x = self; - if x < min { x = min; } - if x > max { x = max; } + if x < min { + x = min; + } + if x > max { + x = max; + } x } @@ -978,8 +972,8 @@ impl f64 { mod tests { use crate::f64; use crate::f64::*; - use crate::num::*; use crate::num::FpCategory as Fp; + use crate::num::*; #[test] fn test_num_f64() { diff --git a/src/libstd/ffi/mod.rs b/src/libstd/ffi/mod.rs index 28d9906eb93b5..72f7367c9dcdb 100644 --- a/src/libstd/ffi/mod.rs +++ b/src/libstd/ffi/mod.rs @@ -155,21 +155,23 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::c_str::{CString, CStr, NulError, IntoStringError}; #[stable(feature = "cstr_from_bytes", since = "1.10.0")] -pub use self::c_str::{FromBytesWithNulError}; +pub use self::c_str::FromBytesWithNulError; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::c_str::{CStr, CString, IntoStringError, NulError}; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::os_str::{OsString, OsStr}; +pub use self::os_str::{OsStr, OsString}; #[stable(feature = "core_c_void", since = "1.30.0")] pub use core::ffi::c_void; -#[unstable(feature = "c_variadic", - reason = "the `c_variadic` feature has not been properly tested on \ - all supported platforms", - issue = "44930")] +#[unstable( + feature = "c_variadic", + reason = "the `c_variadic` feature has not been properly tested on \ + all supported platforms", + issue = "44930" +)] pub use core::ffi::{VaList, VaListImpl}; mod c_str; diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs index 30db6a58d40c2..e5cf022f0444e 100644 --- a/src/libstd/fs.rs +++ b/src/libstd/fs.rs @@ -9,12 +9,12 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fmt; use crate::ffi::OsString; -use crate::io::{self, SeekFrom, Seek, Read, Initializer, Write, IoSlice, IoSliceMut}; +use crate::fmt; +use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write}; use crate::path::{Path, PathBuf}; use crate::sys::fs as fs_imp; -use crate::sys_common::{AsInnerMut, FromInner, AsInner, IntoInner}; +use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; use crate::time::SystemTime; /// A reference to an open file on the filesystem. @@ -585,9 +585,7 @@ impl File { /// ``` #[stable(feature = "file_try_clone", since = "1.9.0")] pub fn try_clone(&self) -> io::Result { - Ok(File { - inner: self.inner.duplicate()? - }) + Ok(File { inner: self.inner.duplicate()? }) } /// Changes the permissions on the underlying file. @@ -629,7 +627,9 @@ impl File { } impl AsInner for File { - fn as_inner(&self) -> &fs_imp::File { &self.inner } + fn as_inner(&self) -> &fs_imp::File { + &self.inner + } } impl FromInner for File { fn from_inner(f: fs_imp::File) -> File { @@ -674,7 +674,9 @@ impl Write for File { self.inner.write_vectored(bufs) } - fn flush(&mut self) -> io::Result<()> { self.inner.flush() } + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } } #[stable(feature = "rust1", since = "1.0.0")] impl Seek for File { @@ -707,7 +709,9 @@ impl Write for &File { self.inner.write_vectored(bufs) } - fn flush(&mut self) -> io::Result<()> { self.inner.flush() } + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } } #[stable(feature = "rust1", since = "1.0.0")] impl Seek for &File { @@ -748,7 +752,8 @@ impl OpenOptions { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn read(&mut self, read: bool) -> &mut OpenOptions { - self.0.read(read); self + self.0.read(read); + self } /// Sets the option for write access. @@ -768,7 +773,8 @@ impl OpenOptions { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn write(&mut self, write: bool) -> &mut OpenOptions { - self.0.write(write); self + self.0.write(write); + self } /// Sets the option for the append mode. @@ -814,7 +820,8 @@ impl OpenOptions { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn append(&mut self, append: bool) -> &mut OpenOptions { - self.0.append(append); self + self.0.append(append); + self } /// Sets the option for truncating a previous file. @@ -833,7 +840,8 @@ impl OpenOptions { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions { - self.0.truncate(truncate); self + self.0.truncate(truncate); + self } /// Sets the option for creating a new file. @@ -856,7 +864,8 @@ impl OpenOptions { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn create(&mut self, create: bool) -> &mut OpenOptions { - self.0.create(create); self + self.0.create(create); + self } /// Sets the option to always create a new file. @@ -889,7 +898,8 @@ impl OpenOptions { /// ``` #[stable(feature = "expand_open_options2", since = "1.9.0")] pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions { - self.0.create_new(create_new); self + self.0.create_new(create_new); + self } /// Opens a file at `path` with the options specified by `self`. @@ -946,11 +956,15 @@ impl OpenOptions { } impl AsInner for OpenOptions { - fn as_inner(&self) -> &fs_imp::OpenOptions { &self.0 } + fn as_inner(&self) -> &fs_imp::OpenOptions { + &self.0 + } } impl AsInnerMut for OpenOptions { - fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 } + fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { + &mut self.0 + } } impl Metadata { @@ -994,7 +1008,9 @@ impl Metadata { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn is_dir(&self) -> bool { self.file_type().is_dir() } + pub fn is_dir(&self) -> bool { + self.file_type().is_dir() + } /// Returns `true` if this metadata is for a regular file. The /// result is mutually exclusive to the result of @@ -1017,7 +1033,9 @@ impl Metadata { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn is_file(&self) -> bool { self.file_type().is_file() } + pub fn is_file(&self) -> bool { + self.file_type().is_file() + } /// Returns the size of the file, in bytes, this metadata is for. /// @@ -1034,7 +1052,9 @@ impl Metadata { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn len(&self) -> u64 { self.0.size() } + pub fn len(&self) -> u64 { + self.0.size() + } /// Returns the permissions of the file this metadata is for. /// @@ -1170,11 +1190,15 @@ impl fmt::Debug for Metadata { } impl AsInner for Metadata { - fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 } + fn as_inner(&self) -> &fs_imp::FileAttr { + &self.0 + } } impl FromInner for Metadata { - fn from_inner(attr: fs_imp::FileAttr) -> Metadata { Metadata(attr) } + fn from_inner(attr: fs_imp::FileAttr) -> Metadata { + Metadata(attr) + } } impl Permissions { @@ -1194,7 +1218,9 @@ impl Permissions { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn readonly(&self) -> bool { self.0.readonly() } + pub fn readonly(&self) -> bool { + self.0.readonly() + } /// Modifies the readonly flag for this set of permissions. If the /// `readonly` argument is `true`, using the resulting `Permission` will @@ -1256,7 +1282,9 @@ impl FileType { /// } /// ``` #[stable(feature = "file_type", since = "1.1.0")] - pub fn is_dir(&self) -> bool { self.0.is_dir() } + pub fn is_dir(&self) -> bool { + self.0.is_dir() + } /// Tests whether this file type represents a regular file. /// The result is mutually exclusive to the results of @@ -1280,7 +1308,9 @@ impl FileType { /// } /// ``` #[stable(feature = "file_type", since = "1.1.0")] - pub fn is_file(&self) -> bool { self.0.is_file() } + pub fn is_file(&self) -> bool { + self.0.is_file() + } /// Tests whether this file type represents a symbolic link. /// The result is mutually exclusive to the results of @@ -1314,11 +1344,15 @@ impl FileType { /// } /// ``` #[stable(feature = "file_type", since = "1.1.0")] - pub fn is_symlink(&self) -> bool { self.0.is_symlink() } + pub fn is_symlink(&self) -> bool { + self.0.is_symlink() + } } impl AsInner for FileType { - fn as_inner(&self) -> &fs_imp::FileType { &self.0 } + fn as_inner(&self) -> &fs_imp::FileType { + &self.0 + } } impl FromInner for Permissions { @@ -1328,7 +1362,9 @@ impl FromInner for Permissions { } impl AsInner for Permissions { - fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 } + fn as_inner(&self) -> &fs_imp::FilePermissions { + &self.0 + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1370,7 +1406,9 @@ impl DirEntry { /// /// The exact text, of course, depends on what files you have in `.`. #[stable(feature = "rust1", since = "1.0.0")] - pub fn path(&self) -> PathBuf { self.0.path() } + pub fn path(&self) -> PathBuf { + self.0.path() + } /// Returns the metadata for the file that this entry points at. /// @@ -1468,14 +1506,14 @@ impl DirEntry { #[stable(feature = "dir_entry_debug", since = "1.13.0")] impl fmt::Debug for DirEntry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("DirEntry") - .field(&self.path()) - .finish() + f.debug_tuple("DirEntry").field(&self.path()).finish() } } impl AsInner for DirEntry { - fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 } + fn as_inner(&self) -> &fs_imp::DirEntry { + &self.0 + } } /// Removes a file from the filesystem. @@ -1744,9 +1782,11 @@ pub fn hard_link, Q: AsRef>(src: P, dst: Q) -> io::Result<( /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_deprecated(since = "1.1.0", - reason = "replaced with std::os::unix::fs::symlink and \ - std::os::windows::fs::{symlink_file, symlink_dir}")] +#[rustc_deprecated( + since = "1.1.0", + reason = "replaced with std::os::unix::fs::symlink and \ + std::os::windows::fs::{symlink_file, symlink_dir}" +)] pub fn soft_link, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { fs_imp::symlink(src.as_ref(), dst.as_ref()) } @@ -2089,8 +2129,7 @@ pub fn read_dir>(path: P) -> io::Result { /// } /// ``` #[stable(feature = "set_permissions", since = "1.1.0")] -pub fn set_permissions>(path: P, perm: Permissions) - -> io::Result<()> { +pub fn set_permissions>(path: P, perm: Permissions) -> io::Result<()> { fs_imp::set_perm(path.as_ref(), perm.0) } @@ -2107,10 +2146,7 @@ impl DirBuilder { /// ``` #[stable(feature = "dir_builder", since = "1.6.0")] pub fn new() -> DirBuilder { - DirBuilder { - inner: fs_imp::DirBuilder::new(), - recursive: false, - } + DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false } } /// Indicates that directories should be created recursively, creating all @@ -2157,16 +2193,12 @@ impl DirBuilder { } fn _create(&self, path: &Path) -> io::Result<()> { - if self.recursive { - self.create_dir_all(path) - } else { - self.inner.mkdir(path) - } + if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) } } fn create_dir_all(&self, path: &Path) -> io::Result<()> { if path == Path::new("") { - return Ok(()) + return Ok(()); } match self.inner.mkdir(path) { @@ -2177,7 +2209,9 @@ impl DirBuilder { } match path.parent() { Some(p) => self.create_dir_all(p)?, - None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")), + None => { + return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")); + } } match self.inner.mkdir(path) { Ok(()) => Ok(()), @@ -2201,48 +2235,62 @@ mod tests { use crate::io::{ErrorKind, SeekFrom}; use crate::path::Path; use crate::str; - use crate::sys_common::io::test::{TempDir, tmpdir}; + use crate::sys_common::io::test::{tmpdir, TempDir}; use crate::thread; use rand::{rngs::StdRng, RngCore, SeedableRng}; - #[cfg(windows)] - use crate::os::windows::fs::{symlink_dir, symlink_file}; - #[cfg(windows)] - use crate::sys::fs::symlink_junction; #[cfg(unix)] use crate::os::unix::fs::symlink as symlink_dir; #[cfg(unix)] use crate::os::unix::fs::symlink as symlink_file; #[cfg(unix)] use crate::os::unix::fs::symlink as symlink_junction; + #[cfg(windows)] + use crate::os::windows::fs::{symlink_dir, symlink_file}; + #[cfg(windows)] + use crate::sys::fs::symlink_junction; - macro_rules! check { ($e:expr) => ( - match $e { - Ok(t) => t, - Err(e) => panic!("{} failed with: {}", stringify!($e), e), - } - ) } + macro_rules! check { + ($e:expr) => { + match $e { + Ok(t) => t, + Err(e) => panic!("{} failed with: {}", stringify!($e), e), + } + }; + } #[cfg(windows)] - macro_rules! error { ($e:expr, $s:expr) => ( - match $e { - Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s), - Err(ref err) => assert!(err.raw_os_error() == Some($s), - format!("`{}` did not have a code of `{}`", err, $s)) - } - ) } + macro_rules! error { + ($e:expr, $s:expr) => { + match $e { + Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s), + Err(ref err) => assert!( + err.raw_os_error() == Some($s), + format!("`{}` did not have a code of `{}`", err, $s) + ), + } + }; + } #[cfg(unix)] - macro_rules! error { ($e:expr, $s:expr) => ( error_contains!($e, $s) ) } - - macro_rules! error_contains { ($e:expr, $s:expr) => ( - match $e { - Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s), - Err(ref err) => assert!(err.to_string().contains($s), - format!("`{}` did not contain `{}`", err, $s)) - } - ) } + macro_rules! error { + ($e:expr, $s:expr) => { + error_contains!($e, $s) + }; + } + + macro_rules! error_contains { + ($e:expr, $s:expr) => { + match $e { + Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s), + Err(ref err) => assert!( + err.to_string().contains($s), + format!("`{}` did not contain `{}`", err, $s) + ), + } + }; + } // Several test fail on windows if the user does not have permission to // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of @@ -2251,7 +2299,9 @@ mod tests { // tests most of the time, but at least we do if the user has the right // permissions. pub fn got_symlink_permission(tmpdir: &TempDir) -> bool { - if cfg!(unix) { return true } + if cfg!(unix) { + return true; + } let link = tmpdir.join("some_hopefully_unique_link_name"); match symlink_file(r"nonexisting_target", link) { @@ -2276,7 +2326,7 @@ mod tests { let mut read_buf = [0; 1028]; let read_str = match check!(read_stream.read(&mut read_buf)) { 0 => panic!("shouldn't happen"), - n => str::from_utf8(&read_buf[..n]).unwrap().to_string() + n => str::from_utf8(&read_buf[..n]).unwrap().to_string(), }; assert_eq!(read_str, message); } @@ -2363,9 +2413,9 @@ mod tests { #[test] fn file_test_io_seek_and_write() { - let initial_msg = "food-is-yummy"; - let overwrite_msg = "-the-bar!!"; - let final_msg = "foo-the-bar!!"; + let initial_msg = "food-is-yummy"; + let overwrite_msg = "-the-bar!!"; + let final_msg = "foo-the-bar!!"; let seek_idx = 3; let mut read_mem = [0; 13]; let tmpdir = tmpdir(); @@ -2388,7 +2438,7 @@ mod tests { #[test] fn file_test_io_seek_shakedown() { // 01234567890123 - let initial_msg = "qwer-asdf-zxcv"; + let initial_msg = "qwer-asdf-zxcv"; let chunk_one: &str = "qwer"; let chunk_two: &str = "asdf"; let chunk_three: &str = "zxcv"; @@ -2497,13 +2547,11 @@ mod tests { check!(fs::create_dir(filename)); let mask = 0o7777; - check!(fs::set_permissions(filename, - fs::Permissions::from_mode(0))); + check!(fs::set_permissions(filename, fs::Permissions::from_mode(0))); let metadata0 = check!(fs::metadata(filename)); assert_eq!(mask & metadata0.permissions().mode(), 0); - check!(fs::set_permissions(filename, - fs::Permissions::from_mode(0o1777))); + check!(fs::set_permissions(filename, fs::Permissions::from_mode(0o1777))); let metadata1 = check!(fs::metadata(filename)); assert_eq!(mask & metadata1.permissions().mode(), 0o1777); } @@ -2568,8 +2616,7 @@ mod tests { let filename = &tmpdir.join("file_stat_correct_on_is_file.txt"); { let mut opts = OpenOptions::new(); - let mut fs = check!(opts.read(true).write(true) - .create(true).open(filename)); + let mut fs = check!(opts.read(true).write(true).create(true).open(filename)); let msg = "hw"; fs.write(msg.as_bytes()).unwrap(); @@ -2703,7 +2750,7 @@ mod tests { for _ in 0..40 { dir = dir.join("a"); } - let mut join = vec!(); + let mut join = vec![]; for _ in 0..8 { let dir = dir.clone(); join.push(thread::spawn(move || { @@ -2771,7 +2818,9 @@ mod tests { #[cfg(windows)] fn recursive_rmdir_of_file_symlink() { let tmpdir = tmpdir(); - if !got_symlink_permission(&tmpdir) { return }; + if !got_symlink_permission(&tmpdir) { + return; + }; let f1 = tmpdir.join("f1"); let f2 = tmpdir.join("f2"); @@ -2854,8 +2903,7 @@ mod tests { check!(check!(File::open(&out)).read_to_end(&mut v)); assert_eq!(v, b"hello"); - assert_eq!(check!(input.metadata()).permissions(), - check!(out.metadata()).permissions()); + assert_eq!(check!(input.metadata()).permissions(), check!(out.metadata()).permissions()); } #[test] @@ -2865,7 +2913,8 @@ mod tests { check!(File::create(&out)); match fs::copy(&*out, tmpdir.path()) { - Ok(..) => panic!(), Err(..) => {} + Ok(..) => panic!(), + Err(..) => {} } } @@ -2890,7 +2939,8 @@ mod tests { let out = tmpdir.join("out"); match fs::copy(tmpdir.path(), &out) { - Ok(..) => panic!(), Err(..) => {} + Ok(..) => panic!(), + Err(..) => {} } assert!(!out.exists()); } @@ -2938,7 +2988,9 @@ mod tests { #[test] fn copy_file_follows_dst_symlink() { let tmp = tmpdir(); - if !got_symlink_permission(&tmp) { return }; + if !got_symlink_permission(&tmp) { + return; + }; let in_path = tmp.join("in.txt"); let out_path = tmp.join("out.txt"); @@ -2958,7 +3010,9 @@ mod tests { #[test] fn symlinks_work() { let tmpdir = tmpdir(); - if !got_symlink_permission(&tmpdir) { return }; + if !got_symlink_permission(&tmpdir) { + return; + }; let input = tmpdir.join("in.txt"); let out = tmpdir.join("out.txt"); @@ -2966,8 +3020,7 @@ mod tests { check!(check!(File::create(&input)).write("foobar".as_bytes())); check!(symlink_file(&input, &out)); assert!(check!(out.symlink_metadata()).file_type().is_symlink()); - assert_eq!(check!(fs::metadata(&out)).len(), - check!(fs::metadata(&input)).len()); + assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len()); let mut v = Vec::new(); check!(check!(File::open(&out)).read_to_end(&mut v)); assert_eq!(v, b"foobar".to_vec()); @@ -2977,31 +3030,40 @@ mod tests { fn symlink_noexist() { // Symlinks can point to things that don't exist let tmpdir = tmpdir(); - if !got_symlink_permission(&tmpdir) { return }; + if !got_symlink_permission(&tmpdir) { + return; + }; // Use a relative path for testing. Symlinks get normalized by Windows, // so we may not get the same path back for absolute paths check!(symlink_file(&"foo", &tmpdir.join("bar"))); - assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(), - "foo"); + assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(), "foo"); } #[test] fn read_link() { if cfg!(windows) { // directory symlink - assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(), - r"C:\ProgramData"); + assert_eq!( + check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(), + r"C:\ProgramData" + ); // junction - assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(), - r"C:\Users\Default"); + assert_eq!( + check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(), + r"C:\Users\Default" + ); // junction with special permissions - assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(), - r"C:\Users"); + assert_eq!( + check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(), + r"C:\Users" + ); } let tmpdir = tmpdir(); let link = tmpdir.join("link"); - if !got_symlink_permission(&tmpdir) { return }; + if !got_symlink_permission(&tmpdir) { + return; + }; check!(symlink_file(&"foo", &link)); assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo"); } @@ -3023,10 +3085,8 @@ mod tests { check!(check!(File::create(&input)).write("foobar".as_bytes())); check!(fs::hard_link(&input, &out)); - assert_eq!(check!(fs::metadata(&out)).len(), - check!(fs::metadata(&input)).len()); - assert_eq!(check!(fs::metadata(&out)).len(), - check!(input.metadata()).len()); + assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len()); + assert_eq!(check!(fs::metadata(&out)).len(), check!(input.metadata()).len()); let mut v = Vec::new(); check!(check!(File::open(&out)).read_to_end(&mut v)); assert_eq!(v, b"foobar".to_vec()); @@ -3134,15 +3194,22 @@ mod tests { #[test] fn open_flavors() { use crate::fs::OpenOptions as OO; - fn c(t: &T) -> T { t.clone() } + fn c(t: &T) -> T { + t.clone() + } let tmpdir = tmpdir(); - let mut r = OO::new(); r.read(true); - let mut w = OO::new(); w.write(true); - let mut rw = OO::new(); rw.read(true).write(true); - let mut a = OO::new(); a.append(true); - let mut ra = OO::new(); ra.read(true).append(true); + let mut r = OO::new(); + r.read(true); + let mut w = OO::new(); + w.write(true); + let mut rw = OO::new(); + rw.read(true).write(true); + let mut a = OO::new(); + a.append(true); + let mut ra = OO::new(); + ra.read(true).append(true); #[cfg(windows)] let invalid_options = 87; // ERROR_INVALID_PARAMETER @@ -3201,7 +3268,7 @@ mod tests { // Test opening a file without setting an access mode let mut blank = OO::new(); - error!(blank.create(true).open(&tmpdir.join("f")), invalid_options); + error!(blank.create(true).open(&tmpdir.join("f")), invalid_options); // Test write works check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes())); @@ -3279,8 +3346,10 @@ mod tests { assert!(v == &bytes[..]); check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF])); - error_contains!(fs::read_to_string(&tmpdir.join("not-utf8")), - "stream did not contain valid UTF-8"); + error_contains!( + fs::read_to_string(&tmpdir.join("not-utf8")), + "stream did not contain valid UTF-8" + ); let s = "𐁁𐀓𐀠𐀴𐀍"; check!(fs::write(&tmpdir.join("utf8"), s.as_bytes())); @@ -3292,11 +3361,9 @@ mod tests { fn file_try_clone() { let tmpdir = tmpdir(); - let mut f1 = check!(OpenOptions::new() - .read(true) - .write(true) - .create(true) - .open(&tmpdir.join("test"))); + let mut f1 = check!( + OpenOptions::new().read(true).write(true).create(true).open(&tmpdir.join("test")) + ); let mut f2 = check!(f1.try_clone()); check!(f1.write_all(b"hello world")); @@ -3341,7 +3408,9 @@ mod tests { #[test] fn realpath_works() { let tmpdir = tmpdir(); - if !got_symlink_permission(&tmpdir) { return }; + if !got_symlink_permission(&tmpdir) { + return; + }; let tmpdir = fs::canonicalize(tmpdir.path()).unwrap(); let file = tmpdir.join("test"); @@ -3366,7 +3435,9 @@ mod tests { #[test] fn realpath_works_tricky() { let tmpdir = tmpdir(); - if !got_symlink_permission(&tmpdir) { return }; + if !got_symlink_permission(&tmpdir) { + return; + }; let tmpdir = fs::canonicalize(tmpdir.path()).unwrap(); let a = tmpdir.join("a"); @@ -3452,7 +3523,9 @@ mod tests { assert!(junction.is_dir()); assert!(b.exists()); - if !got_symlink_permission(&tmpdir) { return }; + if !got_symlink_permission(&tmpdir) { + return; + }; check!(symlink_dir(&target, &link)); check!(fs::create_dir_all(&d)); assert!(link.is_dir()); @@ -3482,8 +3555,8 @@ mod tests { // Not always available match (a.created(), b.created()) { (Ok(t1), Ok(t2)) => assert!(t1 <= t2), - (Err(e1), Err(e2)) if e1.kind() == ErrorKind::Other && - e2.kind() == ErrorKind::Other => {} + (Err(e1), Err(e2)) + if e1.kind() == ErrorKind::Other && e2.kind() == ErrorKind::Other => {} (a, b) => panic!( "creation time must be always supported or not supported: {:?} {:?}", a, b, diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 557da174d8941..8e81b292f6fa3 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -5,8 +5,9 @@ use crate::io::prelude::*; use crate::cmp; use crate::error; use crate::fmt; -use crate::io::{self, Initializer, DEFAULT_BUF_SIZE, Error, ErrorKind, SeekFrom, IoSlice, - IoSliceMut}; +use crate::io::{ + self, Error, ErrorKind, Initializer, IoSlice, IoSliceMut, SeekFrom, DEFAULT_BUF_SIZE, +}; use crate::memchr; /// The `BufReader` struct adds buffering to any reader. @@ -100,12 +101,7 @@ impl BufReader { let mut buffer = Vec::with_capacity(capacity); buffer.set_len(capacity); inner.initializer().initialize(&mut buffer); - BufReader { - inner, - buf: buffer.into_boxed_slice(), - pos: 0, - cap: 0, - } + BufReader { inner, buf: buffer.into_boxed_slice(), pos: 0, cap: 0 } } } } @@ -130,7 +126,9 @@ impl BufReader { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_ref(&self) -> &R { &self.inner } + pub fn get_ref(&self) -> &R { + &self.inner + } /// Gets a mutable reference to the underlying reader. /// @@ -151,7 +149,9 @@ impl BufReader { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_mut(&mut self) -> &mut R { &mut self.inner } + pub fn get_mut(&mut self) -> &mut R { + &mut self.inner + } /// Returns a reference to the internally buffered data. /// @@ -199,7 +199,9 @@ impl BufReader { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn into_inner(self) -> R { self.inner } + pub fn into_inner(self) -> R { + self.inner + } /// Invalidates all data in the internal buffer. #[inline] @@ -220,17 +222,17 @@ impl BufReader { if offset < 0 { if let Some(new_pos) = pos.checked_sub((-offset) as u64) { self.pos = new_pos as usize; - return Ok(()) + return Ok(()); } } else { if let Some(new_pos) = pos.checked_add(offset as u64) { if new_pos <= self.cap as u64 { self.pos = new_pos as usize; - return Ok(()) + return Ok(()); } } } - self.seek(SeekFrom::Current(offset)).map(|_|()) + self.seek(SeekFrom::Current(offset)).map(|_| ()) } } @@ -293,7 +295,10 @@ impl BufRead for BufReader { } #[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Debug for BufReader where R: fmt::Debug { +impl fmt::Debug for BufReader +where + R: fmt::Debug, +{ fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("BufReader") .field("reader", &self.inner) @@ -483,11 +488,7 @@ impl BufWriter { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn with_capacity(capacity: usize, inner: W) -> BufWriter { - BufWriter { - inner: Some(inner), - buf: Vec::with_capacity(capacity), - panicked: false, - } + BufWriter { inner: Some(inner), buf: Vec::with_capacity(capacity), panicked: false } } fn flush_buf(&mut self) -> io::Result<()> { @@ -501,14 +502,16 @@ impl BufWriter { match r { Ok(0) => { - ret = Err(Error::new(ErrorKind::WriteZero, - "failed to write the buffered data")); + ret = + Err(Error::new(ErrorKind::WriteZero, "failed to write the buffered data")); break; } Ok(n) => written += n, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} - Err(e) => { ret = Err(e); break } - + Err(e) => { + ret = Err(e); + break; + } } } if written > 0 { @@ -531,7 +534,9 @@ impl BufWriter { /// let reference = buffer.get_ref(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_ref(&self) -> &W { self.inner.as_ref().unwrap() } + pub fn get_ref(&self) -> &W { + self.inner.as_ref().unwrap() + } /// Gets a mutable reference to the underlying writer. /// @@ -549,7 +554,9 @@ impl BufWriter { /// let reference = buffer.get_mut(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_mut(&mut self) -> &mut W { self.inner.as_mut().unwrap() } + pub fn get_mut(&mut self) -> &mut W { + self.inner.as_mut().unwrap() + } /// Returns a reference to the internally buffered data. /// @@ -592,7 +599,7 @@ impl BufWriter { pub fn into_inner(mut self) -> Result>> { match self.flush_buf() { Err(e) => Err(IntoInnerError(self, e)), - Ok(()) => Ok(self.inner.take().unwrap()) + Ok(()) => Ok(self.inner.take().unwrap()), } } } @@ -634,7 +641,10 @@ impl Write for BufWriter { } #[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Debug for BufWriter where W: fmt::Debug { +impl fmt::Debug for BufWriter +where + W: fmt::Debug, +{ fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("BufWriter") .field("writer", &self.inner.as_ref().unwrap()) @@ -693,7 +703,9 @@ impl IntoInnerError { /// }; /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn error(&self) -> &Error { &self.1 } + pub fn error(&self) -> &Error { + &self.1 + } /// Returns the buffered writer instance which generated the error. /// @@ -726,12 +738,16 @@ impl IntoInnerError { /// }; /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn into_inner(self) -> W { self.0 } + pub fn into_inner(self) -> W { + self.0 + } } #[stable(feature = "rust1", since = "1.0.0")] impl From> for Error { - fn from(iie: IntoInnerError) -> Error { iie.1 } + fn from(iie: IntoInnerError) -> Error { + iie.1 + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -856,10 +872,7 @@ impl LineWriter { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn with_capacity(capacity: usize, inner: W) -> LineWriter { - LineWriter { - inner: BufWriter::with_capacity(capacity, inner), - need_flush: false, - } + LineWriter { inner: BufWriter::with_capacity(capacity, inner), need_flush: false } } /// Gets a reference to the underlying writer. @@ -879,7 +892,9 @@ impl LineWriter { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_ref(&self) -> &W { self.inner.get_ref() } + pub fn get_ref(&self) -> &W { + self.inner.get_ref() + } /// Gets a mutable reference to the underlying writer. /// @@ -902,7 +917,9 @@ impl LineWriter { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_mut(&mut self) -> &mut W { self.inner.get_mut() } + pub fn get_mut(&mut self) -> &mut W { + self.inner.get_mut() + } /// Unwraps this `LineWriter`, returning the underlying writer. /// @@ -930,10 +947,7 @@ impl LineWriter { #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(self) -> Result>> { self.inner.into_inner().map_err(|IntoInnerError(buf, e)| { - IntoInnerError(LineWriter { - inner: buf, - need_flush: false, - }, e) + IntoInnerError(LineWriter { inner: buf, need_flush: false }, e) }) } } @@ -953,7 +967,6 @@ impl Write for LineWriter { None => return self.inner.write(buf), }; - // Ok, we're going to write a partial amount of the data given first // followed by flushing the newline. After we've successfully written // some data then we *must* report that we wrote that data, so future @@ -962,7 +975,7 @@ impl Write for LineWriter { let n = self.inner.write(&buf[..=i])?; self.need_flush = true; if self.flush().is_err() || n != i + 1 { - return Ok(n) + return Ok(n); } // At this point we successfully wrote `i + 1` bytes and flushed it out, @@ -984,12 +997,17 @@ impl Write for LineWriter { } #[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Debug for LineWriter where W: fmt::Debug { +impl fmt::Debug for LineWriter +where + W: fmt::Debug, +{ fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("LineWriter") .field("writer", &self.inner.inner) - .field("buffer", - &format_args!("{}/{}", self.inner.buf.len(), self.inner.buf.capacity())) + .field( + "buffer", + &format_args!("{}/{}", self.inner.buf.len(), self.inner.buf.capacity()), + ) .finish() } } @@ -1008,11 +1026,7 @@ mod tests { impl Read for ShortReader { fn read(&mut self, _: &mut [u8]) -> io::Result { - if self.lengths.is_empty() { - Ok(0) - } else { - Ok(self.lengths.remove(0)) - } + if self.lengths.is_empty() { Ok(0) } else { Ok(self.lengths.remove(0)) } } } @@ -1123,7 +1137,7 @@ mod tests { fn test_buffered_reader_seek_underflow() { // gimmick reader that yields its position modulo 256 for each byte struct PositionReader { - pos: u64 + pos: u64, } impl Read for PositionReader { fn read(&mut self, buf: &mut [u8]) -> io::Result { @@ -1154,7 +1168,7 @@ mod tests { let mut reader = BufReader::with_capacity(5, PositionReader { pos: 0 }); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); - assert_eq!(reader.seek(SeekFrom::End(-5)).ok(), Some(u64::max_value()-5)); + assert_eq!(reader.seek(SeekFrom::End(-5)).ok(), Some(u64::max_value() - 5)); assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5)); // the following seek will require two underlying seeks let expected = 9223372036854775802; @@ -1361,7 +1375,7 @@ mod tests { #[test] fn test_short_reads() { - let inner = ShortReader{lengths: vec![0, 1, 2, 0, 1, 0]}; + let inner = ShortReader { lengths: vec![0, 1, 2, 0, 1, 0] }; let mut reader = BufReader::new(inner); let mut buf = [0, 0]; assert_eq!(reader.read(&mut buf).unwrap(), 0); @@ -1379,7 +1393,9 @@ mod tests { struct FailFlushWriter; impl Write for FailFlushWriter { - fn write(&mut self, buf: &[u8]) -> io::Result { Ok(buf.len()) } + fn write(&mut self, buf: &[u8]) -> io::Result { + Ok(buf.len()) + } fn flush(&mut self) -> io::Result<()> { Err(io::Error::last_os_error()) } @@ -1405,30 +1421,30 @@ mod tests { WRITES.fetch_add(1, Ordering::SeqCst); panic!(); } - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } thread::spawn(|| { let mut writer = BufWriter::new(PanicWriter); let _ = writer.write(b"hello world"); let _ = writer.flush(); - }).join().unwrap_err(); + }) + .join() + .unwrap_err(); assert_eq!(WRITES.load(Ordering::SeqCst), 1); } #[bench] fn bench_buffered_reader(b: &mut test::Bencher) { - b.iter(|| { - BufReader::new(io::empty()) - }); + b.iter(|| BufReader::new(io::empty())); } #[bench] fn bench_buffered_writer(b: &mut test::Bencher) { - b.iter(|| { - BufWriter::new(io::sink()) - }); + b.iter(|| BufWriter::new(io::sink())); } struct AcceptOneThenFail { @@ -1457,10 +1473,7 @@ mod tests { #[test] fn erroneous_flush_retried() { - let a = AcceptOneThenFail { - written: false, - flushed: false, - }; + let a = AcceptOneThenFail { written: false, flushed: false }; let mut l = LineWriter::new(a); assert_eq!(l.write(b"a\nb\na").unwrap(), 4); diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs index c29a68e6f02b8..c20bd3097b27d 100644 --- a/src/libstd/io/error.rs +++ b/src/libstd/io/error.rs @@ -1,8 +1,8 @@ +use crate::convert::From; use crate::error; use crate::fmt; use crate::result; use crate::sys; -use crate::convert::From; /// A specialized [`Result`](../result/enum.Result.html) type for I/O /// operations. @@ -73,7 +73,7 @@ enum Repr { #[derive(Debug)] struct Custom { kind: ErrorKind, - error: Box, + error: Box, } /// A list specifying general categories of I/O error. @@ -220,9 +220,7 @@ impl From for Error { /// [`Error`]: ../../std/io/struct.Error.html #[inline] fn from(kind: ErrorKind) -> Error { - Error { - repr: Repr::Simple(kind) - } + Error { repr: Repr::Simple(kind) } } } @@ -247,18 +245,14 @@ impl Error { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(kind: ErrorKind, error: E) -> Error - where E: Into> + where + E: Into>, { Self::_new(kind, error.into()) } - fn _new(kind: ErrorKind, error: Box) -> Error { - Error { - repr: Repr::Custom(Box::new(Custom { - kind, - error, - })) - } + fn _new(kind: ErrorKind, error: Box) -> Error { + Error { repr: Repr::Custom(Box::new(Custom { kind, error })) } } /// Returns an error representing the last OS error which occurred. @@ -370,7 +364,7 @@ impl Error { /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] - pub fn get_ref(&self) -> Option<&(dyn error::Error+Send+Sync+'static)> { + pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> { match self.repr { Repr::Os(..) => None, Repr::Simple(..) => None, @@ -441,7 +435,7 @@ impl Error { /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] - pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error+Send+Sync+'static)> { + pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> { match self.repr { Repr::Os(..) => None, Repr::Simple(..) => None, @@ -475,11 +469,11 @@ impl Error { /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] - pub fn into_inner(self) -> Option> { + pub fn into_inner(self) -> Option> { match self.repr { Repr::Os(..) => None, Repr::Simple(..) => None, - Repr::Custom(c) => Some(c.error) + Repr::Custom(c) => Some(c.error), } } @@ -514,11 +508,12 @@ impl Error { impl fmt::Debug for Repr { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - Repr::Os(code) => - fmt.debug_struct("Os") - .field("code", &code) - .field("kind", &sys::decode_error_kind(code)) - .field("message", &sys::os::error_string(code)).finish(), + Repr::Os(code) => fmt + .debug_struct("Os") + .field("code", &code) + .field("kind", &sys::decode_error_kind(code)) + .field("message", &sys::os::error_string(code)) + .finish(), Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt), Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(), } @@ -567,17 +562,17 @@ impl error::Error for Error { } fn _assert_error_is_sync_send() { - fn _is_sync_send() {} + fn _is_sync_send() {} _is_sync_send::(); } #[cfg(test)] mod test { - use super::{Error, ErrorKind, Repr, Custom}; + use super::{Custom, Error, ErrorKind, Repr}; use crate::error; use crate::fmt; - use crate::sys::os::error_string; use crate::sys::decode_error_kind; + use crate::sys::os::error_string; #[test] fn test_debug_error() { @@ -587,20 +582,18 @@ mod test { let err = Error { repr: Repr::Custom(box Custom { kind: ErrorKind::InvalidInput, - error: box Error { - repr: super::Repr::Os(code) - }, - }) + error: box Error { repr: super::Repr::Os(code) }, + }), }; let expected = format!( "Custom {{ \ - kind: InvalidInput, \ - error: Os {{ \ - code: {:?}, \ - kind: {:?}, \ - message: {:?} \ - }} \ - }}", + kind: InvalidInput, \ + error: Os {{ \ + code: {:?}, \ + kind: {:?}, \ + message: {:?} \ + }} \ + }}", code, kind, msg ); assert_eq!(format!("{:?}", err), expected); diff --git a/src/libstd/io/impls.rs b/src/libstd/io/impls.rs index c959f2d389b11..b7f82e652990d 100644 --- a/src/libstd/io/impls.rs +++ b/src/libstd/io/impls.rs @@ -1,7 +1,8 @@ use crate::cmp; -use crate::io::{self, SeekFrom, Read, Initializer, Write, Seek, BufRead, Error, ErrorKind, - IoSliceMut, IoSlice}; use crate::fmt; +use crate::io::{ + self, BufRead, Error, ErrorKind, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write, +}; use crate::mem; // ============================================================================= @@ -42,7 +43,9 @@ impl Read for &mut R { #[stable(feature = "rust1", since = "1.0.0")] impl Write for &mut W { #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result { (**self).write(buf) } + fn write(&mut self, buf: &[u8]) -> io::Result { + (**self).write(buf) + } #[inline] fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { @@ -50,7 +53,9 @@ impl Write for &mut W { } #[inline] - fn flush(&mut self) -> io::Result<()> { (**self).flush() } + fn flush(&mut self) -> io::Result<()> { + (**self).flush() + } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { @@ -65,15 +70,21 @@ impl Write for &mut W { #[stable(feature = "rust1", since = "1.0.0")] impl Seek for &mut S { #[inline] - fn seek(&mut self, pos: SeekFrom) -> io::Result { (**self).seek(pos) } + fn seek(&mut self, pos: SeekFrom) -> io::Result { + (**self).seek(pos) + } } #[stable(feature = "rust1", since = "1.0.0")] impl BufRead for &mut B { #[inline] - fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() } + fn fill_buf(&mut self) -> io::Result<&[u8]> { + (**self).fill_buf() + } #[inline] - fn consume(&mut self, amt: usize) { (**self).consume(amt) } + fn consume(&mut self, amt: usize) { + (**self).consume(amt) + } #[inline] fn read_until(&mut self, byte: u8, buf: &mut Vec) -> io::Result { @@ -121,7 +132,9 @@ impl Read for Box { #[stable(feature = "rust1", since = "1.0.0")] impl Write for Box { #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result { (**self).write(buf) } + fn write(&mut self, buf: &[u8]) -> io::Result { + (**self).write(buf) + } #[inline] fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { @@ -129,7 +142,9 @@ impl Write for Box { } #[inline] - fn flush(&mut self) -> io::Result<()> { (**self).flush() } + fn flush(&mut self) -> io::Result<()> { + (**self).flush() + } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { @@ -144,15 +159,21 @@ impl Write for Box { #[stable(feature = "rust1", since = "1.0.0")] impl Seek for Box { #[inline] - fn seek(&mut self, pos: SeekFrom) -> io::Result { (**self).seek(pos) } + fn seek(&mut self, pos: SeekFrom) -> io::Result { + (**self).seek(pos) + } } #[stable(feature = "rust1", since = "1.0.0")] impl BufRead for Box { #[inline] - fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() } + fn fill_buf(&mut self) -> io::Result<&[u8]> { + (**self).fill_buf() + } #[inline] - fn consume(&mut self, amt: usize) { (**self).consume(amt) } + fn consume(&mut self, amt: usize) { + (**self).consume(amt) + } #[inline] fn read_until(&mut self, byte: u8, buf: &mut Vec) -> io::Result { @@ -227,8 +248,7 @@ impl Read for &[u8] { #[inline] fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { if buf.len() > self.len() { - return Err(Error::new(ErrorKind::UnexpectedEof, - "failed to fill whole buffer")); + return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer")); } let (a, b) = self.split_at(buf.len()); @@ -257,10 +277,14 @@ impl Read for &[u8] { #[stable(feature = "rust1", since = "1.0.0")] impl BufRead for &[u8] { #[inline] - fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(*self) } + fn fill_buf(&mut self) -> io::Result<&[u8]> { + Ok(*self) + } #[inline] - fn consume(&mut self, amt: usize) { *self = &self[amt..]; } + fn consume(&mut self, amt: usize) { + *self = &self[amt..]; + } } /// Write is implemented for `&mut [u8]` by copying into the slice, overwriting @@ -302,7 +326,9 @@ impl Write for &mut [u8] { } #[inline] - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } /// Write is implemented for `Vec` by appending to the vector. @@ -332,7 +358,9 @@ impl Write for Vec { } #[inline] - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } #[cfg(test)] diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index be364a10593da..20c1c5cd1b8ad 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -261,49 +261,54 @@ use crate::cmp; use crate::fmt; -use crate::slice; -use crate::str; use crate::memchr; use crate::ops::{Deref, DerefMut}; use crate::ptr; +use crate::slice; +use crate::str; use crate::sys; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::buffered::{BufReader, BufWriter, LineWriter}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::buffered::IntoInnerError; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::cursor::Cursor; +pub use self::buffered::{BufReader, BufWriter, LineWriter}; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::error::{Result, Error, ErrorKind}; +pub use self::cursor::Cursor; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat}; +pub use self::error::{Error, ErrorKind, Result}; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr}; +pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout}; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::stdio::{StdoutLock, StderrLock, StdinLock}; +pub use self::stdio::{StderrLock, StdinLock, StdoutLock}; #[unstable(feature = "print_internals", issue = "0")] -pub use self::stdio::{_print, _eprint}; +pub use self::stdio::{_eprint, _print}; #[unstable(feature = "libstd_io_internals", issue = "42788")] #[doc(no_inline, hidden)] pub use self::stdio::{set_panic, set_print}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::util::{copy, empty, repeat, sink, Empty, Repeat, Sink}; -pub mod prelude; mod buffered; mod cursor; mod error; mod impls; mod lazy; -mod util; +pub mod prelude; mod stdio; +mod util; const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE; -struct Guard<'a> { buf: &'a mut Vec, len: usize } +struct Guard<'a> { + buf: &'a mut Vec, + len: usize, +} impl Drop for Guard<'_> { fn drop(&mut self) { - unsafe { self.buf.set_len(self.len); } + unsafe { + self.buf.set_len(self.len); + } } } @@ -326,15 +331,15 @@ impl Drop for Guard<'_> { // the function only *appends* bytes to the buffer. We'll get undefined // behavior if existing bytes are overwritten to have non-UTF-8 data. fn append_to_string(buf: &mut String, f: F) -> Result - where F: FnOnce(&mut Vec) -> Result +where + F: FnOnce(&mut Vec) -> Result, { unsafe { let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() }; let ret = f(g.buf); if str::from_utf8(&g.buf[g.len..]).is_err() { ret.and_then(|_| { - Err(Error::new(ErrorKind::InvalidData, - "stream did not contain valid UTF-8")) + Err(Error::new(ErrorKind::InvalidData, "stream did not contain valid UTF-8")) }) } else { g.len = g.buf.len(); @@ -405,23 +410,17 @@ where pub(crate) fn default_read_vectored(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result where - F: FnOnce(&mut [u8]) -> Result + F: FnOnce(&mut [u8]) -> Result, { - let buf = bufs - .iter_mut() - .find(|b| !b.is_empty()) - .map_or(&mut [][..], |b| &mut **b); + let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b); read(buf) } pub(crate) fn default_write_vectored(write: F, bufs: &[IoSlice<'_>]) -> Result where - F: FnOnce(&[u8]) -> Result + F: FnOnce(&[u8]) -> Result, { - let buf = bufs - .iter() - .find(|b| !b.is_empty()) - .map_or(&[][..], |b| &**b); + let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b); write(buf) } @@ -767,14 +766,16 @@ pub trait Read { while !buf.is_empty() { match self.read(buf) { Ok(0) => break, - Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; } + Ok(n) => { + let tmp = buf; + buf = &mut tmp[n..]; + } Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return Err(e), } } if !buf.is_empty() { - Err(Error::new(ErrorKind::UnexpectedEof, - "failed to fill whole buffer")) + Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer")) } else { Ok(()) } @@ -815,7 +816,12 @@ pub trait Read { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn by_ref(&mut self) -> &mut Self where Self: Sized { self } + fn by_ref(&mut self) -> &mut Self + where + Self: Sized, + { + self + } /// Transforms this `Read` instance to an [`Iterator`] over its bytes. /// @@ -852,7 +858,10 @@ pub trait Read { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn bytes(self) -> Bytes where Self: Sized { + fn bytes(self) -> Bytes + where + Self: Sized, + { Bytes { inner: self } } @@ -887,7 +896,10 @@ pub trait Read { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn chain(self, next: R) -> Chain where Self: Sized { + fn chain(self, next: R) -> Chain + where + Self: Sized, + { Chain { first: self, second: next, done_first: false } } @@ -923,7 +935,10 @@ pub trait Read { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn take(self, limit: u64) -> Take where Self: Sized { + fn take(self, limit: u64) -> Take + where + Self: Sized, + { Take { inner: self, limit: limit } } } @@ -1339,8 +1354,9 @@ pub trait Write { fn write_all(&mut self, mut buf: &[u8]) -> Result<()> { while !buf.is_empty() { match self.write(buf) { - Ok(0) => return Err(Error::new(ErrorKind::WriteZero, - "failed to write whole buffer")), + Ok(0) => { + return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer")); + } Ok(n) => buf = &buf[n..], Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return Err(e), @@ -1444,7 +1460,12 @@ pub trait Write { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn by_ref(&mut self) -> &mut Self where Self: Sized { self } + fn by_ref(&mut self) -> &mut Self + where + Self: Sized, + { + self + } } /// The `Seek` trait provides a cursor which can be moved within a stream of @@ -1601,15 +1622,14 @@ pub enum SeekFrom { Current(#[stable(feature = "rust1", since = "1.0.0")] i64), } -fn read_until(r: &mut R, delim: u8, buf: &mut Vec) - -> Result { +fn read_until(r: &mut R, delim: u8, buf: &mut Vec) -> Result { let mut read = 0; loop { let (done, used) = { let available = match r.fill_buf() { Ok(n) => n, Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, - Err(e) => return Err(e) + Err(e) => return Err(e), }; match memchr::memchr(delim, available) { Some(i) => { @@ -1900,7 +1920,10 @@ pub trait BufRead: Read { /// assert_eq!(split_iter.next(), None); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn split(self, byte: u8) -> Split where Self: Sized { + fn split(self, byte: u8) -> Split + where + Self: Sized, + { Split { buf: self, delim: byte } } @@ -1939,7 +1962,10 @@ pub trait BufRead: Read { /// /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line #[stable(feature = "rust1", since = "1.0.0")] - fn lines(self) -> Lines where Self: Sized { + fn lines(self) -> Lines + where + Self: Sized, + { Lines { buf: self } } } @@ -2035,10 +2061,7 @@ impl Chain { #[stable(feature = "std_debug", since = "1.16.0")] impl fmt::Debug for Chain { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Chain") - .field("t", &self.first) - .field("u", &self.second) - .finish() + f.debug_struct("Chain").field("t", &self.first).field("u", &self.second).finish() } } @@ -2066,11 +2089,7 @@ impl Read for Chain { unsafe fn initializer(&self) -> Initializer { let initializer = self.first.initializer(); - if initializer.should_initialize() { - initializer - } else { - self.second.initializer() - } + if initializer.should_initialize() { initializer } else { self.second.initializer() } } } @@ -2079,7 +2098,9 @@ impl BufRead for Chain { fn fill_buf(&mut self) -> Result<&[u8]> { if !self.done_first { match self.first.fill_buf()? { - buf if buf.is_empty() => { self.done_first = true; } + buf if buf.is_empty() => { + self.done_first = true; + } buf => return Ok(buf), } } @@ -2087,11 +2108,7 @@ impl BufRead for Chain { } fn consume(&mut self, amt: usize) { - if !self.done_first { - self.first.consume(amt) - } else { - self.second.consume(amt) - } + if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) } } } @@ -2137,7 +2154,9 @@ impl Take { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn limit(&self) -> u64 { self.limit } + pub fn limit(&self) -> u64 { + self.limit + } /// Sets the number of bytes that can be read before this instance will /// return EOF. This is the same as constructing a new `Take` instance, so @@ -2351,7 +2370,7 @@ impl Iterator for Split { } Some(Ok(buf)) } - Err(e) => Some(Err(e)) + Err(e) => Some(Err(e)), } } } @@ -2385,16 +2404,16 @@ impl Iterator for Lines { } Some(Ok(buf)) } - Err(e) => Some(Err(e)) + Err(e) => Some(Err(e)), } } } #[cfg(test)] mod tests { + use super::{repeat, Cursor, SeekFrom}; use crate::cmp; use crate::io::prelude::*; - use super::{Cursor, SeekFrom, repeat}; use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; use crate::ops::Deref; @@ -2509,16 +2528,14 @@ mod tests { let mut buf = [0; 4]; let mut c = Cursor::new(&b""[..]); - assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), - io::ErrorKind::UnexpectedEof); + assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..])); c.read_exact(&mut buf).unwrap(); assert_eq!(&buf, b"1234"); c.read_exact(&mut buf).unwrap(); assert_eq!(&buf, b"5678"); - assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), - io::ErrorKind::UnexpectedEof); + assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); } #[test] @@ -2526,12 +2543,10 @@ mod tests { let mut buf = [0; 4]; let mut c = &b""[..]; - assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), - io::ErrorKind::UnexpectedEof); + assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); let mut c = &b"123"[..]; - assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), - io::ErrorKind::UnexpectedEof); + assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); // make sure the optimized (early returning) method is being used assert_eq!(&buf, &[0; 4]); @@ -2558,7 +2573,7 @@ mod tests { fn fill_buf(&mut self) -> io::Result<&[u8]> { Err(io::Error::new(io::ErrorKind::Other, "")) } - fn consume(&mut self, _amt: usize) { } + fn consume(&mut self, _amt: usize) {} } let mut buf = [0; 1]; @@ -2591,11 +2606,9 @@ mod tests { #[test] fn chain_bufread() { let testdata = b"ABCDEFGHIJKL"; - let chain1 = (&testdata[..3]).chain(&testdata[3..6]) - .chain(&testdata[6..9]) - .chain(&testdata[9..]); - let chain2 = (&testdata[..4]).chain(&testdata[4..8]) - .chain(&testdata[8..]); + let chain1 = + (&testdata[..3]).chain(&testdata[3..6]).chain(&testdata[6..9]).chain(&testdata[9..]); + let chain2 = (&testdata[..4]).chain(&testdata[4..8]).chain(&testdata[8..]); cmp_bufread(chain1, chain2, &testdata[..]); } @@ -2651,7 +2664,6 @@ mod tests { assert_eq!(c.stream_position()?, 15); assert_eq!(c.stream_position()?, 15); - c.seek(SeekFrom::Start(7))?; c.seek(SeekFrom::Current(2))?; assert_eq!(c.stream_position()?, 9); @@ -2700,9 +2712,7 @@ mod tests { // that will not allocate when the limit has already been reached. In // this case, vec2 never grows. let mut vec2 = Vec::with_capacity(input.len()); - ExampleSliceReader { slice: input } - .take(input.len() as u64) - .read_to_end(&mut vec2)?; + ExampleSliceReader { slice: input }.take(input.len() as u64).read_to_end(&mut vec2)?; assert_eq!(vec2.len(), input.len()); assert_eq!(vec2.capacity(), input.len(), "did not allocate more"); diff --git a/src/libstd/io/prelude.rs b/src/libstd/io/prelude.rs index 2e19edf262126..3baab2be37795 100644 --- a/src/libstd/io/prelude.rs +++ b/src/libstd/io/prelude.rs @@ -11,4 +11,4 @@ #![stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")] -pub use super::{Read, Write, BufRead, Seek}; +pub use super::{BufRead, Read, Seek, Write}; diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index 33cc87eb79555..b09161b97aa5e 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -1,7 +1,7 @@ #![allow(missing_copy_implementations)] use crate::fmt; -use crate::io::{self, Read, Initializer, Write, ErrorKind, BufRead, IoSlice, IoSliceMut}; +use crate::io::{self, BufRead, ErrorKind, Initializer, IoSlice, IoSliceMut, Read, Write}; use crate::mem::MaybeUninit; /// Copies the entire contents of a reader into a writer. @@ -41,7 +41,9 @@ use crate::mem::MaybeUninit; /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn copy(reader: &mut R, writer: &mut W) -> io::Result - where R: Read, W: Write +where + R: Read, + W: Write, { let mut buf = MaybeUninit::<[u8; super::DEFAULT_BUF_SIZE]>::uninit(); // FIXME(#53491): This is calling `get_mut` and `get_ref` on an uninitialized @@ -49,7 +51,9 @@ pub fn copy(reader: &mut R, writer: &mut W) -> io::Result< // This is still technically undefined behavior due to creating a reference // to uninitialized data, but within libstd we can rely on more guarantees // than if this code were in an external lib. - unsafe { reader.initializer().initialize(buf.get_mut()); } + unsafe { + reader.initializer().initialize(buf.get_mut()); + } let mut written = 0; loop { @@ -71,7 +75,9 @@ pub fn copy(reader: &mut R, writer: &mut W) -> io::Result< /// /// [`empty`]: fn.empty.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct Empty { _priv: () } +pub struct Empty { + _priv: (), +} /// Constructs a new handle to an empty reader. /// @@ -91,12 +97,16 @@ pub struct Empty { _priv: () } /// assert!(buffer.is_empty()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] -pub fn empty() -> Empty { Empty { _priv: () } } +pub fn empty() -> Empty { + Empty { _priv: () } +} #[stable(feature = "rust1", since = "1.0.0")] impl Read for Empty { #[inline] - fn read(&mut self, _buf: &mut [u8]) -> io::Result { Ok(0) } + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + Ok(0) + } #[inline] unsafe fn initializer(&self) -> Initializer { @@ -106,7 +116,9 @@ impl Read for Empty { #[stable(feature = "rust1", since = "1.0.0")] impl BufRead for Empty { #[inline] - fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) } + fn fill_buf(&mut self) -> io::Result<&[u8]> { + Ok(&[]) + } #[inline] fn consume(&mut self, _n: usize) {} } @@ -125,7 +137,9 @@ impl fmt::Debug for Empty { /// /// [repeat]: fn.repeat.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct Repeat { byte: u8 } +pub struct Repeat { + byte: u8, +} /// Creates an instance of a reader that infinitely repeats one byte. /// @@ -142,7 +156,9 @@ pub struct Repeat { byte: u8 } /// assert_eq!(buffer, [0b101, 0b101, 0b101]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] -pub fn repeat(byte: u8) -> Repeat { Repeat { byte } } +pub fn repeat(byte: u8) -> Repeat { + Repeat { byte } +} #[stable(feature = "rust1", since = "1.0.0")] impl Read for Repeat { @@ -183,7 +199,9 @@ impl fmt::Debug for Repeat { /// /// [sink]: fn.sink.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct Sink { _priv: () } +pub struct Sink { + _priv: (), +} /// Creates an instance of a writer which will successfully consume all data. /// @@ -200,12 +218,16 @@ pub struct Sink { _priv: () } /// assert_eq!(num_bytes, 5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] -pub fn sink() -> Sink { Sink { _priv: () } } +pub fn sink() -> Sink { + Sink { _priv: () } +} #[stable(feature = "rust1", since = "1.0.0")] impl Write for Sink { #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result { Ok(buf.len()) } + fn write(&mut self, buf: &[u8]) -> io::Result { + Ok(buf.len()) + } #[inline] fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { @@ -214,7 +236,9 @@ impl Write for Sink { } #[inline] - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } #[stable(feature = "std_debug", since = "1.16.0")] @@ -227,7 +251,7 @@ impl fmt::Debug for Sink { #[cfg(test)] mod tests { use crate::io::prelude::*; - use crate::io::{copy, sink, empty, repeat}; + use crate::io::{copy, empty, repeat, sink}; #[test] fn copy_copies() { diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index 2df79ee97fbac..11850a1b5fc38 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -313,9 +313,8 @@ macro_rules! dbg { #[cfg(test)] macro_rules! assert_approx_eq { - ($a:expr, $b:expr) => ({ + ($a:expr, $b:expr) => {{ let (a, b) = (&$a, &$b); - assert!((*a - *b).abs() < 1.0e-6, - "{} is not approximately equal to {}", *a, *b); - }) + assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b); + }}; } diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs index f9255b82fc83e..d5f4ece726bea 100644 --- a/src/libstd/net/addr.rs +++ b/src/libstd/net/addr.rs @@ -1,16 +1,16 @@ +use crate::convert::TryInto; use crate::fmt; use crate::hash; use crate::io; +use crate::iter; use crate::mem; -use crate::net::{ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr}; +use crate::net::{hton, ntoh, IpAddr, Ipv4Addr, Ipv6Addr}; use crate::option; +use crate::slice; use crate::sys::net::netc as c; -use crate::sys_common::{FromInner, AsInner, IntoInner}; use crate::sys_common::net::LookupHost; +use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::vec; -use crate::iter; -use crate::slice; -use crate::convert::TryInto; /// An internet socket address, either IPv4 or IPv6. /// @@ -74,7 +74,9 @@ pub enum SocketAddr { /// ``` #[derive(Copy)] #[stable(feature = "rust1", since = "1.0.0")] -pub struct SocketAddrV4 { inner: c::sockaddr_in } +pub struct SocketAddrV4 { + inner: c::sockaddr_in, +} /// An IPv6 socket address. /// @@ -104,7 +106,9 @@ pub struct SocketAddrV4 { inner: c::sockaddr_in } /// ``` #[derive(Copy)] #[stable(feature = "rust1", since = "1.0.0")] -pub struct SocketAddrV6 { inner: c::sockaddr_in6 } +pub struct SocketAddrV6 { + inner: c::sockaddr_in6, +} impl SocketAddr { /// Creates a new socket address from an [IP address] and a port number. @@ -274,7 +278,7 @@ impl SocketAddrV4 { sin_family: c::AF_INET as c::sa_family_t, sin_port: hton(port), sin_addr: *ip.as_inner(), - .. unsafe { mem::zeroed() } + ..unsafe { mem::zeroed() } }, } } @@ -291,9 +295,7 @@ impl SocketAddrV4 { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn ip(&self) -> &Ipv4Addr { - unsafe { - &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) - } + unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) } } /// Changes the IP address associated with this socket address. @@ -362,8 +364,7 @@ impl SocketAddrV6 { /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) - -> SocketAddrV6 { + pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 { SocketAddrV6 { inner: c::sockaddr_in6 { sin6_family: c::AF_INET6 as c::sa_family_t, @@ -371,7 +372,7 @@ impl SocketAddrV6 { sin6_addr: *ip.as_inner(), sin6_flowinfo: flowinfo, sin6_scope_id: scope_id, - .. unsafe { mem::zeroed() } + ..unsafe { mem::zeroed() } }, } } @@ -388,9 +389,7 @@ impl SocketAddrV6 { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn ip(&self) -> &Ipv6Addr { - unsafe { - &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) - } + unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) } } /// Changes the IP address associated with this socket address. @@ -633,27 +632,31 @@ impl fmt::Debug for SocketAddrV6 { #[stable(feature = "rust1", since = "1.0.0")] impl Clone for SocketAddrV4 { - fn clone(&self) -> SocketAddrV4 { *self } + fn clone(&self) -> SocketAddrV4 { + *self + } } #[stable(feature = "rust1", since = "1.0.0")] impl Clone for SocketAddrV6 { - fn clone(&self) -> SocketAddrV6 { *self } + fn clone(&self) -> SocketAddrV6 { + *self + } } #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for SocketAddrV4 { fn eq(&self, other: &SocketAddrV4) -> bool { - self.inner.sin_port == other.inner.sin_port && - self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr + self.inner.sin_port == other.inner.sin_port + && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr } } #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for SocketAddrV6 { fn eq(&self, other: &SocketAddrV6) -> bool { - self.inner.sin6_port == other.inner.sin6_port && - self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr && - self.inner.sin6_flowinfo == other.inner.sin6_flowinfo && - self.inner.sin6_scope_id == other.inner.sin6_scope_id + self.inner.sin6_port == other.inner.sin6_port + && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr + && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo + && self.inner.sin6_scope_id == other.inner.sin6_scope_id } } #[stable(feature = "rust1", since = "1.0.0")] @@ -670,8 +673,13 @@ impl hash::Hash for SocketAddrV4 { #[stable(feature = "rust1", since = "1.0.0")] impl hash::Hash for SocketAddrV6 { fn hash(&self, s: &mut H) { - (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr, - self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s) + ( + self.inner.sin6_port, + &self.inner.sin6_addr.s6_addr, + self.inner.sin6_flowinfo, + self.inner.sin6_scope_id, + ) + .hash(s) } } @@ -795,7 +803,7 @@ pub trait ToSocketAddrs { /// Returned iterator over socket addresses which this type may correspond /// to. #[stable(feature = "rust1", since = "1.0.0")] - type Iter: Iterator; + type Iter: Iterator; /// Converts this object to an iterator of resolved `SocketAddr`s. /// @@ -864,7 +872,12 @@ impl ToSocketAddrs for (Ipv6Addr, u16) { fn resolve_socket_addr(lh: LookupHost) -> io::Result> { let p = lh.port(); - let v: Vec<_> = lh.map(|mut a| { a.set_port(p); a }).collect(); + let v: Vec<_> = lh + .map(|mut a| { + a.set_port(p); + a + }) + .collect(); Ok(v.into_iter()) } @@ -877,11 +890,11 @@ impl ToSocketAddrs for (&str, u16) { // try to parse the host as a regular IP address first if let Ok(addr) = host.parse::() { let addr = SocketAddrV4::new(addr, port); - return Ok(vec![SocketAddr::V4(addr)].into_iter()) + return Ok(vec![SocketAddr::V4(addr)].into_iter()); } if let Ok(addr) = host.parse::() { let addr = SocketAddrV6::new(addr, port, 0, 0); - return Ok(vec![SocketAddr::V6(addr)].into_iter()) + return Ok(vec![SocketAddr::V6(addr)].into_iter()); } resolve_socket_addr((host, port).try_into()?) @@ -929,8 +942,8 @@ impl ToSocketAddrs for String { #[cfg(all(test, not(target_os = "emscripten")))] mod tests { + use crate::net::test::{sa4, sa6, tsa}; use crate::net::*; - use crate::net::test::{tsa, sa6, sa4}; #[test] fn to_socket_addr_ipaddr_u16() { @@ -991,8 +1004,12 @@ mod tests { #[test] fn set_ip() { - fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) } - fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) } + fn ip4(low: u8) -> Ipv4Addr { + Ipv4Addr::new(77, 88, 21, low) + } + fn ip6(low: u16) -> Ipv6Addr { + Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) + } let mut v4 = SocketAddrV4::new(ip4(11), 80); assert_eq!(v4.ip(), &ip4(11)); @@ -1068,7 +1085,11 @@ mod tests { #[test] fn is_v6() { let v6 = SocketAddr::V6(SocketAddrV6::new( - Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0)); + Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), + 80, + 10, + 0, + )); assert!(!v6.is_ipv4()); assert!(v6.is_ipv6()); } diff --git a/src/libstd/net/parser.rs b/src/libstd/net/parser.rs index 5a76139530a46..8106d1c3315aa 100644 --- a/src/libstd/net/parser.rs +++ b/src/libstd/net/parser.rs @@ -16,10 +16,7 @@ struct Parser<'a> { impl<'a> Parser<'a> { fn new(s: &'a str) -> Parser<'a> { - Parser { - s: s.as_bytes(), - pos: 0, - } + Parser { s: s.as_bytes(), pos: 0 } } fn is_eof(&self) -> bool { @@ -27,7 +24,8 @@ impl<'a> Parser<'a> { } // Commit only if parser returns Some - fn read_atomically(&mut self, cb: F) -> Option where + fn read_atomically(&mut self, cb: F) -> Option + where F: FnOnce(&mut Parser<'_>) -> Option, { let pos = self.pos; @@ -39,17 +37,18 @@ impl<'a> Parser<'a> { } // Commit only if parser read till EOF - fn read_till_eof(&mut self, cb: F) -> Option where + fn read_till_eof(&mut self, cb: F) -> Option + where F: FnOnce(&mut Parser<'_>) -> Option, { - self.read_atomically(move |p| { - cb(p).filter(|_| p.is_eof()) - }) + self.read_atomically(move |p| cb(p).filter(|_| p.is_eof())) } // Return result of first successful parser - fn read_or(&mut self, parsers: &mut [Box) -> Option + 'static>]) - -> Option { + fn read_or( + &mut self, + parsers: &mut [Box) -> Option + 'static>], + ) -> Option { for pf in parsers { if let Some(r) = self.read_atomically(|p: &mut Parser<'_>| pf(p)) { return Some(r); @@ -59,11 +58,8 @@ impl<'a> Parser<'a> { } // Apply 3 parsers sequentially - fn read_seq_3(&mut self, - pa: PA, - pb: PB, - pc: PC) - -> Option<(A, B, C)> where + fn read_seq_3(&mut self, pa: PA, pb: PB, pc: PC) -> Option<(A, B, C)> + where PA: FnOnce(&mut Parser<'_>) -> Option, PB: FnOnce(&mut Parser<'_>) -> Option, PC: FnOnce(&mut Parser<'_>) -> Option, @@ -74,7 +70,7 @@ impl<'a> Parser<'a> { let c = if b.is_some() { pc(p) } else { None }; match (a, b, c) { (Some(a), Some(b), Some(c)) => Some((a, b, c)), - _ => None + _ => None, } }) } @@ -92,11 +88,9 @@ impl<'a> Parser<'a> { // Return char and advance iff next char is equal to requested fn read_given_char(&mut self, c: char) -> Option { - self.read_atomically(|p| { - match p.read_char() { - Some(next) if next == c => Some(next), - _ => None, - } + self.read_atomically(|p| match p.read_char() { + Some(next) if next == c => Some(next), + _ => None, }) } @@ -116,9 +110,7 @@ impl<'a> Parser<'a> { } } - self.read_atomically(|p| { - p.read_char().and_then(|c| parse_digit(c, radix)) - }) + self.read_atomically(|p| p.read_char().and_then(|c| parse_digit(c, radix))) } fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option { @@ -130,14 +122,14 @@ impl<'a> Parser<'a> { r = r * (radix as u32) + (d as u32); digit_count += 1; if digit_count > max_digits || r >= upto { - return None + return None; } } None => { if digit_count == 0 { - return None + return None; } else { - return Some(r) + return Some(r); } } }; @@ -173,12 +165,11 @@ impl<'a> Parser<'a> { assert!(head.len() + tail.len() <= 8); let mut gs = [0; 8]; gs[..head.len()].copy_from_slice(head); - gs[(8 - tail.len()) .. 8].copy_from_slice(tail); + gs[(8 - tail.len())..8].copy_from_slice(tail); Ipv6Addr::new(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7]) } - fn read_groups(p: &mut Parser<'_>, groups: &mut [u16; 8], limit: usize) - -> (usize, bool) { + fn read_groups(p: &mut Parser<'_>, groups: &mut [u16; 8], limit: usize) -> (usize, bool) { let mut i = 0; while i < limit { if i < limit - 1 { @@ -206,7 +197,7 @@ impl<'a> Parser<'a> { }); match group { Some(g) => groups[i] = g, - None => return (i, false) + None => return (i, false), } i += 1; } @@ -218,13 +209,13 @@ impl<'a> Parser<'a> { if head_size == 8 { return Some(Ipv6Addr::new( - head[0], head[1], head[2], head[3], - head[4], head[5], head[6], head[7])) + head[0], head[1], head[2], head[3], head[4], head[5], head[6], head[7], + )); } // IPv4 part is not allowed before `::` if head_ipv4 { - return None + return None; } // read `::` if previous code parsed less than 8 groups @@ -252,9 +243,7 @@ impl<'a> Parser<'a> { fn read_socket_addr_v4(&mut self) -> Option { let ip_addr = |p: &mut Parser<'_>| p.read_ipv4_addr(); let colon = |p: &mut Parser<'_>| p.read_given_char(':'); - let port = |p: &mut Parser<'_>| { - p.read_number(10, 5, 0x10000).map(|n| n as u16) - }; + let port = |p: &mut Parser<'_>| p.read_number(10, 5, 0x10000).map(|n| n as u16); self.read_seq_3(ip_addr, colon, port).map(|t| { let (ip, _, port): (Ipv4Addr, char, u16) = t; @@ -270,9 +259,7 @@ impl<'a> Parser<'a> { p.read_seq_3(open_br, ip_addr, clos_br).map(|t| t.1) }; let colon = |p: &mut Parser<'_>| p.read_given_char(':'); - let port = |p: &mut Parser<'_>| { - p.read_number(10, 5, 0x10000).map(|n| n as u16) - }; + let port = |p: &mut Parser<'_>| p.read_number(10, 5, 0x10000).map(|n| n as u16); self.read_seq_3(ip_addr, colon, port).map(|t| { let (ip, _, port): (Ipv6Addr, char, u16) = t; @@ -293,7 +280,7 @@ impl FromStr for IpAddr { fn from_str(s: &str) -> Result { match Parser::new(s).read_till_eof(|p| p.read_ip_addr()) { Some(s) => Ok(s), - None => Err(AddrParseError(())) + None => Err(AddrParseError(())), } } } @@ -304,7 +291,7 @@ impl FromStr for Ipv4Addr { fn from_str(s: &str) -> Result { match Parser::new(s).read_till_eof(|p| p.read_ipv4_addr()) { Some(s) => Ok(s), - None => Err(AddrParseError(())) + None => Err(AddrParseError(())), } } } @@ -315,7 +302,7 @@ impl FromStr for Ipv6Addr { fn from_str(s: &str) -> Result { match Parser::new(s).read_till_eof(|p| p.read_ipv6_addr()) { Some(s) => Ok(s), - None => Err(AddrParseError(())) + None => Err(AddrParseError(())), } } } diff --git a/src/libstd/net/tcp.rs b/src/libstd/net/tcp.rs index d8b6fb6da9395..5c02215997088 100644 --- a/src/libstd/net/tcp.rs +++ b/src/libstd/net/tcp.rs @@ -2,7 +2,7 @@ use crate::io::prelude::*; use crate::fmt; use crate::io::{self, Initializer, IoSlice, IoSliceMut}; -use crate::net::{ToSocketAddrs, SocketAddr, Shutdown}; +use crate::net::{Shutdown, SocketAddr, ToSocketAddrs}; use crate::sys_common::net as net_imp; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; @@ -93,7 +93,9 @@ pub struct TcpListener(net_imp::TcpListener); /// [`TcpListener`]: ../../std/net/struct.TcpListener.html #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] -pub struct Incoming<'a> { listener: &'a TcpListener } +pub struct Incoming<'a> { + listener: &'a TcpListener, +} impl TcpStream { /// Opens a TCP connection to a remote host. @@ -567,7 +569,9 @@ impl TcpStream { #[stable(feature = "rust1", since = "1.0.0")] impl Read for TcpStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0.read(buf) } + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.0.read(buf) + } fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { self.0.read_vectored(bufs) @@ -580,17 +584,23 @@ impl Read for TcpStream { } #[stable(feature = "rust1", since = "1.0.0")] impl Write for TcpStream { - fn write(&mut self, buf: &[u8]) -> io::Result { self.0.write(buf) } + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { self.0.write_vectored(bufs) } - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } #[stable(feature = "rust1", since = "1.0.0")] impl Read for &TcpStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0.read(buf) } + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.0.read(buf) + } fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { self.0.read_vectored(bufs) @@ -603,25 +613,35 @@ impl Read for &TcpStream { } #[stable(feature = "rust1", since = "1.0.0")] impl Write for &TcpStream { - fn write(&mut self, buf: &[u8]) -> io::Result { self.0.write(buf) } + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { self.0.write_vectored(bufs) } - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } impl AsInner for TcpStream { - fn as_inner(&self) -> &net_imp::TcpStream { &self.0 } + fn as_inner(&self) -> &net_imp::TcpStream { + &self.0 + } } impl FromInner for TcpStream { - fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) } + fn from_inner(inner: net_imp::TcpStream) -> TcpStream { + TcpStream(inner) + } } impl IntoInner for TcpStream { - fn into_inner(self) -> net_imp::TcpStream { self.0 } + fn into_inner(self) -> net_imp::TcpStream { + self.0 + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -814,16 +834,20 @@ impl TcpListener { } #[stable(feature = "net2_mutators", since = "1.9.0")] - #[rustc_deprecated(since = "1.16.0", - reason = "this option can only be set before the socket is bound")] + #[rustc_deprecated( + since = "1.16.0", + reason = "this option can only be set before the socket is bound" + )] #[allow(missing_docs)] pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { self.0.set_only_v6(only_v6) } #[stable(feature = "net2_mutators", since = "1.9.0")] - #[rustc_deprecated(since = "1.16.0", - reason = "this option can only be set before the socket is bound")] + #[rustc_deprecated( + since = "1.16.0", + reason = "this option can only be set before the socket is bound" + )] #[allow(missing_docs)] pub fn only_v6(&self) -> io::Result { self.0.only_v6() @@ -907,7 +931,9 @@ impl<'a> Iterator for Incoming<'a> { } impl AsInner for TcpListener { - fn as_inner(&self) -> &net_imp::TcpListener { &self.0 } + fn as_inner(&self) -> &net_imp::TcpListener { + &self.0 + } } impl FromInner for TcpListener { @@ -917,7 +943,9 @@ impl FromInner for TcpListener { } impl IntoInner for TcpListener { - fn into_inner(self) -> net_imp::TcpListener { self.0 } + fn into_inner(self) -> net_imp::TcpListener { + self.0 + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -930,13 +958,13 @@ impl fmt::Debug for TcpListener { #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))] mod tests { use crate::fmt; - use crate::io::{ErrorKind, IoSlice, IoSliceMut}; use crate::io::prelude::*; - use crate::net::*; + use crate::io::{ErrorKind, IoSlice, IoSliceMut}; use crate::net::test::{next_test_ip4, next_test_ip6}; + use crate::net::*; use crate::sync::mpsc::channel; - use crate::time::{Instant, Duration}; use crate::thread; + use crate::time::{Duration, Instant}; fn each_ip(f: &mut dyn FnMut(SocketAddr)) { f(next_test_ip4()); @@ -949,15 +977,14 @@ mod tests { Ok(t) => t, Err(e) => panic!("received error for `{}`: {}", stringify!($e), e), } - } + }; } #[test] fn bind_error() { match TcpListener::bind("1.1.1.1:9999") { Ok(..) => panic!(), - Err(e) => - assert_eq!(e.kind(), ErrorKind::AddrNotAvailable), + Err(e) => assert_eq!(e.kind(), ErrorKind::AddrNotAvailable), } } @@ -965,11 +992,15 @@ mod tests { fn connect_error() { match TcpStream::connect("0.0.0.0:1") { Ok(..) => panic!(), - Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused || - e.kind() == ErrorKind::InvalidInput || - e.kind() == ErrorKind::AddrInUse || - e.kind() == ErrorKind::AddrNotAvailable, - "bad error: {} {:?}", e, e.kind()), + Err(e) => assert!( + e.kind() == ErrorKind::ConnectionRefused + || e.kind() == ErrorKind::InvalidInput + || e.kind() == ErrorKind::AddrInUse + || e.kind() == ErrorKind::AddrNotAvailable, + "bad error: {} {:?}", + e, + e.kind() + ), } } @@ -979,8 +1010,7 @@ mod tests { let listener = t!(TcpListener::bind(&socket_addr)); let _t = thread::spawn(move || { - let mut stream = t!(TcpStream::connect(&("localhost", - socket_addr.port()))); + let mut stream = t!(TcpStream::connect(&("localhost", socket_addr.port()))); t!(stream.write(&[144])); }); @@ -995,7 +1025,7 @@ mod tests { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let host = match addr { SocketAddr::V4(..) => "127.0.0.1", SocketAddr::V6(..) => "::1", @@ -1017,7 +1047,7 @@ mod tests { let acceptor = t!(TcpListener::bind(&addr)); let (tx, rx) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut stream = t!(TcpStream::connect(&addr)); t!(stream.write(&[99])); tx.send(t!(stream.local_addr())).unwrap(); @@ -1036,7 +1066,7 @@ mod tests { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let _stream = t!(TcpStream::connect(&addr)); // Close }); @@ -1056,7 +1086,7 @@ mod tests { let acceptor = t!(TcpListener::bind(&addr)); let (tx, rx) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { drop(t!(TcpStream::connect(&addr))); tx.send(()).unwrap(); }); @@ -1067,10 +1097,13 @@ mod tests { match stream.write(&buf) { Ok(..) => {} Err(e) => { - assert!(e.kind() == ErrorKind::ConnectionReset || - e.kind() == ErrorKind::BrokenPipe || - e.kind() == ErrorKind::ConnectionAborted, - "unknown error: {}", e); + assert!( + e.kind() == ErrorKind::ConnectionReset + || e.kind() == ErrorKind::BrokenPipe + || e.kind() == ErrorKind::ConnectionAborted, + "unknown error: {}", + e + ); } } }) @@ -1082,7 +1115,7 @@ mod tests { let max = 10; let acceptor = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { for _ in 0..max { let mut stream = t!(TcpStream::connect(&addr)); t!(stream.write(&[99])); @@ -1104,11 +1137,11 @@ mod tests { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let acceptor = acceptor; for (i, stream) in acceptor.incoming().enumerate().take(MAX) { // Start another thread to handle the connection - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut stream = t!(stream); let mut buf = [0]; t!(stream.read(&mut buf)); @@ -1121,9 +1154,11 @@ mod tests { }); fn connect(i: usize, addr: SocketAddr) { - if i == MAX { return } + if i == MAX { + return; + } - let t = thread::spawn(move|| { + let t = thread::spawn(move || { let mut stream = t!(TcpStream::connect(&addr)); // Connect again before writing connect(i + 1, addr); @@ -1139,10 +1174,10 @@ mod tests { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { for stream in acceptor.incoming().take(MAX) { // Start another thread to handle the connection - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut stream = t!(stream); let mut buf = [0]; t!(stream.read(&mut buf)); @@ -1155,9 +1190,11 @@ mod tests { }); fn connect(i: usize, addr: SocketAddr) { - if i == MAX { return } + if i == MAX { + return; + } - let t = thread::spawn(move|| { + let t = thread::spawn(move || { let mut stream = t!(TcpStream::connect(&addr)); connect(i + 1, addr); t!(stream.write(&[99])); @@ -1172,7 +1209,7 @@ mod tests { let listener = t!(TcpListener::bind(&addr)); let so_name = t!(listener.local_addr()); assert_eq!(addr, so_name); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { t!(listener.accept()); }); @@ -1186,7 +1223,7 @@ mod tests { each_ip(&mut |addr| { let (tx, rx) = channel(); let srv = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut cl = t!(srv.accept()).0; cl.write(&[10]).unwrap(); let mut b = [0]; @@ -1215,9 +1252,11 @@ mod tests { let mut a = []; let mut b = [0]; let mut c = [0; 3]; - let len = t!(s2.read_vectored( - &mut [IoSliceMut::new(&mut a), IoSliceMut::new(&mut b), IoSliceMut::new(&mut c)], - )); + let len = t!(s2.read_vectored(&mut [ + IoSliceMut::new(&mut a), + IoSliceMut::new(&mut b), + IoSliceMut::new(&mut c) + ],)); assert!(len > 0); assert_eq!(b, [10]); // some implementations don't support readv, so we may only fill the first buffer @@ -1260,10 +1299,14 @@ mod tests { listener1, listener2 ), Err(e) => { - assert!(e.kind() == ErrorKind::ConnectionRefused || - e.kind() == ErrorKind::Other || - e.kind() == ErrorKind::AddrInUse, - "unknown error: {} {:?}", e, e.kind()); + assert!( + e.kind() == ErrorKind::ConnectionRefused + || e.kind() == ErrorKind::Other + || e.kind() == ErrorKind::AddrInUse, + "unknown error: {} {:?}", + e, + e.kind() + ); } } }) @@ -1274,7 +1317,7 @@ mod tests { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { t!(TcpStream::connect(&addr)); }); @@ -1289,7 +1332,7 @@ mod tests { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut s = t!(TcpStream::connect(&addr)); let mut buf = [0, 0]; assert_eq!(s.read(&mut buf).unwrap(), 1); @@ -1302,7 +1345,7 @@ mod tests { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut s2 = s2; rx1.recv().unwrap(); t!(s2.write(&[1])); @@ -1322,7 +1365,7 @@ mod tests { let (tx1, rx) = channel(); let tx2 = tx1.clone(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut s = t!(TcpStream::connect(&addr)); t!(s.write(&[1])); rx.recv().unwrap(); @@ -1334,7 +1377,7 @@ mod tests { let s2 = t!(s1.try_clone()); let (done, rx) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut s2 = s2; let mut buf = [0, 0]; t!(s2.read(&mut buf)); @@ -1354,7 +1397,7 @@ mod tests { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut s = t!(TcpStream::connect(&addr)); let mut buf = [0, 1]; t!(s.read(&mut buf)); @@ -1365,7 +1408,7 @@ mod tests { let s2 = t!(s1.try_clone()); let (done, rx) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut s2 = s2; t!(s2.write(&[1])); done.send(()).unwrap(); @@ -1382,7 +1425,7 @@ mod tests { fn shutdown_smoke() { each_ip(&mut |addr| { let a = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut c = t!(a.accept()).0; let mut b = [0]; assert_eq!(c.read(&mut b).unwrap(), 0); @@ -1405,7 +1448,7 @@ mod tests { each_ip(&mut |addr| { let a = t!(TcpListener::bind(&addr)); let (tx, rx) = channel::<()>(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let _s = t!(a.accept()); let _ = rx.recv(); }); @@ -1444,7 +1487,7 @@ mod tests { each_ip(&mut |addr| { let a = t!(TcpListener::bind(&addr)); let (tx1, rx) = channel::<()>(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let _s = t!(a.accept()); let _ = rx.recv(); }); @@ -1452,7 +1495,7 @@ mod tests { let s = t!(TcpStream::connect(&addr)); let s2 = t!(s.try_clone()); let (tx, rx) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut s2 = s2; assert_eq!(t!(s2.read(&mut [0])), 0); tx.send(()).unwrap(); @@ -1475,7 +1518,7 @@ mod tests { let (tx, rx) = channel(); let (txdone, rxdone) = channel(); let txdone2 = txdone.clone(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut tcp = t!(TcpStream::connect(&addr)); rx.recv().unwrap(); t!(tcp.write(&[0])); @@ -1486,7 +1529,7 @@ mod tests { let tcp = t!(accept.accept()).0; let tcp2 = t!(tcp.try_clone()); let txdone3 = txdone.clone(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut tcp2 = tcp2; t!(tcp2.read(&mut [0])); txdone3.send(()).unwrap(); @@ -1512,10 +1555,10 @@ mod tests { let a = t!(TcpListener::bind(&addr)); let a2 = t!(a.try_clone()); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let _ = TcpStream::connect(&addr); }); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let _ = TcpStream::connect(&addr); }); @@ -1533,17 +1576,17 @@ mod tests { let (tx, rx) = channel(); let tx2 = tx.clone(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { tx.send(t!(a.accept())).unwrap(); }); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { tx2.send(t!(a2.accept())).unwrap(); }); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let _ = TcpStream::connect(&addr); }); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let _ = TcpStream::connect(&addr); }); @@ -1563,10 +1606,10 @@ mod tests { addr.to_string() } - #[cfg(unix)] - use crate::os::unix::io::AsRawFd; #[cfg(target_env = "sgx")] use crate::os::fortanix_sgx::io::AsRawFd; + #[cfg(unix)] + use crate::os::unix::io::AsRawFd; #[cfg(not(windows))] fn render_inner(addr: &dyn AsRawFd) -> impl fmt::Debug { addr.as_raw_fd() @@ -1576,22 +1619,26 @@ mod tests { addr.as_raw_socket() } - let inner_name = if cfg!(windows) {"socket"} else {"fd"}; + let inner_name = if cfg!(windows) { "socket" } else { "fd" }; let socket_addr = next_test_ip4(); let listener = t!(TcpListener::bind(&socket_addr)); - let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}", - render_socket_addr(&socket_addr), - inner_name, - render_inner(&listener)); + let compare = format!( + "TcpListener {{ addr: {:?}, {}: {:?} }}", + render_socket_addr(&socket_addr), + inner_name, + render_inner(&listener) + ); assert_eq!(format!("{:?}", listener), compare); let stream = t!(TcpStream::connect(&("localhost", socket_addr.port()))); - let compare = format!("TcpStream {{ addr: {:?}, peer: {:?}, {}: {:?} }}", - render_socket_addr(&stream.local_addr().unwrap()), - render_socket_addr(&stream.peer_addr().unwrap()), - inner_name, - render_inner(&stream)); + let compare = format!( + "TcpStream {{ addr: {:?}, peer: {:?}, {}: {:?} }}", + render_socket_addr(&stream.local_addr().unwrap()), + render_socket_addr(&stream.peer_addr().unwrap()), + inner_name, + render_inner(&stream) + ); assert_eq!(format!("{:?}", stream), compare); } @@ -1638,8 +1685,11 @@ mod tests { let mut buf = [0; 10]; let start = Instant::now(); let kind = stream.read_exact(&mut buf).err().expect("expected error").kind(); - assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, - "unexpected_error: {:?}", kind); + assert!( + kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, + "unexpected_error: {:?}", + kind + ); assert!(start.elapsed() > Duration::from_millis(400)); drop(listener); } @@ -1662,8 +1712,11 @@ mod tests { let start = Instant::now(); let kind = stream.read_exact(&mut buf).err().expect("expected error").kind(); - assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, - "unexpected_error: {:?}", kind); + assert!( + kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, + "unexpected_error: {:?}", + kind + ); assert!(start.elapsed() > Duration::from_millis(400)); drop(listener); } @@ -1749,9 +1802,9 @@ mod tests { let (txdone, rxdone) = channel(); let srv = t!(TcpListener::bind(&addr)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut cl = t!(srv.accept()).0; - cl.write(&[1,3,3,7]).unwrap(); + cl.write(&[1, 3, 3, 7]).unwrap(); t!(rxdone.recv()); }); diff --git a/src/libstd/net/test.rs b/src/libstd/net/test.rs index e2991cbdd8822..37937b5ea9541 100644 --- a/src/libstd/net/test.rs +++ b/src/libstd/net/test.rs @@ -1,7 +1,7 @@ #![allow(warnings)] // not used on emscripten use crate::env; -use crate::net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr, ToSocketAddrs}; +use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}; use crate::sync::atomic::{AtomicUsize, Ordering}; static PORT: AtomicUsize = AtomicUsize::new(0); @@ -13,8 +13,7 @@ pub fn next_test_ip4() -> SocketAddr { pub fn next_test_ip6() -> SocketAddr { let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port(); - SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), - port, 0, 0)) + SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), port, 0, 0)) } pub fn sa4(a: Ipv4Addr, p: u16) -> SocketAddr { @@ -41,11 +40,21 @@ fn base_port() -> u16 { } else { env::current_dir().unwrap().into_os_string().into_string().unwrap() }; - let dirs = ["32-opt", "32-nopt", - "musl-64-opt", "cross-opt", - "64-opt", "64-nopt", "64-opt-vg", "64-debug-opt", - "all-opt", "snap3", "dist", "sgx"]; - dirs.iter().enumerate().find(|&(_, dir)| { - cwd.contains(dir) - }).map(|p| p.0).unwrap_or(0) as u16 * 1000 + 19600 + let dirs = [ + "32-opt", + "32-nopt", + "musl-64-opt", + "cross-opt", + "64-opt", + "64-nopt", + "64-opt-vg", + "64-debug-opt", + "all-opt", + "snap3", + "dist", + "sgx", + ]; + dirs.iter().enumerate().find(|&(_, dir)| cwd.contains(dir)).map(|p| p.0).unwrap_or(0) as u16 + * 1000 + + 19600 } diff --git a/src/libstd/net/udp.rs b/src/libstd/net/udp.rs index a9e4457f42374..0096b827ca456 100644 --- a/src/libstd/net/udp.rs +++ b/src/libstd/net/udp.rs @@ -1,6 +1,6 @@ use crate::fmt; use crate::io::{self, Error, ErrorKind}; -use crate::net::{ToSocketAddrs, SocketAddr, Ipv4Addr, Ipv6Addr}; +use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; use crate::sys_common::net as net_imp; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; @@ -171,12 +171,10 @@ impl UdpSocket { /// socket.send_to(&[0; 10], "127.0.0.1:4242").expect("couldn't send data"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn send_to(&self, buf: &[u8], addr: A) - -> io::Result { + pub fn send_to(&self, buf: &[u8], addr: A) -> io::Result { match addr.to_socket_addrs()?.next() { Some(addr) => self.0.send_to(buf, &addr), - None => Err(Error::new(ErrorKind::InvalidInput, - "no addresses to send data to")), + None => Err(Error::new(ErrorKind::InvalidInput, "no addresses to send data to")), } } @@ -817,15 +815,21 @@ impl UdpSocket { } impl AsInner for UdpSocket { - fn as_inner(&self) -> &net_imp::UdpSocket { &self.0 } + fn as_inner(&self) -> &net_imp::UdpSocket { + &self.0 + } } impl FromInner for UdpSocket { - fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { UdpSocket(inner) } + fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { + UdpSocket(inner) + } } impl IntoInner for UdpSocket { - fn into_inner(self) -> net_imp::UdpSocket { self.0 } + fn into_inner(self) -> net_imp::UdpSocket { + self.0 + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -838,12 +842,12 @@ impl fmt::Debug for UdpSocket { #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))] mod tests { use crate::io::ErrorKind; - use crate::net::*; use crate::net::test::{next_test_ip4, next_test_ip6}; + use crate::net::*; use crate::sync::mpsc::channel; use crate::sys_common::AsInner; - use crate::time::{Instant, Duration}; use crate::thread; + use crate::time::{Duration, Instant}; fn each_ip(f: &mut dyn FnMut(SocketAddr, SocketAddr)) { f(next_test_ip4(), next_test_ip4()); @@ -856,16 +860,14 @@ mod tests { Ok(t) => t, Err(e) => panic!("received error for `{}`: {}", stringify!($e), e), } - } + }; } #[test] fn bind_error() { match UdpSocket::bind("1.1.1.1:9999") { Ok(..) => panic!(), - Err(e) => { - assert_eq!(e.kind(), ErrorKind::AddrNotAvailable) - } + Err(e) => assert_eq!(e.kind(), ErrorKind::AddrNotAvailable), } } @@ -875,7 +877,7 @@ mod tests { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let client = t!(UdpSocket::bind(&client_ip)); rx1.recv().unwrap(); t!(client.send_to(&[99], &server_ip)); @@ -917,7 +919,7 @@ mod tests { let sock1 = t!(UdpSocket::bind(&addr1)); let sock2 = t!(UdpSocket::bind(&addr2)); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut buf = [0, 0]; assert_eq!(sock2.recv_from(&mut buf).unwrap(), (1, addr1)); assert_eq!(buf[0], 1); @@ -928,7 +930,7 @@ mod tests { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { rx1.recv().unwrap(); t!(sock3.send_to(&[1], &addr2)); tx2.send(()).unwrap(); @@ -948,7 +950,7 @@ mod tests { let (tx1, rx) = channel(); let tx2 = tx1.clone(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { t!(sock2.send_to(&[1], &addr1)); rx.recv().unwrap(); t!(sock2.send_to(&[2], &addr1)); @@ -958,7 +960,7 @@ mod tests { let sock3 = t!(sock1.try_clone()); let (done, rx) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut buf = [0, 0]; t!(sock3.recv_from(&mut buf)); tx2.send(()).unwrap(); @@ -981,7 +983,7 @@ mod tests { let (tx, rx) = channel(); let (serv_tx, serv_rx) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut buf = [0, 1]; rx.recv().unwrap(); t!(sock2.recv_from(&mut buf)); @@ -992,15 +994,19 @@ mod tests { let (done, rx) = channel(); let tx2 = tx.clone(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { match sock3.send_to(&[1], &addr2) { - Ok(..) => { let _ = tx2.send(()); } + Ok(..) => { + let _ = tx2.send(()); + } Err(..) => {} } done.send(()).unwrap(); }); match sock1.send_to(&[2], &addr2) { - Ok(..) => { let _ = tx.send(()); } + Ok(..) => { + let _ = tx.send(()); + } Err(..) => {} } drop(tx); @@ -1012,13 +1018,13 @@ mod tests { #[test] fn debug() { - let name = if cfg!(windows) {"socket"} else {"fd"}; + let name = if cfg!(windows) { "socket" } else { "fd" }; let socket_addr = next_test_ip4(); let udpsock = t!(UdpSocket::bind(&socket_addr)); let udpsock_inner = udpsock.0.socket().as_inner(); - let compare = format!("UdpSocket {{ addr: {:?}, {}: {:?} }}", - socket_addr, name, udpsock_inner); + let compare = + format!("UdpSocket {{ addr: {:?}, {}: {:?} }}", socket_addr, name, udpsock_inner); assert_eq!(format!("{:?}", udpsock), compare); } @@ -1063,8 +1069,11 @@ mod tests { loop { let kind = stream.recv_from(&mut buf).err().expect("expected error").kind(); if kind != ErrorKind::Interrupted { - assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, - "unexpected_error: {:?}", kind); + assert!( + kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, + "unexpected_error: {:?}", + kind + ); break; } } @@ -1088,8 +1097,11 @@ mod tests { loop { let kind = stream.recv_from(&mut buf).err().expect("expected error").kind(); if kind != ErrorKind::Interrupted { - assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, - "unexpected_error: {:?}", kind); + assert!( + kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, + "unexpected_error: {:?}", + kind + ); break; } } diff --git a/src/libstd/num.rs b/src/libstd/num.rs index 2a2ca0b5237ee..de8acf8d9d472 100644 --- a/src/libstd/num.rs +++ b/src/libstd/num.rs @@ -6,57 +6,65 @@ #![stable(feature = "rust1", since = "1.0.0")] #![allow(missing_docs)] -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::num::{FpCategory, ParseIntError, ParseFloatError, TryFromIntError}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::num::Wrapping; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::num::{FpCategory, ParseFloatError, ParseIntError, TryFromIntError}; -#[stable(feature = "nonzero", since = "1.28.0")] -pub use core::num::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize}; #[stable(feature = "signed_nonzero", since = "1.34.0")] -pub use core::num::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize}; - -#[unstable(feature = "int_error_matching", - reason = "it can be useful to match errors when making error messages \ - for integer parsing", - issue = "22639")] +pub use core::num::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize}; +#[stable(feature = "nonzero", since = "1.28.0")] +pub use core::num::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize}; + +#[unstable( + feature = "int_error_matching", + reason = "it can be useful to match errors when making error messages \ + for integer parsing", + issue = "22639" +)] pub use core::num::IntErrorKind; -#[cfg(test)] use crate::fmt; -#[cfg(test)] use crate::ops::{Add, Sub, Mul, Div, Rem}; +#[cfg(test)] +use crate::fmt; +#[cfg(test)] +use crate::ops::{Add, Div, Mul, Rem, Sub}; /// Helper function for testing numeric operations #[cfg(test)] -pub fn test_num(ten: T, two: T) where +pub fn test_num(ten: T, two: T) +where T: PartialEq - + Add + Sub - + Mul + Div - + Rem + fmt::Debug - + Copy + + Add + + Sub + + Mul + + Div + + Rem + + fmt::Debug + + Copy, { - assert_eq!(ten.add(two), ten + two); - assert_eq!(ten.sub(two), ten - two); - assert_eq!(ten.mul(two), ten * two); - assert_eq!(ten.div(two), ten / two); - assert_eq!(ten.rem(two), ten % two); + assert_eq!(ten.add(two), ten + two); + assert_eq!(ten.sub(two), ten - two); + assert_eq!(ten.mul(two), ten * two); + assert_eq!(ten.div(two), ten / two); + assert_eq!(ten.rem(two), ten % two); } #[cfg(test)] mod tests { - use crate::u8; + use crate::ops::Mul; use crate::u16; use crate::u32; use crate::u64; + use crate::u8; use crate::usize; - use crate::ops::Mul; #[test] fn test_saturating_add_uint() { use crate::usize::MAX; assert_eq!(3_usize.saturating_add(5_usize), 8_usize); - assert_eq!(3_usize.saturating_add(MAX-1), MAX); + assert_eq!(3_usize.saturating_add(MAX - 1), MAX); assert_eq!(MAX.saturating_add(MAX), MAX); - assert_eq!((MAX-2).saturating_add(1), MAX-1); + assert_eq!((MAX - 2).saturating_add(1), MAX - 1); } #[test] @@ -65,16 +73,16 @@ mod tests { assert_eq!(5_usize.saturating_sub(3_usize), 2_usize); assert_eq!(3_usize.saturating_sub(5_usize), 0_usize); assert_eq!(0_usize.saturating_sub(1_usize), 0_usize); - assert_eq!((MAX-1).saturating_sub(MAX), 0); + assert_eq!((MAX - 1).saturating_sub(MAX), 0); } #[test] fn test_saturating_add_int() { - use crate::isize::{MIN,MAX}; + use crate::isize::{MAX, MIN}; assert_eq!(3i32.saturating_add(5), 8); - assert_eq!(3isize.saturating_add(MAX-1), MAX); + assert_eq!(3isize.saturating_add(MAX - 1), MAX); assert_eq!(MAX.saturating_add(MAX), MAX); - assert_eq!((MAX-2).saturating_add(1), MAX-1); + assert_eq!((MAX - 2).saturating_add(1), MAX - 1); assert_eq!(3i32.saturating_add(-5), -2); assert_eq!(MIN.saturating_add(-1), MIN); assert_eq!((-2isize).saturating_add(-MAX), MIN); @@ -82,14 +90,14 @@ mod tests { #[test] fn test_saturating_sub_int() { - use crate::isize::{MIN,MAX}; + use crate::isize::{MAX, MIN}; assert_eq!(3i32.saturating_sub(5), -2); assert_eq!(MIN.saturating_sub(1), MIN); assert_eq!((-2isize).saturating_sub(MAX), MIN); assert_eq!(3i32.saturating_sub(-5), 8); - assert_eq!(3isize.saturating_sub(-(MAX-1)), MAX); + assert_eq!(3isize.saturating_sub(-(MAX - 1)), MAX); assert_eq!(MAX.saturating_sub(-MAX), MAX); - assert_eq!((MAX-2).saturating_sub(-1), MAX-1); + assert_eq!((MAX - 2).saturating_sub(-1), MAX - 1); } #[test] @@ -128,7 +136,7 @@ mod tests { } macro_rules! test_is_power_of_two { - ($test_name:ident, $T:ident) => ( + ($test_name:ident, $T:ident) => { fn $test_name() { #![test] assert_eq!((0 as $T).is_power_of_two(), false); @@ -139,27 +147,29 @@ mod tests { assert_eq!((5 as $T).is_power_of_two(), false); assert_eq!(($T::MAX / 2 + 1).is_power_of_two(), true); } - ) + }; } - test_is_power_of_two!{ test_is_power_of_two_u8, u8 } - test_is_power_of_two!{ test_is_power_of_two_u16, u16 } - test_is_power_of_two!{ test_is_power_of_two_u32, u32 } - test_is_power_of_two!{ test_is_power_of_two_u64, u64 } - test_is_power_of_two!{ test_is_power_of_two_uint, usize } + test_is_power_of_two! { test_is_power_of_two_u8, u8 } + test_is_power_of_two! { test_is_power_of_two_u16, u16 } + test_is_power_of_two! { test_is_power_of_two_u32, u32 } + test_is_power_of_two! { test_is_power_of_two_u64, u64 } + test_is_power_of_two! { test_is_power_of_two_uint, usize } macro_rules! test_next_power_of_two { - ($test_name:ident, $T:ident) => ( + ($test_name:ident, $T:ident) => { fn $test_name() { #![test] assert_eq!((0 as $T).next_power_of_two(), 1); let mut next_power = 1; for i in 1 as $T..40 { - assert_eq!(i.next_power_of_two(), next_power); - if i == next_power { next_power *= 2 } + assert_eq!(i.next_power_of_two(), next_power); + if i == next_power { + next_power *= 2 + } } } - ) + }; } test_next_power_of_two! { test_next_power_of_two_u8, u8 } @@ -169,23 +179,25 @@ mod tests { test_next_power_of_two! { test_next_power_of_two_uint, usize } macro_rules! test_checked_next_power_of_two { - ($test_name:ident, $T:ident) => ( + ($test_name:ident, $T:ident) => { fn $test_name() { #![test] assert_eq!((0 as $T).checked_next_power_of_two(), Some(1)); let smax = $T::MAX >> 1; - assert_eq!(smax.checked_next_power_of_two(), Some(smax+1)); + assert_eq!(smax.checked_next_power_of_two(), Some(smax + 1)); assert_eq!((smax + 1).checked_next_power_of_two(), Some(smax + 1)); assert_eq!((smax + 2).checked_next_power_of_two(), None); assert_eq!(($T::MAX - 1).checked_next_power_of_two(), None); assert_eq!($T::MAX.checked_next_power_of_two(), None); let mut next_power = 1; for i in 1 as $T..40 { - assert_eq!(i.checked_next_power_of_two(), Some(next_power)); - if i == next_power { next_power *= 2 } + assert_eq!(i.checked_next_power_of_two(), Some(next_power)); + if i == next_power { + next_power *= 2 + } } } - ) + }; } test_checked_next_power_of_two! { test_checked_next_power_of_two_u8, u8 } @@ -196,7 +208,7 @@ mod tests { #[test] fn test_pow() { - fn naive_pow + Copy>(one: T, base: T, exp: usize) -> T { + fn naive_pow + Copy>(one: T, base: T, exp: usize) -> T { (0..exp).fold(one, |acc, _| acc * base) } macro_rules! assert_pow { @@ -204,7 +216,7 @@ mod tests { let result = $num.pow($exp); assert_eq!(result, $expected); assert_eq!(result, naive_pow(1, $num, $exp)); - }} + }}; } assert_pow!((3u32, 0 ) => 1); assert_pow!((5u32, 1 ) => 5); @@ -280,7 +292,6 @@ mod tests { } } - #[cfg(test)] mod bench { use test::Bencher; @@ -288,6 +299,8 @@ mod bench { #[bench] fn bench_pow_function(b: &mut Bencher) { let v = (0..1024).collect::>(); - b.iter(|| {v.iter().fold(0u32, |old, new| old.pow(*new as u32));}); + b.iter(|| { + v.iter().fold(0u32, |old, new| old.pow(*new as u32)); + }); } } diff --git a/src/libstd/os/android/fs.rs b/src/libstd/os/android/fs.rs index 90fdee567ae2c..9356e607c908e 100644 --- a/src/libstd/os/android/fs.rs +++ b/src/libstd/os/android/fs.rs @@ -18,9 +18,11 @@ pub trait MetadataExt { /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the /// cross-Unix abstractions contained within the raw stat. #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -62,10 +64,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/android/mod.rs b/src/libstd/os/android/mod.rs index ad1cd85095d69..dbb0127f369fd 100644 --- a/src/libstd/os/android/mod.rs +++ b/src/libstd/os/android/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/android/raw.rs b/src/libstd/os/android/raw.rs index 946a77cbfd325..2b8ade8a82e65 100644 --- a/src/libstd/os/android/raw.rs +++ b/src/libstd/os/android/raw.rs @@ -1,11 +1,13 @@ //! Android-specific raw type definitions #![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)] use crate::os::raw::c_long; @@ -15,12 +17,12 @@ pub type pthread_t = c_long; #[doc(inline)] #[stable(feature = "raw_ext", since = "1.1.0")] -pub use self::arch::{dev_t, mode_t, blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t}; +pub use self::arch::{blkcnt_t, blksize_t, dev_t, ino_t, mode_t, nlink_t, off_t, stat, time_t}; #[cfg(any(target_arch = "arm", target_arch = "x86"))] mod arch { - use crate::os::raw::{c_uint, c_uchar, c_ulonglong, c_longlong, c_ulong}; - use crate::os::unix::raw::{uid_t, gid_t}; + use crate::os::raw::{c_longlong, c_uchar, c_uint, c_ulong, c_ulonglong}; + use crate::os::unix::raw::{gid_t, uid_t}; #[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; @@ -83,14 +85,12 @@ mod arch { #[stable(feature = "raw_ext", since = "1.1.0")] pub st_ino: c_ulonglong, } - } - #[cfg(target_arch = "aarch64")] mod arch { use crate::os::raw::{c_uchar, c_ulong}; - use crate::os::unix::raw::{uid_t, gid_t}; + use crate::os::unix::raw::{gid_t, uid_t}; #[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; @@ -157,8 +157,8 @@ mod arch { #[cfg(target_arch = "x86_64")] mod arch { - use crate::os::raw::{c_uint, c_long, c_ulong}; - use crate::os::unix::raw::{uid_t, gid_t}; + use crate::os::raw::{c_long, c_uint, c_ulong}; + use crate::os::unix::raw::{gid_t, uid_t}; #[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; diff --git a/src/libstd/os/dragonfly/fs.rs b/src/libstd/os/dragonfly/fs.rs index ba3d8d7867def..8552abb1cb977 100644 --- a/src/libstd/os/dragonfly/fs.rs +++ b/src/libstd/os/dragonfly/fs.rs @@ -18,9 +18,11 @@ pub trait MetadataExt { /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the /// cross-Unix abstractions contained within the raw stat. #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -68,10 +70,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/dragonfly/mod.rs b/src/libstd/os/dragonfly/mod.rs index c8df03e742ff2..350b5fca7ea66 100644 --- a/src/libstd/os/dragonfly/mod.rs +++ b/src/libstd/os/dragonfly/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/dragonfly/raw.rs b/src/libstd/os/dragonfly/raw.rs index 46ef5a1e7cf7b..2a2d29043727e 100644 --- a/src/libstd/os/dragonfly/raw.rs +++ b/src/libstd/os/dragonfly/raw.rs @@ -1,24 +1,35 @@ //! Dragonfly-specific raw type definitions #![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)] use crate::os::raw::c_long; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type fflags_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blkcnt_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blksize_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type fflags_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type ino_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type nlink_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type off_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type time_t = i64; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = usize; diff --git a/src/libstd/os/emscripten/fs.rs b/src/libstd/os/emscripten/fs.rs index aa6aa38283def..f5e30dc8eefc9 100644 --- a/src/libstd/os/emscripten/fs.rs +++ b/src/libstd/os/emscripten/fs.rs @@ -18,9 +18,11 @@ pub trait MetadataExt { /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the /// cross-Unix abstractions contained within the raw stat. #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -62,10 +64,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat64 - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat64 as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/emscripten/mod.rs b/src/libstd/os/emscripten/mod.rs index 3111325021a80..d35307162cc7e 100644 --- a/src/libstd/os/emscripten/mod.rs +++ b/src/libstd/os/emscripten/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/emscripten/raw.rs b/src/libstd/os/emscripten/raw.rs index e551348797942..dda7c82525deb 100644 --- a/src/libstd/os/emscripten/raw.rs +++ b/src/libstd/os/emscripten/raw.rs @@ -3,28 +3,38 @@ //! except using the musl-specific stat64 structure in liblibc. #![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)] use crate::os::raw::{c_long, c_short, c_uint, c_ulong}; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = c_ulong; #[doc(inline)] -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = c_long; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blkcnt_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blksize_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type ino_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type nlink_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type off_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type time_t = c_long; #[repr(C)] #[derive(Clone)] diff --git a/src/libstd/os/fortanix_sgx/mod.rs b/src/libstd/os/fortanix_sgx/mod.rs index 4e30b1edd15e8..69923268e570e 100644 --- a/src/libstd/os/fortanix_sgx/mod.rs +++ b/src/libstd/os/fortanix_sgx/mod.rs @@ -21,19 +21,20 @@ pub mod usercalls { /// Lowest-level interfaces to usercalls and usercall ABI type definitions. pub mod raw { + pub use crate::sys::abi::usercalls::raw::{ + accept_stream, alloc, async_queues, bind_stream, close, connect_stream, exit, flush, + free, insecure_time, launch_thread, read, read_alloc, send, wait, write, + }; pub use crate::sys::abi::usercalls::raw::{do_usercall, Usercalls as UsercallNrs}; - pub use crate::sys::abi::usercalls::raw::{accept_stream, alloc, async_queues, bind_stream, - close, connect_stream, exit, flush, free, insecure_time, - launch_thread, read, read_alloc, send, wait, write}; // fortanix-sgx-abi re-exports - pub use crate::sys::abi::usercalls::raw::{ByteBuffer, FifoDescriptor, Return, Usercall}; pub use crate::sys::abi::usercalls::raw::Error; - pub use crate::sys::abi::usercalls::raw::{EV_RETURNQ_NOT_EMPTY, EV_UNPARK, - EV_USERCALLQ_NOT_FULL, FD_STDERR, FD_STDIN, FD_STDOUT, - RESULT_SUCCESS, USERCALL_USER_DEFINED, WAIT_INDEFINITE, - WAIT_NO}; + pub use crate::sys::abi::usercalls::raw::{ByteBuffer, FifoDescriptor, Return, Usercall}; pub use crate::sys::abi::usercalls::raw::{Fd, Result, Tcs}; + pub use crate::sys::abi::usercalls::raw::{ + EV_RETURNQ_NOT_EMPTY, EV_UNPARK, EV_USERCALLQ_NOT_FULL, FD_STDERR, FD_STDIN, FD_STDOUT, + RESULT_SUCCESS, USERCALL_USER_DEFINED, WAIT_INDEFINITE, WAIT_NO, + }; } } @@ -42,7 +43,7 @@ pub mod mem { pub use crate::sys::abi::mem::*; } -pub use crate::sys::ext::{io, arch, ffi}; +pub use crate::sys::ext::{arch, ffi, io}; /// Functions for querying thread-related information. pub mod thread { diff --git a/src/libstd/os/freebsd/fs.rs b/src/libstd/os/freebsd/fs.rs index cfe8d575c673e..6798e0d8f44fa 100644 --- a/src/libstd/os/freebsd/fs.rs +++ b/src/libstd/os/freebsd/fs.rs @@ -18,9 +18,11 @@ pub trait MetadataExt { /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the /// cross-Unix abstractions contained within the raw stat. #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -72,10 +74,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/freebsd/mod.rs b/src/libstd/os/freebsd/mod.rs index 1d9ee5468fe9e..c072fae557fe0 100644 --- a/src/libstd/os/freebsd/mod.rs +++ b/src/libstd/os/freebsd/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/freebsd/raw.rs b/src/libstd/os/freebsd/raw.rs index 0c58154ae607d..aeae08fc6aae0 100644 --- a/src/libstd/os/freebsd/raw.rs +++ b/src/libstd/os/freebsd/raw.rs @@ -1,24 +1,35 @@ //! FreeBSD-specific raw type definitions #![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)] use crate::os::raw::c_long; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type fflags_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blkcnt_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blksize_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type fflags_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type ino_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type nlink_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type off_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type time_t = i64; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = usize; diff --git a/src/libstd/os/fuchsia/mod.rs b/src/libstd/os/fuchsia/mod.rs index 740eb011fb188..cd1b8233eb3ec 100644 --- a/src/libstd/os/fuchsia/mod.rs +++ b/src/libstd/os/fuchsia/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/fuchsia/raw.rs b/src/libstd/os/fuchsia/raw.rs index 7e44a79b371ce..f94659cd5baab 100644 --- a/src/libstd/os/fuchsia/raw.rs +++ b/src/libstd/os/fuchsia/raw.rs @@ -1,38 +1,50 @@ //! Fuchsia-specific raw type definitions #![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)] use crate::os::raw::c_ulong; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = c_ulong; #[doc(inline)] #[stable(feature = "raw_ext", since = "1.1.0")] -pub use self::arch::{off_t, ino_t, nlink_t, blksize_t, blkcnt_t, stat, time_t}; +pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t}; -#[cfg(any(target_arch = "x86", - target_arch = "le32", - target_arch = "powerpc", - target_arch = "arm"))] +#[cfg(any( + target_arch = "x86", + target_arch = "le32", + target_arch = "powerpc", + target_arch = "arm" +))] mod arch { use crate::os::raw::{c_long, c_short, c_uint}; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blksize_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type nlink_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type time_t = i64; #[repr(C)] #[derive(Clone)] @@ -84,20 +96,29 @@ mod arch { use crate::os::raw::{c_long, c_ulong}; #[cfg(target_env = "musl")] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = i64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = i64; #[cfg(not(target_env = "musl"))] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blksize_t = u64; #[cfg(target_env = "musl")] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = u64; #[cfg(not(target_env = "musl"))] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type nlink_t = u64; #[cfg(target_env = "musl")] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = u64; #[cfg(not(target_env = "musl"))] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type time_t = i64; #[repr(C)] #[derive(Clone)] @@ -146,19 +167,25 @@ mod arch { #[cfg(target_arch = "mips64")] mod arch { - pub use libc::{off_t, ino_t, nlink_t, blksize_t, blkcnt_t, stat, time_t}; + pub use libc::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t}; } #[cfg(target_arch = "aarch64")] mod arch { - use crate::os::raw::{c_long, c_int}; + use crate::os::raw::{c_int, c_long}; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blksize_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type nlink_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type time_t = i64; #[repr(C)] #[derive(Clone)] @@ -207,14 +234,20 @@ mod arch { #[cfg(target_arch = "x86_64")] mod arch { - use crate::os::raw::{c_long, c_int}; + use crate::os::raw::{c_int, c_long}; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blksize_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type nlink_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type time_t = i64; #[repr(C)] #[derive(Clone)] diff --git a/src/libstd/os/haiku/fs.rs b/src/libstd/os/haiku/fs.rs index 4097f8c26a62f..13a4a92ae90e4 100644 --- a/src/libstd/os/haiku/fs.rs +++ b/src/libstd/os/haiku/fs.rs @@ -18,9 +18,11 @@ pub trait MetadataExt { /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the /// cross-Unix abstractions contained within the raw stat. #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -66,10 +68,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/haiku/mod.rs b/src/libstd/os/haiku/mod.rs index c6a43d9342d04..73f500cadaa30 100644 --- a/src/libstd/os/haiku/mod.rs +++ b/src/libstd/os/haiku/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/haiku/raw.rs b/src/libstd/os/haiku/raw.rs index d86f4f3ba57cb..0d7e70b6b351d 100644 --- a/src/libstd/os/haiku/raw.rs +++ b/src/libstd/os/haiku/raw.rs @@ -1,23 +1,31 @@ //! Haiku-specific raw type definitions #![stable(feature = "raw_ext", since = "1.1.0")] - #![allow(deprecated)] -use crate::os::raw::{c_long}; -use crate::os::unix::raw::{uid_t, gid_t}; +use crate::os::raw::c_long; +use crate::os::unix::raw::{gid_t, uid_t}; // Use the direct definition of usize, instead of uintptr_t like in libc -#[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = usize; +#[stable(feature = "pthread_t", since = "1.8.0")] +pub type pthread_t = usize; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = i64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = i32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = i32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = i64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = i32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = i64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blkcnt_t = i64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blksize_t = i32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = i32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type ino_t = i64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type nlink_t = i32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type off_t = i64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type time_t = i32; #[repr(C)] #[derive(Clone)] diff --git a/src/libstd/os/ios/fs.rs b/src/libstd/os/ios/fs.rs index 9bdfa8e690b09..08d3e4bcedfe2 100644 --- a/src/libstd/os/ios/fs.rs +++ b/src/libstd/os/ios/fs.rs @@ -18,9 +18,11 @@ pub trait MetadataExt { /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the /// cross-Unix abstractions contained within the raw stat. #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -72,10 +74,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/ios/mod.rs b/src/libstd/os/ios/mod.rs index 098473c0dc96a..fdefa1f6b21c4 100644 --- a/src/libstd/os/ios/mod.rs +++ b/src/libstd/os/ios/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/ios/raw.rs b/src/libstd/os/ios/raw.rs index fa38bca09e26a..97b0a96b0f1c0 100644 --- a/src/libstd/os/ios/raw.rs +++ b/src/libstd/os/ios/raw.rs @@ -1,23 +1,33 @@ //! iOS-specific raw type definitions #![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)] use crate::os::raw::c_long; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blkcnt_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blksize_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type ino_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type nlink_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type off_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type time_t = i64; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = usize; diff --git a/src/libstd/os/linux/fs.rs b/src/libstd/os/linux/fs.rs index 78321ac3185df..dd71201b50b91 100644 --- a/src/libstd/os/linux/fs.rs +++ b/src/libstd/os/linux/fs.rs @@ -34,10 +34,7 @@ pub trait MetadataExt { /// } /// ``` #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated( - since = "1.8.0", - reason = "other methods of this trait are now prefered" - )] + #[rustc_deprecated(since = "1.8.0", reason = "other methods of this trait are now prefered")] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -328,10 +325,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat64 - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat64 as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/linux/mod.rs b/src/libstd/os/linux/mod.rs index 3111325021a80..d35307162cc7e 100644 --- a/src/libstd/os/linux/mod.rs +++ b/src/libstd/os/linux/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/linux/raw.rs b/src/libstd/os/linux/raw.rs index 21e1cf8a22b4b..d9b2236047bdf 100644 --- a/src/libstd/os/linux/raw.rs +++ b/src/libstd/os/linux/raw.rs @@ -1,41 +1,53 @@ //! Linux-specific raw type definitions #![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)] #![allow(missing_debug_implementations)] use crate::os::raw::c_ulong; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = c_ulong; #[doc(inline)] #[stable(feature = "raw_ext", since = "1.1.0")] -pub use self::arch::{off_t, ino_t, nlink_t, blksize_t, blkcnt_t, stat, time_t}; +pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t}; -#[cfg(any(target_arch = "x86", - target_arch = "le32", - target_arch = "powerpc", - target_arch = "arm", - target_arch = "asmjs", - target_arch = "wasm32"))] +#[cfg(any( + target_arch = "x86", + target_arch = "le32", + target_arch = "powerpc", + target_arch = "arm", + target_arch = "asmjs", + target_arch = "wasm32" +))] mod arch { use crate::os::raw::{c_long, c_short, c_uint}; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blksize_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type nlink_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type time_t = i64; #[repr(C)] #[derive(Clone)] @@ -87,20 +99,29 @@ mod arch { use crate::os::raw::{c_long, c_ulong}; #[cfg(target_env = "musl")] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = i64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = i64; #[cfg(not(target_env = "musl"))] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blksize_t = u64; #[cfg(target_env = "musl")] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = u64; #[cfg(not(target_env = "musl"))] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type nlink_t = u64; #[cfg(target_env = "musl")] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = u64; #[cfg(not(target_env = "musl"))] - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type time_t = i64; #[repr(C)] #[derive(Clone)] @@ -149,14 +170,20 @@ mod arch { #[cfg(target_arch = "hexagon")] mod arch { - use crate::os::raw::{c_long, c_int, c_longlong, culonglong}; + use crate::os::raw::{c_int, c_long, c_longlong, culonglong}; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = c_longlong; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = c_long; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = c_ulonglong; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = c_uint; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = c_longlong; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = c_long; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = c_longlong; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blksize_t = c_long; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = c_ulonglong; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type nlink_t = c_uint; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = c_longlong; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type time_t = c_long; #[repr(C)] #[derive(Clone)] @@ -199,27 +226,31 @@ mod arch { #[stable(feature = "raw_ext", since = "1.1.0")] pub st_ctime_nsec: ::c_long, #[stable(feature = "raw_ext", since = "1.1.0")] - pub __pad3: [::c_int;2], + pub __pad3: [::c_int; 2], } } -#[cfg(any(target_arch = "mips64", - target_arch = "s390x", - target_arch = "sparc64"))] +#[cfg(any(target_arch = "mips64", target_arch = "s390x", target_arch = "sparc64"))] mod arch { - pub use libc::{off_t, ino_t, nlink_t, blksize_t, blkcnt_t, stat, time_t}; + pub use libc::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t}; } #[cfg(target_arch = "aarch64")] mod arch { - use crate::os::raw::{c_long, c_int}; + use crate::os::raw::{c_int, c_long}; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blksize_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type nlink_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type time_t = i64; #[repr(C)] #[derive(Clone)] @@ -268,14 +299,20 @@ mod arch { #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64"))] mod arch { - use crate::os::raw::{c_long, c_int}; + use crate::os::raw::{c_int, c_long}; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; - #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blkcnt_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type blksize_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type ino_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type nlink_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type off_t = u64; + #[stable(feature = "raw_ext", since = "1.1.0")] + pub type time_t = i64; #[repr(C)] #[derive(Clone)] diff --git a/src/libstd/os/macos/fs.rs b/src/libstd/os/macos/fs.rs index bf951ee18c9f9..ad313a1240dfc 100644 --- a/src/libstd/os/macos/fs.rs +++ b/src/libstd/os/macos/fs.rs @@ -18,9 +18,11 @@ pub trait MetadataExt { /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the /// cross-Unix abstractions contained within the raw stat. #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -74,10 +76,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/macos/mod.rs b/src/libstd/os/macos/mod.rs index ce48d6e1cc296..791d703b142cf 100644 --- a/src/libstd/os/macos/mod.rs +++ b/src/libstd/os/macos/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/macos/raw.rs b/src/libstd/os/macos/raw.rs index 5685642c07ff8..708261d86bddb 100644 --- a/src/libstd/os/macos/raw.rs +++ b/src/libstd/os/macos/raw.rs @@ -1,23 +1,33 @@ //! macOS-specific raw type definitions #![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)] use crate::os::raw::c_long; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blkcnt_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blksize_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type ino_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type nlink_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type off_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type time_t = i64; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = usize; diff --git a/src/libstd/os/mod.rs b/src/libstd/os/mod.rs index a8d2b0cb397ab..91e37ed833a4f 100644 --- a/src/libstd/os/mod.rs +++ b/src/libstd/os/mod.rs @@ -38,20 +38,35 @@ cfg_if::cfg_if! { } } -#[cfg(target_os = "android")] pub mod android; -#[cfg(target_os = "dragonfly")] pub mod dragonfly; -#[cfg(target_os = "freebsd")] pub mod freebsd; -#[cfg(target_os = "haiku")] pub mod haiku; -#[cfg(target_os = "ios")] pub mod ios; -#[cfg(target_os = "macos")] pub mod macos; -#[cfg(target_os = "netbsd")] pub mod netbsd; -#[cfg(target_os = "openbsd")] pub mod openbsd; -#[cfg(target_os = "solaris")] pub mod solaris; -#[cfg(target_os = "emscripten")] pub mod emscripten; -#[cfg(target_os = "fuchsia")] pub mod fuchsia; -#[cfg(target_os = "redox")] pub mod redox; -#[cfg(target_os = "wasi")] pub mod wasi; -#[cfg(target_os = "vxworks")] pub mod vxworks; -#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))] pub mod fortanix_sgx; +#[cfg(target_os = "android")] +pub mod android; +#[cfg(target_os = "dragonfly")] +pub mod dragonfly; +#[cfg(target_os = "emscripten")] +pub mod emscripten; +#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))] +pub mod fortanix_sgx; +#[cfg(target_os = "freebsd")] +pub mod freebsd; +#[cfg(target_os = "fuchsia")] +pub mod fuchsia; +#[cfg(target_os = "haiku")] +pub mod haiku; +#[cfg(target_os = "ios")] +pub mod ios; +#[cfg(target_os = "macos")] +pub mod macos; +#[cfg(target_os = "netbsd")] +pub mod netbsd; +#[cfg(target_os = "openbsd")] +pub mod openbsd; +#[cfg(target_os = "redox")] +pub mod redox; +#[cfg(target_os = "solaris")] +pub mod solaris; +#[cfg(target_os = "vxworks")] +pub mod vxworks; +#[cfg(target_os = "wasi")] +pub mod wasi; pub mod raw; diff --git a/src/libstd/os/netbsd/fs.rs b/src/libstd/os/netbsd/fs.rs index dedfc6390ce20..90980fdce8028 100644 --- a/src/libstd/os/netbsd/fs.rs +++ b/src/libstd/os/netbsd/fs.rs @@ -18,9 +18,11 @@ pub trait MetadataExt { /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the /// cross-Unix abstractions contained within the raw stat. #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -70,10 +72,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/netbsd/mod.rs b/src/libstd/os/netbsd/mod.rs index 3746363979999..497a51a1df6fd 100644 --- a/src/libstd/os/netbsd/mod.rs +++ b/src/libstd/os/netbsd/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/netbsd/raw.rs b/src/libstd/os/netbsd/raw.rs index 1d5d5c6891e3f..475fcdcc4aaab 100644 --- a/src/libstd/os/netbsd/raw.rs +++ b/src/libstd/os/netbsd/raw.rs @@ -1,25 +1,36 @@ //! NetBSD-specific raw type definitions #![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)] use crate::os::raw::c_long; -use crate::os::unix::raw::{uid_t, gid_t}; +use crate::os::unix::raw::{gid_t, uid_t}; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type fflags_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blkcnt_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blksize_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type fflags_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type ino_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type nlink_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type off_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type time_t = i64; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = usize; diff --git a/src/libstd/os/openbsd/fs.rs b/src/libstd/os/openbsd/fs.rs index 1c019159be026..47da00ae26e72 100644 --- a/src/libstd/os/openbsd/fs.rs +++ b/src/libstd/os/openbsd/fs.rs @@ -18,9 +18,11 @@ pub trait MetadataExt { /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the /// cross-Unix abstractions contained within the raw stat. #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -70,10 +72,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/openbsd/mod.rs b/src/libstd/os/openbsd/mod.rs index 3746363979999..497a51a1df6fd 100644 --- a/src/libstd/os/openbsd/mod.rs +++ b/src/libstd/os/openbsd/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/openbsd/raw.rs b/src/libstd/os/openbsd/raw.rs index 094168453d792..8e34e5483b7a0 100644 --- a/src/libstd/os/openbsd/raw.rs +++ b/src/libstd/os/openbsd/raw.rs @@ -1,24 +1,35 @@ //! OpenBSD-specific raw type definitions #![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)] use crate::os::raw::c_long; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type fflags_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blkcnt_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blksize_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type fflags_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type ino_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type nlink_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type off_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type time_t = i64; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = usize; diff --git a/src/libstd/os/raw/mod.rs b/src/libstd/os/raw/mod.rs index 611a1709c8d91..e09012007f2d4 100644 --- a/src/libstd/os/raw/mod.rs +++ b/src/libstd/os/raw/mod.rs @@ -9,85 +9,135 @@ #![stable(feature = "raw_os", since = "1.1.0")] #[doc(include = "char.md")] -#[cfg(any(all(target_os = "linux", any(target_arch = "aarch64", - target_arch = "arm", - target_arch = "hexagon", - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "s390x")), - all(target_os = "android", any(target_arch = "aarch64", - target_arch = "arm")), - all(target_os = "l4re", target_arch = "x86_64"), - all(target_os = "freebsd", any(target_arch = "aarch64", - target_arch = "arm", - target_arch = "powerpc", - target_arch = "powerpc64")), - all(target_os = "netbsd", any(target_arch = "aarch64", - target_arch = "arm", - target_arch = "powerpc")), - all(target_os = "openbsd", target_arch = "aarch64"), - all(target_os = "vxworks", any(target_arch = "aarch64", - target_arch = "arm", - target_arch = "powerpc64", - target_arch = "powerpc")), - all(target_os = "fuchsia", target_arch = "aarch64")))] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_char = u8; +#[cfg(any( + all( + target_os = "linux", + any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "hexagon", + target_arch = "powerpc", + target_arch = "powerpc64", + target_arch = "s390x" + ) + ), + all(target_os = "android", any(target_arch = "aarch64", target_arch = "arm")), + all(target_os = "l4re", target_arch = "x86_64"), + all( + target_os = "freebsd", + any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "powerpc", + target_arch = "powerpc64" + ) + ), + all( + target_os = "netbsd", + any(target_arch = "aarch64", target_arch = "arm", target_arch = "powerpc") + ), + all(target_os = "openbsd", target_arch = "aarch64"), + all( + target_os = "vxworks", + any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "powerpc64", + target_arch = "powerpc" + ) + ), + all(target_os = "fuchsia", target_arch = "aarch64") +))] +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_char = u8; #[doc(include = "char.md")] -#[cfg(not(any(all(target_os = "linux", any(target_arch = "aarch64", - target_arch = "arm", - target_arch = "hexagon", - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "s390x")), - all(target_os = "android", any(target_arch = "aarch64", - target_arch = "arm")), - all(target_os = "l4re", target_arch = "x86_64"), - all(target_os = "freebsd", any(target_arch = "aarch64", - target_arch = "arm", - target_arch = "powerpc", - target_arch = "powerpc64")), - all(target_os = "netbsd", any(target_arch = "aarch64", - target_arch = "arm", - target_arch = "powerpc")), - all(target_os = "openbsd", target_arch = "aarch64"), - all(target_os = "vxworks", any(target_arch = "aarch64", - target_arch = "arm", - target_arch = "powerpc64", - target_arch = "powerpc")), - all(target_os = "fuchsia", target_arch = "aarch64"))))] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_char = i8; +#[cfg(not(any( + all( + target_os = "linux", + any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "hexagon", + target_arch = "powerpc", + target_arch = "powerpc64", + target_arch = "s390x" + ) + ), + all(target_os = "android", any(target_arch = "aarch64", target_arch = "arm")), + all(target_os = "l4re", target_arch = "x86_64"), + all( + target_os = "freebsd", + any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "powerpc", + target_arch = "powerpc64" + ) + ), + all( + target_os = "netbsd", + any(target_arch = "aarch64", target_arch = "arm", target_arch = "powerpc") + ), + all(target_os = "openbsd", target_arch = "aarch64"), + all( + target_os = "vxworks", + any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "powerpc64", + target_arch = "powerpc" + ) + ), + all(target_os = "fuchsia", target_arch = "aarch64") +)))] +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_char = i8; #[doc(include = "schar.md")] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_schar = i8; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_schar = i8; #[doc(include = "uchar.md")] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_uchar = u8; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_uchar = u8; #[doc(include = "short.md")] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_short = i16; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_short = i16; #[doc(include = "ushort.md")] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_ushort = u16; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_ushort = u16; #[doc(include = "int.md")] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_int = i32; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_int = i32; #[doc(include = "uint.md")] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_uint = u32; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_uint = u32; #[doc(include = "long.md")] #[cfg(any(target_pointer_width = "32", windows))] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_long = i32; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_long = i32; #[doc(include = "ulong.md")] #[cfg(any(target_pointer_width = "32", windows))] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_ulong = u32; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_ulong = u32; #[doc(include = "long.md")] #[cfg(all(target_pointer_width = "64", not(windows)))] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_long = i64; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_long = i64; #[doc(include = "ulong.md")] #[cfg(all(target_pointer_width = "64", not(windows)))] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_ulong = u64; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_ulong = u64; #[doc(include = "longlong.md")] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_longlong = i64; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_longlong = i64; #[doc(include = "ulonglong.md")] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_ulonglong = u64; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_ulonglong = u64; #[doc(include = "float.md")] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_float = f32; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_float = f32; #[doc(include = "double.md")] -#[stable(feature = "raw_os", since = "1.1.0")] pub type c_double = f64; +#[stable(feature = "raw_os", since = "1.1.0")] +pub type c_double = f64; #[stable(feature = "raw_os", since = "1.1.0")] #[doc(no_inline)] diff --git a/src/libstd/os/redox/fs.rs b/src/libstd/os/redox/fs.rs index 80a1290761984..6c87df534bdc6 100644 --- a/src/libstd/os/redox/fs.rs +++ b/src/libstd/os/redox/fs.rs @@ -34,9 +34,11 @@ pub trait MetadataExt { /// } /// ``` #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -327,10 +329,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/redox/mod.rs b/src/libstd/os/redox/mod.rs index c60da5926da6e..d786759c6111a 100644 --- a/src/libstd/os/redox/mod.rs +++ b/src/libstd/os/redox/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/redox/raw.rs b/src/libstd/os/redox/raw.rs index 23d8ff7694bc5..abe6dfc6b0c51 100644 --- a/src/libstd/os/redox/raw.rs +++ b/src/libstd/os/redox/raw.rs @@ -1,30 +1,42 @@ //! Redox-specific raw type definitions #![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)] #![allow(missing_debug_implementations)] use crate::os::raw::{c_char, c_int, c_long, c_ulong, c_void}; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = c_long; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type gid_t = c_int; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = c_int; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type uid_t = c_int; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = c_long; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type gid_t = c_int; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = c_int; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type uid_t = c_int; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = *mut c_void; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = c_ulong; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = c_ulong; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = c_ulong; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = c_ulong; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = c_long; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = c_long; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blkcnt_t = c_ulong; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blksize_t = c_ulong; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type ino_t = c_ulong; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type nlink_t = c_ulong; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type off_t = c_long; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type time_t = c_long; #[repr(C)] #[derive(Clone)] diff --git a/src/libstd/os/solaris/fs.rs b/src/libstd/os/solaris/fs.rs index 55a8d5d1ef007..549d3d756362d 100644 --- a/src/libstd/os/solaris/fs.rs +++ b/src/libstd/os/solaris/fs.rs @@ -18,9 +18,11 @@ pub trait MetadataExt { /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the /// cross-Unix abstractions contained within the raw stat. #[stable(feature = "metadata_ext", since = "1.1.0")] - #[rustc_deprecated(since = "1.8.0", - reason = "deprecated in favor of the accessor \ - methods of this trait")] + #[rustc_deprecated( + since = "1.8.0", + reason = "deprecated in favor of the accessor \ + methods of this trait" + )] #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat; @@ -62,10 +64,7 @@ pub trait MetadataExt { impl MetadataExt for Metadata { #[allow(deprecated)] fn as_raw_stat(&self) -> &raw::stat { - unsafe { - &*(self.as_inner().as_inner() as *const libc::stat - as *const raw::stat) - } + unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) } } fn st_dev(&self) -> u64 { self.as_inner().as_inner().st_dev as u64 diff --git a/src/libstd/os/solaris/mod.rs b/src/libstd/os/solaris/mod.rs index 7f560c9b09332..e4cfd53291a6e 100644 --- a/src/libstd/os/solaris/mod.rs +++ b/src/libstd/os/solaris/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/solaris/raw.rs b/src/libstd/os/solaris/raw.rs index 93270efea2b68..e78f9992bb324 100644 --- a/src/libstd/os/solaris/raw.rs +++ b/src/libstd/os/solaris/raw.rs @@ -1,25 +1,36 @@ //! Solaris-specific raw type definitions #![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)] use crate::os::raw::c_long; -use crate::os::unix::raw::{uid_t, gid_t}; +use crate::os::unix::raw::{gid_t, uid_t}; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type fflags_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64; -#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blkcnt_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type blksize_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type dev_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type fflags_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type ino_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type mode_t = u32; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type nlink_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type off_t = u64; +#[stable(feature = "raw_ext", since = "1.1.0")] +pub type time_t = i64; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = u32; @@ -61,5 +72,5 @@ pub struct stat { #[stable(feature = "raw_ext", since = "1.1.0")] pub st_blocks: blkcnt_t, #[stable(feature = "raw_ext", since = "1.1.0")] - pub __unused: [u8; 16] + pub __unused: [u8; 16], } diff --git a/src/libstd/os/vxworks/mod.rs b/src/libstd/os/vxworks/mod.rs index 2255a103d353d..0a7ac641dd3e1 100644 --- a/src/libstd/os/vxworks/mod.rs +++ b/src/libstd/os/vxworks/mod.rs @@ -2,5 +2,5 @@ #![stable(feature = "raw_ext", since = "1.1.0")] -pub mod raw; pub mod fs; +pub mod raw; diff --git a/src/libstd/os/vxworks/raw.rs b/src/libstd/os/vxworks/raw.rs index ae0560a5a92ac..29a0af5645ee1 100644 --- a/src/libstd/os/vxworks/raw.rs +++ b/src/libstd/os/vxworks/raw.rs @@ -1,7 +1,7 @@ //! VxWorks-specific raw type definitions #![stable(feature = "metadata_ext", since = "1.1.0")] -use crate::os::raw::{c_ulong}; +use crate::os::raw::c_ulong; #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = c_ulong; diff --git a/src/libstd/panic.rs b/src/libstd/panic.rs index cd024068d2d47..ac8e0daf766bf 100644 --- a/src/libstd/panic.rs +++ b/src/libstd/panic.rs @@ -7,21 +7,21 @@ use crate::cell::UnsafeCell; use crate::collections; use crate::fmt; use crate::future::Future; -use crate::pin::Pin; use crate::ops::{Deref, DerefMut}; use crate::panicking; -use crate::ptr::{Unique, NonNull}; +use crate::pin::Pin; +use crate::ptr::{NonNull, Unique}; use crate::rc::Rc; -use crate::sync::{Arc, Mutex, RwLock}; use crate::sync::atomic; +use crate::sync::{Arc, Mutex, RwLock}; use crate::task::{Context, Poll}; use crate::thread::Result; #[stable(feature = "panic_hooks", since = "1.10.0")] -pub use crate::panicking::{take_hook, set_hook}; +pub use crate::panicking::{set_hook, take_hook}; #[stable(feature = "panic_hooks", since = "1.10.0")] -pub use core::panic::{PanicInfo, Location}; +pub use core::panic::{Location, PanicInfo}; /// A marker trait which represents "panic safe" types in Rust. /// @@ -103,8 +103,8 @@ pub use core::panic::{PanicInfo, Location}; /// [`AssertUnwindSafe`]: ./struct.AssertUnwindSafe.html #[stable(feature = "catch_unwind", since = "1.9.0")] #[rustc_on_unimplemented( - message="the type `{Self}` may not be safely transferred across an unwind boundary", - label="`{Self}` may not be safely transferred across an unwind boundary", + message = "the type `{Self}` may not be safely transferred across an unwind boundary", + label = "`{Self}` may not be safely transferred across an unwind boundary" )] pub auto trait UnwindSafe {} @@ -121,10 +121,10 @@ pub auto trait UnwindSafe {} /// [`UnwindSafe`]: ./trait.UnwindSafe.html #[stable(feature = "catch_unwind", since = "1.9.0")] #[rustc_on_unimplemented( - message="the type `{Self}` may contain interior mutability and a reference may not be safely \ - transferrable across a catch_unwind boundary", - label="`{Self}` may contain interior mutability and a reference may not be safely \ - transferrable across a catch_unwind boundary", + message = "the type `{Self}` may contain interior mutability and a reference may not be safely \ + transferrable across a catch_unwind boundary", + label = "`{Self}` may contain interior mutability and a reference may not be safely \ + transferrable across a catch_unwind boundary" )] pub auto trait RefUnwindSafe {} @@ -187,10 +187,7 @@ pub auto trait RefUnwindSafe {} /// // ... /// ``` #[stable(feature = "catch_unwind", since = "1.9.0")] -pub struct AssertUnwindSafe( - #[stable(feature = "catch_unwind", since = "1.9.0")] - pub T -); +pub struct AssertUnwindSafe(#[stable(feature = "catch_unwind", since = "1.9.0")] pub T); // Implementations of the `UnwindSafe` trait: // @@ -290,7 +287,12 @@ impl RefUnwindSafe for atomic::AtomicPtr {} // https://github.com/rust-lang/rust/issues/62301 #[stable(feature = "hashbrown", since = "1.36.0")] impl UnwindSafe for collections::HashMap - where K: UnwindSafe, V: UnwindSafe, S: UnwindSafe {} +where + K: UnwindSafe, + V: UnwindSafe, + S: UnwindSafe, +{ +} #[stable(feature = "catch_unwind", since = "1.9.0")] impl Deref for AssertUnwindSafe { @@ -320,9 +322,7 @@ impl R> FnOnce<()> for AssertUnwindSafe { #[stable(feature = "std_debug", since = "1.16.0")] impl fmt::Debug for AssertUnwindSafe { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("AssertUnwindSafe") - .field(&self.0) - .finish() + f.debug_tuple("AssertUnwindSafe").field(&self.0).finish() } } @@ -391,9 +391,7 @@ impl Future for AssertUnwindSafe { /// ``` #[stable(feature = "catch_unwind", since = "1.9.0")] pub fn catch_unwind R + UnwindSafe, R>(f: F) -> Result { - unsafe { - panicking::r#try(f) - } + unsafe { panicking::r#try(f) } } /// Triggers a panic without invoking the panic hook. diff --git a/src/libstd/path.rs b/src/libstd/path.rs index 6d6bc760649e0..42bca0a9575b3 100644 --- a/src/libstd/path.rs +++ b/src/libstd/path.rs @@ -84,7 +84,7 @@ use crate::sync::Arc; use crate::ffi::{OsStr, OsString}; -use crate::sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix}; +use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR}; //////////////////////////////////////////////////////////////////////////////// // GENERAL NOTES @@ -196,26 +196,13 @@ impl<'a> Prefix<'a> { match *self { Verbatim(x) => 4 + os_str_len(x), VerbatimUNC(x, y) => { - 8 + os_str_len(x) + - if os_str_len(y) > 0 { - 1 + os_str_len(y) - } else { - 0 - } - }, + 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 } + } VerbatimDisk(_) => 6, - UNC(x, y) => { - 2 + os_str_len(x) + - if os_str_len(y) > 0 { - 1 + os_str_len(y) - } else { - 0 - } - }, + UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }, DeviceNS(x) => 4 + os_str_len(x), Disk(_) => 2, } - } /// Determines if the prefix is verbatim, i.e., begins with `\\?\`. @@ -291,8 +278,9 @@ pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP; // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving // `iter` after having exhausted `prefix`. fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option - where I: Iterator> + Clone, - J: Iterator>, +where + I: Iterator> + Clone, + J: Iterator>, { loop { let mut iter_next = iter.clone(); @@ -326,11 +314,7 @@ fn has_redox_scheme(s: &[u8]) -> bool { /// Says whether the first byte after the prefix is a separator. fn has_physical_root(s: &[u8], prefix: Option>) -> bool { - let path = if let Some(p) = prefix { - &s[p.len()..] - } else { - s - }; + let path = if let Some(p) = prefix { &s[p.len()..] } else { s }; !path.is_empty() && is_sep_byte(path[0]) } @@ -352,8 +336,7 @@ fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) { if before == Some(b"") { (Some(file), None) } else { - (before.map(|s| u8_slice_as_os_str(s)), - after.map(|s| u8_slice_as_os_str(s))) + (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) } } } @@ -370,9 +353,9 @@ fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) { /// directory component, and a body (of normal components) #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] enum State { - Prefix = 0, // c: - StartDir = 1, // / or . or nothing - Body = 2, // foo/bar/baz + Prefix = 0, // c: + StartDir = 1, // / or . or nothing + Body = 2, // foo/bar/baz Done = 3, } @@ -509,9 +492,7 @@ pub enum Component<'a> { /// /// [`Prefix`]: enum.Prefix.html #[stable(feature = "rust1", since = "1.0.0")] - Prefix( - #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a> - ), + Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>), /// The root directory component, appears after any prefix and before anything else. /// @@ -637,15 +618,11 @@ impl fmt::Debug for Components<'_> { impl fmt::Debug for DebugHelper<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_list() - .entries(self.0.components()) - .finish() + f.debug_list().entries(self.0.components()).finish() } } - f.debug_tuple("Components") - .field(&DebugHelper(self.as_path())) - .finish() + f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish() } } @@ -664,26 +641,14 @@ impl<'a> Components<'a> { /// how much of the prefix is left from the point of view of iteration? #[inline] fn prefix_remaining(&self) -> usize { - if self.front == State::Prefix { - self.prefix_len() - } else { - 0 - } + if self.front == State::Prefix { self.prefix_len() } else { 0 } } // Given the iteration so far, how much of the pre-State::Body path is left? #[inline] fn len_before_body(&self) -> usize { - let root = if self.front <= State::StartDir && self.has_physical_root { - 1 - } else { - 0 - }; - let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { - 1 - } else { - 0 - }; + let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 }; + let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 }; self.prefix_remaining() + root + cur_dir } @@ -695,11 +660,7 @@ impl<'a> Components<'a> { #[inline] fn is_sep_byte(&self, b: u8) -> bool { - if self.prefix_verbatim() { - is_verbatim_sep(b) - } else { - is_sep_byte(b) - } + if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) } } /// Extracts a slice corresponding to the portion of the path remaining for iteration. @@ -758,8 +719,8 @@ impl<'a> Components<'a> { match comp { b"." if self.prefix_verbatim() => Some(Component::CurDir), b"." => None, // . components are normalized away, except at - // the beginning of a path, which is treated - // separately via `include_cur_dir` + // the beginning of a path, which is treated + // separately via `include_cur_dir` b".." => Some(Component::ParentDir), b"" => None, _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })), @@ -835,15 +796,11 @@ impl fmt::Debug for Iter<'_> { impl fmt::Debug for DebugHelper<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_list() - .entries(self.0.iter()) - .finish() + f.debug_list().entries(self.0.iter()).finish() } } - f.debug_tuple("Iter") - .field(&DebugHelper(self.as_path())) - .finish() + f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish() } } @@ -1174,9 +1131,7 @@ impl PathBuf { /// [`OsString`]: ../ffi/struct.OsString.html #[unstable(feature = "path_buf_capacity", issue = "58234")] pub fn with_capacity(capacity: usize) -> PathBuf { - PathBuf { - inner: OsString::with_capacity(capacity) - } + PathBuf { inner: OsString::with_capacity(capacity) } } /// Coerces to a [`Path`] slice. @@ -1239,8 +1194,10 @@ impl PathBuf { // in the special case of `C:` on Windows, do *not* add a separator { let comps = self.components(); - if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() && - comps.prefix.unwrap().is_drive() { + if comps.prefix_len() > 0 + && comps.prefix_len() == comps.path.len() + && comps.prefix.unwrap().is_drive() + { need_sep = false } } @@ -1527,7 +1484,7 @@ impl From for OsString { /// Converts a `PathBuf` into a `OsString` /// /// This conversion does not allocate or copy memory. - fn from(path_buf : PathBuf) -> OsString { + fn from(path_buf: PathBuf) -> OsString { path_buf.inner } } @@ -1992,13 +1949,11 @@ impl Path { pub fn parent(&self) -> Option<&Path> { let mut comps = self.components(); let comp = comps.next_back(); - comp.and_then(|p| { - match p { - Component::Normal(_) | - Component::CurDir | - Component::ParentDir => Some(comps.as_path()), - _ => None, + comp.and_then(|p| match p { + Component::Normal(_) | Component::CurDir | Component::ParentDir => { + Some(comps.as_path()) } + _ => None, }) } @@ -2026,9 +1981,7 @@ impl Path { /// [`parent`]: struct.Path.html#method.parent #[stable(feature = "path_ancestors", since = "1.28.0")] pub fn ancestors(&self) -> Ancestors<'_> { - Ancestors { - next: Some(&self), - } + Ancestors { next: Some(&self) } } /// Returns the final component of the `Path`, if there is one. @@ -2055,11 +2008,9 @@ impl Path { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn file_name(&self) -> Option<&OsStr> { - self.components().next_back().and_then(|p| { - match p { - Component::Normal(p) => Some(p.as_ref()), - _ => None, - } + self.components().next_back().and_then(|p| match p { + Component::Normal(p) => Some(p.as_ref()), + _ => None, }) } @@ -2092,15 +2043,14 @@ impl Path { /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt"))); /// ``` #[stable(since = "1.7.0", feature = "path_strip_prefix")] - pub fn strip_prefix

(&self, base: P) - -> Result<&Path, StripPrefixError> - where P: AsRef + pub fn strip_prefix

(&self, base: P) -> Result<&Path, StripPrefixError> + where + P: AsRef, { self._strip_prefix(base.as_ref()) } - fn _strip_prefix(&self, base: &Path) - -> Result<&Path, StripPrefixError> { + fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> { iter_after(self.components(), base.components()) .map(|c| c.as_path()) .ok_or(StripPrefixError(())) @@ -2329,8 +2279,8 @@ impl Path { Components { path: self.as_u8_slice(), prefix, - has_physical_root: has_physical_root(self.as_u8_slice(), prefix) || - has_redox_scheme(self.as_u8_slice()), + has_physical_root: has_physical_root(self.as_u8_slice(), prefix) + || has_redox_scheme(self.as_u8_slice()), front: State::Prefix, back: State::Body, } @@ -2727,14 +2677,18 @@ impl AsRef for PathBuf { impl<'a> IntoIterator for &'a PathBuf { type Item = &'a OsStr; type IntoIter = Iter<'a>; - fn into_iter(self) -> Iter<'a> { self.iter() } + fn into_iter(self) -> Iter<'a> { + self.iter() + } } #[stable(feature = "path_into_iter", since = "1.6.0")] impl<'a> IntoIterator for &'a Path { type Item = &'a OsStr; type IntoIter = Iter<'a>; - fn into_iter(self) -> Iter<'a> { self.iter() } + fn into_iter(self) -> Iter<'a> { + self.iter() + } } macro_rules! impl_cmp { @@ -2742,13 +2696,17 @@ macro_rules! impl_cmp { #[stable(feature = "partialeq_path", since = "1.6.0")] impl<'a, 'b> PartialEq<$rhs> for $lhs { #[inline] - fn eq(&self, other: &$rhs) -> bool { ::eq(self, other) } + fn eq(&self, other: &$rhs) -> bool { + ::eq(self, other) + } } #[stable(feature = "partialeq_path", since = "1.6.0")] impl<'a, 'b> PartialEq<$lhs> for $rhs { #[inline] - fn eq(&self, other: &$lhs) -> bool { ::eq(self, other) } + fn eq(&self, other: &$lhs) -> bool { + ::eq(self, other) + } } #[stable(feature = "cmp_path", since = "1.8.0")] @@ -2766,7 +2724,7 @@ macro_rules! impl_cmp { ::partial_cmp(self, other) } } - } + }; } impl_cmp!(PathBuf, Path); @@ -2780,13 +2738,17 @@ macro_rules! impl_cmp_os_str { #[stable(feature = "cmp_path", since = "1.8.0")] impl<'a, 'b> PartialEq<$rhs> for $lhs { #[inline] - fn eq(&self, other: &$rhs) -> bool { ::eq(self, other.as_ref()) } + fn eq(&self, other: &$rhs) -> bool { + ::eq(self, other.as_ref()) + } } #[stable(feature = "cmp_path", since = "1.8.0")] impl<'a, 'b> PartialEq<$lhs> for $rhs { #[inline] - fn eq(&self, other: &$lhs) -> bool { ::eq(self.as_ref(), other) } + fn eq(&self, other: &$lhs) -> bool { + ::eq(self.as_ref(), other) + } } #[stable(feature = "cmp_path", since = "1.8.0")] @@ -2804,7 +2766,7 @@ macro_rules! impl_cmp_os_str { ::partial_cmp(self.as_ref(), other) } } - } + }; } impl_cmp_os_str!(PathBuf, OsStr); @@ -2831,7 +2793,9 @@ impl fmt::Display for StripPrefixError { #[stable(since = "1.7.0", feature = "strip_prefix")] impl Error for StripPrefixError { - fn description(&self) -> &str { "prefix not found" } + fn description(&self) -> &str { + "prefix not found" + } } #[cfg(test)] @@ -2948,568 +2912,568 @@ mod tests { #[cfg(unix)] pub fn test_decompositions_unix() { t!("", - iter: [], - has_root: false, - is_absolute: false, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: [], + has_root: false, + is_absolute: false, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("foo", - iter: ["foo"], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["foo"], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("/", - iter: ["/"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["/"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("/foo", - iter: ["/", "foo"], - has_root: true, - is_absolute: true, - parent: Some("/"), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["/", "foo"], + has_root: true, + is_absolute: true, + parent: Some("/"), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("foo/", - iter: ["foo"], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["foo"], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("/foo/", - iter: ["/", "foo"], - has_root: true, - is_absolute: true, - parent: Some("/"), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["/", "foo"], + has_root: true, + is_absolute: true, + parent: Some("/"), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("foo/bar", - iter: ["foo", "bar"], - has_root: false, - is_absolute: false, - parent: Some("foo"), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); + iter: ["foo", "bar"], + has_root: false, + is_absolute: false, + parent: Some("foo"), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("/foo/bar", - iter: ["/", "foo", "bar"], - has_root: true, - is_absolute: true, - parent: Some("/foo"), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); + iter: ["/", "foo", "bar"], + has_root: true, + is_absolute: true, + parent: Some("/foo"), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("///foo///", - iter: ["/", "foo"], - has_root: true, - is_absolute: true, - parent: Some("/"), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["/", "foo"], + has_root: true, + is_absolute: true, + parent: Some("/"), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("///foo///bar", - iter: ["/", "foo", "bar"], - has_root: true, - is_absolute: true, - parent: Some("///foo"), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); + iter: ["/", "foo", "bar"], + has_root: true, + is_absolute: true, + parent: Some("///foo"), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("./.", - iter: ["."], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["."], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: None, + file_stem: None, + extension: None + ); t!("/..", - iter: ["/", ".."], - has_root: true, - is_absolute: true, - parent: Some("/"), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["/", ".."], + has_root: true, + is_absolute: true, + parent: Some("/"), + file_name: None, + file_stem: None, + extension: None + ); t!("../", - iter: [".."], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: None, - file_stem: None, - extension: None - ); + iter: [".."], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: None, + file_stem: None, + extension: None + ); t!("foo/.", - iter: ["foo"], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["foo"], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("foo/..", - iter: ["foo", ".."], - has_root: false, - is_absolute: false, - parent: Some("foo"), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["foo", ".."], + has_root: false, + is_absolute: false, + parent: Some("foo"), + file_name: None, + file_stem: None, + extension: None + ); t!("foo/./", - iter: ["foo"], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["foo"], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("foo/./bar", - iter: ["foo", "bar"], - has_root: false, - is_absolute: false, - parent: Some("foo"), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); + iter: ["foo", "bar"], + has_root: false, + is_absolute: false, + parent: Some("foo"), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("foo/../", - iter: ["foo", ".."], - has_root: false, - is_absolute: false, - parent: Some("foo"), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["foo", ".."], + has_root: false, + is_absolute: false, + parent: Some("foo"), + file_name: None, + file_stem: None, + extension: None + ); t!("foo/../bar", - iter: ["foo", "..", "bar"], - has_root: false, - is_absolute: false, - parent: Some("foo/.."), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); + iter: ["foo", "..", "bar"], + has_root: false, + is_absolute: false, + parent: Some("foo/.."), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("./a", - iter: [".", "a"], - has_root: false, - is_absolute: false, - parent: Some("."), - file_name: Some("a"), - file_stem: Some("a"), - extension: None - ); + iter: [".", "a"], + has_root: false, + is_absolute: false, + parent: Some("."), + file_name: Some("a"), + file_stem: Some("a"), + extension: None + ); t!(".", - iter: ["."], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["."], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: None, + file_stem: None, + extension: None + ); t!("./", - iter: ["."], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["."], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: None, + file_stem: None, + extension: None + ); t!("a/b", - iter: ["a", "b"], - has_root: false, - is_absolute: false, - parent: Some("a"), - file_name: Some("b"), - file_stem: Some("b"), - extension: None - ); + iter: ["a", "b"], + has_root: false, + is_absolute: false, + parent: Some("a"), + file_name: Some("b"), + file_stem: Some("b"), + extension: None + ); t!("a//b", - iter: ["a", "b"], - has_root: false, - is_absolute: false, - parent: Some("a"), - file_name: Some("b"), - file_stem: Some("b"), - extension: None - ); + iter: ["a", "b"], + has_root: false, + is_absolute: false, + parent: Some("a"), + file_name: Some("b"), + file_stem: Some("b"), + extension: None + ); t!("a/./b", - iter: ["a", "b"], - has_root: false, - is_absolute: false, - parent: Some("a"), - file_name: Some("b"), - file_stem: Some("b"), - extension: None - ); + iter: ["a", "b"], + has_root: false, + is_absolute: false, + parent: Some("a"), + file_name: Some("b"), + file_stem: Some("b"), + extension: None + ); t!("a/b/c", - iter: ["a", "b", "c"], - has_root: false, - is_absolute: false, - parent: Some("a/b"), - file_name: Some("c"), - file_stem: Some("c"), - extension: None - ); + iter: ["a", "b", "c"], + has_root: false, + is_absolute: false, + parent: Some("a/b"), + file_name: Some("c"), + file_stem: Some("c"), + extension: None + ); t!(".foo", - iter: [".foo"], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: Some(".foo"), - file_stem: Some(".foo"), - extension: None - ); + iter: [".foo"], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: Some(".foo"), + file_stem: Some(".foo"), + extension: None + ); } #[test] #[cfg(windows)] pub fn test_decompositions_windows() { t!("", - iter: [], - has_root: false, - is_absolute: false, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: [], + has_root: false, + is_absolute: false, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("foo", - iter: ["foo"], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["foo"], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("/", - iter: ["\\"], - has_root: true, - is_absolute: false, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["\\"], + has_root: true, + is_absolute: false, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\", - iter: ["\\"], - has_root: true, - is_absolute: false, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["\\"], + has_root: true, + is_absolute: false, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("c:", - iter: ["c:"], - has_root: false, - is_absolute: false, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["c:"], + has_root: false, + is_absolute: false, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("c:\\", - iter: ["c:", "\\"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["c:", "\\"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("c:/", - iter: ["c:", "\\"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["c:", "\\"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("/foo", - iter: ["\\", "foo"], - has_root: true, - is_absolute: false, - parent: Some("/"), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["\\", "foo"], + has_root: true, + is_absolute: false, + parent: Some("/"), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("foo/", - iter: ["foo"], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["foo"], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("/foo/", - iter: ["\\", "foo"], - has_root: true, - is_absolute: false, - parent: Some("/"), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["\\", "foo"], + has_root: true, + is_absolute: false, + parent: Some("/"), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("foo/bar", - iter: ["foo", "bar"], - has_root: false, - is_absolute: false, - parent: Some("foo"), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); + iter: ["foo", "bar"], + has_root: false, + is_absolute: false, + parent: Some("foo"), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("/foo/bar", - iter: ["\\", "foo", "bar"], - has_root: true, - is_absolute: false, - parent: Some("/foo"), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); + iter: ["\\", "foo", "bar"], + has_root: true, + is_absolute: false, + parent: Some("/foo"), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("///foo///", - iter: ["\\", "foo"], - has_root: true, - is_absolute: false, - parent: Some("/"), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["\\", "foo"], + has_root: true, + is_absolute: false, + parent: Some("/"), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("///foo///bar", - iter: ["\\", "foo", "bar"], - has_root: true, - is_absolute: false, - parent: Some("///foo"), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); + iter: ["\\", "foo", "bar"], + has_root: true, + is_absolute: false, + parent: Some("///foo"), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("./.", - iter: ["."], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["."], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: None, + file_stem: None, + extension: None + ); t!("/..", - iter: ["\\", ".."], - has_root: true, - is_absolute: false, - parent: Some("/"), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["\\", ".."], + has_root: true, + is_absolute: false, + parent: Some("/"), + file_name: None, + file_stem: None, + extension: None + ); t!("../", - iter: [".."], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: None, - file_stem: None, - extension: None - ); + iter: [".."], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: None, + file_stem: None, + extension: None + ); t!("foo/.", - iter: ["foo"], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["foo"], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("foo/..", - iter: ["foo", ".."], - has_root: false, - is_absolute: false, - parent: Some("foo"), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["foo", ".."], + has_root: false, + is_absolute: false, + parent: Some("foo"), + file_name: None, + file_stem: None, + extension: None + ); t!("foo/./", - iter: ["foo"], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: Some("foo"), - file_stem: Some("foo"), - extension: None - ); + iter: ["foo"], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: Some("foo"), + file_stem: Some("foo"), + extension: None + ); t!("foo/./bar", - iter: ["foo", "bar"], - has_root: false, - is_absolute: false, - parent: Some("foo"), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); + iter: ["foo", "bar"], + has_root: false, + is_absolute: false, + parent: Some("foo"), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("foo/../", - iter: ["foo", ".."], - has_root: false, - is_absolute: false, - parent: Some("foo"), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["foo", ".."], + has_root: false, + is_absolute: false, + parent: Some("foo"), + file_name: None, + file_stem: None, + extension: None + ); t!("foo/../bar", - iter: ["foo", "..", "bar"], - has_root: false, - is_absolute: false, - parent: Some("foo/.."), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); + iter: ["foo", "..", "bar"], + has_root: false, + is_absolute: false, + parent: Some("foo/.."), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("./a", - iter: [".", "a"], - has_root: false, - is_absolute: false, - parent: Some("."), - file_name: Some("a"), - file_stem: Some("a"), - extension: None - ); + iter: [".", "a"], + has_root: false, + is_absolute: false, + parent: Some("."), + file_name: Some("a"), + file_stem: Some("a"), + extension: None + ); t!(".", - iter: ["."], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["."], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: None, + file_stem: None, + extension: None + ); t!("./", - iter: ["."], - has_root: false, - is_absolute: false, - parent: Some(""), - file_name: None, - file_stem: None, - extension: None - ); + iter: ["."], + has_root: false, + is_absolute: false, + parent: Some(""), + file_name: None, + file_stem: None, + extension: None + ); t!("a/b", - iter: ["a", "b"], - has_root: false, - is_absolute: false, - parent: Some("a"), - file_name: Some("b"), - file_stem: Some("b"), - extension: None - ); + iter: ["a", "b"], + has_root: false, + is_absolute: false, + parent: Some("a"), + file_name: Some("b"), + file_stem: Some("b"), + extension: None + ); t!("a//b", - iter: ["a", "b"], - has_root: false, - is_absolute: false, - parent: Some("a"), - file_name: Some("b"), - file_stem: Some("b"), - extension: None - ); + iter: ["a", "b"], + has_root: false, + is_absolute: false, + parent: Some("a"), + file_name: Some("b"), + file_stem: Some("b"), + extension: None + ); t!("a/./b", - iter: ["a", "b"], - has_root: false, - is_absolute: false, - parent: Some("a"), - file_name: Some("b"), - file_stem: Some("b"), - extension: None - ); + iter: ["a", "b"], + has_root: false, + is_absolute: false, + parent: Some("a"), + file_name: Some("b"), + file_stem: Some("b"), + extension: None + ); t!("a/b/c", iter: ["a", "b", "c"], @@ -3521,291 +3485,273 @@ mod tests { extension: None); t!("a\\b\\c", - iter: ["a", "b", "c"], - has_root: false, - is_absolute: false, - parent: Some("a\\b"), - file_name: Some("c"), - file_stem: Some("c"), - extension: None - ); + iter: ["a", "b", "c"], + has_root: false, + is_absolute: false, + parent: Some("a\\b"), + file_name: Some("c"), + file_stem: Some("c"), + extension: None + ); t!("\\a", - iter: ["\\", "a"], - has_root: true, - is_absolute: false, - parent: Some("\\"), - file_name: Some("a"), - file_stem: Some("a"), - extension: None - ); + iter: ["\\", "a"], + has_root: true, + is_absolute: false, + parent: Some("\\"), + file_name: Some("a"), + file_stem: Some("a"), + extension: None + ); t!("c:\\foo.txt", - iter: ["c:", "\\", "foo.txt"], - has_root: true, - is_absolute: true, - parent: Some("c:\\"), - file_name: Some("foo.txt"), - file_stem: Some("foo"), - extension: Some("txt") - ); + iter: ["c:", "\\", "foo.txt"], + has_root: true, + is_absolute: true, + parent: Some("c:\\"), + file_name: Some("foo.txt"), + file_stem: Some("foo"), + extension: Some("txt") + ); t!("\\\\server\\share\\foo.txt", - iter: ["\\\\server\\share", "\\", "foo.txt"], - has_root: true, - is_absolute: true, - parent: Some("\\\\server\\share\\"), - file_name: Some("foo.txt"), - file_stem: Some("foo"), - extension: Some("txt") - ); + iter: ["\\\\server\\share", "\\", "foo.txt"], + has_root: true, + is_absolute: true, + parent: Some("\\\\server\\share\\"), + file_name: Some("foo.txt"), + file_stem: Some("foo"), + extension: Some("txt") + ); t!("\\\\server\\share", - iter: ["\\\\server\\share", "\\"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["\\\\server\\share", "\\"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\server", - iter: ["\\", "server"], - has_root: true, - is_absolute: false, - parent: Some("\\"), - file_name: Some("server"), - file_stem: Some("server"), - extension: None - ); + iter: ["\\", "server"], + has_root: true, + is_absolute: false, + parent: Some("\\"), + file_name: Some("server"), + file_stem: Some("server"), + extension: None + ); t!("\\\\?\\bar\\foo.txt", - iter: ["\\\\?\\bar", "\\", "foo.txt"], - has_root: true, - is_absolute: true, - parent: Some("\\\\?\\bar\\"), - file_name: Some("foo.txt"), - file_stem: Some("foo"), - extension: Some("txt") - ); + iter: ["\\\\?\\bar", "\\", "foo.txt"], + has_root: true, + is_absolute: true, + parent: Some("\\\\?\\bar\\"), + file_name: Some("foo.txt"), + file_stem: Some("foo"), + extension: Some("txt") + ); t!("\\\\?\\bar", - iter: ["\\\\?\\bar"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["\\\\?\\bar"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\?\\", - iter: ["\\\\?\\"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["\\\\?\\"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\?\\UNC\\server\\share\\foo.txt", - iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"], - has_root: true, - is_absolute: true, - parent: Some("\\\\?\\UNC\\server\\share\\"), - file_name: Some("foo.txt"), - file_stem: Some("foo"), - extension: Some("txt") - ); + iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"], + has_root: true, + is_absolute: true, + parent: Some("\\\\?\\UNC\\server\\share\\"), + file_name: Some("foo.txt"), + file_stem: Some("foo"), + extension: Some("txt") + ); t!("\\\\?\\UNC\\server", - iter: ["\\\\?\\UNC\\server"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["\\\\?\\UNC\\server"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\?\\UNC\\", - iter: ["\\\\?\\UNC\\"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["\\\\?\\UNC\\"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\?\\C:\\foo.txt", - iter: ["\\\\?\\C:", "\\", "foo.txt"], - has_root: true, - is_absolute: true, - parent: Some("\\\\?\\C:\\"), - file_name: Some("foo.txt"), - file_stem: Some("foo"), - extension: Some("txt") - ); - + iter: ["\\\\?\\C:", "\\", "foo.txt"], + has_root: true, + is_absolute: true, + parent: Some("\\\\?\\C:\\"), + file_name: Some("foo.txt"), + file_stem: Some("foo"), + extension: Some("txt") + ); t!("\\\\?\\C:\\", - iter: ["\\\\?\\C:", "\\"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); - + iter: ["\\\\?\\C:", "\\"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\?\\C:", - iter: ["\\\\?\\C:"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); - + iter: ["\\\\?\\C:"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\?\\foo/bar", - iter: ["\\\\?\\foo/bar"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); - + iter: ["\\\\?\\foo/bar"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\?\\C:/foo", - iter: ["\\\\?\\C:/foo"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); - + iter: ["\\\\?\\C:/foo"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\.\\foo\\bar", - iter: ["\\\\.\\foo", "\\", "bar"], - has_root: true, - is_absolute: true, - parent: Some("\\\\.\\foo\\"), - file_name: Some("bar"), - file_stem: Some("bar"), - extension: None - ); - + iter: ["\\\\.\\foo", "\\", "bar"], + has_root: true, + is_absolute: true, + parent: Some("\\\\.\\foo\\"), + file_name: Some("bar"), + file_stem: Some("bar"), + extension: None + ); t!("\\\\.\\foo", - iter: ["\\\\.\\foo", "\\"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); - + iter: ["\\\\.\\foo", "\\"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\.\\foo/bar", - iter: ["\\\\.\\foo/bar", "\\"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); - + iter: ["\\\\.\\foo/bar", "\\"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\.\\foo\\bar/baz", - iter: ["\\\\.\\foo", "\\", "bar", "baz"], - has_root: true, - is_absolute: true, - parent: Some("\\\\.\\foo\\bar"), - file_name: Some("baz"), - file_stem: Some("baz"), - extension: None - ); - + iter: ["\\\\.\\foo", "\\", "bar", "baz"], + has_root: true, + is_absolute: true, + parent: Some("\\\\.\\foo\\bar"), + file_name: Some("baz"), + file_stem: Some("baz"), + extension: None + ); t!("\\\\.\\", - iter: ["\\\\.\\", "\\"], - has_root: true, - is_absolute: true, - parent: None, - file_name: None, - file_stem: None, - extension: None - ); + iter: ["\\\\.\\", "\\"], + has_root: true, + is_absolute: true, + parent: None, + file_name: None, + file_stem: None, + extension: None + ); t!("\\\\?\\a\\b\\", - iter: ["\\\\?\\a", "\\", "b"], - has_root: true, - is_absolute: true, - parent: Some("\\\\?\\a\\"), - file_name: Some("b"), - file_stem: Some("b"), - extension: None - ); + iter: ["\\\\?\\a", "\\", "b"], + has_root: true, + is_absolute: true, + parent: Some("\\\\?\\a\\"), + file_name: Some("b"), + file_stem: Some("b"), + extension: None + ); } #[test] pub fn test_stem_ext() { t!("foo", - file_stem: Some("foo"), - extension: None - ); + file_stem: Some("foo"), + extension: None + ); t!("foo.", - file_stem: Some("foo"), - extension: Some("") - ); + file_stem: Some("foo"), + extension: Some("") + ); t!(".foo", - file_stem: Some(".foo"), - extension: None - ); + file_stem: Some(".foo"), + extension: None + ); t!("foo.txt", - file_stem: Some("foo"), - extension: Some("txt") - ); + file_stem: Some("foo"), + extension: Some("txt") + ); t!("foo.bar.txt", - file_stem: Some("foo.bar"), - extension: Some("txt") - ); + file_stem: Some("foo.bar"), + extension: Some("txt") + ); t!("foo.bar.", - file_stem: Some("foo.bar"), - extension: Some("") - ); + file_stem: Some("foo.bar"), + extension: Some("") + ); - t!(".", - file_stem: None, - extension: None - ); + t!(".", file_stem: None, extension: None); - t!("..", - file_stem: None, - extension: None - ); + t!("..", file_stem: None, extension: None); - t!("", - file_stem: None, - extension: None - ); + t!("", file_stem: None, extension: None); } #[test] @@ -3873,26 +3819,20 @@ mod tests { tp!("C:a\\b\\c", "C:d", "C:d"); tp!("C:", r"a\b\c", r"C:a\b\c"); tp!("C:", r"..\a", r"C:..\a"); - tp!("\\\\server\\share\\foo", - "bar", - "\\\\server\\share\\foo\\bar"); + tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar"); tp!("\\\\server\\share\\foo", "C:baz", "C:baz"); tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d"); tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d"); tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d"); tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz"); - tp!("\\\\?\\UNC\\server\\share\\foo", - "bar", - "\\\\?\\UNC\\server\\share\\foo\\bar"); + tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar"); tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a"); tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a"); // Note: modified from old path API tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo"); - tp!("C:\\a", - "\\\\?\\UNC\\server\\share", - "\\\\?\\UNC\\server\\share"); + tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share"); tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz"); tp!("\\\\.\\foo\\bar", "C:a", "C:a"); // again, not sure about the following, but I'm assuming \\.\ should be verbatim @@ -3945,15 +3885,9 @@ mod tests { tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true); tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true); tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false); - tp!("\\\\?\\UNC\\server\\share\\a\\b", - "\\\\?\\UNC\\server\\share\\a", - true); - tp!("\\\\?\\UNC\\server\\share\\a", - "\\\\?\\UNC\\server\\share\\", - true); - tp!("\\\\?\\UNC\\server\\share", - "\\\\?\\UNC\\server\\share", - false); + tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true); + tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true); + tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false); tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true); tp!("\\\\.\\a\\b", "\\\\.\\a\\", true); tp!("\\\\.\\a", "\\\\.\\a", false); @@ -4051,8 +3985,8 @@ mod tests { #[test] pub fn test_compare() { - use crate::hash::{Hash, Hasher}; use crate::collections::hash_map::DefaultHasher; + use crate::hash::{Hash, Hasher}; fn hash(t: T) -> u64 { let mut s = DefaultHasher::new(); @@ -4095,83 +4029,83 @@ mod tests { ); tc!("", "", - eq: true, - starts_with: true, - ends_with: true, - relative_from: Some("") - ); + eq: true, + starts_with: true, + ends_with: true, + relative_from: Some("") + ); tc!("foo", "", - eq: false, - starts_with: true, - ends_with: true, - relative_from: Some("foo") - ); + eq: false, + starts_with: true, + ends_with: true, + relative_from: Some("foo") + ); tc!("", "foo", - eq: false, - starts_with: false, - ends_with: false, - relative_from: None - ); + eq: false, + starts_with: false, + ends_with: false, + relative_from: None + ); tc!("foo", "foo", - eq: true, - starts_with: true, - ends_with: true, - relative_from: Some("") - ); + eq: true, + starts_with: true, + ends_with: true, + relative_from: Some("") + ); tc!("foo/", "foo", - eq: true, - starts_with: true, - ends_with: true, - relative_from: Some("") - ); + eq: true, + starts_with: true, + ends_with: true, + relative_from: Some("") + ); tc!("foo/bar", "foo", - eq: false, - starts_with: true, - ends_with: false, - relative_from: Some("bar") - ); + eq: false, + starts_with: true, + ends_with: false, + relative_from: Some("bar") + ); tc!("foo/bar/baz", "foo/bar", - eq: false, - starts_with: true, - ends_with: false, - relative_from: Some("baz") - ); + eq: false, + starts_with: true, + ends_with: false, + relative_from: Some("baz") + ); tc!("foo/bar", "foo/bar/baz", - eq: false, - starts_with: false, - ends_with: false, - relative_from: None - ); + eq: false, + starts_with: false, + ends_with: false, + relative_from: None + ); tc!("./foo/bar/", ".", + eq: false, + starts_with: true, + ends_with: false, + relative_from: Some("foo/bar") + ); + + if cfg!(windows) { + tc!(r"C:\src\rust\cargo-test\test\Cargo.toml", + r"c:\src\rust\cargo-test\test", eq: false, starts_with: true, ends_with: false, - relative_from: Some("foo/bar") + relative_from: Some("Cargo.toml") ); - if cfg!(windows) { - tc!(r"C:\src\rust\cargo-test\test\Cargo.toml", - r"c:\src\rust\cargo-test\test", - eq: false, - starts_with: true, - ends_with: false, - relative_from: Some("Cargo.toml") - ); - tc!(r"c:\foo", r"C:\foo", - eq: true, - starts_with: true, - ends_with: true, - relative_from: Some("") - ); + eq: true, + starts_with: true, + ends_with: true, + relative_from: Some("") + ); } } diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs index 3e4cf91127fc5..7c0efe828c27a 100644 --- a/src/libstd/prelude/v1.rs +++ b/src/libstd/prelude/v1.rs @@ -2,8 +2,6 @@ //! //! See the [module-level documentation](../index.html) for more. - - #![stable(feature = "rust1", since = "1.0.0")] // Re-exported core operators @@ -22,45 +20,27 @@ pub use crate::mem::drop; // Re-exported types and traits #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] -pub use crate::convert::{AsRef, AsMut, Into, From}; +pub use crate::convert::{AsMut, AsRef, From, Into}; #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] -pub use crate::iter::{Iterator, Extend, IntoIterator}; +pub use crate::iter::{DoubleEndedIterator, ExactSizeIterator}; #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] -pub use crate::iter::{DoubleEndedIterator, ExactSizeIterator}; +pub use crate::iter::{Extend, IntoIterator, Iterator}; #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] -pub use crate::option::Option::{self, Some, None}; +pub use crate::option::Option::{self, None, Some}; #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] -pub use crate::result::Result::{self, Ok, Err}; +pub use crate::result::Result::{self, Err, Ok}; // Re-exported built-in macros #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] #[doc(no_inline)] pub use core::prelude::v1::{ - asm, - assert, - cfg, - column, - compile_error, - concat, - concat_idents, - env, - file, - format_args, - format_args_nl, - global_asm, - include, - include_bytes, - include_str, - line, - log_syntax, - module_path, - option_env, - stringify, - trace_macros, + asm, assert, cfg, column, compile_error, concat, concat_idents, env, file, format_args, + format_args_nl, global_asm, include, include_bytes, include_str, line, log_syntax, module_path, + option_env, stringify, trace_macros, }; // FIXME: Attribute and derive macros are not documented because for them rustdoc generates @@ -69,21 +49,8 @@ pub use core::prelude::v1::{ #[allow(deprecated)] #[doc(hidden)] pub use core::prelude::v1::{ - Clone, - Copy, - Debug, - Default, - Eq, - Hash, - Ord, - PartialEq, - PartialOrd, - RustcDecodable, - RustcEncodable, - bench, - global_allocator, - test, - test_case, + bench, global_allocator, test, test_case, Clone, Copy, Debug, Default, Eq, Hash, Ord, + PartialEq, PartialOrd, RustcDecodable, RustcEncodable, }; // The file so far is equivalent to src/libcore/prelude/v1.rs, @@ -91,13 +58,12 @@ pub use core::prelude::v1::{ // Those files are duplicated rather than using glob imports // because we want docs to show these re-exports as pointing to within `std`. - #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] -pub use crate::boxed::Box; +pub use crate::borrow::ToOwned; #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] -pub use crate::borrow::ToOwned; +pub use crate::boxed::Box; #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use crate::string::{String, ToString}; diff --git a/src/libstd/process.rs b/src/libstd/process.rs index b1274a08cbe77..3eee45d000cd1 100644 --- a/src/libstd/process.rs +++ b/src/libstd/process.rs @@ -186,7 +186,9 @@ pub struct Child { } impl AsInner for Child { - fn as_inner(&self) -> &imp::Process { &self.handle } + fn as_inner(&self) -> &imp::Process { + &self.handle + } } impl FromInner<(imp::Process, imp::StdioPipes)> for Child { @@ -201,7 +203,9 @@ impl FromInner<(imp::Process, imp::StdioPipes)> for Child { } impl IntoInner for Child { - fn into_inner(self) -> imp::Process { self.handle } + fn into_inner(self) -> imp::Process { + self.handle + } } #[stable(feature = "std_debug", since = "1.16.0")] @@ -228,7 +232,7 @@ impl fmt::Debug for Child { /// [dropped]: ../ops/trait.Drop.html #[stable(feature = "process", since = "1.0.0")] pub struct ChildStdin { - inner: AnonPipe + inner: AnonPipe, } #[stable(feature = "process", since = "1.0.0")] @@ -247,11 +251,15 @@ impl Write for ChildStdin { } impl AsInner for ChildStdin { - fn as_inner(&self) -> &AnonPipe { &self.inner } + fn as_inner(&self) -> &AnonPipe { + &self.inner + } } impl IntoInner for ChildStdin { - fn into_inner(self) -> AnonPipe { self.inner } + fn into_inner(self) -> AnonPipe { + self.inner + } } impl FromInner for ChildStdin { @@ -279,7 +287,7 @@ impl fmt::Debug for ChildStdin { /// [dropped]: ../ops/trait.Drop.html #[stable(feature = "process", since = "1.0.0")] pub struct ChildStdout { - inner: AnonPipe + inner: AnonPipe, } #[stable(feature = "process", since = "1.0.0")] @@ -299,11 +307,15 @@ impl Read for ChildStdout { } impl AsInner for ChildStdout { - fn as_inner(&self) -> &AnonPipe { &self.inner } + fn as_inner(&self) -> &AnonPipe { + &self.inner + } } impl IntoInner for ChildStdout { - fn into_inner(self) -> AnonPipe { self.inner } + fn into_inner(self) -> AnonPipe { + self.inner + } } impl FromInner for ChildStdout { @@ -331,7 +343,7 @@ impl fmt::Debug for ChildStdout { /// [dropped]: ../ops/trait.Drop.html #[stable(feature = "process", since = "1.0.0")] pub struct ChildStderr { - inner: AnonPipe + inner: AnonPipe, } #[stable(feature = "process", since = "1.0.0")] @@ -351,11 +363,15 @@ impl Read for ChildStderr { } impl AsInner for ChildStderr { - fn as_inner(&self) -> &AnonPipe { &self.inner } + fn as_inner(&self) -> &AnonPipe { + &self.inner + } } impl IntoInner for ChildStderr { - fn into_inner(self) -> AnonPipe { self.inner } + fn into_inner(self) -> AnonPipe { + self.inner + } } impl FromInner for ChildStderr { @@ -533,7 +549,9 @@ impl Command { /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn args(&mut self, args: I) -> &mut Command - where I: IntoIterator, S: AsRef + where + I: IntoIterator, + S: AsRef, { for arg in args { self.arg(arg.as_ref()); @@ -560,7 +578,9 @@ impl Command { /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn env(&mut self, key: K, val: V) -> &mut Command - where K: AsRef, V: AsRef + where + K: AsRef, + V: AsRef, { self.inner.env_mut().set(key.as_ref(), val.as_ref()); self @@ -592,7 +612,10 @@ impl Command { /// ``` #[stable(feature = "command_envs", since = "1.19.0")] pub fn envs(&mut self, vars: I) -> &mut Command - where I: IntoIterator, K: AsRef, V: AsRef + where + I: IntoIterator, + K: AsRef, + V: AsRef, { for (ref key, ref val) in vars { self.inner.env_mut().set(key.as_ref(), val.as_ref()); @@ -794,7 +817,9 @@ impl Command { /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn output(&mut self) -> io::Result { - self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner) + self.inner + .spawn(imp::Stdio::MakePipe, false) + .map(Child::from_inner) .and_then(|p| p.wait_with_output()) } @@ -819,8 +844,10 @@ impl Command { /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn status(&mut self) -> io::Result { - self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner) - .and_then(|mut p| p.wait()) + self.inner + .spawn(imp::Stdio::Inherit, true) + .map(Child::from_inner) + .and_then(|mut p| p.wait()) } } @@ -835,11 +862,15 @@ impl fmt::Debug for Command { } impl AsInner for Command { - fn as_inner(&self) -> &imp::Command { &self.inner } + fn as_inner(&self) -> &imp::Command { + &self.inner + } } impl AsInnerMut for Command { - fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner } + fn as_inner_mut(&mut self) -> &mut imp::Command { + &mut self.inner + } } /// The output of a finished process. @@ -871,17 +902,16 @@ pub struct Output { #[stable(feature = "process_output_debug", since = "1.7.0")] impl fmt::Debug for Output { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - let stdout_utf8 = str::from_utf8(&self.stdout); let stdout_debug: &dyn fmt::Debug = match stdout_utf8 { Ok(ref str) => str, - Err(_) => &self.stdout + Err(_) => &self.stdout, }; let stderr_utf8 = str::from_utf8(&self.stderr); let stderr_debug: &dyn fmt::Debug = match stderr_utf8 { Ok(ref str) => str, - Err(_) => &self.stderr + Err(_) => &self.stderr, }; fmt.debug_struct("Output") @@ -943,7 +973,9 @@ impl Stdio { /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH"); /// ``` #[stable(feature = "process", since = "1.0.0")] - pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) } + pub fn piped() -> Stdio { + Stdio(imp::Stdio::MakePipe) + } /// The child inherits from the corresponding parent descriptor. /// @@ -980,7 +1012,9 @@ impl Stdio { /// io::stdout().write_all(&output.stdout).unwrap(); /// ``` #[stable(feature = "process", since = "1.0.0")] - pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) } + pub fn inherit() -> Stdio { + Stdio(imp::Stdio::Inherit) + } /// This stream will be ignored. This is the equivalent of attaching the /// stream to `/dev/null` @@ -1017,7 +1051,9 @@ impl Stdio { /// // Ignores any piped-in input /// ``` #[stable(feature = "process", since = "1.0.0")] - pub fn null() -> Stdio { Stdio(imp::Stdio::Null) } + pub fn null() -> Stdio { + Stdio(imp::Stdio::Null) + } } impl FromInner for Stdio { @@ -1217,7 +1253,9 @@ impl ExitStatus { } impl AsInner for ExitStatus { - fn as_inner(&self) -> &imp::ExitStatus { &self.0 } + fn as_inner(&self) -> &imp::ExitStatus { + &self.0 + } } impl FromInner for ExitStatus { @@ -1449,11 +1487,7 @@ impl Child { } let status = self.wait()?; - Ok(Output { - status, - stdout, - stderr, - }) + Ok(Output { status, stdout, stderr }) } } @@ -1604,8 +1638,9 @@ pub fn id() -> u32 { #[cfg_attr(not(test), lang = "termination")] #[unstable(feature = "termination_trait_lib", issue = "43301")] #[rustc_on_unimplemented( - message="`main` has invalid return type `{Self}`", - label="`main` can only return types that implement `{Termination}`")] + message = "`main` has invalid return type `{Self}`", + label = "`main` can only return types that implement `{Termination}`" +)] pub trait Termination { /// Is called to get the representation of the value as status code. /// This status code is returned to the operating system. @@ -1615,7 +1650,9 @@ pub trait Termination { #[unstable(feature = "termination_trait_lib", issue = "43301")] impl Termination for () { #[inline] - fn report(self) -> i32 { ExitCode::SUCCESS.report() } + fn report(self) -> i32 { + ExitCode::SUCCESS.report() + } } #[unstable(feature = "termination_trait_lib", issue = "43301")] @@ -1630,7 +1667,9 @@ impl Termination for Result<(), E> { #[unstable(feature = "termination_trait_lib", issue = "43301")] impl Termination for ! { - fn report(self) -> i32 { self } + fn report(self) -> i32 { + self + } } #[unstable(feature = "termination_trait_lib", issue = "43301")] @@ -1654,9 +1693,9 @@ impl Termination for ExitCode { mod tests { use crate::io::prelude::*; + use super::{Command, Output, Stdio}; use crate::io::ErrorKind; use crate::str; - use super::{Command, Output, Stdio}; // FIXME(#10380) these tests should not all be ignored on android. @@ -1702,15 +1741,12 @@ mod tests { fn signal_reported_right() { use crate::os::unix::process::ExitStatusExt; - let mut p = Command::new("/bin/sh") - .arg("-c").arg("read a") - .stdin(Stdio::piped()) - .spawn().unwrap(); + let mut p = + Command::new("/bin/sh").arg("-c").arg("read a").stdin(Stdio::piped()).spawn().unwrap(); p.kill().unwrap(); match p.wait().unwrap().signal() { - Some(9) => {}, - result => panic!("not terminated by signal 9 (instead, {:?})", - result), + Some(9) => {} + result => panic!("not terminated by signal 9 (instead, {:?})", result), } } @@ -1743,9 +1779,7 @@ mod tests { #[cfg_attr(any(windows, target_os = "android", target_os = "vxworks"), ignore)] fn set_current_dir_works() { let mut cmd = Command::new("/bin/sh"); - cmd.arg("-c").arg("pwd") - .current_dir("/") - .stdout(Stdio::piped()); + cmd.arg("-c").arg("pwd").current_dir("/").stdout(Stdio::piped()); assert_eq!(run_output(cmd), "/\n"); } @@ -1753,10 +1787,12 @@ mod tests { #[cfg_attr(any(windows, target_os = "android", target_os = "vxworks"), ignore)] fn stdin_works() { let mut p = Command::new("/bin/sh") - .arg("-c").arg("read line; echo $line") - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn().unwrap(); + .arg("-c") + .arg("read line; echo $line") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap(); drop(p.stdin.take()); let mut out = String::new(); @@ -1787,19 +1823,18 @@ mod tests { fn test_process_output_fail_to_start() { match Command::new("/no-binary-by-this-name-should-exist").output() { Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound), - Ok(..) => panic!() + Ok(..) => panic!(), } } #[test] #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)] fn test_process_output_output() { - let Output {status, stdout, stderr} - = if cfg!(target_os = "windows") { - Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap() - } else { - Command::new("echo").arg("hello").output().unwrap() - }; + let Output { status, stdout, stderr } = if cfg!(target_os = "windows") { + Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap() + } else { + Command::new("echo").arg("hello").output().unwrap() + }; let output_str = str::from_utf8(&stdout).unwrap(); assert!(status.success()); @@ -1810,12 +1845,11 @@ mod tests { #[test] #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)] fn test_process_output_error() { - let Output {status, stdout, stderr} - = if cfg!(target_os = "windows") { - Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap() - } else { - Command::new("mkdir").arg("./").output().unwrap() - }; + let Output { status, stdout, stderr } = if cfg!(target_os = "windows") { + Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap() + } else { + Command::new("mkdir").arg("./").output().unwrap() + }; assert!(status.code() == Some(1)); assert_eq!(stdout, Vec::new()); @@ -1854,7 +1888,7 @@ mod tests { Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap() }; - let Output {status, stdout, stderr} = prog.wait_with_output().unwrap(); + let Output { status, stdout, stderr } = prog.wait_with_output().unwrap(); let output_str = str::from_utf8(&stdout).unwrap(); assert!(status.success()); @@ -1862,11 +1896,11 @@ mod tests { assert_eq!(stderr, Vec::new()); } - #[cfg(all(unix, not(target_os="android")))] + #[cfg(all(unix, not(target_os = "android")))] pub fn env_cmd() -> Command { Command::new("env") } - #[cfg(target_os="android")] + #[cfg(target_os = "android")] pub fn env_cmd() -> Command { let mut cmd = Command::new("/system/bin/sh"); cmd.arg("-c").arg("set"); @@ -1897,8 +1931,11 @@ mod tests { let result = cmd.output().unwrap(); let output = String::from_utf8_lossy(&result.stdout).to_string(); - assert!(output.contains("RUN_TEST_NEW_ENV=123"), - "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output); + assert!( + output.contains("RUN_TEST_NEW_ENV=123"), + "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", + output + ); } #[test] @@ -1907,8 +1944,11 @@ mod tests { let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap(); let output = String::from_utf8_lossy(&result.stdout).to_string(); - assert!(output.contains("RUN_TEST_NEW_ENV=123"), - "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output); + assert!( + output.contains("RUN_TEST_NEW_ENV=123"), + "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", + output + ); } #[test] @@ -1927,10 +1967,16 @@ mod tests { let output = String::from_utf8_lossy(&result.stdout).to_string(); - assert!(output.contains("RUN_TEST_NEW_ENV1=123"), - "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", output); - assert!(output.contains("RUN_TEST_NEW_ENV2=456"), - "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", output); + assert!( + output.contains("RUN_TEST_NEW_ENV1=123"), + "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", + output + ); + assert!( + output.contains("RUN_TEST_NEW_ENV2=456"), + "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", + output + ); } // Regression tests for #30858. @@ -2005,8 +2051,11 @@ mod tests { extern "system" { fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL; - fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD, - dwContinueStatus: DWORD) -> BOOL; + fn ContinueDebugEvent( + dwProcessId: DWORD, + dwThreadId: DWORD, + dwContinueStatus: DWORD, + ) -> BOOL; } const DEBUG_PROCESS: DWORD = 1; @@ -2015,15 +2064,12 @@ mod tests { let mut child = Command::new("cmd") .creation_flags(DEBUG_PROCESS) - .stdin(Stdio::piped()).spawn().unwrap(); + .stdin(Stdio::piped()) + .spawn() + .unwrap(); child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap(); let mut events = 0; - let mut event = DEBUG_EVENT { - event_code: 0, - process_id: 0, - thread_id: 0, - _junk: [0; 164], - }; + let mut event = DEBUG_EVENT { event_code: 0, process_id: 0, thread_id: 0, _junk: [0; 164] }; loop { if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 { panic!("WaitForDebugEvent failed!"); @@ -2034,9 +2080,10 @@ mod tests { break; } - if unsafe { ContinueDebugEvent(event.process_id, - event.thread_id, - DBG_EXCEPTION_NOT_HANDLED) } == 0 { + if unsafe { + ContinueDebugEvent(event.process_id, event.thread_id, DBG_EXCEPTION_NOT_HANDLED) + } == 0 + { panic!("ContinueDebugEvent failed!"); } } diff --git a/src/libstd/rt.rs b/src/libstd/rt.rs index 63e35d5ed919a..1ed984509d27c 100644 --- a/src/libstd/rt.rs +++ b/src/libstd/rt.rs @@ -6,21 +6,25 @@ //! and should be considered as private implementation details for the //! time being. -#![unstable(feature = "rt", - reason = "this public module should not exist and is highly likely \ - to disappear", - issue = "0")] +#![unstable( + feature = "rt", + reason = "this public module should not exist and is highly likely \ + to disappear", + issue = "0" +)] #![doc(hidden)] - // Re-export some of our utilities which are expected by other crates. pub use crate::panicking::{begin_panic, begin_panic_fmt, update_panic_count}; // To reduce the generated code of the new `lang_start`, this function is doing // the real work. #[cfg(not(test))] -fn lang_start_internal(main: &(dyn Fn() -> i32 + Sync + crate::panic::RefUnwindSafe), - argc: isize, argv: *const *const u8) -> isize { +fn lang_start_internal( + main: &(dyn Fn() -> i32 + Sync + crate::panic::RefUnwindSafe), + argc: isize, + argv: *const *const u8, +) -> isize { use crate::panic; use crate::sys; use crate::sys_common; @@ -55,8 +59,10 @@ fn lang_start_internal(main: &(dyn Fn() -> i32 + Sync + crate::panic::RefUnwindS #[cfg(not(test))] #[lang = "start"] -fn lang_start - (main: fn() -> T, argc: isize, argv: *const *const u8) -> isize -{ +fn lang_start( + main: fn() -> T, + argc: isize, + argv: *const *const u8, +) -> isize { lang_start_internal(&move || main().report(), argc, argv) } diff --git a/src/libstd/sync/barrier.rs b/src/libstd/sync/barrier.rs index 23ba63a61098d..eddbdff257a99 100644 --- a/src/libstd/sync/barrier.rs +++ b/src/libstd/sync/barrier.rs @@ -1,5 +1,5 @@ use crate::fmt; -use crate::sync::{Mutex, Condvar}; +use crate::sync::{Condvar, Mutex}; /// A barrier enables multiple threads to synchronize the beginning /// of some computation. @@ -82,10 +82,7 @@ impl Barrier { #[stable(feature = "rust1", since = "1.0.0")] pub fn new(n: usize) -> Barrier { Barrier { - lock: Mutex::new(BarrierState { - count: 0, - generation_id: 0, - }), + lock: Mutex::new(BarrierState { count: 0, generation_id: 0 }), cvar: Condvar::new(), num_threads: n, } @@ -135,8 +132,7 @@ impl Barrier { if lock.count < self.num_threads { // We need a while loop to guard against spurious wakeups. // http://en.wikipedia.org/wiki/Spurious_wakeup - while local_gen == lock.generation_id && - lock.count < self.num_threads { + while local_gen == lock.generation_id && lock.count < self.num_threads { lock = self.cvar.wait(lock).unwrap(); } BarrierWaitResult(false) @@ -152,9 +148,7 @@ impl Barrier { #[stable(feature = "std_debug", since = "1.16.0")] impl fmt::Debug for BarrierWaitResult { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("BarrierWaitResult") - .field("is_leader", &self.is_leader()) - .finish() + f.debug_struct("BarrierWaitResult").field("is_leader", &self.is_leader()).finish() } } @@ -176,13 +170,15 @@ impl BarrierWaitResult { /// println!("{:?}", barrier_wait_result.is_leader()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn is_leader(&self) -> bool { self.0 } + pub fn is_leader(&self) -> bool { + self.0 + } } #[cfg(test)] mod tests { - use crate::sync::{Arc, Barrier}; use crate::sync::mpsc::{channel, TryRecvError}; + use crate::sync::{Arc, Barrier}; use crate::thread; #[test] @@ -196,7 +192,7 @@ mod tests { for _ in 0..N - 1 { let c = barrier.clone(); let tx = tx.clone(); - thread::spawn(move|| { + thread::spawn(move || { tx.send(c.wait().is_leader()).unwrap(); }); } diff --git a/src/libstd/sync/mpsc/blocking.rs b/src/libstd/sync/mpsc/blocking.rs index 6eacfaec25358..d34de6a4fac3e 100644 --- a/src/libstd/sync/mpsc/blocking.rs +++ b/src/libstd/sync/mpsc/blocking.rs @@ -1,9 +1,9 @@ //! Generic support for building blocking abstractions. -use crate::thread::{self, Thread}; +use crate::mem; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sync::Arc; -use crate::mem; +use crate::thread::{self, Thread}; use crate::time::Instant; struct Inner { @@ -28,16 +28,9 @@ impl !Send for WaitToken {} impl !Sync for WaitToken {} pub fn tokens() -> (WaitToken, SignalToken) { - let inner = Arc::new(Inner { - thread: thread::current(), - woken: AtomicBool::new(false), - }); - let wait_token = WaitToken { - inner: inner.clone(), - }; - let signal_token = SignalToken { - inner, - }; + let inner = Arc::new(Inner { thread: thread::current(), woken: AtomicBool::new(false) }); + let wait_token = WaitToken { inner: inner.clone() }; + let signal_token = SignalToken { inner }; (wait_token, signal_token) } diff --git a/src/libstd/sync/mpsc/cache_aligned.rs b/src/libstd/sync/mpsc/cache_aligned.rs index b14a9e5d61bd9..b0842144328a8 100644 --- a/src/libstd/sync/mpsc/cache_aligned.rs +++ b/src/libstd/sync/mpsc/cache_aligned.rs @@ -8,16 +8,16 @@ pub(super) struct Aligner; pub(super) struct CacheAligned(pub T, pub Aligner); impl Deref for CacheAligned { - type Target = T; - fn deref(&self) -> &Self::Target { - &self.0 - } + type Target = T; + fn deref(&self) -> &Self::Target { + &self.0 + } } impl DerefMut for CacheAligned { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } } impl CacheAligned { diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index c2884a28f3ccd..2831bbcb88d2e 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -269,20 +269,20 @@ // And now that you've seen all the races that I found and attempted to fix, // here's the code for you to find some more! -use crate::sync::Arc; +use crate::cell::UnsafeCell; use crate::error; use crate::fmt; use crate::mem; -use crate::cell::UnsafeCell; +use crate::sync::Arc; use crate::time::{Duration, Instant}; mod blocking; +mod mpsc_queue; mod oneshot; mod shared; +mod spsc_queue; mod stream; mod sync; -mod mpsc_queue; -mod spsc_queue; mod cache_aligned; @@ -322,10 +322,10 @@ pub struct Receiver { // The receiver port can be sent from place to place, so long as it // is not used to receive non-sendable things. #[stable(feature = "rust1", since = "1.0.0")] -unsafe impl Send for Receiver { } +unsafe impl Send for Receiver {} #[stable(feature = "rust1", since = "1.0.0")] -impl !Sync for Receiver { } +impl !Sync for Receiver {} /// An iterator over messages on a [`Receiver`], created by [`iter`]. /// @@ -359,7 +359,7 @@ impl !Sync for Receiver { } #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] pub struct Iter<'a, T: 'a> { - rx: &'a Receiver + rx: &'a Receiver, } /// An iterator that attempts to yield all pending values for a [`Receiver`], @@ -404,7 +404,7 @@ pub struct Iter<'a, T: 'a> { #[stable(feature = "receiver_try_iter", since = "1.15.0")] #[derive(Debug)] pub struct TryIter<'a, T: 'a> { - rx: &'a Receiver + rx: &'a Receiver, } /// An owning iterator over messages on a [`Receiver`], @@ -439,7 +439,7 @@ pub struct TryIter<'a, T: 'a> { #[stable(feature = "receiver_into_iter", since = "1.1.0")] #[derive(Debug)] pub struct IntoIter { - rx: Receiver + rx: Receiver, } /// The sending-half of Rust's asynchronous [`channel`] type. This half can only be @@ -482,10 +482,10 @@ pub struct Sender { // The send port can be sent from place to place, so long as it // is not used to send non-sendable things. #[stable(feature = "rust1", since = "1.0.0")] -unsafe impl Send for Sender { } +unsafe impl Send for Sender {} #[stable(feature = "rust1", since = "1.0.0")] -impl !Sync for Sender { } +impl !Sync for Sender {} /// The sending-half of Rust's synchronous [`sync_channel`] type. /// @@ -772,9 +772,7 @@ pub fn sync_channel(bound: usize) -> (SyncSender, Receiver) { impl Sender { fn new(inner: Flavor) -> Sender { - Sender { - inner: UnsafeCell::new(inner), - } + Sender { inner: UnsafeCell::new(inner) } } /// Attempts to send a value on this channel, returning it back if it could @@ -856,8 +854,7 @@ impl Clone for Sender { let guard = a.postinit_lock(); let rx = Receiver::new(Flavor::Shared(a.clone())); let sleeper = match p.upgrade(rx) { - oneshot::UpSuccess | - oneshot::UpDisconnected => None, + oneshot::UpSuccess | oneshot::UpDisconnected => None, oneshot::UpWoke(task) => Some(task), }; a.inherit_blocker(sleeper, guard); @@ -870,8 +867,7 @@ impl Clone for Sender { let guard = a.postinit_lock(); let rx = Receiver::new(Flavor::Shared(a.clone())); let sleeper = match p.upgrade(rx) { - stream::UpSuccess | - stream::UpDisconnected => None, + stream::UpSuccess | stream::UpDisconnected => None, stream::UpWoke(task) => Some(task), }; a.inherit_blocker(sleeper, guard); @@ -1078,48 +1074,31 @@ impl Receiver { pub fn try_recv(&self) -> Result { loop { let new_port = match *unsafe { self.inner() } { - Flavor::Oneshot(ref p) => { - match p.try_recv() { - Ok(t) => return Ok(t), - Err(oneshot::Empty) => return Err(TryRecvError::Empty), - Err(oneshot::Disconnected) => { - return Err(TryRecvError::Disconnected) - } - Err(oneshot::Upgraded(rx)) => rx, - } - } - Flavor::Stream(ref p) => { - match p.try_recv() { - Ok(t) => return Ok(t), - Err(stream::Empty) => return Err(TryRecvError::Empty), - Err(stream::Disconnected) => { - return Err(TryRecvError::Disconnected) - } - Err(stream::Upgraded(rx)) => rx, - } - } - Flavor::Shared(ref p) => { - match p.try_recv() { - Ok(t) => return Ok(t), - Err(shared::Empty) => return Err(TryRecvError::Empty), - Err(shared::Disconnected) => { - return Err(TryRecvError::Disconnected) - } - } - } - Flavor::Sync(ref p) => { - match p.try_recv() { - Ok(t) => return Ok(t), - Err(sync::Empty) => return Err(TryRecvError::Empty), - Err(sync::Disconnected) => { - return Err(TryRecvError::Disconnected) - } - } - } + Flavor::Oneshot(ref p) => match p.try_recv() { + Ok(t) => return Ok(t), + Err(oneshot::Empty) => return Err(TryRecvError::Empty), + Err(oneshot::Disconnected) => return Err(TryRecvError::Disconnected), + Err(oneshot::Upgraded(rx)) => rx, + }, + Flavor::Stream(ref p) => match p.try_recv() { + Ok(t) => return Ok(t), + Err(stream::Empty) => return Err(TryRecvError::Empty), + Err(stream::Disconnected) => return Err(TryRecvError::Disconnected), + Err(stream::Upgraded(rx)) => rx, + }, + Flavor::Shared(ref p) => match p.try_recv() { + Ok(t) => return Ok(t), + Err(shared::Empty) => return Err(TryRecvError::Empty), + Err(shared::Disconnected) => return Err(TryRecvError::Disconnected), + }, + Flavor::Sync(ref p) => match p.try_recv() { + Ok(t) => return Ok(t), + Err(sync::Empty) => return Err(TryRecvError::Empty), + Err(sync::Disconnected) => return Err(TryRecvError::Disconnected), + }, }; unsafe { - mem::swap(self.inner_mut(), - new_port.inner_mut()); + mem::swap(self.inner_mut(), new_port.inner_mut()); } } } @@ -1185,29 +1164,23 @@ impl Receiver { pub fn recv(&self) -> Result { loop { let new_port = match *unsafe { self.inner() } { - Flavor::Oneshot(ref p) => { - match p.recv(None) { - Ok(t) => return Ok(t), - Err(oneshot::Disconnected) => return Err(RecvError), - Err(oneshot::Upgraded(rx)) => rx, - Err(oneshot::Empty) => unreachable!(), - } - } - Flavor::Stream(ref p) => { - match p.recv(None) { - Ok(t) => return Ok(t), - Err(stream::Disconnected) => return Err(RecvError), - Err(stream::Upgraded(rx)) => rx, - Err(stream::Empty) => unreachable!(), - } - } - Flavor::Shared(ref p) => { - match p.recv(None) { - Ok(t) => return Ok(t), - Err(shared::Disconnected) => return Err(RecvError), - Err(shared::Empty) => unreachable!(), - } - } + Flavor::Oneshot(ref p) => match p.recv(None) { + Ok(t) => return Ok(t), + Err(oneshot::Disconnected) => return Err(RecvError), + Err(oneshot::Upgraded(rx)) => rx, + Err(oneshot::Empty) => unreachable!(), + }, + Flavor::Stream(ref p) => match p.recv(None) { + Ok(t) => return Ok(t), + Err(stream::Disconnected) => return Err(RecvError), + Err(stream::Upgraded(rx)) => rx, + Err(stream::Empty) => unreachable!(), + }, + Flavor::Shared(ref p) => match p.recv(None) { + Ok(t) => return Ok(t), + Err(shared::Disconnected) => return Err(RecvError), + Err(shared::Empty) => unreachable!(), + }, Flavor::Sync(ref p) => return p.recv(None).map_err(|_| RecvError), }; unsafe { @@ -1383,36 +1356,28 @@ impl Receiver { loop { let port_or_empty = match *unsafe { self.inner() } { - Flavor::Oneshot(ref p) => { - match p.recv(Some(deadline)) { - Ok(t) => return Ok(t), - Err(oneshot::Disconnected) => return Err(Disconnected), - Err(oneshot::Upgraded(rx)) => Some(rx), - Err(oneshot::Empty) => None, - } - } - Flavor::Stream(ref p) => { - match p.recv(Some(deadline)) { - Ok(t) => return Ok(t), - Err(stream::Disconnected) => return Err(Disconnected), - Err(stream::Upgraded(rx)) => Some(rx), - Err(stream::Empty) => None, - } - } - Flavor::Shared(ref p) => { - match p.recv(Some(deadline)) { - Ok(t) => return Ok(t), - Err(shared::Disconnected) => return Err(Disconnected), - Err(shared::Empty) => None, - } - } - Flavor::Sync(ref p) => { - match p.recv(Some(deadline)) { - Ok(t) => return Ok(t), - Err(sync::Disconnected) => return Err(Disconnected), - Err(sync::Empty) => None, - } - } + Flavor::Oneshot(ref p) => match p.recv(Some(deadline)) { + Ok(t) => return Ok(t), + Err(oneshot::Disconnected) => return Err(Disconnected), + Err(oneshot::Upgraded(rx)) => Some(rx), + Err(oneshot::Empty) => None, + }, + Flavor::Stream(ref p) => match p.recv(Some(deadline)) { + Ok(t) => return Ok(t), + Err(stream::Disconnected) => return Err(Disconnected), + Err(stream::Upgraded(rx)) => Some(rx), + Err(stream::Empty) => None, + }, + Flavor::Shared(ref p) => match p.recv(Some(deadline)) { + Ok(t) => return Ok(t), + Err(shared::Disconnected) => return Err(Disconnected), + Err(shared::Empty) => None, + }, + Flavor::Sync(ref p) => match p.recv(Some(deadline)) { + Ok(t) => return Ok(t), + Err(sync::Disconnected) => return Err(Disconnected), + Err(sync::Empty) => None, + }, }; if let Some(new_port) = port_or_empty { @@ -1502,21 +1467,24 @@ impl Receiver { pub fn try_iter(&self) -> TryIter<'_, T> { TryIter { rx: self } } - } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> Iterator for Iter<'a, T> { type Item = T; - fn next(&mut self) -> Option { self.rx.recv().ok() } + fn next(&mut self) -> Option { + self.rx.recv().ok() + } } #[stable(feature = "receiver_try_iter", since = "1.15.0")] impl<'a, T> Iterator for TryIter<'a, T> { type Item = T; - fn next(&mut self) -> Option { self.rx.try_recv().ok() } + fn next(&mut self) -> Option { + self.rx.try_recv().ok() + } } #[stable(feature = "receiver_into_iter", since = "1.1.0")] @@ -1524,17 +1492,21 @@ impl<'a, T> IntoIterator for &'a Receiver { type Item = T; type IntoIter = Iter<'a, T>; - fn into_iter(self) -> Iter<'a, T> { self.iter() } + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } } #[stable(feature = "receiver_into_iter", since = "1.1.0")] impl Iterator for IntoIter { type Item = T; - fn next(&mut self) -> Option { self.rx.recv().ok() } + fn next(&mut self) -> Option { + self.rx.recv().ok() + } } #[stable(feature = "receiver_into_iter", since = "1.1.0")] -impl IntoIterator for Receiver { +impl IntoIterator for Receiver { type Item = T; type IntoIter = IntoIter; @@ -1597,27 +1569,18 @@ impl fmt::Debug for TrySendError { impl fmt::Display for TrySendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - TrySendError::Full(..) => { - "sending on a full channel".fmt(f) - } - TrySendError::Disconnected(..) => { - "sending on a closed channel".fmt(f) - } + TrySendError::Full(..) => "sending on a full channel".fmt(f), + TrySendError::Disconnected(..) => "sending on a closed channel".fmt(f), } } } #[stable(feature = "rust1", since = "1.0.0")] impl error::Error for TrySendError { - fn description(&self) -> &str { match *self { - TrySendError::Full(..) => { - "sending on a full channel" - } - TrySendError::Disconnected(..) => { - "sending on a closed channel" - } + TrySendError::Full(..) => "sending on a full channel", + TrySendError::Disconnected(..) => "sending on a closed channel", } } } @@ -1640,7 +1603,6 @@ impl fmt::Display for RecvError { #[stable(feature = "rust1", since = "1.0.0")] impl error::Error for RecvError { - fn description(&self) -> &str { "receiving on a closed channel" } @@ -1650,27 +1612,18 @@ impl error::Error for RecvError { impl fmt::Display for TryRecvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - TryRecvError::Empty => { - "receiving on an empty channel".fmt(f) - } - TryRecvError::Disconnected => { - "receiving on a closed channel".fmt(f) - } + TryRecvError::Empty => "receiving on an empty channel".fmt(f), + TryRecvError::Disconnected => "receiving on a closed channel".fmt(f), } } } #[stable(feature = "rust1", since = "1.0.0")] impl error::Error for TryRecvError { - fn description(&self) -> &str { match *self { - TryRecvError::Empty => { - "receiving on an empty channel" - } - TryRecvError::Disconnected => { - "receiving on a closed channel" - } + TryRecvError::Empty => "receiving on an empty channel", + TryRecvError::Disconnected => "receiving on a closed channel", } } } @@ -1688,12 +1641,8 @@ impl From for TryRecvError { impl fmt::Display for RecvTimeoutError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - RecvTimeoutError::Timeout => { - "timed out waiting on channel".fmt(f) - } - RecvTimeoutError::Disconnected => { - "channel is empty and sending half is closed".fmt(f) - } + RecvTimeoutError::Timeout => "timed out waiting on channel".fmt(f), + RecvTimeoutError::Disconnected => "channel is empty and sending half is closed".fmt(f), } } } @@ -1702,12 +1651,8 @@ impl fmt::Display for RecvTimeoutError { impl error::Error for RecvTimeoutError { fn description(&self) -> &str { match *self { - RecvTimeoutError::Timeout => { - "timed out waiting on channel" - } - RecvTimeoutError::Disconnected => { - "channel is empty and sending half is closed" - } + RecvTimeoutError::Timeout => "timed out waiting on channel", + RecvTimeoutError::Disconnected => "channel is empty and sending half is closed", } } } @@ -1769,7 +1714,7 @@ mod tests { #[test] fn smoke_threads() { let (tx, rx) = channel::(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { tx.send(1).unwrap(); }); assert_eq!(rx.recv().unwrap(), 1); @@ -1801,7 +1746,7 @@ mod tests { #[test] fn port_gone_concurrent() { let (tx, rx) = channel::(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { rx.recv().unwrap(); }); while tx.send(1).is_ok() {} @@ -1811,7 +1756,7 @@ mod tests { fn port_gone_concurrent_shared() { let (tx, rx) = channel::(); let tx2 = tx.clone(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { rx.recv().unwrap(); }); while tx.send(1).is_ok() && tx2.send(1).is_ok() {} @@ -1836,7 +1781,7 @@ mod tests { #[test] fn chan_gone_concurrent() { let (tx, rx) = channel::(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { tx.send(1).unwrap(); tx.send(1).unwrap(); }); @@ -1846,8 +1791,10 @@ mod tests { #[test] fn stress() { let (tx, rx) = channel::(); - let t = thread::spawn(move|| { - for _ in 0..10000 { tx.send(1).unwrap(); } + let t = thread::spawn(move || { + for _ in 0..10000 { + tx.send(1).unwrap(); + } }); for _ in 0..10000 { assert_eq!(rx.recv().unwrap(), 1); @@ -1861,7 +1808,7 @@ mod tests { const NTHREADS: u32 = 8; let (tx, rx) = channel::(); - let t = thread::spawn(move|| { + let t = thread::spawn(move || { for _ in 0..AMT * NTHREADS { assert_eq!(rx.recv().unwrap(), 1); } @@ -1873,8 +1820,10 @@ mod tests { for _ in 0..NTHREADS { let tx = tx.clone(); - thread::spawn(move|| { - for _ in 0..AMT { tx.send(1).unwrap(); } + thread::spawn(move || { + for _ in 0..AMT { + tx.send(1).unwrap(); + } }); } drop(tx); @@ -1885,14 +1834,14 @@ mod tests { fn send_from_outside_runtime() { let (tx1, rx1) = channel::<()>(); let (tx2, rx2) = channel::(); - let t1 = thread::spawn(move|| { + let t1 = thread::spawn(move || { tx1.send(()).unwrap(); for _ in 0..40 { assert_eq!(rx2.recv().unwrap(), 1); } }); rx1.recv().unwrap(); - let t2 = thread::spawn(move|| { + let t2 = thread::spawn(move || { for _ in 0..40 { tx2.send(1).unwrap(); } @@ -1904,7 +1853,7 @@ mod tests { #[test] fn recv_from_outside_runtime() { let (tx, rx) = channel::(); - let t = thread::spawn(move|| { + let t = thread::spawn(move || { for _ in 0..40 { assert_eq!(rx.recv().unwrap(), 1); } @@ -1919,11 +1868,11 @@ mod tests { fn no_runtime() { let (tx1, rx1) = channel::(); let (tx2, rx2) = channel::(); - let t1 = thread::spawn(move|| { + let t1 = thread::spawn(move || { assert_eq!(rx1.recv().unwrap(), 1); tx2.send(2).unwrap(); }); - let t2 = thread::spawn(move|| { + let t2 = thread::spawn(move || { tx1.send(1).unwrap(); assert_eq!(rx2.recv().unwrap(), 2); }); @@ -1956,11 +1905,12 @@ mod tests { #[test] fn oneshot_single_thread_recv_chan_close() { // Receiving on a closed chan will panic - let res = thread::spawn(move|| { + let res = thread::spawn(move || { let (tx, rx) = channel::(); drop(tx); rx.recv().unwrap(); - }).join(); + }) + .join(); // What is our res? assert!(res.is_err()); } @@ -2025,7 +1975,7 @@ mod tests { #[test] fn oneshot_multi_task_recv_then_send() { let (tx, rx) = channel::>(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { assert!(*rx.recv().unwrap() == 10); }); @@ -2035,12 +1985,13 @@ mod tests { #[test] fn oneshot_multi_task_recv_then_close() { let (tx, rx) = channel::>(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { drop(tx); }); - let res = thread::spawn(move|| { + let res = thread::spawn(move || { assert!(*rx.recv().unwrap() == 10); - }).join(); + }) + .join(); assert!(res.is_err()); } @@ -2048,7 +1999,7 @@ mod tests { fn oneshot_multi_thread_close_stress() { for _ in 0..stress_factor() { let (tx, rx) = channel::(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { drop(rx); }); drop(tx); @@ -2059,12 +2010,13 @@ mod tests { fn oneshot_multi_thread_send_close_stress() { for _ in 0..stress_factor() { let (tx, rx) = channel::(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { drop(rx); }); - let _ = thread::spawn(move|| { + let _ = thread::spawn(move || { tx.send(1).unwrap(); - }).join(); + }) + .join(); } } @@ -2072,14 +2024,15 @@ mod tests { fn oneshot_multi_thread_recv_close_stress() { for _ in 0..stress_factor() { let (tx, rx) = channel::(); - thread::spawn(move|| { - let res = thread::spawn(move|| { + thread::spawn(move || { + let res = thread::spawn(move || { rx.recv().unwrap(); - }).join(); + }) + .join(); assert!(res.is_err()); }); - let _t = thread::spawn(move|| { - thread::spawn(move|| { + let _t = thread::spawn(move || { + thread::spawn(move || { drop(tx); }); }); @@ -2090,7 +2043,7 @@ mod tests { fn oneshot_multi_thread_send_recv_stress() { for _ in 0..stress_factor() { let (tx, rx) = channel::>(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { tx.send(box 10).unwrap(); }); assert!(*rx.recv().unwrap() == 10); @@ -2106,18 +2059,22 @@ mod tests { recv(rx, 0); fn send(tx: Sender>, i: i32) { - if i == 10 { return } + if i == 10 { + return; + } - thread::spawn(move|| { + thread::spawn(move || { tx.send(box i).unwrap(); send(tx, i + 1); }); } fn recv(rx: Receiver>, i: i32) { - if i == 10 { return } + if i == 10 { + return; + } - thread::spawn(move|| { + thread::spawn(move || { assert!(*rx.recv().unwrap() == i); recv(rx, i + 1); }); @@ -2214,9 +2171,8 @@ mod tests { #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31 fn very_long_recv_timeout_wont_panic() { let (tx, rx) = channel::<()>(); - let join_handle = thread::spawn(move || { - rx.recv_timeout(Duration::from_secs(u64::max_value())) - }); + let join_handle = + thread::spawn(move || rx.recv_timeout(Duration::from_secs(u64::max_value()))); thread::sleep(Duration::from_secs(1)); assert!(tx.send(()).is_ok()); assert_eq!(join_handle.join().unwrap(), Ok(())); @@ -2226,8 +2182,12 @@ mod tests { fn recv_a_lot() { // Regression test that we don't run out of stack in scheduler context let (tx, rx) = channel(); - for _ in 0..10000 { tx.send(()).unwrap(); } - for _ in 0..10000 { rx.recv().unwrap(); } + for _ in 0..10000 { + tx.send(()).unwrap(); + } + for _ in 0..10000 { + rx.recv().unwrap(); + } } #[test] @@ -2237,12 +2197,14 @@ mod tests { let total = 5; for _ in 0..total { let tx = tx.clone(); - thread::spawn(move|| { + thread::spawn(move || { tx.send(()).unwrap(); }); } - for _ in 0..total { rx.recv().unwrap(); } + for _ in 0..total { + rx.recv().unwrap(); + } assert_eq!(rx.recv_timeout(Duration::from_millis(1)), Err(RecvTimeoutError::Timeout)); tx.send(()).unwrap(); @@ -2255,7 +2217,7 @@ mod tests { let total = stress_factor() + 100; for _ in 0..total { let tx = tx.clone(); - thread::spawn(move|| { + thread::spawn(move || { tx.send(()).unwrap(); }); } @@ -2270,7 +2232,7 @@ mod tests { let (tx, rx) = channel::(); let (total_tx, total_rx) = channel::(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut acc = 0; for x in rx.iter() { acc += x; @@ -2290,7 +2252,7 @@ mod tests { let (tx, rx) = channel::(); let (count_tx, count_rx) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut count = 0; for x in rx.iter() { if count >= 3 { @@ -2316,7 +2278,7 @@ mod tests { let (response_tx, response_rx) = channel(); // Request `x`s until we have `6`. - let t = thread::spawn(move|| { + let t = thread::spawn(move || { let mut count = 0; loop { for x in response_rx.try_iter() { @@ -2341,11 +2303,11 @@ mod tests { #[test] fn test_recv_into_iter_owned() { let mut iter = { - let (tx, rx) = channel::(); - tx.send(1).unwrap(); - tx.send(2).unwrap(); + let (tx, rx) = channel::(); + tx.send(1).unwrap(); + tx.send(2).unwrap(); - rx.into_iter() + rx.into_iter() }; assert_eq!(iter.next().unwrap(), 1); assert_eq!(iter.next().unwrap(), 2); @@ -2369,7 +2331,7 @@ mod tests { let (tx1, rx1) = channel::(); let (tx2, rx2) = channel::<()>(); let (tx3, rx3) = channel::<()>(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { rx2.recv().unwrap(); tx1.send(1).unwrap(); tx3.send(()).unwrap(); @@ -2394,13 +2356,15 @@ mod tests { fn destroy_upgraded_shared_port_when_sender_still_active() { let (tx, rx) = channel(); let (tx2, rx2) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { rx.recv().unwrap(); // wait on a oneshot - drop(rx); // destroy a shared + drop(rx); // destroy a shared tx2.send(()).unwrap(); }); // make sure the other thread has gone to sleep - for _ in 0..5000 { thread::yield_now(); } + for _ in 0..5000 { + thread::yield_now(); + } // upgrade to a shared chan and send a message let t = tx.clone(); @@ -2468,7 +2432,7 @@ mod sync_tests { #[test] fn smoke_threads() { let (tx, rx) = sync_channel::(0); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { tx.send(1).unwrap(); }); assert_eq!(rx.recv().unwrap(), 1); @@ -2493,7 +2457,7 @@ mod sync_tests { #[test] fn port_gone_concurrent() { let (tx, rx) = sync_channel::(0); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { rx.recv().unwrap(); }); while tx.send(1).is_ok() {} @@ -2503,7 +2467,7 @@ mod sync_tests { fn port_gone_concurrent_shared() { let (tx, rx) = sync_channel::(0); let tx2 = tx.clone(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { rx.recv().unwrap(); }); while tx.send(1).is_ok() && tx2.send(1).is_ok() {} @@ -2528,7 +2492,7 @@ mod sync_tests { #[test] fn chan_gone_concurrent() { let (tx, rx) = sync_channel::(0); - thread::spawn(move|| { + thread::spawn(move || { tx.send(1).unwrap(); tx.send(1).unwrap(); }); @@ -2538,8 +2502,10 @@ mod sync_tests { #[test] fn stress() { let (tx, rx) = sync_channel::(0); - thread::spawn(move|| { - for _ in 0..10000 { tx.send(1).unwrap(); } + thread::spawn(move || { + for _ in 0..10000 { + tx.send(1).unwrap(); + } }); for _ in 0..10000 { assert_eq!(rx.recv().unwrap(), 1); @@ -2551,8 +2517,10 @@ mod sync_tests { fn stress_recv_timeout_two_threads() { let (tx, rx) = sync_channel::(0); - thread::spawn(move|| { - for _ in 0..10000 { tx.send(1).unwrap(); } + thread::spawn(move || { + for _ in 0..10000 { + tx.send(1).unwrap(); + } }); let mut recv_count = 0; @@ -2561,7 +2529,7 @@ mod sync_tests { Ok(v) => { assert_eq!(v, 1); recv_count += 1; - }, + } Err(RecvTimeoutError::Timeout) => continue, Err(RecvTimeoutError::Disconnected) => break, } @@ -2578,14 +2546,14 @@ mod sync_tests { let (tx, rx) = sync_channel::(0); let (dtx, drx) = sync_channel::<()>(0); - thread::spawn(move|| { + thread::spawn(move || { let mut recv_count = 0; loop { match rx.recv_timeout(Duration::from_millis(10)) { Ok(v) => { assert_eq!(v, 1); recv_count += 1; - }, + } Err(RecvTimeoutError::Timeout) => continue, Err(RecvTimeoutError::Disconnected) => break, } @@ -2599,8 +2567,10 @@ mod sync_tests { for _ in 0..NTHREADS { let tx = tx.clone(); - thread::spawn(move|| { - for _ in 0..AMT { tx.send(1).unwrap(); } + thread::spawn(move || { + for _ in 0..AMT { + tx.send(1).unwrap(); + } }); } @@ -2616,7 +2586,7 @@ mod sync_tests { let (tx, rx) = sync_channel::(0); let (dtx, drx) = sync_channel::<()>(0); - thread::spawn(move|| { + thread::spawn(move || { for _ in 0..AMT * NTHREADS { assert_eq!(rx.recv().unwrap(), 1); } @@ -2629,8 +2599,10 @@ mod sync_tests { for _ in 0..NTHREADS { let tx = tx.clone(); - thread::spawn(move|| { - for _ in 0..AMT { tx.send(1).unwrap(); } + thread::spawn(move || { + for _ in 0..AMT { + tx.send(1).unwrap(); + } }); } drop(tx); @@ -2662,11 +2634,12 @@ mod sync_tests { #[test] fn oneshot_single_thread_recv_chan_close() { // Receiving on a closed chan will panic - let res = thread::spawn(move|| { + let res = thread::spawn(move || { let (tx, rx) = sync_channel::(0); drop(tx); rx.recv().unwrap(); - }).join(); + }) + .join(); // What is our res? assert!(res.is_err()); } @@ -2746,7 +2719,7 @@ mod sync_tests { #[test] fn oneshot_multi_task_recv_then_send() { let (tx, rx) = sync_channel::>(0); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { assert!(*rx.recv().unwrap() == 10); }); @@ -2756,12 +2729,13 @@ mod sync_tests { #[test] fn oneshot_multi_task_recv_then_close() { let (tx, rx) = sync_channel::>(0); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { drop(tx); }); - let res = thread::spawn(move|| { + let res = thread::spawn(move || { assert!(*rx.recv().unwrap() == 10); - }).join(); + }) + .join(); assert!(res.is_err()); } @@ -2769,7 +2743,7 @@ mod sync_tests { fn oneshot_multi_thread_close_stress() { for _ in 0..stress_factor() { let (tx, rx) = sync_channel::(0); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { drop(rx); }); drop(tx); @@ -2780,12 +2754,13 @@ mod sync_tests { fn oneshot_multi_thread_send_close_stress() { for _ in 0..stress_factor() { let (tx, rx) = sync_channel::(0); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { drop(rx); }); let _ = thread::spawn(move || { tx.send(1).unwrap(); - }).join(); + }) + .join(); } } @@ -2793,14 +2768,15 @@ mod sync_tests { fn oneshot_multi_thread_recv_close_stress() { for _ in 0..stress_factor() { let (tx, rx) = sync_channel::(0); - let _t = thread::spawn(move|| { - let res = thread::spawn(move|| { + let _t = thread::spawn(move || { + let res = thread::spawn(move || { rx.recv().unwrap(); - }).join(); + }) + .join(); assert!(res.is_err()); }); - let _t = thread::spawn(move|| { - thread::spawn(move|| { + let _t = thread::spawn(move || { + thread::spawn(move || { drop(tx); }); }); @@ -2811,7 +2787,7 @@ mod sync_tests { fn oneshot_multi_thread_send_recv_stress() { for _ in 0..stress_factor() { let (tx, rx) = sync_channel::>(0); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { tx.send(box 10).unwrap(); }); assert!(*rx.recv().unwrap() == 10); @@ -2827,18 +2803,22 @@ mod sync_tests { recv(rx, 0); fn send(tx: SyncSender>, i: i32) { - if i == 10 { return } + if i == 10 { + return; + } - thread::spawn(move|| { + thread::spawn(move || { tx.send(box i).unwrap(); send(tx, i + 1); }); } fn recv(rx: Receiver>, i: i32) { - if i == 10 { return } + if i == 10 { + return; + } - thread::spawn(move|| { + thread::spawn(move || { assert!(*rx.recv().unwrap() == i); recv(rx, i + 1); }); @@ -2850,8 +2830,12 @@ mod sync_tests { fn recv_a_lot() { // Regression test that we don't run out of stack in scheduler context let (tx, rx) = sync_channel(10000); - for _ in 0..10000 { tx.send(()).unwrap(); } - for _ in 0..10000 { rx.recv().unwrap(); } + for _ in 0..10000 { + tx.send(()).unwrap(); + } + for _ in 0..10000 { + rx.recv().unwrap(); + } } #[test] @@ -2860,7 +2844,7 @@ mod sync_tests { let total = stress_factor() + 100; for _ in 0..total { let tx = tx.clone(); - thread::spawn(move|| { + thread::spawn(move || { tx.send(()).unwrap(); }); } @@ -2875,7 +2859,7 @@ mod sync_tests { let (tx, rx) = sync_channel::(0); let (total_tx, total_rx) = sync_channel::(0); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut acc = 0; for x in rx.iter() { acc += x; @@ -2895,7 +2879,7 @@ mod sync_tests { let (tx, rx) = sync_channel::(0); let (count_tx, count_rx) = sync_channel(0); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { let mut count = 0; for x in rx.iter() { if count >= 3 { @@ -2920,7 +2904,7 @@ mod sync_tests { let (tx1, rx1) = sync_channel::(1); let (tx2, rx2) = sync_channel::<()>(1); let (tx3, rx3) = sync_channel::<()>(1); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { rx2.recv().unwrap(); tx1.send(1).unwrap(); tx3.send(()).unwrap(); @@ -2945,13 +2929,15 @@ mod sync_tests { fn destroy_upgraded_shared_port_when_sender_still_active() { let (tx, rx) = sync_channel::<()>(0); let (tx2, rx2) = sync_channel::<()>(0); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { rx.recv().unwrap(); // wait on a oneshot - drop(rx); // destroy a shared + drop(rx); // destroy a shared tx2.send(()).unwrap(); }); // make sure the other thread has gone to sleep - for _ in 0..5000 { thread::yield_now(); } + for _ in 0..5000 { + thread::yield_now(); + } // upgrade to a shared chan and send a message let t = tx.clone(); @@ -2965,14 +2951,18 @@ mod sync_tests { #[test] fn send1() { let (tx, rx) = sync_channel::(0); - let _t = thread::spawn(move|| { rx.recv().unwrap(); }); + let _t = thread::spawn(move || { + rx.recv().unwrap(); + }); assert_eq!(tx.send(1), Ok(())); } #[test] fn send2() { let (tx, rx) = sync_channel::(0); - let _t = thread::spawn(move|| { drop(rx); }); + let _t = thread::spawn(move || { + drop(rx); + }); assert!(tx.send(1).is_err()); } @@ -2980,7 +2970,9 @@ mod sync_tests { fn send3() { let (tx, rx) = sync_channel::(1); assert_eq!(tx.send(1), Ok(())); - let _t =thread::spawn(move|| { drop(rx); }); + let _t = thread::spawn(move || { + drop(rx); + }); assert!(tx.send(1).is_err()); } @@ -2990,11 +2982,11 @@ mod sync_tests { let tx2 = tx.clone(); let (done, donerx) = channel(); let done2 = done.clone(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { assert!(tx.send(1).is_err()); done.send(()).unwrap(); }); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { assert!(tx2.send(2).is_err()); done2.send(()).unwrap(); }); @@ -3030,7 +3022,7 @@ mod sync_tests { let (tx1, rx1) = sync_channel::<()>(3); let (tx2, rx2) = sync_channel::<()>(3); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { rx1.recv().unwrap(); tx2.try_send(()).unwrap(); }); diff --git a/src/libstd/sync/mpsc/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs index 8f5681b97f44d..6e7a7be4430ed 100644 --- a/src/libstd/sync/mpsc/mpsc_queue.rs +++ b/src/libstd/sync/mpsc/mpsc_queue.rs @@ -13,8 +13,8 @@ pub use self::PopResult::*; -use core::ptr; use core::cell::UnsafeCell; +use core::ptr; use crate::boxed::Box; use crate::sync::atomic::{AtomicPtr, Ordering}; @@ -45,15 +45,12 @@ pub struct Queue { tail: UnsafeCell<*mut Node>, } -unsafe impl Send for Queue { } -unsafe impl Sync for Queue { } +unsafe impl Send for Queue {} +unsafe impl Sync for Queue {} impl Node { unsafe fn new(v: Option) -> *mut Node { - Box::into_raw(box Node { - next: AtomicPtr::new(ptr::null_mut()), - value: v, - }) + Box::into_raw(box Node { next: AtomicPtr::new(ptr::null_mut()), value: v }) } } @@ -62,10 +59,7 @@ impl Queue { /// one consumer. pub fn new() -> Queue { let stub = unsafe { Node::new(None) }; - Queue { - head: AtomicPtr::new(stub), - tail: UnsafeCell::new(stub), - } + Queue { head: AtomicPtr::new(stub), tail: UnsafeCell::new(stub) } } /// Pushes a new value onto this queue. @@ -101,7 +95,7 @@ impl Queue { return Data(ret); } - if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent} + if self.head.load(Ordering::Acquire) == tail { Empty } else { Inconsistent } } } } @@ -121,7 +115,7 @@ impl Drop for Queue { #[cfg(all(test, not(target_os = "emscripten")))] mod tests { - use super::{Queue, Data, Empty, Inconsistent}; + use super::{Data, Empty, Inconsistent, Queue}; use crate::sync::mpsc::channel; use crate::sync::Arc; use crate::thread; @@ -140,7 +134,7 @@ mod tests { let q = Queue::new(); match q.pop() { Empty => {} - Inconsistent | Data(..) => panic!() + Inconsistent | Data(..) => panic!(), } let (tx, rx) = channel(); let q = Arc::new(q); @@ -148,7 +142,7 @@ mod tests { for _ in 0..nthreads { let tx = tx.clone(); let q = q.clone(); - thread::spawn(move|| { + thread::spawn(move || { for i in 0..nmsgs { q.push(i); } @@ -159,8 +153,8 @@ mod tests { let mut i = 0; while i < nthreads * nmsgs { match q.pop() { - Empty | Inconsistent => {}, - Data(_) => { i += 1 } + Empty | Inconsistent => {} + Data(_) => i += 1, } } drop(tx); diff --git a/src/libstd/sync/mpsc/oneshot.rs b/src/libstd/sync/mpsc/oneshot.rs index e7a5cc46b31a8..bbe77e7d0fb5c 100644 --- a/src/libstd/sync/mpsc/oneshot.rs +++ b/src/libstd/sync/mpsc/oneshot.rs @@ -21,22 +21,21 @@ /// consuming the port). This upgrade is then also stored in the shared packet. /// The one caveat to consider is that when a port sees a disconnected channel /// it must check for data because there is no "data plus upgrade" state. - pub use self::Failure::*; -pub use self::UpgradeResult::*; use self::MyUpgrade::*; +pub use self::UpgradeResult::*; -use crate::sync::mpsc::Receiver; -use crate::sync::mpsc::blocking::{self, SignalToken}; use crate::cell::UnsafeCell; use crate::ptr; use crate::sync::atomic::{AtomicUsize, Ordering}; +use crate::sync::mpsc::blocking::{self, SignalToken}; +use crate::sync::mpsc::Receiver; use crate::time::Instant; // Various states you can find a port in. -const EMPTY: usize = 0; // initial state: no data, no blocked receiver -const DATA: usize = 1; // data ready for receiver to take -const DISCONNECTED: usize = 2; // channel is disconnected OR upgraded +const EMPTY: usize = 0; // initial state: no data, no blocked receiver +const DATA: usize = 1; // data ready for receiver to take +const DISCONNECTED: usize = 2; // channel is disconnected OR upgraded // Any other value represents a pointer to a SignalToken value. The // protocol ensures that when the state moves *to* a pointer, // ownership of the token is given to the packet, and when the state @@ -178,21 +177,17 @@ impl Packet { // and an upgrade flags the channel as disconnected, so when we see // this we first need to check if there's data available and *then* // we go through and process the upgrade. - DISCONNECTED => { - match (&mut *self.data.get()).take() { - Some(data) => Ok(data), - None => { - match ptr::replace(self.upgrade.get(), SendUsed) { - SendUsed | NothingSent => Err(Disconnected), - GoUp(upgrade) => Err(Upgraded(upgrade)) - } - } - } - } + DISCONNECTED => match (&mut *self.data.get()).take() { + Some(data) => Ok(data), + None => match ptr::replace(self.upgrade.get(), SendUsed) { + SendUsed | NothingSent => Err(Disconnected), + GoUp(upgrade) => Err(Upgraded(upgrade)), + }, + }, // We are the sole receiver; there cannot be a blocking // receiver already. - _ => unreachable!() + _ => unreachable!(), } } } @@ -217,10 +212,13 @@ impl Packet { // If the other end is already disconnected, then we failed the // upgrade. Be sure to trash the port we were given. - DISCONNECTED => { ptr::replace(self.upgrade.get(), prev); UpDisconnected } + DISCONNECTED => { + ptr::replace(self.upgrade.get(), prev); + UpDisconnected + } // If someone's waiting, we gotta wake them up - ptr => UpWoke(SignalToken::cast_from_usize(ptr)) + ptr => UpWoke(SignalToken::cast_from_usize(ptr)), } } } @@ -232,7 +230,7 @@ impl Packet { // If someone's waiting, we gotta wake them up ptr => unsafe { SignalToken::cast_from_usize(ptr).signal(); - } + }, } } @@ -246,10 +244,12 @@ impl Packet { // There's data on the channel, so make sure we destroy it promptly. // This is why not using an arc is a little difficult (need the box // to stay valid while we take the data). - DATA => unsafe { (&mut *self.data.get()).take().unwrap(); }, + DATA => unsafe { + (&mut *self.data.get()).take().unwrap(); + }, // We're the only ones that can block on this port - _ => unreachable!() + _ => unreachable!(), } } @@ -265,13 +265,11 @@ impl Packet { let state = match self.state.load(Ordering::SeqCst) { // Each of these states means that no further activity will happen // with regard to abortion selection - s @ EMPTY | - s @ DATA | - s @ DISCONNECTED => s, + s @ EMPTY | s @ DATA | s @ DISCONNECTED => s, // If we've got a blocked thread, then use an atomic to gain ownership // of it (may fail) - ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst) + ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst), }; // Now that we've got ownership of our state, figure out what to do @@ -302,7 +300,7 @@ impl Packet { ptr => unsafe { drop(SignalToken::cast_from_usize(ptr)); Ok(false) - } + }, } } } diff --git a/src/libstd/sync/mpsc/shared.rs b/src/libstd/sync/mpsc/shared.rs index dbcdcdac93268..2b0393573fdc4 100644 --- a/src/libstd/sync/mpsc/shared.rs +++ b/src/libstd/sync/mpsc/shared.rs @@ -7,7 +7,6 @@ /// High level implementation details can be found in the comment of the parent /// module. You'll also note that the implementation of the shared and stream /// channels are quite similar, and this is no coincidence! - pub use self::Failure::*; use self::StartResult::*; @@ -17,7 +16,7 @@ use core::isize; use crate::cell::UnsafeCell; use crate::ptr; -use crate::sync::atomic::{AtomicUsize, AtomicIsize, AtomicBool, Ordering}; +use crate::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering}; use crate::sync::mpsc::blocking::{self, SignalToken}; use crate::sync::mpsc::mpsc_queue as mpsc; use crate::sync::{Mutex, MutexGuard}; @@ -34,9 +33,9 @@ const MAX_STEALS: isize = 1 << 20; pub struct Packet { queue: mpsc::Queue, - cnt: AtomicIsize, // How many items are on this channel + cnt: AtomicIsize, // How many items are on this channel steals: UnsafeCell, // How many times has a port received without blocking? - to_wake: AtomicUsize, // SignalToken for wake up + to_wake: AtomicUsize, // SignalToken for wake up // The number of channels which are currently using this packet. channels: AtomicUsize, @@ -92,9 +91,7 @@ impl Packet { // threads in select(). // // This can only be called at channel-creation time - pub fn inherit_blocker(&self, - token: Option, - guard: MutexGuard<'_, ()>) { + pub fn inherit_blocker(&self, token: Option, guard: MutexGuard<'_, ()>) { token.map(|token| { assert_eq!(self.cnt.load(Ordering::SeqCst), 0); assert_eq!(self.to_wake.load(Ordering::SeqCst), 0); @@ -119,7 +116,9 @@ impl Packet { // To offset this bad increment, we initially set the steal count to // -1. You'll find some special code in abort_selection() as well to // ensure that this -1 steal count doesn't escape too far. - unsafe { *self.steals.get() = -1; } + unsafe { + *self.steals.get() = -1; + } }); // When the shared packet is constructed, we grabbed this lock. The @@ -132,7 +131,9 @@ impl Packet { pub fn send(&self, t: T) -> Result<(), T> { // See Port::drop for what's going on - if self.port_dropped.load(Ordering::SeqCst) { return Err(t) } + if self.port_dropped.load(Ordering::SeqCst) { + return Err(t); + } // Note that the multiple sender case is a little trickier // semantically than the single sender case. The logic for @@ -160,7 +161,7 @@ impl Packet { // received". Once we get beyond this check, we have permanently // entered the realm of "this may be received" if self.cnt.load(Ordering::SeqCst) < DISCONNECTED + FUDGE { - return Err(t) + return Err(t); } self.queue.push(t); @@ -197,7 +198,7 @@ impl Packet { // maybe we're done, if we're not the last ones // here, then we need to go try again. if self.sender_drain.fetch_sub(1, Ordering::SeqCst) == 1 { - break + break; } } @@ -236,7 +237,10 @@ impl Packet { } match self.try_recv() { - data @ Ok(..) => unsafe { *self.steals.get() -= 1; data }, + data @ Ok(..) => unsafe { + *self.steals.get() -= 1; + data + }, data => data, } } @@ -252,12 +256,16 @@ impl Packet { let steals = ptr::replace(self.steals.get(), 0); match self.cnt.fetch_sub(1 + steals, Ordering::SeqCst) { - DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); } + DISCONNECTED => { + self.cnt.store(DISCONNECTED, Ordering::SeqCst); + } // If we factor in our steals and notice that the channel has no // data, we successfully sleep n => { assert!(n >= 0); - if n - steals <= 0 { return Installed } + if n - steals <= 0 { + return Installed; + } } } @@ -290,7 +298,10 @@ impl Packet { loop { thread::yield_now(); match self.queue.pop() { - mpsc::Data(t) => { data = t; break } + mpsc::Data(t) => { + data = t; + break; + } mpsc::Empty => panic!("inconsistent => empty"), mpsc::Inconsistent => {} } @@ -361,9 +372,13 @@ impl Packet { } match self.cnt.swap(DISCONNECTED, Ordering::SeqCst) { - -1 => { self.take_to_wake().signal(); } + -1 => { + self.take_to_wake().signal(); + } DISCONNECTED => {} - n => { assert!(n >= 0); } + n => { + assert!(n >= 0); + } } } @@ -380,7 +395,9 @@ impl Packet { // control of this thread. loop { match self.queue.pop() { - mpsc::Data(..) => { steals += 1; } + mpsc::Data(..) => { + steals += 1; + } mpsc::Empty | mpsc::Inconsistent => break, } } @@ -406,7 +423,7 @@ impl Packet { self.cnt.store(DISCONNECTED, Ordering::SeqCst); DISCONNECTED } - n => n + n => n, } } @@ -432,7 +449,7 @@ impl Packet { // positive. let steals = { let cnt = self.cnt.load(Ordering::SeqCst); - if cnt < 0 && cnt != DISCONNECTED {-cnt} else {0} + if cnt < 0 && cnt != DISCONNECTED { -cnt } else { 0 } }; let prev = self.bump(steals + 1); diff --git a/src/libstd/sync/mpsc/spsc_queue.rs b/src/libstd/sync/mpsc/spsc_queue.rs index 0edb1c24e8016..c51aa7619db77 100644 --- a/src/libstd/sync/mpsc/spsc_queue.rs +++ b/src/libstd/sync/mpsc/spsc_queue.rs @@ -6,8 +6,8 @@ // http://www.1024cores.net/home/lock-free-algorithms/queues/unbounded-spsc-queue -use core::ptr; use core::cell::UnsafeCell; +use core::ptr; use crate::boxed::Box; use crate::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; @@ -19,16 +19,16 @@ struct Node { // FIXME: this could be an uninitialized T if we're careful enough, and // that would reduce memory usage (and be a bit faster). // is it worth it? - value: Option, // nullable for re-use of nodes - cached: bool, // This node goes into the node cache - next: AtomicPtr>, // next node in the queue + value: Option, // nullable for re-use of nodes + cached: bool, // This node goes into the node cache + next: AtomicPtr>, // next node in the queue } /// The single-producer single-consumer queue. This structure is not cloneable, /// but it can be safely shared in an Arc if it is guaranteed that there /// is only one popper and one pusher touching the queue at any one point in /// time. -pub struct Queue { +pub struct Queue { // consumer fields consumer: CacheAligned>, @@ -38,9 +38,9 @@ pub struct Queue { struct Consumer { tail: UnsafeCell<*mut Node>, // where to pop from - tail_prev: AtomicPtr>, // where to pop from - cache_bound: usize, // maximum cache size - cached_nodes: AtomicUsize, // number of nodes marked as cachable + tail_prev: AtomicPtr>, // where to pop from + cache_bound: usize, // maximum cache size + cached_nodes: AtomicUsize, // number of nodes marked as cachable addition: Addition, } @@ -51,9 +51,9 @@ struct Producer { addition: Addition, } -unsafe impl Send for Queue { } +unsafe impl Send for Queue {} -unsafe impl Sync for Queue { } +unsafe impl Sync for Queue {} impl Node { fn new() -> *mut Node { @@ -66,7 +66,6 @@ impl Node { } impl Queue { - /// Creates a new queue. With given additional elements in the producer and /// consumer portions of the queue. /// @@ -107,13 +106,13 @@ impl Queue Queue Queue Queue> = Box::from_raw(tail); @@ -234,9 +235,9 @@ impl Drop for Queue { assert_eq!(&*vec, &[1]); - }, - None => unreachable!() + } + None => unreachable!(), } match queue.pop() { Some(vec) => { assert_eq!(&*vec, &[1]); - }, - None => unreachable!() + } + None => unreachable!(), } } } @@ -316,7 +317,7 @@ mod tests { let (tx, rx) = channel(); let q2 = q.clone(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { for _ in 0..100000 { loop { match q2.pop() { diff --git a/src/libstd/sync/mpsc/stream.rs b/src/libstd/sync/mpsc/stream.rs index 4087728276179..2e3270e81fcd0 100644 --- a/src/libstd/sync/mpsc/stream.rs +++ b/src/libstd/sync/mpsc/stream.rs @@ -6,10 +6,9 @@ /// /// High level implementation details can be found in the comment of the parent /// module. - pub use self::Failure::*; -pub use self::UpgradeResult::*; use self::Message::*; +pub use self::UpgradeResult::*; use core::cmp; use core::isize; @@ -19,10 +18,10 @@ use crate::ptr; use crate::thread; use crate::time::Instant; -use crate::sync::atomic::{AtomicIsize, AtomicUsize, Ordering, AtomicBool}; -use crate::sync::mpsc::Receiver; +use crate::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering}; use crate::sync::mpsc::blocking::{self, SignalToken}; use crate::sync::mpsc::spsc_queue as spsc; +use crate::sync::mpsc::Receiver; const DISCONNECTED: isize = isize::MIN; #[cfg(test)] @@ -36,17 +35,16 @@ pub struct Packet { } struct ProducerAddition { - cnt: AtomicIsize, // How many items are on this channel + cnt: AtomicIsize, // How many items are on this channel to_wake: AtomicUsize, // SignalToken for the blocked thread to wake up port_dropped: AtomicBool, // flag if the channel has been destroyed. } struct ConsumerAddition { - steals: UnsafeCell, // How many times has a port received without blocking? + steals: UnsafeCell, // How many times has a port received without blocking? } - pub enum Failure { Empty, Disconnected, @@ -69,18 +67,18 @@ enum Message { impl Packet { pub fn new() -> Packet { Packet { - queue: unsafe { spsc::Queue::with_additions( - 128, - ProducerAddition { - cnt: AtomicIsize::new(0), - to_wake: AtomicUsize::new(0), - - port_dropped: AtomicBool::new(false), - }, - ConsumerAddition { - steals: UnsafeCell::new(0), - } - )}, + queue: unsafe { + spsc::Queue::with_additions( + 128, + ProducerAddition { + cnt: AtomicIsize::new(0), + to_wake: AtomicUsize::new(0), + + port_dropped: AtomicBool::new(false), + }, + ConsumerAddition { steals: UnsafeCell::new(0) }, + ) + }, } } @@ -88,11 +86,15 @@ impl Packet { // If the other port has deterministically gone away, then definitely // must return the data back up the stack. Otherwise, the data is // considered as being sent. - if self.queue.producer_addition().port_dropped.load(Ordering::SeqCst) { return Err(t) } + if self.queue.producer_addition().port_dropped.load(Ordering::SeqCst) { + return Err(t); + } match self.do_send(Data(t)) { - UpSuccess | UpDisconnected => {}, - UpWoke(token) => { token.signal(); } + UpSuccess | UpDisconnected => {} + UpWoke(token) => { + token.signal(); + } } Ok(()) } @@ -101,7 +103,7 @@ impl Packet { // If the port has gone away, then there's no need to proceed any // further. if self.queue.producer_addition().port_dropped.load(Ordering::SeqCst) { - return UpDisconnected + return UpDisconnected; } self.do_send(GoUp(up)) @@ -136,7 +138,10 @@ impl Packet { // Otherwise we just sent some data on a non-waiting queue, so just // make sure the world is sane and carry on! - n => { assert!(n >= 0); UpSuccess } + n => { + assert!(n >= 0); + UpSuccess + } } } @@ -166,7 +171,9 @@ impl Packet { // data, we successfully sleep n => { assert!(n >= 0); - if n - steals <= 0 { return Ok(()) } + if n - steals <= 0 { + return Ok(()); + } } } @@ -199,8 +206,7 @@ impl Packet { // Messages which actually popped from the queue shouldn't count as // a steal, so offset the decrement here (we already have our // "steal" factored into the channel count above). - data @ Ok(..) | - data @ Err(Upgraded(..)) => unsafe { + data @ Ok(..) | data @ Err(Upgraded(..)) => unsafe { *self.queue.consumer_addition().steals.get() -= 1; data }, @@ -226,8 +232,10 @@ impl Packet { if *self.queue.consumer_addition().steals.get() > MAX_STEALS { match self.queue.producer_addition().cnt.swap(0, Ordering::SeqCst) { DISCONNECTED => { - self.queue.producer_addition().cnt.store( - DISCONNECTED, Ordering::SeqCst); + self.queue + .producer_addition() + .cnt + .store(DISCONNECTED, Ordering::SeqCst); } n => { let m = cmp::min(n, *self.queue.consumer_addition().steals.get()); @@ -259,13 +267,11 @@ impl Packet { // We can ignore steals because the other end is // disconnected and we'll never need to really factor in our // steals again. - _ => { - match self.queue.pop() { - Some(Data(t)) => Ok(t), - Some(GoUp(up)) => Err(Upgraded(up)), - None => Err(Disconnected), - } - } + _ => match self.queue.pop() { + Some(Data(t)) => Ok(t), + Some(GoUp(up)) => Err(Upgraded(up)), + None => Err(Disconnected), + }, } } } @@ -275,9 +281,13 @@ impl Packet { // Dropping a channel is pretty simple, we just flag it as disconnected // and then wakeup a blocker if there is one. match self.queue.producer_addition().cnt.swap(DISCONNECTED, Ordering::SeqCst) { - -1 => { self.take_to_wake().signal(); } + -1 => { + self.take_to_wake().signal(); + } DISCONNECTED => {} - n => { assert!(n >= 0); } + n => { + assert!(n >= 0); + } } } @@ -314,10 +324,15 @@ impl Packet { let mut steals = unsafe { *self.queue.consumer_addition().steals.get() }; while { let cnt = self.queue.producer_addition().cnt.compare_and_swap( - steals, DISCONNECTED, Ordering::SeqCst); + steals, + DISCONNECTED, + Ordering::SeqCst, + ); cnt != DISCONNECTED && cnt != steals } { - while let Some(_) = self.queue.pop() { steals += 1; } + while let Some(_) = self.queue.pop() { + steals += 1; + } } // At this point in time, we have gated all future senders from sending, @@ -338,13 +353,12 @@ impl Packet { self.queue.producer_addition().cnt.store(DISCONNECTED, Ordering::SeqCst); DISCONNECTED } - n => n + n => n, } } // Removes a previous thread from being blocked in this port - pub fn abort_selection(&self, - was_upgrade: bool) -> Result> { + pub fn abort_selection(&self, was_upgrade: bool) -> Result> { // If we're aborting selection after upgrading from a oneshot, then // we're guarantee that no one is waiting. The only way that we could // have seen the upgrade is if data was actually sent on the channel @@ -361,7 +375,7 @@ impl Packet { if was_upgrade { assert_eq!(unsafe { *self.queue.consumer_addition().steals.get() }, 0); assert_eq!(self.queue.producer_addition().to_wake.load(Ordering::SeqCst), 0); - return Ok(true) + return Ok(true); } // We want to make sure that the count on the channel goes non-negative, @@ -416,12 +430,10 @@ impl Packet { // upgraded port. if has_data { match self.queue.peek() { - Some(&mut GoUp(..)) => { - match self.queue.pop() { - Some(GoUp(port)) => Err(port), - _ => unreachable!(), - } - } + Some(&mut GoUp(..)) => match self.queue.pop() { + Some(GoUp(port)) => Err(port), + _ => unreachable!(), + }, _ => Ok(true), } } else { diff --git a/src/libstd/sync/mpsc/sync.rs b/src/libstd/sync/mpsc/sync.rs index 58a4b716afb81..79e868171546b 100644 --- a/src/libstd/sync/mpsc/sync.rs +++ b/src/libstd/sync/mpsc/sync.rs @@ -1,3 +1,4 @@ +use self::Blocker::*; /// Synchronous channels/ports /// /// This channel implementation differs significantly from the asynchronous @@ -22,17 +23,15 @@ /// implementation shares almost all code for the buffered and unbuffered cases /// of a synchronous channel. There are a few branches for the unbuffered case, /// but they're mostly just relevant to blocking senders. - pub use self::Failure::*; -use self::Blocker::*; use core::intrinsics::abort; use core::isize; use core::mem; use core::ptr; -use crate::sync::atomic::{Ordering, AtomicUsize}; -use crate::sync::mpsc::blocking::{self, WaitToken, SignalToken}; +use crate::sync::atomic::{AtomicUsize, Ordering}; +use crate::sync::mpsc::blocking::{self, SignalToken, WaitToken}; use crate::sync::{Mutex, MutexGuard}; use crate::time::Instant; @@ -46,9 +45,9 @@ pub struct Packet { lock: Mutex>, } -unsafe impl Send for Packet { } +unsafe impl Send for Packet {} -unsafe impl Sync for Packet { } +unsafe impl Sync for Packet {} struct State { disconnected: bool, // Is the channel disconnected yet? @@ -72,7 +71,7 @@ unsafe impl Send for State {} enum Blocker { BlockedSender(SignalToken), BlockedReceiver(SignalToken), - NoneBlocked + NoneBlocked, } /// Simple queue for threading threads together. Nodes are stack-allocated, so @@ -104,35 +103,35 @@ pub enum Failure { /// Atomically blocks the current thread, placing it into `slot`, unlocking `lock` /// in the meantime. This re-locks the mutex upon returning. -fn wait<'a, 'b, T>(lock: &'a Mutex>, - mut guard: MutexGuard<'b, State>, - f: fn(SignalToken) -> Blocker) - -> MutexGuard<'a, State> -{ +fn wait<'a, 'b, T>( + lock: &'a Mutex>, + mut guard: MutexGuard<'b, State>, + f: fn(SignalToken) -> Blocker, +) -> MutexGuard<'a, State> { let (wait_token, signal_token) = blocking::tokens(); match mem::replace(&mut guard.blocker, f(signal_token)) { NoneBlocked => {} _ => unreachable!(), } - drop(guard); // unlock - wait_token.wait(); // block + drop(guard); // unlock + wait_token.wait(); // block lock.lock().unwrap() // relock } /// Same as wait, but waiting at most until `deadline`. -fn wait_timeout_receiver<'a, 'b, T>(lock: &'a Mutex>, - deadline: Instant, - mut guard: MutexGuard<'b, State>, - success: &mut bool) - -> MutexGuard<'a, State> -{ +fn wait_timeout_receiver<'a, 'b, T>( + lock: &'a Mutex>, + deadline: Instant, + mut guard: MutexGuard<'b, State>, + success: &mut bool, +) -> MutexGuard<'a, State> { let (wait_token, signal_token) = blocking::tokens(); match mem::replace(&mut guard.blocker, BlockedReceiver(signal_token)) { NoneBlocked => {} _ => unreachable!(), } - drop(guard); // unlock - *success = wait_token.wait_max_until(deadline); // block + drop(guard); // unlock + *success = wait_token.wait_max_until(deadline); // block let mut new_guard = lock.lock().unwrap(); // relock if !*success { abort_selection(&mut new_guard); @@ -147,7 +146,10 @@ fn abort_selection(guard: &mut MutexGuard<'_, State>) -> bool { guard.blocker = BlockedSender(token); true } - BlockedReceiver(token) => { drop(token); false } + BlockedReceiver(token) => { + drop(token); + false + } } } @@ -168,12 +170,9 @@ impl Packet { blocker: NoneBlocked, cap: capacity, canceled: None, - queue: Queue { - head: ptr::null_mut(), - tail: ptr::null_mut(), - }, + queue: Queue { head: ptr::null_mut(), tail: ptr::null_mut() }, buf: Buffer { - buf: (0..capacity + if capacity == 0 {1} else {0}).map(|_| None).collect(), + buf: (0..capacity + if capacity == 0 { 1 } else { 0 }).map(|_| None).collect(), start: 0, size: 0, }, @@ -200,7 +199,9 @@ impl Packet { pub fn send(&self, t: T) -> Result<(), T> { let mut guard = self.acquire_send_slot(); - if guard.disconnected { return Err(t) } + if guard.disconnected { + return Err(t); + } guard.buf.enqueue(t); match mem::replace(&mut guard.blocker, NoneBlocked) { @@ -213,14 +214,17 @@ impl Packet { assert!(guard.canceled.is_none()); guard.canceled = Some(unsafe { mem::transmute(&mut canceled) }); let mut guard = wait(&self.lock, guard, BlockedSender); - if canceled {Err(guard.buf.dequeue())} else {Ok(())} + if canceled { Err(guard.buf.dequeue()) } else { Ok(()) } } // success, we buffered some data NoneBlocked => Ok(()), // success, someone's about to receive our buffered data. - BlockedReceiver(token) => { wakeup(token, guard); Ok(()) } + BlockedReceiver(token) => { + wakeup(token, guard); + Ok(()) + } BlockedSender(..) => panic!("lolwut"), } @@ -271,10 +275,8 @@ impl Packet { // while loop because we're the only receiver. if !guard.disconnected && guard.buf.size() == 0 { if let Some(deadline) = deadline { - guard = wait_timeout_receiver(&self.lock, - deadline, - guard, - &mut woke_up_after_waiting); + guard = + wait_timeout_receiver(&self.lock, deadline, guard, &mut woke_up_after_waiting); } else { guard = wait(&self.lock, guard, BlockedReceiver); woke_up_after_waiting = true; @@ -290,7 +292,9 @@ impl Packet { // Pick up the data, wake up our neighbors, and carry on assert!(guard.buf.size() > 0 || (deadline.is_some() && !woke_up_after_waiting)); - if guard.buf.size() == 0 { return Err(Empty); } + if guard.buf.size() == 0 { + return Err(Empty); + } let ret = guard.buf.dequeue(); self.wakeup_senders(woke_up_after_waiting, guard); @@ -301,8 +305,12 @@ impl Packet { let mut guard = self.lock.lock().unwrap(); // Easy cases first - if guard.disconnected && guard.buf.size() == 0 { return Err(Disconnected) } - if guard.buf.size() == 0 { return Err(Empty) } + if guard.disconnected && guard.buf.size() == 0 { + return Err(Disconnected); + } + if guard.buf.size() == 0 { + return Err(Empty); + } // Be sure to wake up neighbors let ret = Ok(guard.buf.dequeue()); @@ -357,12 +365,14 @@ impl Packet { // Only flag the channel as disconnected if we're the last channel match self.channels.fetch_sub(1, Ordering::SeqCst) { 1 => {} - _ => return + _ => return, } // Not much to do other than wake up a receiver if one's there let mut guard = self.lock.lock().unwrap(); - if guard.disconnected { return } + if guard.disconnected { + return; + } guard.disconnected = true; match mem::replace(&mut guard.blocker, NoneBlocked) { NoneBlocked => {} @@ -374,7 +384,9 @@ impl Packet { pub fn drop_port(&self) { let mut guard = self.lock.lock().unwrap(); - if guard.disconnected { return } + if guard.disconnected { + return; + } guard.disconnected = true; // If the capacity is 0, then the sender may want its data back after @@ -382,15 +394,9 @@ impl Packet { // the buffered data. As with many other portions of this code, this // needs to be careful to destroy the data *outside* of the lock to // prevent deadlock. - let _data = if guard.cap != 0 { - mem::take(&mut guard.buf.buf) - } else { - Vec::new() - }; - let mut queue = mem::replace(&mut guard.queue, Queue { - head: ptr::null_mut(), - tail: ptr::null_mut(), - }); + let _data = if guard.cap != 0 { mem::take(&mut guard.buf.buf) } else { Vec::new() }; + let mut queue = + mem::replace(&mut guard.queue, Queue { head: ptr::null_mut(), tail: ptr::null_mut() }); let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) { NoneBlocked => None, @@ -402,7 +408,9 @@ impl Packet { }; mem::drop(guard); - while let Some(token) = queue.dequeue() { token.signal(); } + while let Some(token) = queue.dequeue() { + token.signal(); + } waiter.map(|t| t.signal()); } } @@ -416,7 +424,6 @@ impl Drop for Packet { } } - //////////////////////////////////////////////////////////////////////////////// // Buffer, a simple ring buffer backed by Vec //////////////////////////////////////////////////////////////////////////////// @@ -437,8 +444,12 @@ impl Buffer { result.take().unwrap() } - fn size(&self) -> usize { self.size } - fn capacity(&self) -> usize { self.buf.len() } + fn size(&self) -> usize { + self.size + } + fn capacity(&self) -> usize { + self.buf.len() + } } //////////////////////////////////////////////////////////////////////////////// @@ -466,7 +477,7 @@ impl Queue { fn dequeue(&mut self) -> Option { if self.head.is_null() { - return None + return None; } let node = self.head; self.head = unsafe { (*node).next }; 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); diff --git a/src/libstd/sys_common/alloc.rs b/src/libstd/sys_common/alloc.rs index 1cfc7ed17f2e4..713b9949f6461 100644 --- a/src/libstd/sys_common/alloc.rs +++ b/src/libstd/sys_common/alloc.rs @@ -6,20 +6,24 @@ use crate::ptr; // The minimum alignment guaranteed by the architecture. This value is used to // add fast paths for low alignment values. -#[cfg(all(any(target_arch = "x86", - target_arch = "arm", - target_arch = "mips", - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "asmjs", - target_arch = "wasm32", - target_arch = "hexagon")))] +#[cfg(all(any( + target_arch = "x86", + target_arch = "arm", + target_arch = "mips", + target_arch = "powerpc", + target_arch = "powerpc64", + target_arch = "asmjs", + target_arch = "wasm32", + target_arch = "hexagon" +)))] pub const MIN_ALIGN: usize = 8; -#[cfg(all(any(target_arch = "x86_64", - target_arch = "aarch64", - target_arch = "mips64", - target_arch = "s390x", - target_arch = "sparc64")))] +#[cfg(all(any( + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "mips64", + target_arch = "s390x", + target_arch = "sparc64" +)))] pub const MIN_ALIGN: usize = 16; pub unsafe fn realloc_fallback( diff --git a/src/libstd/sys_common/bytestring.rs b/src/libstd/sys_common/bytestring.rs index 429ecf6281b3e..dccc3bc4a19a8 100644 --- a/src/libstd/sys_common/bytestring.rs +++ b/src/libstd/sys_common/bytestring.rs @@ -25,7 +25,7 @@ pub fn debug_fmt_bytestring(slice: &[u8], f: &mut Formatter<'_>) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::fmt::{Formatter, Result, Debug}; + use crate::fmt::{Debug, Formatter, Result}; #[test] fn smoke() { @@ -37,7 +37,7 @@ mod tests { } } - let input = b"\xF0hello,\tworld"; + let input = b"\xF0hello,\tworld"; let expected = r#""\xF0hello,\tworld""#; let output = format!("{:?}", Helper(input)); diff --git a/src/libstd/sys_common/fs.rs b/src/libstd/sys_common/fs.rs index 7152fcd215c9a..e30e8018a31fe 100644 --- a/src/libstd/sys_common/fs.rs +++ b/src/libstd/sys_common/fs.rs @@ -1,13 +1,15 @@ #![allow(dead_code)] // not used on all platforms -use crate::path::Path; use crate::fs; use crate::io::{self, Error, ErrorKind}; +use crate::path::Path; pub fn copy(from: &Path, to: &Path) -> io::Result { 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 = fs::File::open(from)?; @@ -21,11 +23,7 @@ pub fn copy(from: &Path, to: &Path) -> io::Result { pub fn remove_dir_all(path: &Path) -> io::Result<()> { let filetype = fs::symlink_metadata(path)?.file_type(); - if filetype.is_symlink() { - fs::remove_file(path) - } else { - remove_dir_all_recursive(path) - } + if filetype.is_symlink() { fs::remove_file(path) } else { remove_dir_all_recursive(path) } } fn remove_dir_all_recursive(path: &Path) -> io::Result<()> { diff --git a/src/libstd/sys_common/io.rs b/src/libstd/sys_common/io.rs index 8789abe55c3d0..7c1d98a5abd59 100644 --- a/src/libstd/sys_common/io.rs +++ b/src/libstd/sys_common/io.rs @@ -3,9 +3,9 @@ pub const DEFAULT_BUF_SIZE: usize = 8 * 1024; #[cfg(test)] #[allow(dead_code)] // not used on emscripten pub mod test { - use crate::path::{Path, PathBuf}; use crate::env; use crate::fs; + use crate::path::{Path, PathBuf}; use rand::RngCore; pub struct TempDir(PathBuf); diff --git a/src/libstd/sys_common/net.rs b/src/libstd/sys_common/net.rs index 391f670346f2a..9d40d9f0afd5c 100644 --- a/src/libstd/sys_common/net.rs +++ b/src/libstd/sys_common/net.rs @@ -1,79 +1,119 @@ use crate::cmp; +use crate::convert::{TryFrom, TryInto}; use crate::ffi::CString; use crate::fmt; use crate::io::{self, Error, ErrorKind, IoSlice, IoSliceMut}; use crate::mem; -use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr}; +use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; use crate::ptr; -use crate::sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t}; use crate::sys::net::netc as c; +use crate::sys::net::{cvt, cvt_gai, cvt_r, init, wrlen_t, Socket}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; -use crate::convert::{TryFrom, TryInto}; use libc::{c_int, c_void}; -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd", target_os = "netbsd", - target_os = "solaris", target_os = "haiku", target_os = "l4re"))] -use crate::sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP; -#[cfg(not(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd", target_os = "netbsd", - target_os = "solaris", target_os = "haiku", target_os = "l4re")))] +#[cfg(not(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris", + target_os = "haiku", + target_os = "l4re" +)))] use crate::sys::net::netc::IPV6_ADD_MEMBERSHIP; -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd", target_os = "netbsd", - target_os = "solaris", target_os = "haiku", target_os = "l4re"))] -use crate::sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP; -#[cfg(not(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd", target_os = "netbsd", - target_os = "solaris", target_os = "haiku", target_os = "l4re")))] +#[cfg(not(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris", + target_os = "haiku", + target_os = "l4re" +)))] use crate::sys::net::netc::IPV6_DROP_MEMBERSHIP; +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris", + target_os = "haiku", + target_os = "l4re" +))] +use crate::sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP; +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris", + target_os = "haiku", + target_os = "l4re" +))] +use crate::sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP; -#[cfg(any(target_os = "linux", target_os = "android", - target_os = "dragonfly", target_os = "freebsd", - target_os = "openbsd", target_os = "netbsd", - target_os = "haiku"))] +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "haiku" +))] use libc::MSG_NOSIGNAL; -#[cfg(not(any(target_os = "linux", target_os = "android", - target_os = "dragonfly", target_os = "freebsd", - target_os = "openbsd", target_os = "netbsd", - target_os = "haiku")))] +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "haiku" +)))] const MSG_NOSIGNAL: c_int = 0x0; //////////////////////////////////////////////////////////////////////////////// // sockaddr and misc bindings //////////////////////////////////////////////////////////////////////////////// -pub fn setsockopt(sock: &Socket, opt: c_int, val: c_int, - payload: T) -> io::Result<()> { +pub fn setsockopt(sock: &Socket, opt: c_int, val: c_int, payload: T) -> io::Result<()> { unsafe { let payload = &payload as *const T as *const c_void; - cvt(c::setsockopt(*sock.as_inner(), opt, val, payload, - mem::size_of::() as c::socklen_t))?; + cvt(c::setsockopt( + *sock.as_inner(), + opt, + val, + payload, + mem::size_of::() as c::socklen_t, + ))?; Ok(()) } } -pub fn getsockopt(sock: &Socket, opt: c_int, - val: c_int) -> io::Result { +pub fn getsockopt(sock: &Socket, opt: c_int, val: c_int) -> io::Result { unsafe { let mut slot: T = mem::zeroed(); let mut len = mem::size_of::() as c::socklen_t; - cvt(c::getsockopt(*sock.as_inner(), opt, val, - &mut slot as *mut _ as *mut _, - &mut len))?; + cvt(c::getsockopt(*sock.as_inner(), opt, val, &mut slot as *mut _ as *mut _, &mut len))?; assert_eq!(len as usize, mem::size_of::()); Ok(slot) } } fn sockname(f: F) -> io::Result - where F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int +where + F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int, { unsafe { let mut storage: c::sockaddr_storage = mem::zeroed(); @@ -83,8 +123,7 @@ fn sockname(f: F) -> io::Result } } -pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, - len: usize) -> io::Result { +pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, len: usize) -> io::Result { match storage.ss_family as c_int { c::AF_INET => { assert!(len as usize >= mem::size_of::()); @@ -98,9 +137,7 @@ pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, *(storage as *const _ as *const c::sockaddr_in6) }))) } - _ => { - Err(Error::new(ErrorKind::InvalidInput, "invalid argument")) - } + _ => Err(Error::new(ErrorKind::InvalidInput, "invalid argument")), } } @@ -121,7 +158,7 @@ fn to_ipv6mr_interface(value: u32) -> libc::c_uint { pub struct LookupHost { original: *mut c::addrinfo, cur: *mut c::addrinfo, - port: u16 + port: u16, } impl LookupHost { @@ -137,9 +174,7 @@ impl Iterator for LookupHost { unsafe { let cur = self.cur.as_ref()?; self.cur = cur.ai_next; - match sockaddr_to_addr(mem::transmute(cur.ai_addr), - cur.ai_addrlen as usize) - { + match sockaddr_to_addr(mem::transmute(cur.ai_addr), cur.ai_addrlen as usize) { Ok(addr) => return Some(addr), Err(_) => continue, } @@ -162,13 +197,12 @@ impl TryFrom<&str> for LookupHost { fn try_from(s: &str) -> io::Result { macro_rules! try_opt { - ($e:expr, $msg:expr) => ( + ($e:expr, $msg:expr) => { match $e { Some(r) => r, - None => return Err(io::Error::new(io::ErrorKind::InvalidInput, - $msg)), + None => return Err(io::Error::new(io::ErrorKind::InvalidInput, $msg)), } - ) + }; } // split the string by ':' and convert the second part to u16 @@ -192,9 +226,8 @@ impl<'a> TryFrom<(&'a str, u16)> for LookupHost { hints.ai_socktype = c::SOCK_STREAM; let mut res = ptr::null_mut(); unsafe { - cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)).map(|_| { - LookupHost { original: res, cur: res, port } - }) + cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)) + .map(|_| LookupHost { original: res, cur: res, port }) } } } @@ -228,9 +261,13 @@ impl TcpStream { Ok(TcpStream { inner: sock }) } - 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, dur: Option) -> io::Result<()> { self.inner.set_timeout(dur, c::SO_RCVTIMEO) @@ -263,10 +300,7 @@ impl TcpStream { pub fn write(&self, buf: &[u8]) -> io::Result { let len = cmp::min(buf.len(), ::max_value() as usize) as wrlen_t; let ret = cvt(unsafe { - c::send(*self.inner.as_inner(), - buf.as_ptr() as *const c_void, - len, - MSG_NOSIGNAL) + c::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL) })?; Ok(ret as usize) } @@ -276,15 +310,11 @@ impl TcpStream { } pub fn peer_addr(&self) -> io::Result { - sockname(|buf, len| unsafe { - c::getpeername(*self.inner.as_inner(), buf, len) - }) + sockname(|buf, len| unsafe { c::getpeername(*self.inner.as_inner(), buf, len) }) } pub fn socket_addr(&self) -> io::Result { - sockname(|buf, len| unsafe { - c::getsockname(*self.inner.as_inner(), buf, len) - }) + sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) }) } pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { @@ -339,9 +369,8 @@ impl fmt::Debug for TcpStream { res.field("peer", &peer); } - let name = if cfg!(windows) {"socket"} else {"fd"}; - res.field(name, &self.inner.as_inner()) - .finish() + let name = if cfg!(windows) { "socket" } else { "fd" }; + res.field(name, &self.inner.as_inner()).finish() } } @@ -365,8 +394,7 @@ impl TcpListener { // to quickly rebind a socket, without needing to wait for // the OS to clean up the previous one. if !cfg!(windows) { - setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR, - 1 as c_int)?; + setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR, 1 as c_int)?; } // Bind our new socket @@ -378,23 +406,24 @@ impl TcpListener { Ok(TcpListener { inner: sock }) } - 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 { - sockname(|buf, len| unsafe { - c::getsockname(*self.inner.as_inner(), buf, len) - }) + sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) }) } pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() }; let mut len = mem::size_of_val(&storage) as c::socklen_t; - let sock = self.inner.accept(&mut storage as *mut _ as *mut _, - &mut len)?; + let sock = self.inner.accept(&mut storage as *mut _ as *mut _, &mut len)?; let addr = sockaddr_to_addr(&storage, len as usize)?; - Ok((TcpStream { inner: sock, }, addr)) + Ok((TcpStream { inner: sock }, addr)) } pub fn duplicate(&self) -> io::Result { @@ -442,9 +471,8 @@ impl fmt::Debug for TcpListener { res.field("addr", &addr); } - let name = if cfg!(windows) {"socket"} else {"fd"}; - res.field(name, &self.inner.as_inner()) - .finish() + let name = if cfg!(windows) { "socket" } else { "fd" }; + res.field(name, &self.inner.as_inner()).finish() } } @@ -468,20 +496,20 @@ impl UdpSocket { Ok(UdpSocket { inner: sock }) } - 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 { - sockname(|buf, len| unsafe { - c::getpeername(*self.inner.as_inner(), buf, len) - }) + sockname(|buf, len| unsafe { c::getpeername(*self.inner.as_inner(), buf, len) }) } pub fn socket_addr(&self) -> io::Result { - sockname(|buf, len| unsafe { - c::getsockname(*self.inner.as_inner(), buf, len) - }) + sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) }) } pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { @@ -496,9 +524,14 @@ impl UdpSocket { let len = cmp::min(buf.len(), ::max_value() as usize) as wrlen_t; let (dstp, dstlen) = dst.into_inner(); let ret = cvt(unsafe { - c::sendto(*self.inner.as_inner(), - buf.as_ptr() as *const c_void, len, - MSG_NOSIGNAL, dstp, dstlen) + c::sendto( + *self.inner.as_inner(), + buf.as_ptr() as *const c_void, + len, + MSG_NOSIGNAL, + dstp, + dstlen, + ) })?; Ok(ret as usize) } @@ -559,8 +592,7 @@ impl UdpSocket { Ok(raw != 0) } - pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) - -> io::Result<()> { + pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { let mreq = c::ip_mreq { imr_multiaddr: *multiaddr.as_inner(), imr_interface: *interface.as_inner(), @@ -568,8 +600,7 @@ impl UdpSocket { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq) } - pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) - -> io::Result<()> { + pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { let mreq = c::ipv6_mreq { ipv6mr_multiaddr: *multiaddr.as_inner(), ipv6mr_interface: to_ipv6mr_interface(interface), @@ -577,8 +608,7 @@ impl UdpSocket { setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq) } - pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) - -> io::Result<()> { + pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { let mreq = c::ip_mreq { imr_multiaddr: *multiaddr.as_inner(), imr_interface: *interface.as_inner(), @@ -586,8 +616,7 @@ impl UdpSocket { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq) } - pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) - -> io::Result<()> { + pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { let mreq = c::ipv6_mreq { ipv6mr_multiaddr: *multiaddr.as_inner(), ipv6mr_interface: to_ipv6mr_interface(interface), @@ -623,10 +652,7 @@ impl UdpSocket { pub fn send(&self, buf: &[u8]) -> io::Result { let len = cmp::min(buf.len(), ::max_value() as usize) as wrlen_t; let ret = cvt(unsafe { - c::send(*self.inner.as_inner(), - buf.as_ptr() as *const c_void, - len, - MSG_NOSIGNAL) + c::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL) })?; Ok(ret as usize) } @@ -651,9 +677,8 @@ impl fmt::Debug for UdpSocket { res.field("addr", &addr); } - let name = if cfg!(windows) {"socket"} else {"fd"}; - res.field(name, &self.inner.as_inner()) - .finish() + let name = if cfg!(windows) { "socket" } else { "fd" }; + res.field(name, &self.inner.as_inner()).finish() } } @@ -667,10 +692,15 @@ mod tests { let mut addrs = HashMap::new(); let lh = match LookupHost::try_from(("localhost", 0)) { Ok(lh) => lh, - Err(e) => panic!("couldn't resolve `localhost': {}", e) + Err(e) => panic!("couldn't resolve `localhost': {}", e), }; - for sa in lh { *addrs.entry(sa).or_insert(0) += 1; }; - assert_eq!(addrs.iter().filter(|&(_, &v)| v > 1).collect::>(), vec![], - "There should be no duplicate localhost entries"); + for sa in lh { + *addrs.entry(sa).or_insert(0) += 1; + } + assert_eq!( + addrs.iter().filter(|&(_, &v)| v > 1).collect::>(), + vec![], + "There should be no duplicate localhost entries" + ); } } diff --git a/src/libstd/sys_common/os_str_bytes.rs b/src/libstd/sys_common/os_str_bytes.rs index 3753269adfe45..a2608ad4000d4 100644 --- a/src/libstd/sys_common/os_str_bytes.rs +++ b/src/libstd/sys_common/os_str_bytes.rs @@ -4,18 +4,18 @@ use crate::borrow::Cow; use crate::ffi::{OsStr, OsString}; use crate::fmt; -use crate::str; use crate::mem; use crate::rc::Rc; +use crate::str; use crate::sync::Arc; -use crate::sys_common::{FromInner, IntoInner, AsInner}; use crate::sys_common::bytestring::debug_fmt_bytestring; +use crate::sys_common::{AsInner, FromInner, IntoInner}; use core::str::lossy::Utf8Lossy; #[derive(Clone, Hash)] pub(crate) struct Buf { - pub inner: Vec + pub inner: Vec, } // FIXME: @@ -25,7 +25,7 @@ pub(crate) struct Buf { // Anyway, `Slice` representation and layout are considered implementation detail, are // not documented and must not be relied upon. pub(crate) struct Slice { - pub inner: [u8] + pub inner: [u8], } impl fmt::Debug for Slice { @@ -64,7 +64,6 @@ impl AsInner<[u8]> for Buf { } } - impl Buf { pub fn from_string(s: String) -> Buf { Buf { inner: s.into_bytes() } @@ -72,9 +71,7 @@ impl Buf { #[inline] pub fn with_capacity(capacity: usize) -> Buf { - Buf { - inner: Vec::with_capacity(capacity) - } + Buf { inner: Vec::with_capacity(capacity) } } #[inline] @@ -112,7 +109,7 @@ impl Buf { } pub fn into_string(self) -> Result { - String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } ) + String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() }) } pub fn push_slice(&mut self, s: &Slice) { diff --git a/src/libstd/sys_common/poison.rs b/src/libstd/sys_common/poison.rs index adac45f2d59da..0157b952996ac 100644 --- a/src/libstd/sys_common/poison.rs +++ b/src/libstd/sys_common/poison.rs @@ -1,9 +1,11 @@ -use crate::error::{Error}; +use crate::error::Error; use crate::fmt; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::thread; -pub struct Flag { failed: AtomicBool } +pub struct Flag { + failed: AtomicBool, +} // Note that the Ordering uses to access the `failed` field of `Flag` below is // always `Relaxed`, and that's because this isn't actually protecting any data, @@ -24,11 +26,7 @@ impl Flag { #[inline] pub fn borrow(&self) -> LockResult { let ret = Guard { panicking: thread::panicking() }; - if self.get() { - Err(PoisonError::new(ret)) - } else { - Ok(ret) - } + if self.get() { Err(PoisonError::new(ret)) } else { Ok(ret) } } #[inline] @@ -192,17 +190,23 @@ impl PoisonError { /// println!("recovered {} items", data.len()); /// ``` #[stable(feature = "sync_poison", since = "1.2.0")] - pub fn into_inner(self) -> T { self.guard } + pub fn into_inner(self) -> T { + self.guard + } /// Reaches into this error indicating that a lock is poisoned, returning a /// reference to the underlying guard to allow access regardless. #[stable(feature = "sync_poison", since = "1.2.0")] - pub fn get_ref(&self) -> &T { &self.guard } + pub fn get_ref(&self) -> &T { + &self.guard + } /// Reaches into this error indicating that a lock is poisoned, returning a /// mutable reference to the underlying guard to allow access regardless. #[stable(feature = "sync_poison", since = "1.2.0")] - pub fn get_mut(&mut self) -> &mut T { &mut self.guard } + pub fn get_mut(&mut self) -> &mut T { + &mut self.guard + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -217,7 +221,7 @@ impl fmt::Debug for TryLockError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f), - TryLockError::WouldBlock => "WouldBlock".fmt(f) + TryLockError::WouldBlock => "WouldBlock".fmt(f), } } } @@ -227,8 +231,9 @@ impl fmt::Display for TryLockError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { TryLockError::Poisoned(..) => "poisoned lock: another task failed inside", - TryLockError::WouldBlock => "try_lock failed because the operation would block" - }.fmt(f) + TryLockError::WouldBlock => "try_lock failed because the operation would block", + } + .fmt(f) } } @@ -237,23 +242,24 @@ impl Error for TryLockError { fn description(&self) -> &str { match *self { TryLockError::Poisoned(ref p) => p.description(), - TryLockError::WouldBlock => "try_lock failed because the operation would block" + TryLockError::WouldBlock => "try_lock failed because the operation would block", } } fn cause(&self) -> Option<&dyn Error> { match *self { TryLockError::Poisoned(ref p) => Some(p), - _ => None + _ => None, } } } -pub fn map_result(result: LockResult, f: F) - -> LockResult - where F: FnOnce(T) -> U { +pub fn map_result(result: LockResult, f: F) -> LockResult +where + F: FnOnce(T) -> U, +{ match result { Ok(t) => Ok(f(t)), - Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))) + Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))), } } diff --git a/src/libstd/sys_common/process.rs b/src/libstd/sys_common/process.rs index bdf66fca35970..55b421794c413 100644 --- a/src/libstd/sys_common/process.rs +++ b/src/libstd/sys_common/process.rs @@ -11,16 +11,12 @@ use crate::sys::process::EnvKey; pub struct CommandEnv { clear: bool, saw_path: bool, - vars: BTreeMap> + vars: BTreeMap>, } impl Default for CommandEnv { fn default() -> Self { - CommandEnv { - clear: false, - saw_path: false, - vars: Default::default() - } + CommandEnv { clear: false, saw_path: false, vars: Default::default() } } } @@ -64,11 +60,7 @@ impl CommandEnv { } pub fn capture_if_changed(&self) -> Option> { - if self.is_unchanged() { - None - } else { - Some(self.capture()) - } + if self.is_unchanged() { None } else { Some(self.capture()) } } // The following functions build up changes diff --git a/src/libstd/sys_common/thread_info.rs b/src/libstd/sys_common/thread_info.rs index b3c21ec508a9e..f09d16c33e6d6 100644 --- a/src/libstd/sys_common/thread_info.rs +++ b/src/libstd/sys_common/thread_info.rs @@ -12,16 +12,19 @@ struct ThreadInfo { thread_local! { static THREAD_INFO: RefCell> = RefCell::new(None) } impl ThreadInfo { - fn with(f: F) -> Option where F: FnOnce(&mut ThreadInfo) -> R { - THREAD_INFO.try_with(move |c| { - if c.borrow().is_none() { - *c.borrow_mut() = Some(ThreadInfo { - stack_guard: None, - thread: Thread::new(None), - }) - } - f(c.borrow_mut().as_mut().unwrap()) - }).ok() + fn with(f: F) -> Option + where + F: FnOnce(&mut ThreadInfo) -> R, + { + THREAD_INFO + .try_with(move |c| { + if c.borrow().is_none() { + *c.borrow_mut() = + Some(ThreadInfo { stack_guard: None, thread: Thread::new(None) }) + } + f(c.borrow_mut().as_mut().unwrap()) + }) + .ok() } } @@ -35,10 +38,7 @@ pub fn stack_guard() -> Option { pub fn set(stack_guard: Option, thread: Thread) { THREAD_INFO.with(|c| assert!(c.borrow().is_none())); - THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo{ - stack_guard, - thread, - })); + THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo { stack_guard, thread })); } pub fn reset_guard(stack_guard: Option) { diff --git a/src/libstd/sys_common/util.rs b/src/libstd/sys_common/util.rs index 7936dd35999e2..00f7db4c03761 100644 --- a/src/libstd/sys_common/util.rs +++ b/src/libstd/sys_common/util.rs @@ -16,11 +16,15 @@ pub fn dumb_print(args: fmt::Arguments<'_>) { pub fn abort(args: fmt::Arguments<'_>) -> ! { dumb_print(format_args!("fatal runtime error: {}\n", args)); - unsafe { crate::sys::abort_internal(); } + unsafe { + crate::sys::abort_internal(); + } } #[allow(dead_code)] // stack overflow detection not enabled on all platforms pub unsafe fn report_overflow() { - dumb_print(format_args!("\nthread '{}' has overflowed its stack\n", - thread::current().name().unwrap_or(""))); + dumb_print(format_args!( + "\nthread '{}' has overflowed its stack\n", + thread::current().name().unwrap_or("") + )); } diff --git a/src/libstd/sys_common/wtf8.rs b/src/libstd/sys_common/wtf8.rs index 81e606fc16583..1d96cdfe46042 100644 --- a/src/libstd/sys_common/wtf8.rs +++ b/src/libstd/sys_common/wtf8.rs @@ -39,7 +39,7 @@ const UTF8_REPLACEMENT_CHARACTER: &str = "\u{FFFD}"; /// a code point that is not a surrogate (U+D800 to U+DFFF). #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)] pub struct CodePoint { - value: u32 + value: u32, } /// Format the code point as `U+` followed by four to six hexadecimal digits. @@ -66,8 +66,8 @@ impl CodePoint { #[inline] pub fn from_u32(value: u32) -> Option { match value { - 0 ..= 0x10FFFF => Some(CodePoint { value }), - _ => None + 0..=0x10FFFF => Some(CodePoint { value }), + _ => None, } } @@ -91,8 +91,8 @@ impl CodePoint { #[inline] pub fn to_char(&self) -> Option { match self.value { - 0xD800 ..= 0xDFFF => None, - _ => Some(unsafe { char::from_u32_unchecked(self.value) }) + 0xD800..=0xDFFF => None, + _ => Some(unsafe { char::from_u32_unchecked(self.value) }), } } @@ -112,7 +112,7 @@ impl CodePoint { /// if they’re not in a surrogate pair. #[derive(Eq, PartialEq, Ord, PartialOrd, Clone)] pub struct Wtf8Buf { - bytes: Vec + bytes: Vec, } impl ops::Deref for Wtf8Buf { @@ -188,9 +188,7 @@ impl Wtf8Buf { Err(surrogate) => { let surrogate = surrogate.unpaired_surrogate(); // Surrogates are known to be in the code point range. - let code_point = unsafe { - CodePoint::from_u32_unchecked(surrogate as u32) - }; + let code_point = unsafe { CodePoint::from_u32_unchecked(surrogate as u32) }; // Skip the WTF-8 concatenation check, // surrogate pairs are already decoded by decode_utf16 string.push_code_point_unchecked(code_point) @@ -203,9 +201,7 @@ impl Wtf8Buf { /// Copied from String::push /// This does **not** include the WTF-8 concatenation check. fn push_code_point_unchecked(&mut self, code_point: CodePoint) { - let c = unsafe { - char::from_u32_unchecked(code_point.value) - }; + let c = unsafe { char::from_u32_unchecked(code_point.value) }; let mut bytes = [0; 4]; let bytes = c.encode_utf8(&mut bytes).as_bytes(); self.bytes.extend_from_slice(bytes) @@ -278,7 +274,7 @@ impl Wtf8Buf { self.push_char(decode_surrogate_pair(lead, trail)); self.bytes.extend_from_slice(other_without_trail_surrogate); } - _ => self.bytes.extend_from_slice(&other.bytes) + _ => self.bytes.extend_from_slice(&other.bytes), } } @@ -300,7 +296,7 @@ impl Wtf8Buf { let len_without_lead_surrogate = self.len() - 3; self.bytes.truncate(len_without_lead_surrogate); self.push_char(decode_surrogate_pair(lead, trail as u16)); - return + return; } } @@ -347,8 +343,8 @@ impl Wtf8Buf { pos = surrogate_pos + 3; self.bytes[surrogate_pos..pos] .copy_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes()); - }, - None => return unsafe { String::from_utf8_unchecked(self.bytes) } + } + None => return unsafe { String::from_utf8_unchecked(self.bytes) }, } } } @@ -371,7 +367,7 @@ impl Wtf8Buf { /// This replaces surrogate code point pairs with supplementary code points, /// like concatenating ill-formed UTF-16 strings effectively would. impl FromIterator for Wtf8Buf { - fn from_iter>(iter: T) -> Wtf8Buf { + fn from_iter>(iter: T) -> Wtf8Buf { let mut string = Wtf8Buf::new(); string.extend(iter); string @@ -383,7 +379,7 @@ impl FromIterator for Wtf8Buf { /// This replaces surrogate code point pairs with supplementary code points, /// like concatenating ill-formed UTF-16 strings effectively would. impl Extend for Wtf8Buf { - fn extend>(&mut self, iter: T) { + fn extend>(&mut self, iter: T) { let iterator = iter.into_iter(); let (low, _high) = iterator.size_hint(); // Lower bound of one byte per code point (ASCII only) @@ -398,11 +394,13 @@ impl Extend for Wtf8Buf { /// if they’re not in a surrogate pair. #[derive(Eq, Ord, PartialEq, PartialOrd)] pub struct Wtf8 { - bytes: [u8] + bytes: [u8], } impl AsInner<[u8]> for Wtf8 { - fn as_inner(&self) -> &[u8] { &self.bytes } + fn as_inner(&self) -> &[u8] { + &self.bytes + } } /// Format the slice with double quotes, @@ -421,19 +419,13 @@ impl fmt::Debug for Wtf8 { formatter.write_str("\"")?; let mut pos = 0; while let Some((surrogate_pos, surrogate)) = self.next_surrogate(pos) { - write_str_escaped( - formatter, - unsafe { str::from_utf8_unchecked( - &self.bytes[pos .. surrogate_pos] - )}, - )?; + write_str_escaped(formatter, unsafe { + str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos]) + })?; write!(formatter, "\\u{{{:x}}}", surrogate)?; pos = surrogate_pos + 3; } - write_str_escaped( - formatter, - unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) }, - )?; + write_str_escaped(formatter, unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) })?; formatter.write_str("\"") } } @@ -446,20 +438,14 @@ impl fmt::Display for Wtf8 { match self.next_surrogate(pos) { Some((surrogate_pos, _)) => { formatter.write_str(unsafe { - str::from_utf8_unchecked(&wtf8_bytes[pos .. surrogate_pos]) + str::from_utf8_unchecked(&wtf8_bytes[pos..surrogate_pos]) })?; formatter.write_str(UTF8_REPLACEMENT_CHARACTER)?; pos = surrogate_pos + 3; - }, + } None => { - let s = unsafe { - str::from_utf8_unchecked(&wtf8_bytes[pos..]) - }; - if pos == 0 { - return s.fmt(formatter) - } else { - return formatter.write_str(s) - } + let s = unsafe { str::from_utf8_unchecked(&wtf8_bytes[pos..]) }; + if pos == 0 { return s.fmt(formatter) } else { return formatter.write_str(s) } } } } @@ -513,8 +499,8 @@ impl Wtf8 { #[inline] pub fn ascii_byte_at(&self, position: usize) -> u8 { match self.bytes[position] { - ascii_byte @ 0x00 ..= 0x7F => ascii_byte, - _ => 0xFF + ascii_byte @ 0x00..=0x7F => ascii_byte, + _ => 0xFF, } } @@ -558,13 +544,13 @@ impl Wtf8 { loop { match self.next_surrogate(pos) { Some((surrogate_pos, _)) => { - utf8_bytes.extend_from_slice(&wtf8_bytes[pos .. surrogate_pos]); + utf8_bytes.extend_from_slice(&wtf8_bytes[pos..surrogate_pos]); utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes()); pos = surrogate_pos + 3; - }, + } None => { utf8_bytes.extend_from_slice(&wtf8_bytes[pos..]); - return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) }) + return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) }); } } } @@ -594,9 +580,9 @@ impl Wtf8 { } else if b == 0xED { match (iter.next(), iter.next()) { (Some(&b2), Some(&b3)) if b2 >= 0xA0 => { - return Some((pos, decode_surrogate(b2, b3))) + return Some((pos, decode_surrogate(b2, b3))); } - _ => pos += 3 + _ => pos += 3, } } else if b < 0xF0 { iter.next(); @@ -615,11 +601,11 @@ impl Wtf8 { fn final_lead_surrogate(&self) -> Option { let len = self.len(); if len < 3 { - return None + return None; } match &self.bytes[(len - 3)..] { &[0xED, b2 @ 0xA0..=0xAF, b3] => Some(decode_surrogate(b2, b3)), - _ => None + _ => None, } } @@ -627,11 +613,11 @@ impl Wtf8 { fn initial_trail_surrogate(&self) -> Option { let len = self.len(); if len < 3 { - return None + return None; } match &self.bytes[..3] { &[0xED, b2 @ 0xB0..=0xBF, b3] => Some(decode_surrogate(b2, b3)), - _ => None + _ => None, } } @@ -661,7 +647,6 @@ impl Wtf8 { } } - /// Returns a slice of the given string for the byte range [`begin`..`end`). /// /// # Panics @@ -674,9 +659,10 @@ impl ops::Index> for Wtf8 { #[inline] fn index(&self, range: ops::Range) -> &Wtf8 { // is_code_point_boundary checks that the index is in [0, .len()] - if range.start <= range.end && - is_code_point_boundary(self, range.start) && - is_code_point_boundary(self, range.end) { + if range.start <= range.end + && is_code_point_boundary(self, range.start) + && is_code_point_boundary(self, range.end) + { unsafe { slice_unchecked(self, range.start, range.end) } } else { slice_error_fail(self, range.start, range.end) @@ -748,7 +734,9 @@ fn decode_surrogate_pair(lead: u16, trail: u16) -> char { /// Copied from core::str::StrPrelude::is_char_boundary #[inline] pub fn is_code_point_boundary(slice: &Wtf8, index: usize) -> bool { - if index == slice.len() { return true; } + if index == slice.len() { + return true; + } match slice.bytes.get(index) { None => false, Some(&b) => b < 128 || b >= 192, @@ -759,18 +747,14 @@ pub fn is_code_point_boundary(slice: &Wtf8, index: usize) -> bool { #[inline] pub unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 { // memory layout of an &[u8] and &Wtf8 are the same - Wtf8::from_bytes_unchecked(slice::from_raw_parts( - s.bytes.as_ptr().add(begin), - end - begin - )) + Wtf8::from_bytes_unchecked(slice::from_raw_parts(s.bytes.as_ptr().add(begin), end - begin)) } /// Copied from core::str::raw::slice_error_fail #[inline(never)] pub fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! { assert!(begin <= end); - panic!("index {} and/or {} in `{:?}` do not lie on character boundary", - begin, end, s); + panic!("index {} and/or {} in `{:?}` do not lie on character boundary", begin, end, s); } /// Iterator for the code points of a WTF-8 string. @@ -778,7 +762,7 @@ pub fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! { /// Created with the method `.code_points()`. #[derive(Clone)] pub struct Wtf8CodePoints<'a> { - bytes: slice::Iter<'a, u8> + bytes: slice::Iter<'a, u8>, } impl<'a> Iterator for Wtf8CodePoints<'a> { @@ -801,7 +785,7 @@ impl<'a> Iterator for Wtf8CodePoints<'a> { #[derive(Clone)] pub struct EncodeWide<'a> { code_points: Wtf8CodePoints<'a>, - extra: u16 + extra: u16, } // Copied from libunicode/u_str.rs @@ -819,9 +803,7 @@ impl<'a> Iterator for EncodeWide<'a> { let mut buf = [0; 2]; self.code_points.next().map(|code_point| { - let c = unsafe { - char::from_u32_unchecked(code_point.value) - }; + let c = unsafe { char::from_u32_unchecked(code_point.value) }; let n = c.encode_utf16(&mut buf).len(); if n == 2 { self.extra = buf[1]; @@ -864,13 +846,15 @@ impl Hash for Wtf8 { } impl Wtf8 { - pub fn make_ascii_uppercase(&mut self) { self.bytes.make_ascii_uppercase() } + pub fn make_ascii_uppercase(&mut self) { + self.bytes.make_ascii_uppercase() + } } #[cfg(test)] mod tests { - use crate::borrow::Cow; use super::*; + use crate::borrow::Cow; #[test] fn code_point_from_u32() { @@ -882,7 +866,9 @@ mod tests { #[test] fn code_point_to_u32() { - fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() } + fn c(value: u32) -> CodePoint { + CodePoint::from_u32(value).unwrap() + } assert_eq!(c(0).to_u32(), 0); assert_eq!(c(0xD800).to_u32(), 0xD800); assert_eq!(c(0x10FFFF).to_u32(), 0x10FFFF); @@ -902,7 +888,9 @@ mod tests { #[test] fn code_point_to_char() { - fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() } + fn c(value: u32) -> CodePoint { + CodePoint::from_u32(value).unwrap() + } assert_eq!(c(0x61).to_char(), Some('a')); assert_eq!(c(0x1F4A9).to_char(), Some('💩')); assert_eq!(c(0xD800).to_char(), None); @@ -910,7 +898,9 @@ mod tests { #[test] fn code_point_to_char_lossy() { - fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() } + fn c(value: u32) -> CodePoint { + CodePoint::from_u32(value).unwrap() + } assert_eq!(c(0x61).to_char_lossy(), 'a'); assert_eq!(c(0x1F4A9).to_char_lossy(), '💩'); assert_eq!(c(0xD800).to_char_lossy(), '\u{FFFD}'); @@ -924,23 +914,25 @@ mod tests { #[test] fn wtf8buf_from_str() { assert_eq!(Wtf8Buf::from_str("").bytes, b""); - assert_eq!(Wtf8Buf::from_str("aé 💩").bytes, - b"a\xC3\xA9 \xF0\x9F\x92\xA9"); + assert_eq!(Wtf8Buf::from_str("aé 💩").bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9"); } #[test] fn wtf8buf_from_string() { assert_eq!(Wtf8Buf::from_string(String::from("")).bytes, b""); - assert_eq!(Wtf8Buf::from_string(String::from("aé 💩")).bytes, - b"a\xC3\xA9 \xF0\x9F\x92\xA9"); + assert_eq!( + Wtf8Buf::from_string(String::from("aé 💩")).bytes, + b"a\xC3\xA9 \xF0\x9F\x92\xA9" + ); } #[test] fn wtf8buf_from_wide() { assert_eq!(Wtf8Buf::from_wide(&[]).bytes, b""); - assert_eq!(Wtf8Buf::from_wide( - &[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes, - b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9"); + assert_eq!( + Wtf8Buf::from_wide(&[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes, + b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9" + ); } #[test] @@ -966,41 +958,43 @@ mod tests { string.push(CodePoint::from_char('💩')); assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9"); - fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() } + fn c(value: u32) -> CodePoint { + CodePoint::from_u32(value).unwrap() + } let mut string = Wtf8Buf::new(); - string.push(c(0xD83D)); // lead - string.push(c(0xDCA9)); // trail - assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic! + string.push(c(0xD83D)); // lead + string.push(c(0xDCA9)); // trail + assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic! let mut string = Wtf8Buf::new(); - string.push(c(0xD83D)); // lead - string.push(c(0x20)); // not surrogate - string.push(c(0xDCA9)); // trail + string.push(c(0xD83D)); // lead + string.push(c(0x20)); // not surrogate + string.push(c(0xDCA9)); // trail assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9"); let mut string = Wtf8Buf::new(); - string.push(c(0xD800)); // lead - string.push(c(0xDBFF)); // lead + string.push(c(0xD800)); // lead + string.push(c(0xDBFF)); // lead assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF"); let mut string = Wtf8Buf::new(); - string.push(c(0xD800)); // lead - string.push(c(0xE000)); // not surrogate + string.push(c(0xD800)); // lead + string.push(c(0xE000)); // not surrogate assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80"); let mut string = Wtf8Buf::new(); - string.push(c(0xD7FF)); // not surrogate - string.push(c(0xDC00)); // trail + string.push(c(0xD7FF)); // not surrogate + string.push(c(0xDC00)); // trail assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80"); let mut string = Wtf8Buf::new(); - string.push(c(0x61)); // not surrogate, < 3 bytes - string.push(c(0xDC00)); // trail + string.push(c(0x61)); // not surrogate, < 3 bytes + string.push(c(0xDC00)); // trail assert_eq!(string.bytes, b"\x61\xED\xB0\x80"); let mut string = Wtf8Buf::new(); - string.push(c(0xDC00)); // trail + string.push(c(0xDC00)); // trail assert_eq!(string.bytes, b"\xED\xB0\x80"); } @@ -1011,41 +1005,43 @@ mod tests { string.push_wtf8(Wtf8::from_str(" 💩")); assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9"); - fn w(v: &[u8]) -> &Wtf8 { unsafe { Wtf8::from_bytes_unchecked(v) } } + fn w(v: &[u8]) -> &Wtf8 { + unsafe { Wtf8::from_bytes_unchecked(v) } + } let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\xA0\xBD")); // lead - string.push_wtf8(w(b"\xED\xB2\xA9")); // trail - assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic! + string.push_wtf8(w(b"\xED\xA0\xBD")); // lead + string.push_wtf8(w(b"\xED\xB2\xA9")); // trail + assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic! let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\xA0\xBD")); // lead - string.push_wtf8(w(b" ")); // not surrogate - string.push_wtf8(w(b"\xED\xB2\xA9")); // trail + string.push_wtf8(w(b"\xED\xA0\xBD")); // lead + string.push_wtf8(w(b" ")); // not surrogate + string.push_wtf8(w(b"\xED\xB2\xA9")); // trail assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9"); let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\xA0\x80")); // lead - string.push_wtf8(w(b"\xED\xAF\xBF")); // lead + string.push_wtf8(w(b"\xED\xA0\x80")); // lead + string.push_wtf8(w(b"\xED\xAF\xBF")); // lead assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF"); let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\xA0\x80")); // lead - string.push_wtf8(w(b"\xEE\x80\x80")); // not surrogate + string.push_wtf8(w(b"\xED\xA0\x80")); // lead + string.push_wtf8(w(b"\xEE\x80\x80")); // not surrogate assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80"); let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\x9F\xBF")); // not surrogate - string.push_wtf8(w(b"\xED\xB0\x80")); // trail + string.push_wtf8(w(b"\xED\x9F\xBF")); // not surrogate + string.push_wtf8(w(b"\xED\xB0\x80")); // trail assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80"); let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"a")); // not surrogate, < 3 bytes - string.push_wtf8(w(b"\xED\xB0\x80")); // trail + string.push_wtf8(w(b"a")); // not surrogate, < 3 bytes + string.push_wtf8(w(b"\xED\xB0\x80")); // trail assert_eq!(string.bytes, b"\x61\xED\xB0\x80"); let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\xB0\x80")); // trail + string.push_wtf8(w(b"\xED\xB0\x80")); // trail assert_eq!(string.bytes, b"\xED\xB0\x80"); } @@ -1093,7 +1089,7 @@ mod tests { } assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9"); - assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! + assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9"); assert_eq!(f(&[0xD800, 0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF"); assert_eq!(f(&[0xD800, 0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80"); @@ -1105,16 +1101,17 @@ mod tests { #[test] fn wtf8buf_extend() { fn e(initial: &[u32], extended: &[u32]) -> Wtf8Buf { - fn c(value: &u32) -> CodePoint { CodePoint::from_u32(*value).unwrap() } + fn c(value: &u32) -> CodePoint { + CodePoint::from_u32(*value).unwrap() + } let mut string = initial.iter().map(c).collect::(); string.extend(extended.iter().map(c)); string } - assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes, - b"a\xC3\xA9 \xF0\x9F\x92\xA9"); + assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9"); - assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! + assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9"); assert_eq!(e(&[0xD800], &[0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF"); assert_eq!(e(&[0xD800], &[0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80"); @@ -1156,13 +1153,13 @@ mod tests { #[test] fn wtf8_slice() { - assert_eq!(&Wtf8::from_str("aé 💩")[1.. 4].bytes, b"\xC3\xA9 "); + assert_eq!(&Wtf8::from_str("aé 💩")[1..4].bytes, b"\xC3\xA9 "); } #[test] #[should_panic] fn wtf8_slice_not_code_point_boundary() { - &Wtf8::from_str("aé 💩")[2.. 4]; + &Wtf8::from_str("aé 💩")[2..4]; } #[test] @@ -1199,7 +1196,9 @@ mod tests { #[test] fn wtf8_code_points() { - fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() } + fn c(value: u32) -> CodePoint { + CodePoint::from_u32(value).unwrap() + } fn cp(string: &Wtf8Buf) -> Vec> { string.code_points().map(|c| c.to_char()).collect::>() } @@ -1249,7 +1248,9 @@ mod tests { let mut string = Wtf8Buf::from_str("aé "); string.push(CodePoint::from_u32(0xD83D).unwrap()); string.push_char('💩'); - assert_eq!(string.encode_wide().collect::>(), - vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]); + assert_eq!( + string.encode_wide().collect::>(), + vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9] + ); } } diff --git a/src/libstd/tests/env.rs b/src/libstd/tests/env.rs index f8014cb2ad9af..c94fc41178dfe 100644 --- a/src/libstd/tests/env.rs +++ b/src/libstd/tests/env.rs @@ -1,13 +1,12 @@ use std::env::*; -use std::ffi::{OsString, OsStr}; +use std::ffi::{OsStr, OsString}; -use rand::{thread_rng, Rng}; use rand::distributions::Alphanumeric; +use rand::{thread_rng, Rng}; fn make_rand_name() -> OsString { let rng = thread_rng(); - let n = format!("TEST{}", rng.sample_iter(&Alphanumeric).take(10) - .collect::()); + let n = format!("TEST{}", rng.sample_iter(&Alphanumeric).take(10).collect::()); let n = OsString::from(n); assert!(var_os(&n).is_none()); n @@ -73,11 +72,7 @@ fn test_env_set_var() { let mut e = vars_os(); set_var(&n, "VALUE"); - assert!(!e.any(|(k, v)| { - &*k == &*n && &*v == "VALUE" - })); + assert!(!e.any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); - assert!(vars_os().any(|(k, v)| { - &*k == &*n && &*v == "VALUE" - })); + assert!(vars_os().any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); } diff --git a/src/libstd/thread/local.rs b/src/libstd/thread/local.rs index 46453b47fca8d..9c530e7b3248c 100644 --- a/src/libstd/thread/local.rs +++ b/src/libstd/thread/local.rs @@ -142,9 +142,7 @@ macro_rules! thread_local { } #[doc(hidden)] -#[unstable(feature = "thread_local_internals", - reason = "should not be necessary", - issue = "0")] +#[unstable(feature = "thread_local_internals", reason = "should not be necessary", issue = "0")] #[macro_export] #[allow_internal_unstable(thread_local_internals, cfg_target_thread_local, thread_local)] #[allow_internal_unsafe] @@ -214,13 +212,13 @@ impl Error for AccessError {} impl LocalKey { #[doc(hidden)] - #[unstable(feature = "thread_local_internals", - reason = "recently added to create a key", - issue = "0")] + #[unstable( + feature = "thread_local_internals", + reason = "recently added to create a key", + issue = "0" + )] pub const unsafe fn new(inner: unsafe fn() -> Option<&'static T>) -> LocalKey { - LocalKey { - inner, - } + LocalKey { inner } } /// Acquires a reference to the value in this TLS key. @@ -235,9 +233,13 @@ impl LocalKey { /// previously been run for this thread. #[stable(feature = "rust1", since = "1.0.0")] pub fn with(&'static self, f: F) -> R - where F: FnOnce(&T) -> R { - self.try_with(f).expect("cannot access a Thread Local Storage value \ - during or after destruction") + where + F: FnOnce(&T) -> R, + { + self.try_with(f).expect( + "cannot access a Thread Local Storage value \ + during or after destruction", + ) } /// Acquires a reference to the value in this TLS key. @@ -256,9 +258,7 @@ impl LocalKey { F: FnOnce(&T) -> R, { unsafe { - let thread_local = (self.inner)().ok_or(AccessError { - _private: (), - })?; + let thread_local = (self.inner)().ok_or(AccessError { _private: () })?; Ok(f(thread_local)) } } @@ -266,8 +266,8 @@ impl LocalKey { mod lazy { use crate::cell::UnsafeCell; - use crate::mem; use crate::hint; + use crate::mem; pub struct LazyKeyInner { inner: UnsafeCell>, @@ -275,9 +275,7 @@ mod lazy { impl LazyKeyInner { pub const fn new() -> LazyKeyInner { - LazyKeyInner { - inner: UnsafeCell::new(None), - } + LazyKeyInner { inner: UnsafeCell::new(None) } } pub unsafe fn get(&self) -> Option<&'static T> { @@ -334,7 +332,7 @@ pub mod statik { inner: LazyKeyInner, } - unsafe impl Sync for Key { } + unsafe impl Sync for Key {} impl fmt::Debug for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -344,9 +342,7 @@ pub mod statik { impl Key { pub const fn new() -> Key { - Key { - inner: LazyKeyInner::new(), - } + Key { inner: LazyKeyInner::new() } } pub unsafe fn get(&self, init: fn() -> T) -> Option<&'static T> { @@ -404,10 +400,7 @@ pub mod fast { impl Key { pub const fn new() -> Key { - Key { - inner: LazyKeyInner::new(), - dtor_state: Cell::new(DtorState::Unregistered), - } + Key { inner: LazyKeyInner::new(), dtor_state: Cell::new(DtorState::Unregistered) } } pub unsafe fn get T>(&self, init: F) -> Option<&'static T> { @@ -441,8 +434,7 @@ pub mod fast { match self.dtor_state.get() { DtorState::Unregistered => { // dtor registration happens before initialization. - register_dtor(self as *const _ as *mut u8, - destroy_value::); + register_dtor(self as *const _ as *mut u8, destroy_value::); self.dtor_state.set(DtorState::Registered); true } @@ -450,14 +442,12 @@ pub mod fast { // recursively initialized true } - DtorState::RunningOrHasRun => { - false - } + DtorState::RunningOrHasRun => false, } } } - unsafe extern fn destroy_value(ptr: *mut u8) { + unsafe extern "C" fn destroy_value(ptr: *mut u8) { let ptr = ptr as *mut Key; // Right before we run the user destructor be sure to set the @@ -491,7 +481,7 @@ pub mod os { } } - unsafe impl Sync for Key { } + unsafe impl Sync for Key {} struct Value { inner: LazyKeyInner, @@ -500,10 +490,7 @@ pub mod os { impl Key { pub const fn new() -> Key { - Key { - os: OsStaticKey::new(Some(destroy_value::)), - marker: marker::PhantomData - } + Key { os: OsStaticKey::new(Some(destroy_value::)), marker: marker::PhantomData } } pub unsafe fn get(&'static self, init: fn() -> T) -> Option<&'static T> { @@ -523,16 +510,13 @@ pub mod os { let ptr = self.os.get() as *mut Value; if ptr as usize == 1 { // destructor is running - return None + return None; } let ptr = if ptr.is_null() { // If the lookup returned null, we haven't initialized our own // local copy, so do that now. - let ptr: Box> = box Value { - inner: LazyKeyInner::new(), - key: self, - }; + let ptr: Box> = box Value { inner: LazyKeyInner::new(), key: self }; let ptr = Box::into_raw(ptr); self.os.set(ptr as *mut u8); ptr @@ -545,7 +529,7 @@ pub mod os { } } - unsafe extern fn destroy_value(ptr: *mut u8) { + unsafe extern "C" fn destroy_value(ptr: *mut u8) { // The OS TLS ensures that this key contains a NULL value when this // destructor starts to run. We set it back to a sentinel value of 1 to // ensure that any future calls to `get` for this thread will return @@ -563,8 +547,8 @@ pub mod os { #[cfg(all(test, not(target_os = "emscripten")))] mod tests { - use crate::sync::mpsc::{channel, Sender}; use crate::cell::{Cell, UnsafeCell}; + use crate::sync::mpsc::{channel, Sender}; use crate::thread; struct Foo(Sender<()>); @@ -585,7 +569,7 @@ mod tests { f.set(2); }); let (tx, rx) = channel(); - let _t = thread::spawn(move|| { + let _t = thread::spawn(move || { FOO.with(|f| { assert_eq!(f.get(), 1); }); @@ -610,7 +594,10 @@ mod tests { thread::spawn(|| { assert!(FOO.try_with(|_| ()).is_ok()); - }).join().ok().expect("thread panicked"); + }) + .join() + .ok() + .expect("thread panicked"); } #[test] @@ -618,7 +605,7 @@ mod tests { thread_local!(static FOO: UnsafeCell> = UnsafeCell::new(None)); let (tx, rx) = channel(); - let _t = thread::spawn(move|| unsafe { + let _t = thread::spawn(move || unsafe { let mut tx = Some(tx); FOO.with(|f| { *f.get() = Some(Foo(tx.take().unwrap())); @@ -662,9 +649,12 @@ mod tests { } } - thread::spawn(move|| { + thread::spawn(move || { drop(S1); - }).join().ok().expect("thread panicked"); + }) + .join() + .ok() + .expect("thread panicked"); } #[test] @@ -678,9 +668,12 @@ mod tests { } } - thread::spawn(move|| unsafe { + thread::spawn(move || unsafe { K1.with(|s| *s.get() = Some(S1)); - }).join().ok().expect("thread panicked"); + }) + .join() + .ok() + .expect("thread panicked"); } // Note that this test will deadlock if TLS destructors aren't run (this @@ -701,7 +694,7 @@ mod tests { } let (tx, rx) = channel(); - let _t = thread::spawn(move|| unsafe { + let _t = thread::spawn(move || unsafe { let mut tx = Some(tx); K1.with(|s| *s.get() = Some(S1(tx.take().unwrap()))); }); @@ -716,7 +709,9 @@ mod dynamic_tests { #[test] fn smoke() { - fn square(i: i32) -> i32 { i * i } + fn square(i: i32) -> i32 { + i * i + } thread_local!(static FOO: i32 = square(3)); FOO.with(|f| { diff --git a/src/test/ui/fmt/format-string-error.rs b/src/test/ui/fmt/format-string-error.rs index 691c06a2402c5..eae4f3cb5479f 100644 --- a/src/test/ui/fmt/format-string-error.rs +++ b/src/test/ui/fmt/format-string-error.rs @@ -6,10 +6,12 @@ fn main() { println!("{{}}"); println!("}"); //~^ ERROR invalid format string: unmatched `}` found - let _ = format!("{_foo}", _foo = 6usize); - //~^ ERROR invalid format string: invalid argument name `_foo` let _ = format!("{_}", _ = 6usize); //~^ ERROR invalid format string: invalid argument name `_` + let _ = format!("{a:_}", a = "", _ = 0); + //~^ ERROR invalid format string: invalid argument name `_` + let _ = format!("{a:._$}", a = "", _ = 0); + //~^ ERROR invalid format string: invalid argument name `_` let _ = format!("{"); //~^ ERROR invalid format string: expected `'}'` but string was terminated let _ = format!("}"); diff --git a/src/test/ui/fmt/format-string-error.stderr b/src/test/ui/fmt/format-string-error.stderr index 32119b18774b2..8b018480fb082 100644 --- a/src/test/ui/fmt/format-string-error.stderr +++ b/src/test/ui/fmt/format-string-error.stderr @@ -16,24 +16,32 @@ LL | println!("}"); | = note: if you intended to print `}`, you can escape it using `}}` -error: invalid format string: invalid argument name `_foo` +error: invalid format string: invalid argument name `_` --> $DIR/format-string-error.rs:9:23 | -LL | let _ = format!("{_foo}", _foo = 6usize); - | ^^^^ invalid argument name in format string +LL | let _ = format!("{_}", _ = 6usize); + | ^ invalid argument name in format string | - = note: argument names cannot start with an underscore + = note: argument name cannot be a single underscore error: invalid format string: invalid argument name `_` - --> $DIR/format-string-error.rs:11:23 + --> $DIR/format-string-error.rs:11:25 | -LL | let _ = format!("{_}", _ = 6usize); - | ^ invalid argument name in format string +LL | let _ = format!("{a:_}", a = "", _ = 0); + | ^ invalid argument name in format string + | + = note: argument name cannot be a single underscore + +error: invalid format string: invalid argument name `_` + --> $DIR/format-string-error.rs:13:26 + | +LL | let _ = format!("{a:._$}", a = "", _ = 0); + | ^ invalid argument name in format string | - = note: argument names cannot start with an underscore + = note: argument name cannot be a single underscore error: invalid format string: expected `'}'` but string was terminated - --> $DIR/format-string-error.rs:13:23 + --> $DIR/format-string-error.rs:15:23 | LL | let _ = format!("{"); | -^ expected `'}'` in format string @@ -43,7 +51,7 @@ LL | let _ = format!("{"); = note: if you intended to print `{`, you can escape it using `{{` error: invalid format string: unmatched `}` found - --> $DIR/format-string-error.rs:15:22 + --> $DIR/format-string-error.rs:17:22 | LL | let _ = format!("}"); | ^ unmatched `}` in format string @@ -51,7 +59,7 @@ LL | let _ = format!("}"); = note: if you intended to print `}`, you can escape it using `}}` error: invalid format string: expected `'}'`, found `'\'` - --> $DIR/format-string-error.rs:17:23 + --> $DIR/format-string-error.rs:19:23 | LL | let _ = format!("{\}"); | -^ expected `}` in format string @@ -61,7 +69,7 @@ LL | let _ = format!("{\}"); = note: if you intended to print `{`, you can escape it using `{{` error: invalid format string: expected `'}'` but string was terminated - --> $DIR/format-string-error.rs:19:35 + --> $DIR/format-string-error.rs:21:35 | LL | let _ = format!("\n\n\n{\n\n\n"); | - ^ expected `'}'` in format string @@ -71,7 +79,7 @@ LL | let _ = format!("\n\n\n{\n\n\n"); = note: if you intended to print `{`, you can escape it using `{{` error: invalid format string: expected `'}'` but string was terminated - --> $DIR/format-string-error.rs:25:3 + --> $DIR/format-string-error.rs:27:3 | LL | {"###); | -^ expected `'}'` in format string @@ -81,7 +89,7 @@ LL | {"###); = note: if you intended to print `{`, you can escape it using `{{` error: invalid format string: expected `'}'` but string was terminated - --> $DIR/format-string-error.rs:33:1 + --> $DIR/format-string-error.rs:35:1 | LL | { | - because of this opening brace @@ -92,7 +100,7 @@ LL | "###); = note: if you intended to print `{`, you can escape it using `{{` error: invalid format string: unmatched `}` found - --> $DIR/format-string-error.rs:39:2 + --> $DIR/format-string-error.rs:41:2 | LL | } | ^ unmatched `}` in format string @@ -100,7 +108,7 @@ LL | } = note: if you intended to print `}`, you can escape it using `}}` error: invalid format string: unmatched `}` found - --> $DIR/format-string-error.rs:47:9 + --> $DIR/format-string-error.rs:49:9 | LL | } | ^ unmatched `}` in format string @@ -108,10 +116,10 @@ LL | } = note: if you intended to print `}`, you can escape it using `}}` error: 3 positional arguments in format string, but there are 2 arguments - --> $DIR/format-string-error.rs:51:15 + --> $DIR/format-string-error.rs:53:15 | LL | println!("{} {} {}", 1, 2); | ^^ ^^ ^^ - - -error: aborting due to 13 previous errors +error: aborting due to 14 previous errors diff --git a/src/test/ui/ifmt.rs b/src/test/ui/ifmt.rs index 841be20ef8645..1a070843cc446 100644 --- a/src/test/ui/ifmt.rs +++ b/src/test/ui/ifmt.rs @@ -90,6 +90,7 @@ pub fn main() { t!(format!("{foo} {bar}", foo=0, bar=1), "0 1"); t!(format!("{foo} {1} {bar} {0}", 0, 1, foo=2, bar=3), "2 1 3 0"); t!(format!("{} {0}", "a"), "a a"); + t!(format!("{_foo}", _foo = 6usize), "6"); t!(format!("{foo_bar}", foo_bar=1), "1"); t!(format!("{}", 5 + 5), "10"); t!(format!("{:#4}", C), "☃123"); @@ -125,6 +126,7 @@ pub fn main() { t!(format!("{:.*}", 4, "aaaaaaaaaaaaaaaaaa"), "aaaa"); t!(format!("{:.1$}", "aaaaaaaaaaaaaaaaaa", 4), "aaaa"); t!(format!("{:.a$}", "aaaaaaaaaaaaaaaaaa", a=4), "aaaa"); + t!(format!("{:._a$}", "aaaaaaaaaaaaaaaaaa", _a=4), "aaaa"); t!(format!("{:1$}", "a", 4), "a "); t!(format!("{1:0$}", 4, "a"), "a "); t!(format!("{:a$}", "a", a=4), "a "); diff --git a/src/test/ui/issues/issue-27033.stderr b/src/test/ui/issues/issue-27033.stderr index 2d6d2ef41bd74..d3f8407f8e262 100644 --- a/src/test/ui/issues/issue-27033.stderr +++ b/src/test/ui/issues/issue-27033.stderr @@ -6,8 +6,8 @@ LL | None @ _ => {} | ::: $SRC_DIR/libstd/prelude/v1.rs:LL:COL | -LL | pub use crate::option::Option::{self, Some, None}; - | ---- the unit variant `None` is defined here +LL | pub use crate::option::Option::{self, None, Some}; + | ---- the unit variant `None` is defined here error[E0530]: match bindings cannot shadow constants --> $DIR/issue-27033.rs:8:9