diff options
| author | David Tolnay <dtolnay@gmail.com> | 2019-11-27 10:29:00 -0800 |
|---|---|---|
| committer | David Tolnay <dtolnay@gmail.com> | 2019-11-29 18:43:27 -0800 |
| commit | 4436c9d35498e7ae3da261f6141d6d73b915e1e8 (patch) | |
| tree | 5bee9f8714a41c4ad672d0cc5c302ede56197726 /src/libstd/io | |
| parent | 9081929d45f12d3f56d43b1d6db7519981580fc9 (diff) | |
| download | rust-4436c9d35498e7ae3da261f6141d6d73b915e1e8.tar.gz rust-4436c9d35498e7ae3da261f6141d6d73b915e1e8.zip | |
Format libstd with rustfmt
This commit applies rustfmt with rust-lang/rust's default settings to
files in src/libstd *that are not involved in any currently open PR* to
minimize merge conflicts. THe list of files involved in open PRs was
determined by querying GitHub's GraphQL API with this script:
https://gist.github.com/dtolnay/aa9c34993dc051a4f344d1b10e4487e8
With the list of files from the script in outstanding_files, the
relevant commands were:
$ find src/libstd -name '*.rs' \
| xargs rustfmt --edition=2018 --unstable-features --skip-children
$ rg libstd outstanding_files | xargs git checkout --
Repeating this process several months apart should get us coverage of
most of the rest of libstd.
To confirm no funny business:
$ git checkout $THIS_COMMIT^
$ git show --pretty= --name-only $THIS_COMMIT \
| xargs rustfmt --edition=2018 --unstable-features --skip-children
$ git diff $THIS_COMMIT # there should be no difference
Diffstat (limited to 'src/libstd/io')
| -rw-r--r-- | src/libstd/io/buffered.rs | 147 | ||||
| -rw-r--r-- | src/libstd/io/error.rs | 65 | ||||
| -rw-r--r-- | src/libstd/io/impls.rs | 64 | ||||
| -rw-r--r-- | src/libstd/io/mod.rs | 168 | ||||
| -rw-r--r-- | src/libstd/io/prelude.rs | 2 | ||||
| -rw-r--r-- | src/libstd/io/util.rs | 52 |
6 files changed, 283 insertions, 215 deletions
diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 557da174d89..8e81b292f6f 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -5,8 +5,9 @@ use crate::io::prelude::*; use crate::cmp; use crate::error; use crate::fmt; -use crate::io::{self, Initializer, DEFAULT_BUF_SIZE, Error, ErrorKind, SeekFrom, IoSlice, - IoSliceMut}; +use crate::io::{ + self, Error, ErrorKind, Initializer, IoSlice, IoSliceMut, SeekFrom, DEFAULT_BUF_SIZE, +}; use crate::memchr; /// The `BufReader<R>` struct adds buffering to any reader. @@ -100,12 +101,7 @@ impl<R: Read> 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 @@ impl<R> BufReader<R> { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_mut(&mut self) -> &mut R { &mut self.inner } + pub fn get_mut(&mut self) -> &mut R { + &mut self.inner + } /// Returns a reference to the internally buffered data. /// @@ -199,7 +199,9 @@ impl<R> BufReader<R> { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn into_inner(self) -> R { self.inner } + pub fn into_inner(self) -> R { + self.inner + } /// Invalidates all data in the internal buffer. #[inline] @@ -220,17 +222,17 @@ impl<R: Seek> BufReader<R> { if offset < 0 { if let Some(new_pos) = pos.checked_sub((-offset) as u64) { self.pos = new_pos as usize; - return Ok(()) + return Ok(()); } } else { if let Some(new_pos) = pos.checked_add(offset as u64) { if new_pos <= self.cap as u64 { self.pos = new_pos as usize; - return Ok(()) + return Ok(()); } } } - self.seek(SeekFrom::Current(offset)).map(|_|()) + self.seek(SeekFrom::Current(offset)).map(|_| ()) } } @@ -293,7 +295,10 @@ impl<R: Read> BufRead for BufReader<R> { } #[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 @@ impl<W: Write> 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 @@ impl<W: Write> BufWriter<W> { match r { Ok(0) => { - ret = Err(Error::new(ErrorKind::WriteZero, - "failed to write the buffered data")); + ret = + Err(Error::new(ErrorKind::WriteZero, "failed to write the buffered data")); break; } Ok(n) => written += n, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} - Err(e) => { ret = Err(e); break } - + Err(e) => { + ret = Err(e); + break; + } } } if written > 0 { @@ -531,7 +534,9 @@ impl<W: Write> BufWriter<W> { /// let reference = buffer.get_ref(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_ref(&self) -> &W { self.inner.as_ref().unwrap() } + pub fn get_ref(&self) -> &W { + self.inner.as_ref().unwrap() + } /// Gets a mutable reference to the underlying writer. /// @@ -549,7 +554,9 @@ impl<W: Write> BufWriter<W> { /// let reference = buffer.get_mut(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_mut(&mut self) -> &mut W { self.inner.as_mut().unwrap() } + pub fn get_mut(&mut self) -> &mut W { + self.inner.as_mut().unwrap() + } /// Returns a reference to the internally buffered data. /// @@ -592,7 +599,7 @@ impl<W: Write> BufWriter<W> { 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 @@ impl<W: Write> Write for BufWriter<W> { } #[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 @@ impl<W> IntoInnerError<W> { /// }; /// ``` #[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 @@ impl<W: Write> 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 @@ impl<W: Write> 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 @@ impl<W: Write> LineWriter<W> { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_mut(&mut self) -> &mut W { self.inner.get_mut() } + pub fn get_mut(&mut self) -> &mut W { + self.inner.get_mut() + } /// Unwraps this `LineWriter`, returning the underlying writer. /// @@ -930,10 +947,7 @@ impl<W: Write> LineWriter<W> { #[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 @@ impl<W: Write> Write for LineWriter<W> { None => return self.inner.write(buf), }; - // Ok, we're going to write a partial amount of the data given first // followed by flushing the newline. After we've successfully written // some data then we *must* report that we wrote that data, so future @@ -962,7 +975,7 @@ impl<W: Write> Write for LineWriter<W> { let n = self.inner.write(&buf[..=i])?; self.need_flush = true; if self.flush().is_err() || n != i + 1 { - return Ok(n) + return Ok(n); } // At this point we successfully wrote `i + 1` bytes and flushed it out, @@ -984,12 +997,17 @@ impl<W: Write> Write for LineWriter<W> { } #[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 @@ mod tests { 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 @@ mod tests { fn test_buffered_reader_seek_underflow() { // gimmick reader that yields its position modulo 256 for each byte struct PositionReader { - pos: u64 + pos: u64, } impl Read for PositionReader { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { @@ -1154,7 +1168,7 @@ mod tests { let mut reader = BufReader::with_capacity(5, PositionReader { pos: 0 }); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); - assert_eq!(reader.seek(SeekFrom::End(-5)).ok(), Some(u64::max_value()-5)); + assert_eq!(reader.seek(SeekFrom::End(-5)).ok(), Some(u64::max_value() - 5)); assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5)); // the following seek will require two underlying seeks let expected = 9223372036854775802; @@ -1361,7 +1375,7 @@ mod tests { #[test] fn test_short_reads() { - let inner = ShortReader{lengths: vec![0, 1, 2, 0, 1, 0]}; + let inner = ShortReader { lengths: vec![0, 1, 2, 0, 1, 0] }; let mut reader = BufReader::new(inner); let mut buf = [0, 0]; assert_eq!(reader.read(&mut buf).unwrap(), 0); @@ -1379,7 +1393,9 @@ mod tests { struct FailFlushWriter; impl Write for FailFlushWriter { - fn write(&mut self, buf: &[u8]) -> io::Result<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 @@ mod tests { WRITES.fetch_add(1, Ordering::SeqCst); panic!(); } - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } thread::spawn(|| { let mut writer = BufWriter::new(PanicWriter); let _ = writer.write(b"hello world"); let _ = writer.flush(); - }).join().unwrap_err(); + }) + .join() + .unwrap_err(); assert_eq!(WRITES.load(Ordering::SeqCst), 1); } #[bench] fn bench_buffered_reader(b: &mut test::Bencher) { - b.iter(|| { - BufReader::new(io::empty()) - }); + b.iter(|| BufReader::new(io::empty())); } #[bench] fn bench_buffered_writer(b: &mut test::Bencher) { - b.iter(|| { - BufWriter::new(io::sink()) - }); + b.iter(|| BufWriter::new(io::sink())); } struct AcceptOneThenFail { @@ -1457,10 +1473,7 @@ mod tests { #[test] fn erroneous_flush_retried() { - let a = AcceptOneThenFail { - written: false, - flushed: false, - }; + let a = AcceptOneThenFail { written: false, flushed: false }; let mut l = LineWriter::new(a); assert_eq!(l.write(b"a\nb\na").unwrap(), 4); diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs index c29a68e6f02..c20bd3097b2 100644 --- a/src/libstd/io/error.rs +++ b/src/libstd/io/error.rs @@ -1,8 +1,8 @@ +use crate::convert::From; use crate::error; use crate::fmt; use crate::result; use crate::sys; -use crate::convert::From; /// A specialized [`Result`](../result/enum.Result.html) type for I/O /// operations. @@ -73,7 +73,7 @@ enum Repr { #[derive(Debug)] struct Custom { kind: ErrorKind, - error: Box<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 @@ impl Error { /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] - pub fn get_ref(&self) -> Option<&(dyn error::Error+Send+Sync+'static)> { + pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> { match self.repr { Repr::Os(..) => None, Repr::Simple(..) => None, @@ -441,7 +435,7 @@ impl Error { /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] - pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error+Send+Sync+'static)> { + pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> { match self.repr { Repr::Os(..) => None, Repr::Simple(..) => None, @@ -475,11 +469,11 @@ impl Error { /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] - pub fn into_inner(self) -> Option<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 @@ impl Error { impl fmt::Debug for Repr { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - Repr::Os(code) => - fmt.debug_struct("Os") - .field("code", &code) - .field("kind", &sys::decode_error_kind(code)) - .field("message", &sys::os::error_string(code)).finish(), + Repr::Os(code) => fmt + .debug_struct("Os") + .field("code", &code) + .field("kind", &sys::decode_error_kind(code)) + .field("message", &sys::os::error_string(code)) + .finish(), Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt), Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(), } @@ -567,17 +562,17 @@ impl error::Error for Error { } fn _assert_error_is_sync_send() { - fn _is_sync_send<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 @@ mod test { let err = Error { repr: Repr::Custom(box Custom { kind: ErrorKind::InvalidInput, - error: box Error { - repr: super::Repr::Os(code) - }, - }) + error: box Error { repr: super::Repr::Os(code) }, + }), }; let expected = format!( "Custom {{ \ - kind: InvalidInput, \ - error: Os {{ \ - code: {:?}, \ - kind: {:?}, \ - message: {:?} \ - }} \ - }}", + kind: InvalidInput, \ + error: Os {{ \ + code: {:?}, \ + kind: {:?}, \ + message: {:?} \ + }} \ + }}", code, kind, msg ); assert_eq!(format!("{:?}", err), expected); diff --git a/src/libstd/io/impls.rs b/src/libstd/io/impls.rs index c959f2d389b..b7f82e65299 100644 --- a/src/libstd/io/impls.rs +++ b/src/libstd/io/impls.rs @@ -1,7 +1,8 @@ use crate::cmp; -use crate::io::{self, SeekFrom, Read, Initializer, Write, Seek, BufRead, Error, ErrorKind, - IoSliceMut, IoSlice}; use crate::fmt; +use crate::io::{ + self, BufRead, Error, ErrorKind, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write, +}; use crate::mem; // ============================================================================= @@ -42,7 +43,9 @@ impl<R: Read + ?Sized> Read for &mut R { #[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 @@ impl<W: Write + ?Sized> Write for &mut W { } #[inline] - fn flush(&mut self) -> io::Result<()> { (**self).flush() } + fn flush(&mut self) -> io::Result<()> { + (**self).flush() + } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { @@ -65,15 +70,21 @@ impl<W: Write + ?Sized> Write for &mut W { #[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 @@ impl<R: Read + ?Sized> Read for Box<R> { #[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 @@ impl<W: Write + ?Sized> Write for Box<W> { } #[inline] - fn flush(&mut self) -> io::Result<()> { (**self).flush() } + fn flush(&mut self) -> io::Result<()> { + (**self).flush() + } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { @@ -144,15 +159,21 @@ impl<W: Write + ?Sized> Write for Box<W> { #[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 @@ impl Read for &[u8] { #[inline] fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { if buf.len() > self.len() { - return Err(Error::new(ErrorKind::UnexpectedEof, - "failed to fill whole buffer")); + return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer")); } let (a, b) = self.split_at(buf.len()); @@ -257,10 +277,14 @@ impl Read for &[u8] { #[stable(feature = "rust1", since = "1.0.0")] impl BufRead for &[u8] { #[inline] - fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(*self) } + fn fill_buf(&mut self) -> io::Result<&[u8]> { + Ok(*self) + } #[inline] - fn consume(&mut self, amt: usize) { *self = &self[amt..]; } + fn consume(&mut self, amt: usize) { + *self = &self[amt..]; + } } /// Write is implemented for `&mut [u8]` by copying into the slice, overwriting @@ -302,7 +326,9 @@ impl Write for &mut [u8] { } #[inline] - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } /// Write is implemented for `Vec<u8>` by appending to the vector. @@ -332,7 +358,9 @@ impl Write for Vec<u8> { } #[inline] - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } #[cfg(test)] diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index be364a10593..20c1c5cd1b8 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -261,49 +261,54 @@ use crate::cmp; use crate::fmt; -use crate::slice; -use crate::str; use crate::memchr; use crate::ops::{Deref, DerefMut}; use crate::ptr; +use crate::slice; +use crate::str; use crate::sys; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::buffered::{BufReader, BufWriter, LineWriter}; -#[stable(feature = "rust1", since = "1.0.0")] pub use self::buffered::IntoInnerError; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::cursor::Cursor; +pub use self::buffered::{BufReader, BufWriter, LineWriter}; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::error::{Result, Error, ErrorKind}; +pub use self::cursor::Cursor; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat}; +pub use self::error::{Error, ErrorKind, Result}; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr}; +pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout}; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::stdio::{StdoutLock, StderrLock, StdinLock}; +pub use self::stdio::{StderrLock, StdinLock, StdoutLock}; #[unstable(feature = "print_internals", issue = "0")] -pub use self::stdio::{_print, _eprint}; +pub use self::stdio::{_eprint, _print}; #[unstable(feature = "libstd_io_internals", issue = "42788")] #[doc(no_inline, hidden)] pub use self::stdio::{set_panic, set_print}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::util::{copy, empty, repeat, sink, Empty, Repeat, Sink}; -pub mod prelude; mod buffered; mod cursor; mod error; mod impls; mod lazy; -mod util; +pub mod prelude; mod stdio; +mod util; const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE; -struct Guard<'a> { buf: &'a mut Vec<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 @@ impl Drop for Guard<'_> { // the function only *appends* bytes to the buffer. We'll get undefined // behavior if existing bytes are overwritten to have non-UTF-8 data. fn append_to_string<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 @@ where 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 @@ pub trait Read { while !buf.is_empty() { match self.read(buf) { Ok(0) => break, - Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; } + Ok(n) => { + let tmp = buf; + buf = &mut tmp[n..]; + } Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return Err(e), } } if !buf.is_empty() { - Err(Error::new(ErrorKind::UnexpectedEof, - "failed to fill whole buffer")) + Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer")) } else { Ok(()) } @@ -815,7 +816,12 @@ pub trait Read { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn by_ref(&mut self) -> &mut Self where Self: Sized { self } + fn by_ref(&mut self) -> &mut Self + where + Self: Sized, + { + self + } /// Transforms this `Read` instance to an [`Iterator`] over its bytes. /// @@ -852,7 +858,10 @@ pub trait Read { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn bytes(self) -> Bytes<Self> where Self: Sized { + fn bytes(self) -> Bytes<Self> + where + Self: Sized, + { Bytes { inner: self } } @@ -887,7 +896,10 @@ pub trait Read { /// } /// ``` #[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 @@ pub trait Read { /// } /// ``` #[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 @@ pub trait Write { fn write_all(&mut self, mut buf: &[u8]) -> Result<()> { while !buf.is_empty() { match self.write(buf) { - Ok(0) => return Err(Error::new(ErrorKind::WriteZero, - "failed to write whole buffer")), + Ok(0) => { + return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer")); + } Ok(n) => buf = &buf[n..], Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return Err(e), @@ -1444,7 +1460,12 @@ pub trait Write { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn by_ref(&mut self) -> &mut Self where Self: Sized { self } + fn by_ref(&mut self) -> &mut Self + where + Self: Sized, + { + self + } } /// The `Seek` trait provides a cursor which can be moved within a stream of @@ -1601,15 +1622,14 @@ pub enum SeekFrom { Current(#[stable(feature = "rust1", since = "1.0.0")] i64), } -fn read_until<R: 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 @@ pub trait BufRead: Read { /// 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 @@ pub trait BufRead: Read { /// /// [`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 @@ impl<T, U> Chain<T, 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 @@ impl<T: Read, U: Read> Read for Chain<T, U> { 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 @@ impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> { } 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 @@ impl<B: BufRead> Iterator for Split<B> { } Some(Ok(buf)) } - Err(e) => Some(Err(e)) + Err(e) => Some(Err(e)), } } } @@ -2385,16 +2404,16 @@ impl<B: BufRead> Iterator for Lines<B> { } Some(Ok(buf)) } - Err(e) => Some(Err(e)) + Err(e) => Some(Err(e)), } } } #[cfg(test)] mod tests { + use super::{repeat, Cursor, SeekFrom}; use crate::cmp; use crate::io::prelude::*; - use super::{Cursor, SeekFrom, repeat}; use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; use crate::ops::Deref; @@ -2509,16 +2528,14 @@ mod tests { let mut buf = [0; 4]; let mut c = Cursor::new(&b""[..]); - assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), - io::ErrorKind::UnexpectedEof); + assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..])); c.read_exact(&mut buf).unwrap(); assert_eq!(&buf, b"1234"); c.read_exact(&mut buf).unwrap(); assert_eq!(&buf, b"5678"); - assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), - io::ErrorKind::UnexpectedEof); + assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); } #[test] @@ -2526,12 +2543,10 @@ mod tests { let mut buf = [0; 4]; let mut c = &b""[..]; - assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), - io::ErrorKind::UnexpectedEof); + assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); let mut c = &b"123"[..]; - assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), - io::ErrorKind::UnexpectedEof); + assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); // make sure the optimized (early returning) method is being used assert_eq!(&buf, &[0; 4]); @@ -2558,7 +2573,7 @@ mod tests { fn fill_buf(&mut self) -> io::Result<&[u8]> { Err(io::Error::new(io::ErrorKind::Other, "")) } - fn consume(&mut self, _amt: usize) { } + fn consume(&mut self, _amt: usize) {} } let mut buf = [0; 1]; @@ -2591,11 +2606,9 @@ mod tests { #[test] fn chain_bufread() { let testdata = b"ABCDEFGHIJKL"; - let chain1 = (&testdata[..3]).chain(&testdata[3..6]) - .chain(&testdata[6..9]) - .chain(&testdata[9..]); - let chain2 = (&testdata[..4]).chain(&testdata[4..8]) - .chain(&testdata[8..]); + let chain1 = + (&testdata[..3]).chain(&testdata[3..6]).chain(&testdata[6..9]).chain(&testdata[9..]); + let chain2 = (&testdata[..4]).chain(&testdata[4..8]).chain(&testdata[8..]); cmp_bufread(chain1, chain2, &testdata[..]); } @@ -2651,7 +2664,6 @@ mod tests { assert_eq!(c.stream_position()?, 15); assert_eq!(c.stream_position()?, 15); - c.seek(SeekFrom::Start(7))?; c.seek(SeekFrom::Current(2))?; assert_eq!(c.stream_position()?, 9); @@ -2700,9 +2712,7 @@ mod tests { // that will not allocate when the limit has already been reached. In // this case, vec2 never grows. let mut vec2 = Vec::with_capacity(input.len()); - ExampleSliceReader { slice: input } - .take(input.len() as u64) - .read_to_end(&mut vec2)?; + ExampleSliceReader { slice: input }.take(input.len() as u64).read_to_end(&mut vec2)?; assert_eq!(vec2.len(), input.len()); assert_eq!(vec2.capacity(), input.len(), "did not allocate more"); diff --git a/src/libstd/io/prelude.rs b/src/libstd/io/prelude.rs index 2e19edf2621..3baab2be377 100644 --- a/src/libstd/io/prelude.rs +++ b/src/libstd/io/prelude.rs @@ -11,4 +11,4 @@ #![stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")] -pub use super::{Read, Write, BufRead, Seek}; +pub use super::{BufRead, Read, Seek, Write}; diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index 33cc87eb795..b09161b97aa 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -1,7 +1,7 @@ #![allow(missing_copy_implementations)] use crate::fmt; -use crate::io::{self, Read, Initializer, Write, ErrorKind, BufRead, IoSlice, IoSliceMut}; +use crate::io::{self, BufRead, ErrorKind, Initializer, IoSlice, IoSliceMut, Read, Write}; use crate::mem::MaybeUninit; /// Copies the entire contents of a reader into a writer. @@ -41,7 +41,9 @@ use crate::mem::MaybeUninit; /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn copy<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 @@ impl Read for Empty { #[stable(feature = "rust1", since = "1.0.0")] impl BufRead for Empty { #[inline] - fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) } + fn fill_buf(&mut self) -> io::Result<&[u8]> { + Ok(&[]) + } #[inline] fn consume(&mut self, _n: usize) {} } @@ -125,7 +137,9 @@ impl fmt::Debug for Empty { /// /// [repeat]: fn.repeat.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct Repeat { byte: u8 } +pub struct Repeat { + byte: u8, +} /// Creates an instance of a reader that infinitely repeats one byte. /// @@ -142,7 +156,9 @@ pub struct Repeat { byte: u8 } /// assert_eq!(buffer, [0b101, 0b101, 0b101]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] -pub fn repeat(byte: u8) -> Repeat { Repeat { byte } } +pub fn repeat(byte: u8) -> Repeat { + Repeat { byte } +} #[stable(feature = "rust1", since = "1.0.0")] impl Read for Repeat { @@ -183,7 +199,9 @@ impl fmt::Debug for Repeat { /// /// [sink]: fn.sink.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct Sink { _priv: () } +pub struct Sink { + _priv: (), +} /// Creates an instance of a writer which will successfully consume all data. /// @@ -200,12 +218,16 @@ pub struct Sink { _priv: () } /// assert_eq!(num_bytes, 5); /// ``` #[stable(feature = "rust1", since = "1.0.0")] -pub fn sink() -> Sink { Sink { _priv: () } } +pub fn sink() -> Sink { + Sink { _priv: () } +} #[stable(feature = "rust1", since = "1.0.0")] impl Write for Sink { #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result<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 @@ impl Write for Sink { } #[inline] - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } #[stable(feature = "std_debug", since = "1.16.0")] @@ -227,7 +251,7 @@ impl fmt::Debug for Sink { #[cfg(test)] mod tests { use crate::io::prelude::*; - use crate::io::{copy, sink, empty, repeat}; + use crate::io::{copy, empty, repeat, sink}; #[test] fn copy_copies() { |
