提交 d8bdb3fd 编写于 作者: B bors

Auto merge of #66887 - dtolnay:rollup-uxowp8d, r=Centril

Rollup of 4 pull requests

Successful merges:

 - #66818 (Format libstd/os with rustfmt)
 - #66819 (Format libstd/sys with rustfmt)
 - #66820 (Format libstd with rustfmt)
 - #66847 (Allow any identifier as format arg name)

Failed merges:

r? @ghost
......@@ -442,20 +442,9 @@ fn position(&mut self) -> Option<Position> {
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 @@ fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
/// 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
......
......@@ -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.
///
......
......@@ -95,10 +95,10 @@
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.
///
......
#![cfg(test)]
use test::Bencher;
use std::collections::HashMap;
use test::Bencher;
#[bench]
fn new_drop(b: &mut Bencher) {
......
......@@ -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;
......
......@@ -78,7 +78,9 @@ pub fn set_current_dir<P: AsRef<Path>>(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<usize>) {
self.inner.size_hint()
}
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
}
#[stable(feature = "std_debug", since = "1.16.0")]
......@@ -164,8 +168,12 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[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<usize>) { self.inner.size_hint() }
fn next(&mut self) -> Option<(OsString, OsString)> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
#[stable(feature = "std_debug", since = "1.16.0")]
......@@ -239,9 +247,8 @@ pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
}
fn _var_os(key: &OsStr) -> Option<OsString> {
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<K: AsRef<OsStr>, V: AsRef<OsStr>>(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: AsRef<OsStr>>(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<T: AsRef<OsStr> + ?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<PathBuf> { self.inner.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
fn next(&mut self) -> Option<PathBuf> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
#[stable(feature = "std_debug", since = "1.16.0")]
......@@ -430,7 +441,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[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<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: IntoIterator<Item=T>, T: AsRef<OsStr>
where
I: IntoIterator<Item = T>,
T: AsRef<OsStr>,
{
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 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[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 @@ fn description(&self) -> &str { self.inner.description() }
/// 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<PathBuf> {
os_imp::home_dir()
......@@ -674,7 +689,9 @@ pub fn current_exe() -> io::Result<PathBuf> {
/// [`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<String> {
self.inner.next().map(|s| s.into_string().unwrap())
}
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
fn size_hint(&self) -> (usize, Option<usize>) {
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 @@ fn next_back(&mut self) -> Option<String> {
#[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<OsString> { self.inner.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
fn next(&mut self) -> Option<OsString> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
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<OsString> { self.inner.next_back() }
fn next_back(&mut self) -> Option<OsString> {
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 @@ fn split_paths_windows() {
use crate::path::PathBuf;
fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
split_paths(unparsed).collect::<Vec<_>>() ==
parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
split_paths(unparsed).collect::<Vec<_>>()
== parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
}
assert!(check_parse("", &mut [""]));
......@@ -1042,11 +1073,12 @@ fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
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 @@ fn split_paths_unix() {
use crate::path::PathBuf;
fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
split_paths(unparsed).collect::<Vec<_>>() ==
parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
split_paths(unparsed).collect::<Vec<_>>()
== parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
}
assert!(check_parse("", &mut [""]));
......@@ -1072,15 +1104,12 @@ fn join_paths_unix() {
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 @@ fn join_paths_windows() {
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 @@ fn test_eq(input: &[&str], output: &str) -> bool {
fn args_debug() {
assert_eq!(
format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
format!("{:?}", args()));
format!("{:?}", args())
);
assert_eq!(
format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
format!("{:?}", args_os()));
format!("{:?}", args_os())
);
}
}
......@@ -14,15 +14,15 @@
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 @@ pub fn trunc(self) -> 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 @@ pub fn abs(self) -> 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 @@ pub fn mul_add(self, a: f32, b: f32) -> 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 @@ pub fn div_euclid(self, rhs: f32) -> 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 @@ pub fn powf(self, n: f32) -> 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 @@ pub fn ln(self) -> 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 @@ pub fn log10(self) -> 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 @@ pub fn asinh(self) -> 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 @@ pub fn atanh(self) -> 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 @@ fn test_abs() {
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 @@ fn test_signum() {
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 @@ fn test_is_sign_positive() {
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 @@ fn test_is_sign_negative() {
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());
}
......
......@@ -14,15 +14,15 @@
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 @@ pub fn trunc(self) -> 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 @@ pub fn abs(self) -> 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 @@ pub fn div_euclid(self, rhs: f64) -> 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 @@ pub fn powf(self, n: f64) -> 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 @@ pub fn exp2(self) -> 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 @@ pub fn ln(self) -> 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 @@ pub fn log(self, base: f64) -> f64 { self.ln() / base.ln() }
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 @@ pub fn log2(self) -> 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 @@ pub fn log10(self) -> 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 @@ pub fn asinh(self) -> 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 @@ pub fn atanh(self) -> 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 @@ fn log_wrapper<F: Fn(f64) -> f64>(self, log_fn: F) -> 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() {
......
......@@ -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;
......
此差异已折叠。
......@@ -5,8 +5,9 @@
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<R>` struct adds buffering to any reader.
......@@ -100,12 +101,7 @@ pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> {
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<R> BufReader<R> {
/// }
/// ```
#[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 @@ pub fn get_ref(&self) -> &R { &self.inner }
/// }
/// ```
#[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 @@ pub fn buffer(&self) -> &[u8] {
/// }
/// ```
#[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 @@ pub fn seek_relative(&mut self, offset: i64) -> io::Result<()> {
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 @@ fn consume(&mut self, amt: usize) {
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<R> fmt::Debug for BufReader<R> where R: fmt::Debug {
impl<R> fmt::Debug for BufReader<R>
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 @@ pub fn new(inner: W) -> BufWriter<W> {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with_capacity(capacity: usize, inner: W) -> BufWriter<W> {
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 @@ fn flush_buf(&mut self) -> io::Result<()> {
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 @@ fn flush_buf(&mut self) -> io::Result<()> {
/// 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 @@ pub fn get_ref(&self) -> &W { self.inner.as_ref().unwrap() }
/// 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 @@ pub fn buffer(&self) -> &[u8] {
pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> {
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 @@ fn flush(&mut self) -> io::Result<()> {
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<W: Write> fmt::Debug for BufWriter<W> where W: fmt::Debug {
impl<W: Write> fmt::Debug for BufWriter<W>
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<W> IntoInnerError<W> {
/// };
/// ```
#[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 @@ pub fn error(&self) -> &Error { &self.1 }
/// };
/// ```
#[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<W> From<IntoInnerError<W>> for Error {
fn from(iie: IntoInnerError<W>) -> Error { iie.1 }
fn from(iie: IntoInnerError<W>) -> Error {
iie.1
}
}
#[stable(feature = "rust1", since = "1.0.0")]
......@@ -856,10 +872,7 @@ pub fn new(inner: W) -> LineWriter<W> {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with_capacity(capacity: usize, inner: W) -> LineWriter<W> {
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 @@ pub fn with_capacity(capacity: usize, inner: W) -> LineWriter<W> {
/// }
/// ```
#[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 @@ pub fn get_ref(&self) -> &W { self.inner.get_ref() }
/// }
/// ```
#[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 @@ pub fn get_mut(&mut self) -> &mut W { self.inner.get_mut() }
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> {
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 @@ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
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 @@ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
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 @@ fn flush(&mut self) -> io::Result<()> {
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<W: Write> fmt::Debug for LineWriter<W> where W: fmt::Debug {
impl<W: Write> fmt::Debug for LineWriter<W>
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 @@ pub struct ShortReader {
impl Read for ShortReader {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
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 @@ fn test_buffered_reader_invalidated_after_seek() {
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<usize> {
......@@ -1154,7 +1168,7 @@ fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
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 @@ fn test_lines() {
#[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 @@ fn dont_panic_in_drop_on_panicked_flush() {
struct FailFlushWriter;
impl Write for FailFlushWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Err(io::Error::last_os_error())
}
......@@ -1405,30 +1421,30 @@ fn write(&mut self, _: &[u8]) -> io::Result<usize> {
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 @@ fn flush(&mut self) -> io::Result<()> {
#[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);
......
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<dyn error::Error+Send+Sync>,
error: Box<dyn error::Error + Send + Sync>,
}
/// A list specifying general categories of I/O error.
......@@ -220,9 +220,7 @@ impl From<ErrorKind> 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<E>(kind: ErrorKind, error: E) -> Error
where E: Into<Box<dyn error::Error+Send+Sync>>
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
Self::_new(kind, error.into())
}
fn _new(kind: ErrorKind, error: Box<dyn error::Error+Send+Sync>) -> Error {
Error {
repr: Repr::Custom(Box::new(Custom {
kind,
error,
}))
}
fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
Error { repr: Repr::Custom(Box::new(Custom { kind, error })) }
}
/// Returns an error representing the last OS error which occurred.
......@@ -370,7 +364,7 @@ pub fn raw_os_error(&self) -> Option<i32> {
/// }
/// ```
#[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 @@ pub fn get_ref(&self) -> Option<&(dyn error::Error+Send+Sync+'static)> {
/// }
/// ```
#[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 @@ pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error+Send+Sync+'static)> {
/// }
/// ```
#[stable(feature = "io_error_inner", since = "1.3.0")]
pub fn into_inner(self) -> Option<Box<dyn error::Error+Send+Sync>> {
pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
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 @@ pub fn kind(&self) -> ErrorKind {
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 @@ fn source(&self) -> Option<&(dyn error::Error + 'static)> {
}
fn _assert_error_is_sync_send() {
fn _is_sync_send<T: Sync+Send>() {}
fn _is_sync_send<T: Sync + Send>() {}
_is_sync_send::<Error>();
}
#[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 @@ fn test_debug_error() {
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);
......
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 @@ fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<W: Write + ?Sized> Write for &mut W {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) }
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(**self).write(buf)
}
#[inline]
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
......@@ -50,7 +53,9 @@ fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
}
#[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 @@ fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<S: Seek + ?Sized> Seek for &mut S {
#[inline]
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) }
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
(**self).seek(pos)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<B: BufRead + ?Sized> 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<u8>) -> io::Result<usize> {
......@@ -121,7 +132,9 @@ fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<W: Write + ?Sized> Write for Box<W> {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) }
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(**self).write(buf)
}
#[inline]
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
......@@ -129,7 +142,9 @@ fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
}
#[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 @@ fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<S: Seek + ?Sized> Seek for Box<S> {
#[inline]
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) }
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
(**self).seek(pos)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<B: BufRead + ?Sized> BufRead for Box<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<u8>) -> io::Result<usize> {
......@@ -227,8 +248,7 @@ unsafe fn initializer(&self) -> Initializer {
#[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 @@ fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
#[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 @@ fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
}
#[inline]
fn flush(&mut self) -> io::Result<()> { Ok(()) }
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
/// Write is implemented for `Vec<u8>` by appending to the vector.
......@@ -332,7 +358,9 @@ fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
}
#[inline]
fn flush(&mut self) -> io::Result<()> { Ok(()) }
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[cfg(test)]
......
......@@ -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<u8>, len: usize }
struct Guard<'a> {
buf: &'a mut Vec<u8>,
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 @@ fn drop(&mut self) {
// 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<F>(buf: &mut String, f: F) -> Result<usize>
where F: FnOnce(&mut Vec<u8>) -> Result<usize>
where
F: FnOnce(&mut Vec<u8>) -> Result<usize>,
{
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 @@ fn read_to_end_with_reservation<R, F>(
pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
where
F: FnOnce(&mut [u8]) -> Result<usize>
F: FnOnce(&mut [u8]) -> Result<usize>,
{
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<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
where
F: FnOnce(&[u8]) -> Result<usize>
F: FnOnce(&[u8]) -> Result<usize>,
{
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 @@ fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
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 @@ fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
/// }
/// ```
#[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 @@ fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn bytes(self) -> Bytes<Self> where Self: Sized {
fn bytes(self) -> Bytes<Self>
where
Self: Sized,
{
Bytes { inner: self }
}
......@@ -887,7 +896,10 @@ fn bytes(self) -> Bytes<Self> where Self: Sized {
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
fn chain<R: Read>(self, next: R) -> Chain<Self, R>
where
Self: Sized,
{
Chain { first: self, second: next, done_first: false }
}
......@@ -923,7 +935,10 @@ fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn take(self, limit: u64) -> Take<Self> where Self: Sized {
fn take(self, limit: u64) -> Take<Self>
where
Self: Sized,
{
Take { inner: self, limit: limit }
}
}
......@@ -1339,8 +1354,9 @@ fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
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 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
/// }
/// ```
#[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: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
-> Result<usize> {
fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
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 @@ fn read_line(&mut self, buf: &mut String) -> Result<usize> {
/// assert_eq!(split_iter.next(), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn split(self, byte: u8) -> Split<Self> where Self: Sized {
fn split(self, byte: u8) -> Split<Self>
where
Self: Sized,
{
Split { buf: self, delim: byte }
}
......@@ -1939,7 +1962,10 @@ fn split(self, byte: u8) -> Split<Self> where Self: Sized {
///
/// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
#[stable(feature = "rust1", since = "1.0.0")]
fn lines(self) -> Lines<Self> where Self: Sized {
fn lines(self) -> Lines<Self>
where
Self: Sized,
{
Lines { buf: self }
}
}
......@@ -2035,10 +2061,7 @@ pub fn get_mut(&mut self) -> (&mut T, &mut U) {
#[stable(feature = "std_debug", since = "1.16.0")]
impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
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 @@ fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
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<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
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 @@ fn fill_buf(&mut self) -> Result<&[u8]> {
}
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<T> Take<T> {
/// }
/// ```
#[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 @@ fn next(&mut self) -> Option<Result<Vec<u8>>> {
}
Some(Ok(buf))
}
Err(e) => Some(Err(e))
Err(e) => Some(Err(e)),
}
}
}
......@@ -2385,16 +2404,16 @@ fn next(&mut self) -> Option<Result<String>> {
}
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 @@ fn read_exact() {
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 @@ fn read_exact_slice() {
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 @@ impl BufRead for R {
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 @@ fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8
#[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 @@ fn seek_position() -> io::Result<()> {
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 @@ fn test_read_to_end_capacity() -> io::Result<()> {
// 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");
......
......@@ -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};
#![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 @@
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
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<R: ?Sized, W: ?Sized>(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<R: ?Sized, W: ?Sized>(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<usize> { Ok(0) }
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
#[inline]
unsafe fn initializer(&self) -> Initializer {
......@@ -106,7 +116,9 @@ unsafe fn initializer(&self) -> Initializer {
#[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 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///
/// [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 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///
/// [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<usize> { Ok(buf.len()) }
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
Ok(buf.len())
}
#[inline]
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
......@@ -214,7 +236,9 @@ fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
}
#[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 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[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() {
......
......@@ -313,9 +313,8 @@
#[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);
}};
}
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 @@ pub fn new(ip: Ipv4Addr, port: u16) -> 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 @@ pub fn new(ip: Ipv4Addr, port: u16) -> 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 @@ pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
sin6_addr: *ip.as_inner(),
sin6_flowinfo: flowinfo,
sin6_scope_id: scope_id,
.. unsafe { mem::zeroed() }
..unsafe { mem::zeroed() }
},
}
}
......@@ -388,9 +389,7 @@ pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
/// ```
#[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 @@ fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
#[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 @@ fn hash<H: hash::Hasher>(&self, s: &mut H) {
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for SocketAddrV6 {
fn hash<H: hash::Hasher>(&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<Item=SocketAddr>;
type Iter: Iterator<Item = SocketAddr>;
/// Converts this object to an iterator of resolved `SocketAddr`s.
///
......@@ -864,7 +872,12 @@ fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
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 @@ fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
// try to parse the host as a regular IP address first
if let Ok(addr) = host.parse::<Ipv4Addr>() {
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::<Ipv6Addr>() {
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 @@ fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
#[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 @@ fn to_socket_addr_str_bad() {
#[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 @@ fn is_v4() {
#[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());
}
......
......@@ -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 @@ fn is_eof(&self) -> bool {
}
// Commit only if parser returns Some
fn read_atomically<T, F>(&mut self, cb: F) -> Option<T> where
fn read_atomically<T, F>(&mut self, cb: F) -> Option<T>
where
F: FnOnce(&mut Parser<'_>) -> Option<T>,
{
let pos = self.pos;
......@@ -39,17 +37,18 @@ fn read_atomically<T, F>(&mut self, cb: F) -> Option<T> where
}
// Commit only if parser read till EOF
fn read_till_eof<T, F>(&mut self, cb: F) -> Option<T> where
fn read_till_eof<T, F>(&mut self, cb: F) -> Option<T>
where
F: FnOnce(&mut Parser<'_>) -> Option<T>,
{
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<T>(&mut self, parsers: &mut [Box<dyn FnMut(&mut Parser<'_>) -> Option<T> + 'static>])
-> Option<T> {
fn read_or<T>(
&mut self,
parsers: &mut [Box<dyn FnMut(&mut Parser<'_>) -> Option<T> + 'static>],
) -> Option<T> {
for pf in parsers {
if let Some(r) = self.read_atomically(|p: &mut Parser<'_>| pf(p)) {
return Some(r);
......@@ -59,11 +58,8 @@ fn read_or<T>(&mut self, parsers: &mut [Box<dyn FnMut(&mut Parser<'_>) -> Option
}
// Apply 3 parsers sequentially
fn read_seq_3<A, B, C, PA, PB, PC>(&mut self,
pa: PA,
pb: PB,
pc: PC)
-> Option<(A, B, C)> where
fn read_seq_3<A, B, C, PA, PB, PC>(&mut self, pa: PA, pb: PB, pc: PC) -> Option<(A, B, C)>
where
PA: FnOnce(&mut Parser<'_>) -> Option<A>,
PB: FnOnce(&mut Parser<'_>) -> Option<B>,
PC: FnOnce(&mut Parser<'_>) -> Option<C>,
......@@ -74,7 +70,7 @@ fn read_seq_3<A, B, C, PA, PB, PC>(&mut self,
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 @@ fn read_char(&mut self) -> Option<char> {
// Return char and advance iff next char is equal to requested
fn read_given_char(&mut self, c: char) -> Option<char> {
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 @@ fn parse_digit(c: char, radix: u8) -> Option<u8> {
}
}
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<u32> {
......@@ -130,14 +122,14 @@ fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<
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 @@ fn ipv6_addr_from_head_tail(head: &[u16], tail: &[u16]) -> Ipv6Addr {
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 @@ fn ipv6_addr_from_head_tail(head: &[u16], tail: &[u16]) -> Ipv6Addr {
});
match group {
Some(g) => groups[i] = g,
None => return (i, false)
None => return (i, false),
}
i += 1;
}
......@@ -218,13 +209,13 @@ fn ipv6_addr_from_head_tail(head: &[u16], tail: &[u16]) -> Ipv6Addr {
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 @@ fn read_ip_addr(&mut self) -> Option<IpAddr> {
fn read_socket_addr_v4(&mut self) -> Option<SocketAddrV4> {
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 @@ fn read_socket_addr_v6(&mut self) -> Option<SocketAddrV6> {
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<IpAddr, AddrParseError> {
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<Ipv4Addr, AddrParseError> {
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<Ipv6Addr, AddrParseError> {
match Parser::new(s).read_till_eof(|p| p.read_ipv6_addr()) {
Some(s) => Ok(s),
None => Err(AddrParseError(()))
None => Err(AddrParseError(())),
}
}
}
......
此差异已折叠。
#![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
}
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 @@ pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
/// 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<A: ToSocketAddrs>(&self, buf: &[u8], addr: A)
-> io::Result<usize> {
pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
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 @@ pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
}
impl AsInner<net_imp::UdpSocket> for UdpSocket {
fn as_inner(&self) -> &net_imp::UdpSocket { &self.0 }
fn as_inner(&self) -> &net_imp::UdpSocket {
&self.0
}
}
impl FromInner<net_imp::UdpSocket> for UdpSocket {
fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { UdpSocket(inner) }
fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket {
UdpSocket(inner)
}
}
impl IntoInner<net_imp::UdpSocket> 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 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[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 @@ fn each_ip(f: &mut dyn FnMut(SocketAddr, SocketAddr)) {
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 @@ fn socket_smoke_test_ip4() {
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 @@ fn udp_clone_smoke() {
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 @@ fn udp_clone_smoke() {
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 @@ fn udp_clone_two_read() {
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 @@ fn udp_clone_two_read() {
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 @@ fn udp_clone_two_write() {
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 @@ fn udp_clone_two_write() {
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 @@ fn udp_clone_two_write() {
#[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 @@ fn test_read_timeout() {
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 @@ fn test_read_with_timeout() {
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;
}
}
......
......@@ -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<T>(ten: T, two: T) where
pub fn test_num<T>(ten: T, two: T)
where
T: PartialEq
+ Add<Output=T> + Sub<Output=T>
+ Mul<Output=T> + Div<Output=T>
+ Rem<Output=T> + fmt::Debug
+ Copy
+ Add<Output = T>
+ Sub<Output = T>
+ Mul<Output = T>
+ Div<Output = T>
+ Rem<Output = T>
+ 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 @@ fn test_saturating_sub_uint() {
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 @@ fn test_saturating_add_int() {
#[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 @@ fn test_checked_mul() {
}
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 @@ fn $test_name() {
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 @@ fn $test_name() {
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 @@ fn $test_name() {
#[test]
fn test_pow() {
fn naive_pow<T: Mul<Output=T> + Copy>(one: T, base: T, exp: usize) -> T {
fn naive_pow<T: Mul<Output = T> + Copy>(one: T, base: T, exp: usize) -> T {
(0..exp).fold(one, |acc, _| acc * base)
}
macro_rules! assert_pow {
......@@ -204,7 +216,7 @@ fn naive_pow<T: Mul<Output=T> + Copy>(one: T, base: T, exp: usize) -> T {
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 @@ fn test_uint_from_str_overflow() {
}
}
#[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::<Vec<u32>>();
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));
});
}
}
......@@ -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
......
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
//! 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 @@
#[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 @@ pub struct stat {
#[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 @@ pub struct stat {
#[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;
......
......@@ -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
......
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
//! 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;
......
......@@ -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
......
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
......@@ -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)]
......
......@@ -21,19 +21,20 @@ pub mod alloc {
/// 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 {
......
......@@ -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
......
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
//! 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;
......
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
//! 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 @@ pub struct stat {
#[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 @@ pub struct stat {
#[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)]
......
......@@ -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
......
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
//! 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)]
......
......@@ -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
......
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
//! 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;
......
......@@ -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
......
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
此差异已折叠。
......@@ -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
......
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
//! 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;
......
此差异已折叠。
......@@ -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
......
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
此差异已折叠。
此差异已折叠。
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
此差异已折叠。
此差异已折叠。
此差异已折叠。
......@@ -2,5 +2,5 @@
#![stable(feature = "raw_ext", since = "1.1.0")]
pub mod raw;
pub mod fs;
pub mod raw;
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册