1//! Traits, helpers, and type definitions for core I/O functionality.2//!3//! The `std::io` module contains a number of common things you'll need4//! when doing input and output. The most core part of this module is5//! the [`Read`] and [`Write`] traits, which provide the6//! most general interface for reading and writing input and output.7//!8//! ## Read and Write9//!10//! Because they are traits, [`Read`] and [`Write`] are implemented by a number11//! of other types, and you can implement them for your types too. As such,12//! you'll see a few different types of I/O throughout the documentation in13//! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For14//! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on15//! [`File`]s:16//!17//! ```no_run18//! use std::io;19//! use std::io::prelude::*;20//! use std::fs::File;21//!22//! fn main() -> io::Result<()> {23//! let mut f = File::open("foo.txt")?;24//! let mut buffer = [0; 10];25//!26//! // read up to 10 bytes27//! let n = f.read(&mut buffer)?;28//!29//! println!("The bytes: {:?}", &buffer[..n]);30//! Ok(())31//! }32//! ```33//!34//! [`Read`] and [`Write`] are so important, implementors of the two traits have a35//! nickname: readers and writers. So you'll sometimes see 'a reader' instead36//! of 'a type that implements the [`Read`] trait'. Much easier!37//!38//! ## Seek and BufRead39//!40//! Beyond that, there are two important traits that are provided: [`Seek`]41//! and [`BufRead`]. Both of these build on top of a reader to control42//! how the reading happens. [`Seek`] lets you control where the next byte is43//! coming from:44//!45//! ```no_run46//! use std::io;47//! use std::io::prelude::*;48//! use std::io::SeekFrom;49//! use std::fs::File;50//!51//! fn main() -> io::Result<()> {52//! let mut f = File::open("foo.txt")?;53//! let mut buffer = [0; 10];54//!55//! // skip to the last 10 bytes of the file56//! f.seek(SeekFrom::End(-10))?;57//!58//! // read up to 10 bytes59//! let n = f.read(&mut buffer)?;60//!61//! println!("The bytes: {:?}", &buffer[..n]);62//! Ok(())63//! }64//! ```65//!66//! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but67//! to show it off, we'll need to talk about buffers in general. Keep reading!68//!69//! ## BufReader and BufWriter70//!71//! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be72//! making near-constant calls to the operating system. To help with this,73//! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap74//! readers and writers. The wrapper uses a buffer, reducing the number of75//! calls and providing nicer methods for accessing exactly what you want.76//!77//! For example, [`BufReader`] works with the [`BufRead`] trait to add extra78//! methods to any reader:79//!80//! ```no_run81//! use std::io;82//! use std::io::prelude::*;83//! use std::io::BufReader;84//! use std::fs::File;85//!86//! fn main() -> io::Result<()> {87//! let f = File::open("foo.txt")?;88//! let mut reader = BufReader::new(f);89//! let mut buffer = String::new();90//!91//! // read a line into buffer92//! reader.read_line(&mut buffer)?;93//!94//! println!("{buffer}");95//! Ok(())96//! }97//! ```98//!99//! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call100//! to [`write`][`Write::write`]:101//!102//! ```no_run103//! use std::io;104//! use std::io::prelude::*;105//! use std::io::BufWriter;106//! use std::fs::File;107//!108//! fn main() -> io::Result<()> {109//! let f = File::create("foo.txt")?;110//! {111//! let mut writer = BufWriter::new(f);112//!113//! // write a byte to the buffer114//! writer.write(&[42])?;115//!116//! } // the buffer is flushed once writer goes out of scope117//!118//! Ok(())119//! }120//! ```121//!122//! ## Standard input and output123//!124//! A very common source of input is standard input:125//!126//! ```no_run127//! use std::io;128//!129//! fn main() -> io::Result<()> {130//! let mut input = String::new();131//!132//! io::stdin().read_line(&mut input)?;133//!134//! println!("You typed: {}", input.trim());135//! Ok(())136//! }137//! ```138//!139//! Note that you cannot use the [`?` operator] in functions that do not return140//! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]141//! or `match` on the return value to catch any possible errors:142//!143//! ```no_run144//! use std::io;145//!146//! let mut input = String::new();147//!148//! io::stdin().read_line(&mut input).unwrap();149//! ```150//!151//! And a very common source of output is standard output:152//!153//! ```no_run154//! use std::io;155//! use std::io::prelude::*;156//!157//! fn main() -> io::Result<()> {158//! io::stdout().write(&[42])?;159//! Ok(())160//! }161//! ```162//!163//! Of course, using [`io::stdout`] directly is less common than something like164//! [`println!`].165//!166//! ## Iterator types167//!168//! A large number of the structures provided by `std::io` are for various169//! ways of iterating over I/O. For example, [`Lines`] is used to split over170//! lines:171//!172//! ```no_run173//! use std::io;174//! use std::io::prelude::*;175//! use std::io::BufReader;176//! use std::fs::File;177//!178//! fn main() -> io::Result<()> {179//! let f = File::open("foo.txt")?;180//! let reader = BufReader::new(f);181//!182//! for line in reader.lines() {183//! println!("{}", line?);184//! }185//! Ok(())186//! }187//! ```188//!189//! ## Functions190//!191//! There are a number of [functions][functions-list] that offer access to various192//! features. For example, we can use three of these functions to copy everything193//! from standard input to standard output:194//!195//! ```no_run196//! use std::io;197//!198//! fn main() -> io::Result<()> {199//! io::copy(&mut io::stdin(), &mut io::stdout())?;200//! Ok(())201//! }202//! ```203//!204//! [functions-list]: #functions-1205//!206//! ## io::Result207//!208//! Last, but certainly not least, is [`io::Result`]. This type is used209//! as the return type of many `std::io` functions that can cause an error, and210//! can be returned from your own functions as well. Many of the examples in this211//! module use the [`?` operator]:212//!213//! ```214//! use std::io;215//!216//! fn read_input() -> io::Result<()> {217//! let mut input = String::new();218//!219//! io::stdin().read_line(&mut input)?;220//!221//! println!("You typed: {}", input.trim());222//!223//! Ok(())224//! }225//! ```226//!227//! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very228//! common type for functions which don't have a 'real' return value, but do want to229//! return errors if they happen. In this case, the only purpose of this function is230//! to read the line and print it, so we use `()`.231//!232//! ## Platform-specific behavior233//!234//! Many I/O functions throughout the standard library are documented to indicate235//! what various library or syscalls they are delegated to. This is done to help236//! applications both understand what's happening under the hood as well as investigate237//! any possibly unclear semantics. Note, however, that this is informative, not a binding238//! contract. The implementation of many of these functions are subject to change over239//! time and may call fewer or more syscalls/library functions.240//!241//! ## I/O Safety242//!243//! Rust follows an I/O safety discipline that is comparable to its memory safety discipline. This244//! means that file descriptors can be *exclusively owned*. (Here, "file descriptor" is meant to245//! subsume similar concepts that exist across a wide range of operating systems even if they might246//! use a different name, such as "handle".) An exclusively owned file descriptor is one that no247//! other code is allowed to access in any way, but the owner is allowed to access and even close248//! it any time. A type that owns its file descriptor should usually close it in its `drop`249//! function. Types like [`File`] own their file descriptor. Similarly, file descriptors250//! can be *borrowed*, granting the temporary right to perform operations on this file descriptor.251//! This indicates that the file descriptor will not be closed for the lifetime of the borrow, but252//! it does *not* imply any right to close this file descriptor, since it will likely be owned by253//! someone else.254//!255//! The platform-specific parts of the Rust standard library expose types that reflect these256//! concepts, see [`os::unix`] and [`os::windows`].257//!258//! To uphold I/O safety, it is crucial that no code acts on file descriptors it does not own or259//! borrow, and no code closes file descriptors it does not own. In other words, a safe function260//! that takes a regular integer, treats it as a file descriptor, and acts on it, is *unsound*.261//!262//! Not upholding I/O safety and acting on a file descriptor without proof of ownership can lead to263//! misbehavior and even Undefined Behavior in code that relies on ownership of its file264//! descriptors: a closed file descriptor could be re-allocated, so the original owner of that file265//! descriptor is now working on the wrong file. Some code might even rely on fully encapsulating266//! its file descriptors with no operations being performed by any other part of the program.267//!268//! Note that exclusive ownership of a file descriptor does *not* imply exclusive ownership of the269//! underlying kernel object that the file descriptor references (also called "open file description" on270//! some operating systems). File descriptors basically work like [`Arc`]: when you receive an owned271//! file descriptor, you cannot know whether there are any other file descriptors that reference the272//! same kernel object. However, when you create a new kernel object, you know that you are holding273//! the only reference to it. Just be careful not to lend it to anyone, since they can obtain a274//! clone and then you can no longer know what the reference count is! In that sense, [`OwnedFd`] is275//! like `Arc` and [`BorrowedFd<'a>`] is like `&'a Arc` (and similar for the Windows types). In276//! particular, given a `BorrowedFd<'a>`, you are not allowed to close the file descriptor -- just277//! like how, given a `&'a Arc`, you are not allowed to decrement the reference count and278//! potentially free the underlying object. There is no equivalent to `Box` for file descriptors in279//! the standard library (that would be a type that guarantees that the reference count is `1`),280//! however, it would be possible for a crate to define a type with those semantics.281//!282//! [`File`]: crate::fs::File283//! [`TcpStream`]: crate::net::TcpStream284//! [`io::stdout`]: stdout285//! [`io::Result`]: self::Result286//! [`?` operator]: ../../book/appendix-02-operators.html287//! [`Result`]: crate::result::Result288//! [`.unwrap()`]: crate::result::Result::unwrap289//! [`os::unix`]: ../os/unix/io/index.html290//! [`os::windows`]: ../os/windows/io/index.html291//! [`OwnedFd`]: ../os/fd/struct.OwnedFd.html292//! [`BorrowedFd<'a>`]: ../os/fd/struct.BorrowedFd.html293//! [`Arc`]: crate::sync::Arc294295#![stable(feature = "rust1", since = "1.0.0")]296297#[cfg(test)]298mod tests;299300#[unstable(feature = "read_buf", issue = "78485")]301pub use core::io::{BorrowedBuf, BorrowedCursor};302use core::slice::memchr;303304#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]305pub use self::buffered::WriterPanicked;306#[unstable(feature = "raw_os_error_ty", issue = "107792")]307pub use self::error::RawOsError;308#[doc(hidden)]309#[unstable(feature = "io_const_error_internals", issue = "none")]310pub use self::error::SimpleMessage;311#[unstable(feature = "io_const_error", issue = "133448")]312pub use self::error::const_error;313#[stable(feature = "anonymous_pipe", since = "1.87.0")]314pub use self::pipe::{PipeReader, PipeWriter, pipe};315#[stable(feature = "is_terminal", since = "1.70.0")]316pub use self::stdio::IsTerminal;317pub(crate) use self::stdio::attempt_print_to_stderr;318#[unstable(feature = "print_internals", issue = "none")]319#[doc(hidden)]320pub use self::stdio::{_eprint, _print};321#[unstable(feature = "internal_output_capture", issue = "none")]322#[doc(no_inline, hidden)]323pub use self::stdio::{set_output_capture, try_set_output_capture};324#[stable(feature = "rust1", since = "1.0.0")]325pub use self::{326 buffered::{BufReader, BufWriter, IntoInnerError, LineWriter},327 copy::copy,328 cursor::Cursor,329 error::{Error, ErrorKind, Result},330 stdio::{Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock, stderr, stdin, stdout},331 util::{Empty, Repeat, Sink, empty, repeat, sink},332};333use crate::mem::{MaybeUninit, take};334use crate::ops::{Deref, DerefMut};335use crate::{cmp, fmt, slice, str, sys};336337mod buffered;338pub(crate) mod copy;339mod cursor;340mod error;341mod impls;342mod pipe;343pub mod prelude;344mod stdio;345mod util;346347const DEFAULT_BUF_SIZE: usize = crate::sys::io::DEFAULT_BUF_SIZE;348349pub(crate) use stdio::cleanup;350351struct Guard<'a> {352 buf: &'a mut Vec<u8>,353 len: usize,354}355356impl Drop for Guard<'_> {357 fn drop(&mut self) {358 unsafe {359 self.buf.set_len(self.len);360 }361 }362}363364// Several `read_to_string` and `read_line` methods in the standard library will365// append data into a `String` buffer, but we need to be pretty careful when366// doing this. The implementation will just call `.as_mut_vec()` and then367// delegate to a byte-oriented reading method, but we must ensure that when368// returning we never leave `buf` in a state such that it contains invalid UTF-8369// in its bounds.370//371// To this end, we use an RAII guard (to protect against panics) which updates372// the length of the string when it is dropped. This guard initially truncates373// the string to the prior length and only after we've validated that the374// new contents are valid UTF-8 do we allow it to set a longer length.375//376// The unsafety in this function is twofold:377//378// 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8379// checks.380// 2. We're passing a raw buffer to the function `f`, and it is expected that381// the function only *appends* bytes to the buffer. We'll get undefined382// behavior if existing bytes are overwritten to have non-UTF-8 data.383pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>384where385 F: FnOnce(&mut Vec<u8>) -> Result<usize>,386{387 let mut g = Guard { len: buf.len(), buf: unsafe { buf.as_mut_vec() } };388 let ret = f(g.buf);389390 // SAFETY: the caller promises to only append data to `buf`391 let appended = unsafe { g.buf.get_unchecked(g.len..) };392 if str::from_utf8(appended).is_err() {393 ret.and_then(|_| Err(Error::INVALID_UTF8))394 } else {395 g.len = g.buf.len();396 ret397 }398}399400// Here we must serve many masters with conflicting goals:401//402// - avoid allocating unless necessary403// - avoid overallocating if we know the exact size (#89165)404// - avoid passing large buffers to readers that always initialize the free capacity if they perform short reads (#23815, #23820)405// - pass large buffers to readers that do not initialize the spare capacity. this can amortize per-call overheads406// - and finally pass not-too-small and not-too-large buffers to Windows read APIs because they manage to suffer from both problems407// at the same time, i.e. small reads suffer from syscall overhead, all reads incur costs proportional to buffer size (#110650)408//409pub(crate) fn default_read_to_end<R: Read + ?Sized>(410 r: &mut R,411 buf: &mut Vec<u8>,412 size_hint: Option<usize>,413) -> Result<usize> {414 let start_len = buf.len();415 let start_cap = buf.capacity();416 // Optionally limit the maximum bytes read on each iteration.417 // This adds an arbitrary fiddle factor to allow for more data than we expect.418 let mut max_read_size = size_hint419 .and_then(|s| s.checked_add(1024)?.checked_next_multiple_of(DEFAULT_BUF_SIZE))420 .unwrap_or(DEFAULT_BUF_SIZE);421422 const PROBE_SIZE: usize = 32;423424 fn small_probe_read<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {425 let mut probe = [0u8; PROBE_SIZE];426427 loop {428 match r.read(&mut probe) {429 Ok(n) => {430 // there is no way to recover from allocation failure here431 // because the data has already been read.432 buf.extend_from_slice(&probe[..n]);433 return Ok(n);434 }435 Err(ref e) if e.is_interrupted() => continue,436 Err(e) => return Err(e),437 }438 }439 }440441 // avoid inflating empty/small vecs before we have determined that there's anything to read442 if (size_hint.is_none() || size_hint == Some(0)) && buf.capacity() - buf.len() < PROBE_SIZE {443 let read = small_probe_read(r, buf)?;444445 if read == 0 {446 return Ok(0);447 }448 }449450 loop {451 if buf.len() == buf.capacity() && buf.capacity() == start_cap {452 // The buffer might be an exact fit. Let's read into a probe buffer453 // and see if it returns `Ok(0)`. If so, we've avoided an454 // unnecessary doubling of the capacity. But if not, append the455 // probe buffer to the primary buffer and let its capacity grow.456 let read = small_probe_read(r, buf)?;457458 if read == 0 {459 return Ok(buf.len() - start_len);460 }461 }462463 if buf.len() == buf.capacity() {464 // buf is full, need more space465 buf.try_reserve(PROBE_SIZE)?;466 }467468 let mut spare = buf.spare_capacity_mut();469 let buf_len = cmp::min(spare.len(), max_read_size);470 spare = &mut spare[..buf_len];471 let mut read_buf: BorrowedBuf<'_> = spare.into();472473 // Note that we don't track already initialized bytes here, but this is fine474 // because we explicitly limit the read size475 let mut cursor = read_buf.unfilled();476 let result = loop {477 match r.read_buf(cursor.reborrow()) {478 Err(e) if e.is_interrupted() => continue,479 // Do not stop now in case of error: we might have received both data480 // and an error481 res => break res,482 }483 };484485 let bytes_read = cursor.written();486 let is_init = read_buf.is_init();487488 // SAFETY: BorrowedBuf's invariants mean this much memory is initialized.489 unsafe {490 let new_len = bytes_read + buf.len();491 buf.set_len(new_len);492 }493494 // Now that all data is pushed to the vector, we can fail without data loss495 result?;496497 if bytes_read == 0 {498 return Ok(buf.len() - start_len);499 }500501 // Use heuristics to determine the max read size if no initial size hint was provided502 if size_hint.is_none() {503 // The reader is returning short reads but it doesn't call ensure_init().504 // In that case we no longer need to restrict read sizes to avoid505 // initialization costs.506 // When reading from disk we usually don't get any short reads except at EOF.507 // So we wait for at least 2 short reads before uncapping the read buffer;508 // this helps with the Windows issue.509 if !is_init {510 max_read_size = usize::MAX;511 }512 // we have passed a larger buffer than previously and the513 // reader still hasn't returned a short read514 else if buf_len >= max_read_size && bytes_read == buf_len {515 max_read_size = max_read_size.saturating_mul(2);516 }517 }518 }519}520521pub(crate) fn default_read_to_string<R: Read + ?Sized>(522 r: &mut R,523 buf: &mut String,524 size_hint: Option<usize>,525) -> Result<usize> {526 // Note that we do *not* call `r.read_to_end()` here. We are passing527 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`528 // method to fill it up. An arbitrary implementation could overwrite the529 // entire contents of the vector, not just append to it (which is what530 // we are expecting).531 //532 // To prevent extraneously checking the UTF-8-ness of the entire buffer533 // we pass it to our hardcoded `default_read_to_end` implementation which534 // we know is guaranteed to only read data into the end of the buffer.535 unsafe { append_to_string(buf, |b| default_read_to_end(r, b, size_hint)) }536}537538pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>539where540 F: FnOnce(&mut [u8]) -> Result<usize>,541{542 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);543 read(buf)544}545546pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>547where548 F: FnOnce(&[u8]) -> Result<usize>,549{550 let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);551 write(buf)552}553554pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {555 while !buf.is_empty() {556 match this.read(buf) {557 Ok(0) => break,558 Ok(n) => {559 buf = &mut buf[n..];560 }561 Err(ref e) if e.is_interrupted() => {}562 Err(e) => return Err(e),563 }564 }565 if !buf.is_empty() { Err(Error::READ_EXACT_EOF) } else { Ok(()) }566}567568pub(crate) fn default_read_buf<F>(read: F, mut cursor: BorrowedCursor<'_>) -> Result<()>569where570 F: FnOnce(&mut [u8]) -> Result<usize>,571{572 let n = read(cursor.ensure_init())?;573 cursor.advance_checked(n);574 Ok(())575}576577pub(crate) fn default_read_buf_exact<R: Read + ?Sized>(578 this: &mut R,579 mut cursor: BorrowedCursor<'_>,580) -> Result<()> {581 while cursor.capacity() > 0 {582 let prev_written = cursor.written();583 match this.read_buf(cursor.reborrow()) {584 Ok(()) => {}585 Err(e) if e.is_interrupted() => continue,586 Err(e) => return Err(e),587 }588589 if cursor.written() == prev_written {590 return Err(Error::READ_EXACT_EOF);591 }592 }593594 Ok(())595}596597pub(crate) fn default_write_fmt<W: Write + ?Sized>(598 this: &mut W,599 args: fmt::Arguments<'_>,600) -> Result<()> {601 // Create a shim which translates a `Write` to a `fmt::Write` and saves off602 // I/O errors, instead of discarding them.603 struct Adapter<'a, T: ?Sized + 'a> {604 inner: &'a mut T,605 error: Result<()>,606 }607608 impl<T: Write + ?Sized> fmt::Write for Adapter<'_, T> {609 fn write_str(&mut self, s: &str) -> fmt::Result {610 match self.inner.write_all(s.as_bytes()) {611 Ok(()) => Ok(()),612 Err(e) => {613 self.error = Err(e);614 Err(fmt::Error)615 }616 }617 }618 }619620 let mut output = Adapter { inner: this, error: Ok(()) };621 match fmt::write(&mut output, args) {622 Ok(()) => Ok(()),623 Err(..) => {624 // Check whether the error came from the underlying `Write`.625 if output.error.is_err() {626 output.error627 } else {628 // This shouldn't happen: the underlying stream did not error,629 // but somehow the formatter still errored?630 panic!(631 "a formatting trait implementation returned an error when the underlying stream did not"632 );633 }634 }635 }636}637638/// The `Read` trait allows for reading bytes from a source.639///640/// Implementors of the `Read` trait are called 'readers'.641///642/// Readers are defined by one required method, [`read()`]. Each call to [`read()`]643/// will attempt to pull bytes from this source into a provided buffer. A644/// number of other methods are implemented in terms of [`read()`], giving645/// implementors a number of ways to read bytes while only needing to implement646/// a single method.647///648/// Readers are intended to be composable with one another. Many implementors649/// throughout [`std::io`] take and provide types which implement the `Read`650/// trait.651///652/// Please note that each call to [`read()`] may involve a system call, and653/// therefore, using something that implements [`BufRead`], such as654/// [`BufReader`], will be more efficient.655///656/// Repeated calls to the reader use the same cursor, so for example657/// calling `read_to_end` twice on a [`File`] will only return the file's658/// contents once. It's recommended to first call `rewind()` in that case.659///660/// # Examples661///662/// [`File`]s implement `Read`:663///664/// ```no_run665/// use std::io;666/// use std::io::prelude::*;667/// use std::fs::File;668///669/// fn main() -> io::Result<()> {670/// let mut f = File::open("foo.txt")?;671/// let mut buffer = [0; 10];672///673/// // read up to 10 bytes674/// f.read(&mut buffer)?;675///676/// let mut buffer = Vec::new();677/// // read the whole file678/// f.read_to_end(&mut buffer)?;679///680/// // read into a String, so that you don't need to do the conversion.681/// let mut buffer = String::new();682/// f.read_to_string(&mut buffer)?;683///684/// // and more! See the other methods for more details.685/// Ok(())686/// }687/// ```688///689/// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:690///691/// ```no_run692/// # use std::io;693/// use std::io::prelude::*;694///695/// fn main() -> io::Result<()> {696/// let mut b = "This string will be read".as_bytes();697/// let mut buffer = [0; 10];698///699/// // read up to 10 bytes700/// b.read(&mut buffer)?;701///702/// // etc... it works exactly as a File does!703/// Ok(())704/// }705/// ```706///707/// [`read()`]: Read::read708/// [`&str`]: prim@str709/// [`std::io`]: self710/// [`File`]: crate::fs::File711#[stable(feature = "rust1", since = "1.0.0")]712#[doc(notable_trait)]713#[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]714pub trait Read {715 /// Pull some bytes from this source into the specified buffer, returning716 /// how many bytes were read.717 ///718 /// This function does not provide any guarantees about whether it blocks719 /// waiting for data, but if an object needs to block for a read and cannot,720 /// it will typically signal this via an [`Err`] return value.721 ///722 /// If the return value of this method is [`Ok(n)`], then implementations must723 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates724 /// that the buffer `buf` has been filled in with `n` bytes of data from this725 /// source. If `n` is `0`, then it can indicate one of two scenarios:726 ///727 /// 1. This reader has reached its "end of file" and will likely no longer728 /// be able to produce bytes. Note that this does not mean that the729 /// reader will *always* no longer be able to produce bytes. As an example,730 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],731 /// where returning zero indicates the connection was shut down correctly. While732 /// for [`File`], it is possible to reach the end of file and get zero as result,733 /// but if more data is appended to the file, future calls to `read` will return734 /// more data.735 /// 2. The buffer specified was 0 bytes in length.736 ///737 /// It is not an error if the returned value `n` is smaller than the buffer size,738 /// even when the reader is not at the end of the stream yet.739 /// This may happen for example because fewer bytes are actually available right now740 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.741 ///742 /// As this trait is safe to implement, callers in unsafe code cannot rely on743 /// `n <= buf.len()` for safety.744 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.745 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if746 /// `n > buf.len()`.747 ///748 /// *Implementations* of this method can make no assumptions about the contents of `buf` when749 /// this function is called. It is recommended that implementations only write data to `buf`750 /// instead of reading its contents.751 ///752 /// Correspondingly, however, *callers* of this method in unsafe code must not assume753 /// any guarantees about how the implementation uses `buf`. The trait is safe to implement,754 /// so it is possible that the code that's supposed to write to the buffer might also read755 /// from it. It is your responsibility to make sure that `buf` is initialized756 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one757 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.758 ///759 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit760 ///761 /// # Errors762 ///763 /// If this function encounters any form of I/O or other error, an error764 /// variant will be returned. If an error is returned then it must be765 /// guaranteed that no bytes were read.766 ///767 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read768 /// operation should be retried if there is nothing else to do.769 ///770 /// # Examples771 ///772 /// [`File`]s implement `Read`:773 ///774 /// [`Ok(n)`]: Ok775 /// [`File`]: crate::fs::File776 /// [`TcpStream`]: crate::net::TcpStream777 ///778 /// ```no_run779 /// use std::io;780 /// use std::io::prelude::*;781 /// use std::fs::File;782 ///783 /// fn main() -> io::Result<()> {784 /// let mut f = File::open("foo.txt")?;785 /// let mut buffer = [0; 10];786 ///787 /// // read up to 10 bytes788 /// let n = f.read(&mut buffer[..])?;789 ///790 /// println!("The bytes: {:?}", &buffer[..n]);791 /// Ok(())792 /// }793 /// ```794 #[stable(feature = "rust1", since = "1.0.0")]795 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;796797 /// Like `read`, except that it reads into a slice of buffers.798 ///799 /// Data is copied to fill each buffer in order, with the final buffer800 /// written to possibly being only partially filled. This method must801 /// behave equivalently to a single call to `read` with concatenated802 /// buffers.803 ///804 /// The default implementation calls `read` with either the first nonempty805 /// buffer provided, or an empty one if none exists.806 #[stable(feature = "iovec", since = "1.36.0")]807 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {808 default_read_vectored(|b| self.read(b), bufs)809 }810811 /// Determines if this `Read`er has an efficient `read_vectored`812 /// implementation.813 ///814 /// If a `Read`er does not override the default `read_vectored`815 /// implementation, code using it may want to avoid the method all together816 /// and coalesce writes into a single buffer for higher performance.817 ///818 /// The default implementation returns `false`.819 #[unstable(feature = "can_vector", issue = "69941")]820 fn is_read_vectored(&self) -> bool {821 false822 }823824 /// Reads all bytes until EOF in this source, placing them into `buf`.825 ///826 /// All bytes read from this source will be appended to the specified buffer827 /// `buf`. This function will continuously call [`read()`] to append more data to828 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of829 /// non-[`ErrorKind::Interrupted`] kind.830 ///831 /// If successful, this function will return the total number of bytes read.832 ///833 /// # Errors834 ///835 /// If this function encounters an error of the kind836 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation837 /// will continue.838 ///839 /// If any other read error is encountered then this function immediately840 /// returns. Any bytes which have already been read will be appended to841 /// `buf`.842 ///843 /// # Examples844 ///845 /// [`File`]s implement `Read`:846 ///847 /// [`read()`]: Read::read848 /// [`Ok(0)`]: Ok849 /// [`File`]: crate::fs::File850 ///851 /// ```no_run852 /// use std::io;853 /// use std::io::prelude::*;854 /// use std::fs::File;855 ///856 /// fn main() -> io::Result<()> {857 /// let mut f = File::open("foo.txt")?;858 /// let mut buffer = Vec::new();859 ///860 /// // read the whole file861 /// f.read_to_end(&mut buffer)?;862 /// Ok(())863 /// }864 /// ```865 ///866 /// (See also the [`std::fs::read`] convenience function for reading from a867 /// file.)868 ///869 /// [`std::fs::read`]: crate::fs::read870 ///871 /// ## Implementing `read_to_end`872 ///873 /// When implementing the `io::Read` trait, it is recommended to allocate874 /// memory using [`Vec::try_reserve`]. However, this behavior is not guaranteed875 /// by all implementations, and `read_to_end` may not handle out-of-memory876 /// situations gracefully.877 ///878 /// ```no_run879 /// # use std::io::{self, BufRead};880 /// # struct Example { example_datasource: io::Empty } impl Example {881 /// # fn get_some_data_for_the_example(&self) -> &'static [u8] { &[] }882 /// fn read_to_end(&mut self, dest_vec: &mut Vec<u8>) -> io::Result<usize> {883 /// let initial_vec_len = dest_vec.len();884 /// loop {885 /// let src_buf = self.example_datasource.fill_buf()?;886 /// if src_buf.is_empty() {887 /// break;888 /// }889 /// dest_vec.try_reserve(src_buf.len())?;890 /// dest_vec.extend_from_slice(src_buf);891 ///892 /// // Any irreversible side effects should happen after `try_reserve` succeeds,893 /// // to avoid losing data on allocation error.894 /// let read = src_buf.len();895 /// self.example_datasource.consume(read);896 /// }897 /// Ok(dest_vec.len() - initial_vec_len)898 /// }899 /// # }900 /// ```901 ///902 /// # Usage Notes903 ///904 /// `read_to_end` attempts to read a source until EOF, but many sources are continuous streams905 /// that do not send EOF. In these cases, `read_to_end` will block indefinitely. Standard input906 /// is one such stream which may be finite if piped, but is typically continuous. For example,907 /// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.908 /// Reading user input or running programs that remain open indefinitely will never terminate909 /// the stream with `EOF` (e.g. `yes | my-rust-program`).910 ///911 /// Using `.lines()` with a [`BufReader`] or using [`read`] can provide a better solution912 ///913 ///[`read`]: Read::read914 ///915 /// [`Vec::try_reserve`]: crate::vec::Vec::try_reserve916 #[stable(feature = "rust1", since = "1.0.0")]917 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {918 default_read_to_end(self, buf, None)919 }920921 /// Reads all bytes until EOF in this source, appending them to `buf`.922 ///923 /// If successful, this function returns the number of bytes which were read924 /// and appended to `buf`.925 ///926 /// # Errors927 ///928 /// If the data in this stream is *not* valid UTF-8 then an error is929 /// returned and `buf` is unchanged.930 ///931 /// See [`read_to_end`] for other error semantics.932 ///933 /// [`read_to_end`]: Read::read_to_end934 ///935 /// # Examples936 ///937 /// [`File`]s implement `Read`:938 ///939 /// [`File`]: crate::fs::File940 ///941 /// ```no_run942 /// use std::io;943 /// use std::io::prelude::*;944 /// use std::fs::File;945 ///946 /// fn main() -> io::Result<()> {947 /// let mut f = File::open("foo.txt")?;948 /// let mut buffer = String::new();949 ///950 /// f.read_to_string(&mut buffer)?;951 /// Ok(())952 /// }953 /// ```954 ///955 /// (See also the [`std::fs::read_to_string`] convenience function for956 /// reading from a file.)957 ///958 /// # Usage Notes959 ///960 /// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams961 /// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input962 /// is one such stream which may be finite if piped, but is typically continuous. For example,963 /// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.964 /// Reading user input or running programs that remain open indefinitely will never terminate965 /// the stream with `EOF` (e.g. `yes | my-rust-program`).966 ///967 /// Using `.lines()` with a [`BufReader`] or using [`read`] can provide a better solution968 ///969 ///[`read`]: Read::read970 ///971 /// [`std::fs::read_to_string`]: crate::fs::read_to_string972 #[stable(feature = "rust1", since = "1.0.0")]973 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {974 default_read_to_string(self, buf, None)975 }976977 /// Reads the exact number of bytes required to fill `buf`.978 ///979 /// This function reads as many bytes as necessary to completely fill the980 /// specified buffer `buf`.981 ///982 /// *Implementations* of this method can make no assumptions about the contents of `buf` when983 /// this function is called. It is recommended that implementations only write data to `buf`984 /// instead of reading its contents. The documentation on [`read`] has a more detailed985 /// explanation of this subject.986 ///987 /// # Errors988 ///989 /// If this function encounters an error of the kind990 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation991 /// will continue.992 ///993 /// If this function encounters an "end of file" before completely filling994 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].995 /// The contents of `buf` are unspecified in this case.996 ///997 /// If any other read error is encountered then this function immediately998 /// returns. The contents of `buf` are unspecified in this case.999 ///1000 /// If this function returns an error, it is unspecified how many bytes it1001 /// has read, but it will never read more than would be necessary to1002 /// completely fill the buffer.1003 ///1004 /// # Examples1005 ///1006 /// [`File`]s implement `Read`:1007 ///1008 /// [`read`]: Read::read1009 /// [`File`]: crate::fs::File1010 ///1011 /// ```no_run1012 /// use std::io;1013 /// use std::io::prelude::*;1014 /// use std::fs::File;1015 ///1016 /// fn main() -> io::Result<()> {1017 /// let mut f = File::open("foo.txt")?;1018 /// let mut buffer = [0; 10];1019 ///1020 /// // read exactly 10 bytes1021 /// f.read_exact(&mut buffer)?;1022 /// Ok(())1023 /// }1024 /// ```1025 #[stable(feature = "read_exact", since = "1.6.0")]1026 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {1027 default_read_exact(self, buf)1028 }10291030 /// Pull some bytes from this source into the specified buffer.1031 ///1032 /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use1033 /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.1034 ///1035 /// The default implementation delegates to `read`.1036 ///1037 /// This method makes it possible to return both data and an error but it is advised against.1038 #[unstable(feature = "read_buf", issue = "78485")]1039 fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<()> {1040 default_read_buf(|b| self.read(b), buf)1041 }10421043 /// Reads the exact number of bytes required to fill `cursor`.1044 ///1045 /// This is similar to the [`read_exact`](Read::read_exact) method, except1046 /// that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use1047 /// with uninitialized buffers.1048 ///1049 /// # Errors1050 ///1051 /// If this function encounters an error of the kind [`ErrorKind::Interrupted`]1052 /// then the error is ignored and the operation will continue.1053 ///1054 /// If this function encounters an "end of file" before completely filling1055 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].1056 ///1057 /// If any other read error is encountered then this function immediately1058 /// returns.1059 ///1060 /// If this function returns an error, all bytes read will be appended to `cursor`.1061 #[unstable(feature = "read_buf", issue = "78485")]1062 fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {1063 default_read_buf_exact(self, cursor)1064 }10651066 /// Creates a "by reference" adapter for this instance of `Read`.1067 ///1068 /// The returned adapter also implements `Read` and will simply borrow this1069 /// current reader.1070 ///1071 /// # Examples1072 ///1073 /// [`File`]s implement `Read`:1074 ///1075 /// [`File`]: crate::fs::File1076 ///1077 /// ```no_run1078 /// use std::io;1079 /// use std::io::Read;1080 /// use std::fs::File;1081 ///1082 /// fn main() -> io::Result<()> {1083 /// let mut f = File::open("foo.txt")?;1084 /// let mut buffer = Vec::new();1085 /// let mut other_buffer = Vec::new();1086 ///1087 /// {1088 /// let reference = f.by_ref();1089 ///1090 /// // read at most 5 bytes1091 /// reference.take(5).read_to_end(&mut buffer)?;1092 ///1093 /// } // drop our &mut reference so we can use f again1094 ///1095 /// // original file still usable, read the rest1096 /// f.read_to_end(&mut other_buffer)?;1097 /// Ok(())1098 /// }1099 /// ```1100 #[stable(feature = "rust1", since = "1.0.0")]1101 fn by_ref(&mut self) -> &mut Self1102 where1103 Self: Sized,1104 {1105 self1106 }11071108 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.1109 ///1110 /// The returned type implements [`Iterator`] where the [`Item`] is1111 /// <code>[Result]<[u8], [io::Error]></code>.1112 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]1113 /// otherwise. EOF is mapped to returning [`None`] from this iterator.1114 ///1115 /// The default implementation calls `read` for each byte,1116 /// which can be very inefficient for data that's not in memory,1117 /// such as [`File`]. Consider using a [`BufReader`] in such cases.1118 ///1119 /// # Examples1120 ///1121 /// [`File`]s implement `Read`:1122 ///1123 /// [`Item`]: Iterator::Item1124 /// [`File`]: crate::fs::File "fs::File"1125 /// [Result]: crate::result::Result "Result"1126 /// [io::Error]: self::Error "io::Error"1127 ///1128 /// ```no_run1129 /// use std::io;1130 /// use std::io::prelude::*;1131 /// use std::io::BufReader;1132 /// use std::fs::File;1133 ///1134 /// fn main() -> io::Result<()> {1135 /// let f = BufReader::new(File::open("foo.txt")?);1136 ///1137 /// for byte in f.bytes() {1138 /// println!("{}", byte?);1139 /// }1140 /// Ok(())1141 /// }1142 /// ```1143 #[stable(feature = "rust1", since = "1.0.0")]1144 fn bytes(self) -> Bytes<Self>1145 where1146 Self: Sized,1147 {1148 Bytes { inner: self }1149 }11501151 /// Creates an adapter which will chain this stream with another.1152 ///1153 /// The returned `Read` instance will first read all bytes from this object1154 /// until EOF is encountered. Afterwards the output is equivalent to the1155 /// output of `next`.1156 ///1157 /// # Examples1158 ///1159 /// [`File`]s implement `Read`:1160 ///1161 /// [`File`]: crate::fs::File1162 ///1163 /// ```no_run1164 /// use std::io;1165 /// use std::io::prelude::*;1166 /// use std::fs::File;1167 ///1168 /// fn main() -> io::Result<()> {1169 /// let f1 = File::open("foo.txt")?;1170 /// let f2 = File::open("bar.txt")?;1171 ///1172 /// let mut handle = f1.chain(f2);1173 /// let mut buffer = String::new();1174 ///1175 /// // read the value into a String. We could use any Read method here,1176 /// // this is just one example.1177 /// handle.read_to_string(&mut buffer)?;1178 /// Ok(())1179 /// }1180 /// ```1181 #[stable(feature = "rust1", since = "1.0.0")]1182 fn chain<R: Read>(self, next: R) -> Chain<Self, R>1183 where1184 Self: Sized,1185 {1186 Chain { first: self, second: next, done_first: false }1187 }11881189 /// Creates an adapter which will read at most `limit` bytes from it.1190 ///1191 /// This function returns a new instance of `Read` which will read at most1192 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any1193 /// read errors will not count towards the number of bytes read and future1194 /// calls to [`read()`] may succeed.1195 ///1196 /// # Examples1197 ///1198 /// [`File`]s implement `Read`:1199 ///1200 /// [`File`]: crate::fs::File1201 /// [`Ok(0)`]: Ok1202 /// [`read()`]: Read::read1203 ///1204 /// ```no_run1205 /// use std::io;1206 /// use std::io::prelude::*;1207 /// use std::fs::File;1208 ///1209 /// fn main() -> io::Result<()> {1210 /// let f = File::open("foo.txt")?;1211 /// let mut buffer = [0; 5];1212 ///1213 /// // read at most five bytes1214 /// let mut handle = f.take(5);1215 ///1216 /// handle.read(&mut buffer)?;1217 /// Ok(())1218 /// }1219 /// ```1220 #[stable(feature = "rust1", since = "1.0.0")]1221 fn take(self, limit: u64) -> Take<Self>1222 where1223 Self: Sized,1224 {1225 Take { inner: self, len: limit, limit }1226 }12271228 /// Read and return a fixed array of bytes from this source.1229 ///1230 /// This function uses an array sized based on a const generic size known at compile time. You1231 /// can specify the size with turbofish (`reader.read_array::<8>()`), or let type inference1232 /// determine the number of bytes needed based on how the return value gets used. For instance,1233 /// this function works well with functions like [`u64::from_le_bytes`] to turn an array of1234 /// bytes into an integer of the same size.1235 ///1236 /// Like `read_exact`, if this function encounters an "end of file" before reading the desired1237 /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].1238 ///1239 /// ```1240 /// #![feature(read_array)]1241 /// use std::io::Cursor;1242 /// use std::io::prelude::*;1243 ///1244 /// fn main() -> std::io::Result<()> {1245 /// let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);1246 /// let x = u64::from_le_bytes(buf.read_array()?);1247 /// let y = u32::from_be_bytes(buf.read_array()?);1248 /// let z = u16::from_be_bytes(buf.read_array()?);1249 /// assert_eq!(x, 0x807060504030201);1250 /// assert_eq!(y, 0x9080706);1251 /// assert_eq!(z, 0x504);1252 /// Ok(())1253 /// }1254 /// ```1255 #[unstable(feature = "read_array", issue = "148848")]1256 fn read_array<const N: usize>(&mut self) -> Result<[u8; N]>1257 where1258 Self: Sized,1259 {1260 let mut buf = [MaybeUninit::uninit(); N];1261 let mut borrowed_buf = BorrowedBuf::from(buf.as_mut_slice());1262 self.read_buf_exact(borrowed_buf.unfilled())?;1263 // Guard against incorrect `read_buf_exact` implementations.1264 assert_eq!(borrowed_buf.len(), N);1265 Ok(unsafe { MaybeUninit::array_assume_init(buf) })1266 }1267}12681269/// Reads all bytes from a [reader][Read] into a new [`String`].1270///1271/// This is a convenience function for [`Read::read_to_string`]. Using this1272/// function avoids having to create a variable first and provides more type1273/// safety since you can only get the buffer out if there were no errors. (If you1274/// use [`Read::read_to_string`] you have to remember to check whether the read1275/// succeeded because otherwise your buffer will be empty or only partially full.)1276///1277/// # Performance1278///1279/// The downside of this function's increased ease of use and type safety is1280/// that it gives you less control over performance. For example, you can't1281/// pre-allocate memory like you can using [`String::with_capacity`] and1282/// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error1283/// occurs while reading.1284///1285/// In many cases, this function's performance will be adequate and the ease of use1286/// and type safety tradeoffs will be worth it. However, there are cases where you1287/// need more control over performance, and in those cases you should definitely use1288/// [`Read::read_to_string`] directly.1289///1290/// Note that in some special cases, such as when reading files, this function will1291/// pre-allocate memory based on the size of the input it is reading. In those1292/// cases, the performance should be as good as if you had used1293/// [`Read::read_to_string`] with a manually pre-allocated buffer.1294///1295/// # Errors1296///1297/// This function forces you to handle errors because the output (the `String`)1298/// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors1299/// that can occur. If any error occurs, you will get an [`Err`], so you1300/// don't have to worry about your buffer being empty or partially full.1301///1302/// # Examples1303///1304/// ```no_run1305/// # use std::io;1306/// fn main() -> io::Result<()> {1307/// let stdin = io::read_to_string(io::stdin())?;1308/// println!("Stdin was:");1309/// println!("{stdin}");1310/// Ok(())1311/// }1312/// ```1313///1314/// # Usage Notes1315///1316/// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams1317/// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input1318/// is one such stream which may be finite if piped, but is typically continuous. For example,1319/// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.1320/// Reading user input or running programs that remain open indefinitely will never terminate1321/// the stream with `EOF` (e.g. `yes | my-rust-program`).1322///1323/// Using `.lines()` with a [`BufReader`] or using [`read`] can provide a better solution1324///1325///[`read`]: Read::read1326///1327#[stable(feature = "io_read_to_string", since = "1.65.0")]1328pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> {1329 let mut buf = String::new();1330 reader.read_to_string(&mut buf)?;1331 Ok(buf)1332}13331334/// A buffer type used with `Read::read_vectored`.1335///1336/// It is semantically a wrapper around a `&mut [u8]`, but is guaranteed to be1337/// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on1338/// Windows.1339#[stable(feature = "iovec", since = "1.36.0")]1340#[repr(transparent)]1341pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);13421343#[stable(feature = "iovec_send_sync", since = "1.44.0")]1344unsafe impl<'a> Send for IoSliceMut<'a> {}13451346#[stable(feature = "iovec_send_sync", since = "1.44.0")]1347unsafe impl<'a> Sync for IoSliceMut<'a> {}13481349#[stable(feature = "iovec", since = "1.36.0")]1350impl<'a> fmt::Debug for IoSliceMut<'a> {1351 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {1352 fmt::Debug::fmt(self.0.as_slice(), fmt)1353 }1354}13551356impl<'a> IoSliceMut<'a> {1357 /// Creates a new `IoSliceMut` wrapping a byte slice.1358 ///1359 /// # Panics1360 ///1361 /// Panics on Windows if the slice is larger than 4GB.1362 #[stable(feature = "iovec", since = "1.36.0")]1363 #[inline]1364 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {1365 IoSliceMut(sys::io::IoSliceMut::new(buf))1366 }13671368 /// Advance the internal cursor of the slice.1369 ///1370 /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of1371 /// multiple buffers.1372 ///1373 /// # Panics1374 ///1375 /// Panics when trying to advance beyond the end of the slice.1376 ///1377 /// # Examples1378 ///1379 /// ```1380 /// use std::io::IoSliceMut;1381 /// use std::ops::Deref;1382 ///1383 /// let mut data = [1; 8];1384 /// let mut buf = IoSliceMut::new(&mut data);1385 ///1386 /// // Mark 3 bytes as read.1387 /// buf.advance(3);1388 /// assert_eq!(buf.deref(), [1; 5].as_ref());1389 /// ```1390 #[stable(feature = "io_slice_advance", since = "1.81.0")]1391 #[inline]1392 pub fn advance(&mut self, n: usize) {1393 self.0.advance(n)1394 }13951396 /// Advance a slice of slices.1397 ///1398 /// Shrinks the slice to remove any `IoSliceMut`s that are fully advanced over.1399 /// If the cursor ends up in the middle of an `IoSliceMut`, it is modified1400 /// to start at that cursor.1401 ///1402 /// For example, if we have a slice of two 8-byte `IoSliceMut`s, and we advance by 10 bytes,1403 /// the result will only include the second `IoSliceMut`, advanced by 2 bytes.1404 ///1405 /// # Panics1406 ///1407 /// Panics when trying to advance beyond the end of the slices.1408 ///1409 /// # Examples1410 ///1411 /// ```1412 /// use std::io::IoSliceMut;1413 /// use std::ops::Deref;1414 ///1415 /// let mut buf1 = [1; 8];1416 /// let mut buf2 = [2; 16];1417 /// let mut buf3 = [3; 8];1418 /// let mut bufs = &mut [1419 /// IoSliceMut::new(&mut buf1),1420 /// IoSliceMut::new(&mut buf2),1421 /// IoSliceMut::new(&mut buf3),1422 /// ][..];1423 ///1424 /// // Mark 10 bytes as read.1425 /// IoSliceMut::advance_slices(&mut bufs, 10);1426 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());1427 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());1428 /// ```1429 #[stable(feature = "io_slice_advance", since = "1.81.0")]1430 #[inline]1431 pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) {1432 // Number of buffers to remove.1433 let mut remove = 0;1434 // Remaining length before reaching n.1435 let mut left = n;1436 for buf in bufs.iter() {1437 if let Some(remainder) = left.checked_sub(buf.len()) {1438 left = remainder;1439 remove += 1;1440 } else {1441 break;1442 }1443 }14441445 *bufs = &mut take(bufs)[remove..];1446 if bufs.is_empty() {1447 assert!(left == 0, "advancing io slices beyond their length");1448 } else {1449 bufs[0].advance(left);1450 }1451 }14521453 /// Get the underlying bytes as a mutable slice with the original lifetime.1454 ///1455 /// # Examples1456 ///1457 /// ```1458 /// #![feature(io_slice_as_bytes)]1459 /// use std::io::IoSliceMut;1460 ///1461 /// let mut data = *b"abcdef";1462 /// let io_slice = IoSliceMut::new(&mut data);1463 /// io_slice.into_slice()[0] = b'A';1464 ///1465 /// assert_eq!(&data, b"Abcdef");1466 /// ```1467 #[unstable(feature = "io_slice_as_bytes", issue = "132818")]1468 pub const fn into_slice(self) -> &'a mut [u8] {1469 self.0.into_slice()1470 }1471}14721473#[stable(feature = "iovec", since = "1.36.0")]1474impl<'a> Deref for IoSliceMut<'a> {1475 type Target = [u8];14761477 #[inline]1478 fn deref(&self) -> &[u8] {1479 self.0.as_slice()1480 }1481}14821483#[stable(feature = "iovec", since = "1.36.0")]1484impl<'a> DerefMut for IoSliceMut<'a> {1485 #[inline]1486 fn deref_mut(&mut self) -> &mut [u8] {1487 self.0.as_mut_slice()1488 }1489}14901491/// A buffer type used with `Write::write_vectored`.1492///1493/// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be1494/// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on1495/// Windows.1496#[stable(feature = "iovec", since = "1.36.0")]1497#[derive(Copy, Clone)]1498#[repr(transparent)]1499pub struct IoSlice<'a>(sys::io::IoSlice<'a>);15001501#[stable(feature = "iovec_send_sync", since = "1.44.0")]1502unsafe impl<'a> Send for IoSlice<'a> {}15031504#[stable(feature = "iovec_send_sync", since = "1.44.0")]1505unsafe impl<'a> Sync for IoSlice<'a> {}15061507#[stable(feature = "iovec", since = "1.36.0")]1508impl<'a> fmt::Debug for IoSlice<'a> {1509 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {1510 fmt::Debug::fmt(self.0.as_slice(), fmt)1511 }1512}15131514impl<'a> IoSlice<'a> {1515 /// Creates a new `IoSlice` wrapping a byte slice.1516 ///1517 /// # Panics1518 ///1519 /// Panics on Windows if the slice is larger than 4GB.1520 #[stable(feature = "iovec", since = "1.36.0")]1521 #[must_use]1522 #[inline]1523 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {1524 IoSlice(sys::io::IoSlice::new(buf))1525 }15261527 /// Advance the internal cursor of the slice.1528 ///1529 /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple1530 /// buffers.1531 ///1532 /// # Panics1533 ///1534 /// Panics when trying to advance beyond the end of the slice.1535 ///1536 /// # Examples1537 ///1538 /// ```1539 /// use std::io::IoSlice;1540 /// use std::ops::Deref;1541 ///1542 /// let data = [1; 8];1543 /// let mut buf = IoSlice::new(&data);1544 ///1545 /// // Mark 3 bytes as read.1546 /// buf.advance(3);1547 /// assert_eq!(buf.deref(), [1; 5].as_ref());1548 /// ```1549 #[stable(feature = "io_slice_advance", since = "1.81.0")]1550 #[inline]1551 pub fn advance(&mut self, n: usize) {1552 self.0.advance(n)1553 }15541555 /// Advance a slice of slices.1556 ///1557 /// Shrinks the slice to remove any `IoSlice`s that are fully advanced over.1558 /// If the cursor ends up in the middle of an `IoSlice`, it is modified1559 /// to start at that cursor.1560 ///1561 /// For example, if we have a slice of two 8-byte `IoSlice`s, and we advance by 10 bytes,1562 /// the result will only include the second `IoSlice`, advanced by 2 bytes.1563 ///1564 /// # Panics1565 ///1566 /// Panics when trying to advance beyond the end of the slices.1567 ///1568 /// # Examples1569 ///1570 /// ```1571 /// use std::io::IoSlice;1572 /// use std::ops::Deref;1573 ///1574 /// let buf1 = [1; 8];1575 /// let buf2 = [2; 16];1576 /// let buf3 = [3; 8];1577 /// let mut bufs = &mut [1578 /// IoSlice::new(&buf1),1579 /// IoSlice::new(&buf2),1580 /// IoSlice::new(&buf3),1581 /// ][..];1582 ///1583 /// // Mark 10 bytes as written.1584 /// IoSlice::advance_slices(&mut bufs, 10);1585 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());1586 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());1587 #[stable(feature = "io_slice_advance", since = "1.81.0")]1588 #[inline]1589 pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) {1590 // Number of buffers to remove.1591 let mut remove = 0;1592 // Remaining length before reaching n. This prevents overflow1593 // that could happen if the length of slices in `bufs` were instead1594 // accumulated. Those slice may be aliased and, if they are large1595 // enough, their added length may overflow a `usize`.1596 let mut left = n;1597 for buf in bufs.iter() {1598 if let Some(remainder) = left.checked_sub(buf.len()) {1599 left = remainder;1600 remove += 1;1601 } else {1602 break;1603 }1604 }16051606 *bufs = &mut take(bufs)[remove..];1607 if bufs.is_empty() {1608 assert!(left == 0, "advancing io slices beyond their length");1609 } else {1610 bufs[0].advance(left);1611 }1612 }16131614 /// Get the underlying bytes as a slice with the original lifetime.1615 ///1616 /// This doesn't borrow from `self`, so is less restrictive than calling1617 /// `.deref()`, which does.1618 ///1619 /// # Examples1620 ///1621 /// ```1622 /// #![feature(io_slice_as_bytes)]1623 /// use std::io::IoSlice;1624 ///1625 /// let data = b"abcdef";1626 ///1627 /// let mut io_slice = IoSlice::new(data);1628 /// let tail = &io_slice.as_slice()[3..];1629 ///1630 /// // This works because `tail` doesn't borrow `io_slice`1631 /// io_slice = IoSlice::new(tail);1632 ///1633 /// assert_eq!(io_slice.as_slice(), b"def");1634 /// ```1635 #[unstable(feature = "io_slice_as_bytes", issue = "132818")]1636 pub const fn as_slice(self) -> &'a [u8] {1637 self.0.as_slice()1638 }1639}16401641#[stable(feature = "iovec", since = "1.36.0")]1642impl<'a> Deref for IoSlice<'a> {1643 type Target = [u8];16441645 #[inline]1646 fn deref(&self) -> &[u8] {1647 self.0.as_slice()1648 }1649}16501651/// A trait for objects which are byte-oriented sinks.1652///1653/// Implementors of the `Write` trait are sometimes called 'writers'.1654///1655/// Writers are defined by two required methods, [`write`] and [`flush`]:1656///1657/// * The [`write`] method will attempt to write some data into the object,1658/// returning how many bytes were successfully written.1659///1660/// * The [`flush`] method is useful for adapters and explicit buffers1661/// themselves for ensuring that all buffered data has been pushed out to the1662/// 'true sink'.1663///1664/// Writers are intended to be composable with one another. Many implementors1665/// throughout [`std::io`] take and provide types which implement the `Write`1666/// trait.1667///1668/// [`write`]: Write::write1669/// [`flush`]: Write::flush1670/// [`std::io`]: self1671///1672/// # Examples1673///1674/// ```no_run1675/// use std::io::prelude::*;1676/// use std::fs::File;1677///1678/// fn main() -> std::io::Result<()> {1679/// let data = b"some bytes";1680///1681/// let mut pos = 0;1682/// let mut buffer = File::create("foo.txt")?;1683///1684/// while pos < data.len() {1685/// let bytes_written = buffer.write(&data[pos..])?;1686/// pos += bytes_written;1687/// }1688/// Ok(())1689/// }1690/// ```1691///1692/// The trait also provides convenience methods like [`write_all`], which calls1693/// `write` in a loop until its entire input has been written.1694///1695/// [`write_all`]: Write::write_all1696#[stable(feature = "rust1", since = "1.0.0")]1697#[doc(notable_trait)]1698#[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]1699pub trait Write {1700 /// Writes a buffer into this writer, returning how many bytes were written.1701 ///1702 /// This function will attempt to write the entire contents of `buf`, but1703 /// the entire write might not succeed, or the write may also generate an1704 /// error. Typically, a call to `write` represents one attempt to write to1705 /// any wrapped object.1706 ///1707 /// Calls to `write` are not guaranteed to block waiting for data to be1708 /// written, and a write which would otherwise block can be indicated through1709 /// an [`Err`] variant.1710 ///1711 /// If this method consumed `n > 0` bytes of `buf` it must return [`Ok(n)`].1712 /// If the return value is `Ok(n)` then `n` must satisfy `n <= buf.len()`.1713 /// A return value of `Ok(0)` typically means that the underlying object is1714 /// no longer able to accept bytes and will likely not be able to in the1715 /// future as well, or that the buffer provided is empty.1716 ///1717 /// # Errors1718 ///1719 /// Each call to `write` may generate an I/O error indicating that the1720 /// operation could not be completed. If an error is returned then no bytes1721 /// in the buffer were written to this writer.1722 ///1723 /// It is **not** considered an error if the entire buffer could not be1724 /// written to this writer.1725 ///1726 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the1727 /// write operation should be retried if there is nothing else to do.1728 ///1729 /// # Examples1730 ///1731 /// ```no_run1732 /// use std::io::prelude::*;1733 /// use std::fs::File;1734 ///1735 /// fn main() -> std::io::Result<()> {1736 /// let mut buffer = File::create("foo.txt")?;1737 ///1738 /// // Writes some prefix of the byte string, not necessarily all of it.1739 /// buffer.write(b"some bytes")?;1740 /// Ok(())1741 /// }1742 /// ```1743 ///1744 /// [`Ok(n)`]: Ok1745 #[stable(feature = "rust1", since = "1.0.0")]1746 fn write(&mut self, buf: &[u8]) -> Result<usize>;17471748 /// Like [`write`], except that it writes from a slice of buffers.1749 ///1750 /// Data is copied from each buffer in order, with the final buffer1751 /// read from possibly being only partially consumed. This method must1752 /// behave as a call to [`write`] with the buffers concatenated would.1753 ///1754 /// The default implementation calls [`write`] with either the first nonempty1755 /// buffer provided, or an empty one if none exists.1756 ///1757 /// # Examples1758 ///1759 /// ```no_run1760 /// use std::io::IoSlice;1761 /// use std::io::prelude::*;1762 /// use std::fs::File;1763 ///1764 /// fn main() -> std::io::Result<()> {1765 /// let data1 = [1; 8];1766 /// let data2 = [15; 8];1767 /// let io_slice1 = IoSlice::new(&data1);1768 /// let io_slice2 = IoSlice::new(&data2);1769 ///1770 /// let mut buffer = File::create("foo.txt")?;1771 ///1772 /// // Writes some prefix of the byte string, not necessarily all of it.1773 /// buffer.write_vectored(&[io_slice1, io_slice2])?;1774 /// Ok(())1775 /// }1776 /// ```1777 ///1778 /// [`write`]: Write::write1779 #[stable(feature = "iovec", since = "1.36.0")]1780 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {1781 default_write_vectored(|b| self.write(b), bufs)1782 }17831784 /// Determines if this `Write`r has an efficient [`write_vectored`]1785 /// implementation.1786 ///1787 /// If a `Write`r does not override the default [`write_vectored`]1788 /// implementation, code using it may want to avoid the method all together1789 /// and coalesce writes into a single buffer for higher performance.1790 ///1791 /// The default implementation returns `false`.1792 ///1793 /// [`write_vectored`]: Write::write_vectored1794 #[unstable(feature = "can_vector", issue = "69941")]1795 fn is_write_vectored(&self) -> bool {1796 false1797 }17981799 /// Flushes this output stream, ensuring that all intermediately buffered1800 /// contents reach their destination.1801 ///1802 /// # Errors1803 ///1804 /// It is considered an error if not all bytes could be written due to1805 /// I/O errors or EOF being reached.1806 ///1807 /// # Examples1808 ///1809 /// ```no_run1810 /// use std::io::prelude::*;1811 /// use std::io::BufWriter;1812 /// use std::fs::File;1813 ///1814 /// fn main() -> std::io::Result<()> {1815 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);1816 ///1817 /// buffer.write_all(b"some bytes")?;1818 /// buffer.flush()?;1819 /// Ok(())1820 /// }1821 /// ```1822 #[stable(feature = "rust1", since = "1.0.0")]1823 fn flush(&mut self) -> Result<()>;18241825 /// Attempts to write an entire buffer into this writer.1826 ///1827 /// This method will continuously call [`write`] until there is no more data1828 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is1829 /// returned. This method will not return until the entire buffer has been1830 /// successfully written or such an error occurs. The first error that is1831 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be1832 /// returned.1833 ///1834 /// If the buffer contains no data, this will never call [`write`].1835 ///1836 /// # Errors1837 ///1838 /// This function will return the first error of1839 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.1840 ///1841 /// [`write`]: Write::write1842 ///1843 /// # Examples1844 ///1845 /// ```no_run1846 /// use std::io::prelude::*;1847 /// use std::fs::File;1848 ///1849 /// fn main() -> std::io::Result<()> {1850 /// let mut buffer = File::create("foo.txt")?;1851 ///1852 /// buffer.write_all(b"some bytes")?;1853 /// Ok(())1854 /// }1855 /// ```1856 #[stable(feature = "rust1", since = "1.0.0")]1857 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {1858 while !buf.is_empty() {1859 match self.write(buf) {1860 Ok(0) => {1861 return Err(Error::WRITE_ALL_EOF);1862 }1863 Ok(n) => buf = &buf[n..],1864 Err(ref e) if e.is_interrupted() => {}1865 Err(e) => return Err(e),1866 }1867 }1868 Ok(())1869 }18701871 /// Attempts to write multiple buffers into this writer.1872 ///1873 /// This method will continuously call [`write_vectored`] until there is no1874 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]1875 /// kind is returned. This method will not return until all buffers have1876 /// been successfully written or such an error occurs. The first error that1877 /// is not of [`ErrorKind::Interrupted`] kind generated from this method1878 /// will be returned.1879 ///1880 /// If the buffer contains no data, this will never call [`write_vectored`].1881 ///1882 /// # Notes1883 ///1884 /// Unlike [`write_vectored`], this takes a *mutable* reference to1885 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to1886 /// modify the slice to keep track of the bytes already written.1887 ///1888 /// Once this function returns, the contents of `bufs` are unspecified, as1889 /// this depends on how many calls to [`write_vectored`] were necessary. It is1890 /// best to understand this function as taking ownership of `bufs` and to1891 /// not use `bufs` afterwards. The underlying buffers, to which the1892 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and1893 /// can be reused.1894 ///1895 /// [`write_vectored`]: Write::write_vectored1896 ///1897 /// # Examples1898 ///1899 /// ```1900 /// #![feature(write_all_vectored)]1901 /// # fn main() -> std::io::Result<()> {1902 ///1903 /// use std::io::{Write, IoSlice};1904 ///1905 /// let mut writer = Vec::new();1906 /// let bufs = &mut [1907 /// IoSlice::new(&[1]),1908 /// IoSlice::new(&[2, 3]),1909 /// IoSlice::new(&[4, 5, 6]),1910 /// ];1911 ///1912 /// writer.write_all_vectored(bufs)?;1913 /// // Note: the contents of `bufs` is now undefined, see the Notes section.1914 ///1915 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);1916 /// # Ok(()) }1917 /// ```1918 #[unstable(feature = "write_all_vectored", issue = "70436")]1919 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {1920 // Guarantee that bufs is empty if it contains no data,1921 // to avoid calling write_vectored if there is no data to be written.1922 IoSlice::advance_slices(&mut bufs, 0);1923 while !bufs.is_empty() {1924 match self.write_vectored(bufs) {1925 Ok(0) => {1926 return Err(Error::WRITE_ALL_EOF);1927 }1928 Ok(n) => IoSlice::advance_slices(&mut bufs, n),1929 Err(ref e) if e.is_interrupted() => {}1930 Err(e) => return Err(e),1931 }1932 }1933 Ok(())1934 }19351936 /// Writes a formatted string into this writer, returning any error1937 /// encountered.1938 ///1939 /// This method is primarily used to interface with the1940 /// [`format_args!()`] macro, and it is rare that this should1941 /// explicitly be called. The [`write!()`] macro should be favored to1942 /// invoke this method instead.1943 ///1944 /// This function internally uses the [`write_all`] method on1945 /// this trait and hence will continuously write data so long as no errors1946 /// are received. This also means that partial writes are not indicated in1947 /// this signature.1948 ///1949 /// [`write_all`]: Write::write_all1950 ///1951 /// # Errors1952 ///1953 /// This function will return any I/O error reported while formatting.1954 ///1955 /// # Examples1956 ///1957 /// ```no_run1958 /// use std::io::prelude::*;1959 /// use std::fs::File;1960 ///1961 /// fn main() -> std::io::Result<()> {1962 /// let mut buffer = File::create("foo.txt")?;1963 ///1964 /// // this call1965 /// write!(buffer, "{:.*}", 2, 1.234567)?;1966 /// // turns into this:1967 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;1968 /// Ok(())1969 /// }1970 /// ```1971 #[stable(feature = "rust1", since = "1.0.0")]1972 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<()> {1973 if let Some(s) = args.as_statically_known_str() {1974 self.write_all(s.as_bytes())1975 } else {1976 default_write_fmt(self, args)1977 }1978 }19791980 /// Creates a "by reference" adapter for this instance of `Write`.1981 ///1982 /// The returned adapter also implements `Write` and will simply borrow this1983 /// current writer.1984 ///1985 /// # Examples1986 ///1987 /// ```no_run1988 /// use std::io::Write;1989 /// use std::fs::File;1990 ///1991 /// fn main() -> std::io::Result<()> {1992 /// let mut buffer = File::create("foo.txt")?;1993 ///1994 /// let reference = buffer.by_ref();1995 ///1996 /// // we can use reference just like our original buffer1997 /// reference.write_all(b"some bytes")?;1998 /// Ok(())1999 /// }2000 /// ```
Findings
✓ No findings reported for this file.