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 need
4//! when doing input and output. The most core part of this module is
5//! the [`Read`] and [`Write`] traits, which provide the
6//! most general interface for reading and writing input and output.
7//!
8//! ## Read and Write
9//!
10//! Because they are traits, [`Read`] and [`Write`] are implemented by a number
11//! 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 in
13//! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
14//! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
15//! [`File`]s:
16//!
17//! ```no_run
18//! 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 bytes
27//! 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 a
35//! nickname: readers and writers. So you'll sometimes see 'a reader' instead
36//! of 'a type that implements the [`Read`] trait'. Much easier!
37//!
38//! ## Seek and BufRead
39//!
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 control
42//! how the reading happens. [`Seek`] lets you control where the next byte is
43//! coming from:
44//!
45//! ```no_run
46//! 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 file
56//! f.seek(SeekFrom::End(-10))?;
57//!
58//! // read up to 10 bytes
59//! 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, but
67//! to show it off, we'll need to talk about buffers in general. Keep reading!
68//!
69//! ## BufReader and BufWriter
70//!
71//! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
72//! making near-constant calls to the operating system. To help with this,
73//! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
74//! readers and writers. The wrapper uses a buffer, reducing the number of
75//! calls and providing nicer methods for accessing exactly what you want.
76//!
77//! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
78//! methods to any reader:
79//!
80//! ```no_run
81//! 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 buffer
92//! 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 call
100//! to [`write`][`Write::write`]:
101//!
102//! ```no_run
103//! 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 buffer
114//! writer.write(&[42])?;
115//!
116//! } // the buffer is flushed once writer goes out of scope
117//!
118//! Ok(())
119//! }
120//! ```
121//!
122//! ## Standard input and output
123//!
124//! A very common source of input is standard input:
125//!
126//! ```no_run
127//! 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 return
140//! 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_run
144//! 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_run
154//! 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 like
164//! [`println!`].
165//!
166//! ## Iterator types
167//!
168//! A large number of the structures provided by `std::io` are for various
169//! ways of iterating over I/O. For example, [`Lines`] is used to split over
170//! lines:
171//!
172//! ```no_run
173//! 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//! ## Functions
190//!
191//! There are a number of [functions][functions-list] that offer access to various
192//! features. For example, we can use three of these functions to copy everything
193//! from standard input to standard output:
194//!
195//! ```no_run
196//! 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-1
205//!
206//! ## io::Result
207//!
208//! Last, but certainly not least, is [`io::Result`]. This type is used
209//! as the return type of many `std::io` functions that can cause an error, and
210//! can be returned from your own functions as well. Many of the examples in this
211//! 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 very
228//! common type for functions which don't have a 'real' return value, but do want to
229//! return errors if they happen. In this case, the only purpose of this function is
230//! to read the line and print it, so we use `()`.
231//!
232//! ## Platform-specific behavior
233//!
234//! Many I/O functions throughout the standard library are documented to indicate
235//! what various library or syscalls they are delegated to. This is done to help
236//! applications both understand what's happening under the hood as well as investigate
237//! any possibly unclear semantics. Note, however, that this is informative, not a binding
238//! contract. The implementation of many of these functions are subject to change over
239//! time and may call fewer or more syscalls/library functions.
240//!
241//! ## I/O Safety
242//!
243//! Rust follows an I/O safety discipline that is comparable to its memory safety discipline. This
244//! means that file descriptors can be *exclusively owned*. (Here, "file descriptor" is meant to
245//! subsume similar concepts that exist across a wide range of operating systems even if they might
246//! use a different name, such as "handle".) An exclusively owned file descriptor is one that no
247//! other code is allowed to access in any way, but the owner is allowed to access and even close
248//! 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 descriptors
250//! 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, but
252//! it does *not* imply any right to close this file descriptor, since it will likely be owned by
253//! someone else.
254//!
255//! The platform-specific parts of the Rust standard library expose types that reflect these
256//! 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 or
259//! borrow, and no code closes file descriptors it does not own. In other words, a safe function
260//! 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 to
263//! misbehavior and even Undefined Behavior in code that relies on ownership of its file
264//! descriptors: a closed file descriptor could be re-allocated, so the original owner of that file
265//! descriptor is now working on the wrong file. Some code might even rely on fully encapsulating
266//! 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 the
269//! underlying kernel object that the file descriptor references (also called "file description" on
270//! some operating systems). File descriptors basically work like [`Arc`]: when you receive an owned
271//! file descriptor, you cannot know whether there are any other file descriptors that reference the
272//! same kernel object. However, when you create a new kernel object, you know that you are holding
273//! the only reference to it. Just be careful not to lend it to anyone, since they can obtain a
274//! clone and then you can no longer know what the reference count is! In that sense, [`OwnedFd`] is
275//! like `Arc` and [`BorrowedFd<'a>`] is like `&'a Arc` (and similar for the Windows types). In
276//! particular, given a `BorrowedFd<'a>`, you are not allowed to close the file descriptor -- just
277//! like how, given a `&'a Arc`, you are not allowed to decrement the reference count and
278//! potentially free the underlying object. There is no equivalent to `Box` for file descriptors in
279//! 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::File
283//! [`TcpStream`]: crate::net::TcpStream
284//! [`io::stdout`]: stdout
285//! [`io::Result`]: self::Result
286//! [`?` operator]: ../../book/appendix-02-operators.html
287//! [`Result`]: crate::result::Result
288//! [`.unwrap()`]: crate::result::Result::unwrap
289//! [`os::unix`]: ../os/unix/io/index.html
290//! [`os::windows`]: ../os/windows/io/index.html
291//! [`OwnedFd`]: ../os/fd/struct.OwnedFd.html
292//! [`BorrowedFd<'a>`]: ../os/fd/struct.BorrowedFd.html
293//! [`Arc`]: crate::sync::Arc
294
295#![stable(feature = "rust1", since = "1.0.0")]
296
297#[cfg(test)]
298mod tests;
299
300use crate::cmp;
301use crate::fmt;
302use crate::mem::take;
303use crate::ops::{Deref, DerefMut};
304use crate::slice;
305use crate::str;
306use crate::sys;
307use crate::sys_common::memchr;
308
309#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
310pub use self::buffered::WriterPanicked;
311#[unstable(feature = "raw_os_error_ty", issue = "107792")]
312pub use self::error::RawOsError;
313pub(crate) use self::stdio::attempt_print_to_stderr;
314#[unstable(feature = "internal_output_capture", issue = "none")]
315#[doc(no_inline, hidden)]
316pub use self::stdio::set_output_capture;
317#[stable(feature = "is_terminal", since = "1.70.0")]
318pub use self::stdio::IsTerminal;
319#[unstable(feature = "print_internals", issue = "none")]
320#[doc(hidden)]
321pub use self::stdio::{_eprint, _print};
322#[stable(feature = "rust1", since = "1.0.0")]
323pub use self::{
324 buffered::{BufReader, BufWriter, IntoInnerError, LineWriter},
325 copy::copy,
326 cursor::Cursor,
327 error::{Error, ErrorKind, Result},
328 stdio::{stderr, stdin, stdout, Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock},
329 util::{empty, repeat, sink, Empty, Repeat, Sink},
330};
331
332#[unstable(feature = "read_buf", issue = "78485")]
333pub use core::io::{BorrowedBuf, BorrowedCursor};
334pub(crate) use error::const_io_error;
335
336mod buffered;
337pub(crate) mod copy;
338mod cursor;
339mod error;
340mod impls;
341pub mod prelude;
342mod stdio;
343mod util;
344
345const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
346
347pub(crate) use stdio::cleanup;
348
349struct Guard<'a> {
350 buf: &'a mut Vec<u8>,
351 len: usize,
352}
353
354impl Drop for Guard<'_> {
355 fn drop(&mut self) {
356 unsafe {
357 self.buf.set_len(self.len);
358 }
359 }
360}
361
362// Several `read_to_string` and `read_line` methods in the standard library will
363// append data into a `String` buffer, but we need to be pretty careful when
364// doing this. The implementation will just call `.as_mut_vec()` and then
365// delegate to a byte-oriented reading method, but we must ensure that when
366// returning we never leave `buf` in a state such that it contains invalid UTF-8
367// in its bounds.
368//
369// To this end, we use an RAII guard (to protect against panics) which updates
370// the length of the string when it is dropped. This guard initially truncates
371// the string to the prior length and only after we've validated that the
372// new contents are valid UTF-8 do we allow it to set a longer length.
373//
374// The unsafety in this function is twofold:
375//
376// 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
377// checks.
378// 2. We're passing a raw buffer to the function `f`, and it is expected that
379// the function only *appends* bytes to the buffer. We'll get undefined
380// behavior if existing bytes are overwritten to have non-UTF-8 data.
381pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
382where
383 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
384{
385 let mut g: Guard<'_> = Guard { len: buf.len(), buf: buf.as_mut_vec() };
386 let ret: Result = f(g.buf);
387 if str::from_utf8(&g.buf[g.len..]).is_err() {
388 ret.and_then(|_| {
389 Err(error::const_io_error!(
390 ErrorKind::InvalidData,
391 "stream did not contain valid UTF-8"
392 ))
393 })
394 } else {
395 g.len = g.buf.len();
396 ret
397 }
398}
399
400// Here we must serve many masters with conflicting goals:
401//
402// - avoid allocating unless necessary
403// - 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 overheads
406// - and finally pass not-too-small and not-too-large buffers to Windows read APIs because they manage to suffer from both problems
407// at the same time, i.e. small reads suffer from syscall overhead, all reads incur initialization cost
408// proportional to buffer size (#110650)
409//
410pub(crate) fn default_read_to_end<R: Read + ?Sized>(
411 r: &mut R,
412 buf: &mut Vec<u8>,
413 size_hint: Option<usize>,
414) -> Result<usize> {
415 let start_len = buf.len();
416 let start_cap = buf.capacity();
417 // Optionally limit the maximum bytes read on each iteration.
418 // This adds an arbitrary fiddle factor to allow for more data than we expect.
419 let mut max_read_size = size_hint
420 .and_then(|s| s.checked_add(1024)?.checked_next_multiple_of(DEFAULT_BUF_SIZE))
421 .unwrap_or(DEFAULT_BUF_SIZE);
422
423 let mut initialized = 0; // Extra initialized bytes from previous loop iteration
424
425 const PROBE_SIZE: usize = 32;
426
427 fn small_probe_read<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
428 let mut probe = [0u8; PROBE_SIZE];
429
430 loop {
431 match r.read(&mut probe) {
432 Ok(n) => {
433 // there is no way to recover from allocation failure here
434 // because the data has already been read.
435 buf.extend_from_slice(&probe[..n]);
436 return Ok(n);
437 }
438 Err(ref e) if e.is_interrupted() => continue,
439 Err(e) => return Err(e),
440 }
441 }
442 }
443
444 // avoid inflating empty/small vecs before we have determined that there's anything to read
445 if (size_hint.is_none() || size_hint == Some(0)) && buf.capacity() - buf.len() < PROBE_SIZE {
446 let read = small_probe_read(r, buf)?;
447
448 if read == 0 {
449 return Ok(0);
450 }
451 }
452
453 loop {
454 if buf.len() == buf.capacity() && buf.capacity() == start_cap {
455 // The buffer might be an exact fit. Let's read into a probe buffer
456 // and see if it returns `Ok(0)`. If so, we've avoided an
457 // unnecessary doubling of the capacity. But if not, append the
458 // probe buffer to the primary buffer and let its capacity grow.
459 let read = small_probe_read(r, buf)?;
460
461 if read == 0 {
462 return Ok(buf.len() - start_len);
463 }
464 }
465
466 if buf.len() == buf.capacity() {
467 // buf is full, need more space
468 buf.try_reserve(PROBE_SIZE).map_err(|_| ErrorKind::OutOfMemory)?;
469 }
470
471 let mut spare = buf.spare_capacity_mut();
472 let buf_len = cmp::min(spare.len(), max_read_size);
473 spare = &mut spare[..buf_len];
474 let mut read_buf: BorrowedBuf<'_> = spare.into();
475
476 // SAFETY: These bytes were initialized but not filled in the previous loop
477 unsafe {
478 read_buf.set_init(initialized);
479 }
480
481 let mut cursor = read_buf.unfilled();
482 loop {
483 match r.read_buf(cursor.reborrow()) {
484 Ok(()) => break,
485 Err(e) if e.is_interrupted() => continue,
486 Err(e) => return Err(e),
487 }
488 }
489
490 let unfilled_but_initialized = cursor.init_ref().len();
491 let bytes_read = cursor.written();
492 let was_fully_initialized = read_buf.init_len() == buf_len;
493
494 if bytes_read == 0 {
495 return Ok(buf.len() - start_len);
496 }
497
498 // store how much was initialized but not filled
499 initialized = unfilled_but_initialized;
500
501 // SAFETY: BorrowedBuf's invariants mean this much memory is initialized.
502 unsafe {
503 let new_len = bytes_read + buf.len();
504 buf.set_len(new_len);
505 }
506
507 // Use heuristics to determine the max read size if no initial size hint was provided
508 if size_hint.is_none() {
509 // The reader is returning short reads but it doesn't call ensure_init().
510 // In that case we no longer need to restrict read sizes to avoid
511 // initialization costs.
512 if !was_fully_initialized {
513 max_read_size = usize::MAX;
514 }
515
516 // we have passed a larger buffer than previously and the
517 // reader still hasn't returned a short read
518 if buf_len >= max_read_size && bytes_read == buf_len {
519 max_read_size = max_read_size.saturating_mul(2);
520 }
521 }
522 }
523}
524
525pub(crate) fn default_read_to_string<R: Read + ?Sized>(
526 r: &mut R,
527 buf: &mut String,
528 size_hint: Option<usize>,
529) -> Result<usize> {
530 // Note that we do *not* call `r.read_to_end()` here. We are passing
531 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
532 // method to fill it up. An arbitrary implementation could overwrite the
533 // entire contents of the vector, not just append to it (which is what
534 // we are expecting).
535 //
536 // To prevent extraneously checking the UTF-8-ness of the entire buffer
537 // we pass it to our hardcoded `default_read_to_end` implementation which
538 // we know is guaranteed to only read data into the end of the buffer.
539 unsafe { append_to_string(buf, |b: &mut Vec| default_read_to_end(r, buf:b, size_hint)) }
540}
541
542pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
543where
544 F: FnOnce(&mut [u8]) -> Result<usize>,
545{
546 let buf: &mut [u8] = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b: &mut IoSliceMut<'_>| &mut **b);
547 read(buf)
548}
549
550pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
551where
552 F: FnOnce(&[u8]) -> Result<usize>,
553{
554 let buf: &[u8] = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b: &IoSlice<'_>| &**b);
555 write(buf)
556}
557
558pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
559 while !buf.is_empty() {
560 match this.read(buf) {
561 Ok(0) => break,
562 Ok(n: usize) => {
563 buf = &mut buf[n..];
564 }
565 Err(ref e: &Error) if e.is_interrupted() => {}
566 Err(e: Error) => return Err(e),
567 }
568 }
569 if !buf.is_empty() {
570 Err(error::const_io_error!(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
571 } else {
572 Ok(())
573 }
574}
575
576pub(crate) fn default_read_buf<F>(read: F, mut cursor: BorrowedCursor<'_>) -> Result<()>
577where
578 F: FnOnce(&mut [u8]) -> Result<usize>,
579{
580 let n: usize = read(cursor.ensure_init().init_mut())?;
581 unsafe {
582 // SAFETY: we initialised using `ensure_init` so there is no uninit data to advance to.
583 cursor.advance(n);
584 }
585 Ok(())
586}
587
588/// The `Read` trait allows for reading bytes from a source.
589///
590/// Implementors of the `Read` trait are called 'readers'.
591///
592/// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
593/// will attempt to pull bytes from this source into a provided buffer. A
594/// number of other methods are implemented in terms of [`read()`], giving
595/// implementors a number of ways to read bytes while only needing to implement
596/// a single method.
597///
598/// Readers are intended to be composable with one another. Many implementors
599/// throughout [`std::io`] take and provide types which implement the `Read`
600/// trait.
601///
602/// Please note that each call to [`read()`] may involve a system call, and
603/// therefore, using something that implements [`BufRead`], such as
604/// [`BufReader`], will be more efficient.
605///
606/// Repeated calls to the reader use the same cursor, so for example
607/// calling `read_to_end` twice on a [`File`] will only return the file's
608/// contents once. It's recommended to first call `rewind()` in that case.
609///
610/// # Examples
611///
612/// [`File`]s implement `Read`:
613///
614/// ```no_run
615/// use std::io;
616/// use std::io::prelude::*;
617/// use std::fs::File;
618///
619/// fn main() -> io::Result<()> {
620/// let mut f = File::open("foo.txt")?;
621/// let mut buffer = [0; 10];
622///
623/// // read up to 10 bytes
624/// f.read(&mut buffer)?;
625///
626/// let mut buffer = Vec::new();
627/// // read the whole file
628/// f.read_to_end(&mut buffer)?;
629///
630/// // read into a String, so that you don't need to do the conversion.
631/// let mut buffer = String::new();
632/// f.read_to_string(&mut buffer)?;
633///
634/// // and more! See the other methods for more details.
635/// Ok(())
636/// }
637/// ```
638///
639/// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
640///
641/// ```no_run
642/// # use std::io;
643/// use std::io::prelude::*;
644///
645/// fn main() -> io::Result<()> {
646/// let mut b = "This string will be read".as_bytes();
647/// let mut buffer = [0; 10];
648///
649/// // read up to 10 bytes
650/// b.read(&mut buffer)?;
651///
652/// // etc... it works exactly as a File does!
653/// Ok(())
654/// }
655/// ```
656///
657/// [`read()`]: Read::read
658/// [`&str`]: prim@str
659/// [`std::io`]: self
660/// [`File`]: crate::fs::File
661#[stable(feature = "rust1", since = "1.0.0")]
662#[doc(notable_trait)]
663#[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
664pub trait Read {
665 /// Pull some bytes from this source into the specified buffer, returning
666 /// how many bytes were read.
667 ///
668 /// This function does not provide any guarantees about whether it blocks
669 /// waiting for data, but if an object needs to block for a read and cannot,
670 /// it will typically signal this via an [`Err`] return value.
671 ///
672 /// If the return value of this method is [`Ok(n)`], then implementations must
673 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
674 /// that the buffer `buf` has been filled in with `n` bytes of data from this
675 /// source. If `n` is `0`, then it can indicate one of two scenarios:
676 ///
677 /// 1. This reader has reached its "end of file" and will likely no longer
678 /// be able to produce bytes. Note that this does not mean that the
679 /// reader will *always* no longer be able to produce bytes. As an example,
680 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],
681 /// where returning zero indicates the connection was shut down correctly. While
682 /// for [`File`], it is possible to reach the end of file and get zero as result,
683 /// but if more data is appended to the file, future calls to `read` will return
684 /// more data.
685 /// 2. The buffer specified was 0 bytes in length.
686 ///
687 /// It is not an error if the returned value `n` is smaller than the buffer size,
688 /// even when the reader is not at the end of the stream yet.
689 /// This may happen for example because fewer bytes are actually available right now
690 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
691 ///
692 /// As this trait is safe to implement, callers in unsafe code cannot rely on
693 /// `n <= buf.len()` for safety.
694 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
695 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
696 /// `n > buf.len()`.
697 ///
698 /// No guarantees are provided about the contents of `buf` when this
699 /// function is called, so implementations cannot rely on any property of the
700 /// contents of `buf` being true. It is recommended that *implementations*
701 /// only write data to `buf` instead of reading its contents.
702 ///
703 /// Correspondingly, however, *callers* of this method in unsafe code must not assume
704 /// any guarantees about how the implementation uses `buf`. The trait is safe to implement,
705 /// so it is possible that the code that's supposed to write to the buffer might also read
706 /// from it. It is your responsibility to make sure that `buf` is initialized
707 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
708 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
709 ///
710 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
711 ///
712 /// # Errors
713 ///
714 /// If this function encounters any form of I/O or other error, an error
715 /// variant will be returned. If an error is returned then it must be
716 /// guaranteed that no bytes were read.
717 ///
718 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
719 /// operation should be retried if there is nothing else to do.
720 ///
721 /// # Examples
722 ///
723 /// [`File`]s implement `Read`:
724 ///
725 /// [`Ok(n)`]: Ok
726 /// [`File`]: crate::fs::File
727 /// [`TcpStream`]: crate::net::TcpStream
728 ///
729 /// ```no_run
730 /// use std::io;
731 /// use std::io::prelude::*;
732 /// use std::fs::File;
733 ///
734 /// fn main() -> io::Result<()> {
735 /// let mut f = File::open("foo.txt")?;
736 /// let mut buffer = [0; 10];
737 ///
738 /// // read up to 10 bytes
739 /// let n = f.read(&mut buffer[..])?;
740 ///
741 /// println!("The bytes: {:?}", &buffer[..n]);
742 /// Ok(())
743 /// }
744 /// ```
745 #[stable(feature = "rust1", since = "1.0.0")]
746 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
747
748 /// Like `read`, except that it reads into a slice of buffers.
749 ///
750 /// Data is copied to fill each buffer in order, with the final buffer
751 /// written to possibly being only partially filled. This method must
752 /// behave equivalently to a single call to `read` with concatenated
753 /// buffers.
754 ///
755 /// The default implementation calls `read` with either the first nonempty
756 /// buffer provided, or an empty one if none exists.
757 #[stable(feature = "iovec", since = "1.36.0")]
758 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
759 default_read_vectored(|b| self.read(b), bufs)
760 }
761
762 /// Determines if this `Read`er has an efficient `read_vectored`
763 /// implementation.
764 ///
765 /// If a `Read`er does not override the default `read_vectored`
766 /// implementation, code using it may want to avoid the method all together
767 /// and coalesce writes into a single buffer for higher performance.
768 ///
769 /// The default implementation returns `false`.
770 #[unstable(feature = "can_vector", issue = "69941")]
771 fn is_read_vectored(&self) -> bool {
772 false
773 }
774
775 /// Read all bytes until EOF in this source, placing them into `buf`.
776 ///
777 /// All bytes read from this source will be appended to the specified buffer
778 /// `buf`. This function will continuously call [`read()`] to append more data to
779 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
780 /// non-[`ErrorKind::Interrupted`] kind.
781 ///
782 /// If successful, this function will return the total number of bytes read.
783 ///
784 /// # Errors
785 ///
786 /// If this function encounters an error of the kind
787 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
788 /// will continue.
789 ///
790 /// If any other read error is encountered then this function immediately
791 /// returns. Any bytes which have already been read will be appended to
792 /// `buf`.
793 ///
794 /// # Examples
795 ///
796 /// [`File`]s implement `Read`:
797 ///
798 /// [`read()`]: Read::read
799 /// [`Ok(0)`]: Ok
800 /// [`File`]: crate::fs::File
801 ///
802 /// ```no_run
803 /// use std::io;
804 /// use std::io::prelude::*;
805 /// use std::fs::File;
806 ///
807 /// fn main() -> io::Result<()> {
808 /// let mut f = File::open("foo.txt")?;
809 /// let mut buffer = Vec::new();
810 ///
811 /// // read the whole file
812 /// f.read_to_end(&mut buffer)?;
813 /// Ok(())
814 /// }
815 /// ```
816 ///
817 /// (See also the [`std::fs::read`] convenience function for reading from a
818 /// file.)
819 ///
820 /// [`std::fs::read`]: crate::fs::read
821 ///
822 /// ## Implementing `read_to_end`
823 ///
824 /// When implementing the `io::Read` trait, it is recommended to allocate
825 /// memory using [`Vec::try_reserve`]. However, this behavior is not guaranteed
826 /// by all implementations, and `read_to_end` may not handle out-of-memory
827 /// situations gracefully.
828 ///
829 /// ```no_run
830 /// # use std::io::{self, BufRead};
831 /// # struct Example { example_datasource: io::Empty } impl Example {
832 /// # fn get_some_data_for_the_example(&self) -> &'static [u8] { &[] }
833 /// fn read_to_end(&mut self, dest_vec: &mut Vec<u8>) -> io::Result<usize> {
834 /// let initial_vec_len = dest_vec.len();
835 /// loop {
836 /// let src_buf = self.example_datasource.fill_buf()?;
837 /// if src_buf.is_empty() {
838 /// break;
839 /// }
840 /// dest_vec.try_reserve(src_buf.len()).map_err(|_| io::ErrorKind::OutOfMemory)?;
841 /// dest_vec.extend_from_slice(src_buf);
842 ///
843 /// // Any irreversible side effects should happen after `try_reserve` succeeds,
844 /// // to avoid losing data on allocation error.
845 /// let read = src_buf.len();
846 /// self.example_datasource.consume(read);
847 /// }
848 /// Ok(dest_vec.len() - initial_vec_len)
849 /// }
850 /// # }
851 /// ```
852 ///
853 /// [`Vec::try_reserve`]: crate::vec::Vec::try_reserve
854 #[stable(feature = "rust1", since = "1.0.0")]
855 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
856 default_read_to_end(self, buf, None)
857 }
858
859 /// Read all bytes until EOF in this source, appending them to `buf`.
860 ///
861 /// If successful, this function returns the number of bytes which were read
862 /// and appended to `buf`.
863 ///
864 /// # Errors
865 ///
866 /// If the data in this stream is *not* valid UTF-8 then an error is
867 /// returned and `buf` is unchanged.
868 ///
869 /// See [`read_to_end`] for other error semantics.
870 ///
871 /// [`read_to_end`]: Read::read_to_end
872 ///
873 /// # Examples
874 ///
875 /// [`File`]s implement `Read`:
876 ///
877 /// [`File`]: crate::fs::File
878 ///
879 /// ```no_run
880 /// use std::io;
881 /// use std::io::prelude::*;
882 /// use std::fs::File;
883 ///
884 /// fn main() -> io::Result<()> {
885 /// let mut f = File::open("foo.txt")?;
886 /// let mut buffer = String::new();
887 ///
888 /// f.read_to_string(&mut buffer)?;
889 /// Ok(())
890 /// }
891 /// ```
892 ///
893 /// (See also the [`std::fs::read_to_string`] convenience function for
894 /// reading from a file.)
895 ///
896 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
897 #[stable(feature = "rust1", since = "1.0.0")]
898 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
899 default_read_to_string(self, buf, None)
900 }
901
902 /// Read the exact number of bytes required to fill `buf`.
903 ///
904 /// This function reads as many bytes as necessary to completely fill the
905 /// specified buffer `buf`.
906 ///
907 /// No guarantees are provided about the contents of `buf` when this
908 /// function is called, so implementations cannot rely on any property of the
909 /// contents of `buf` being true. It is recommended that implementations
910 /// only write data to `buf` instead of reading its contents. The
911 /// documentation on [`read`] has a more detailed explanation on this
912 /// subject.
913 ///
914 /// # Errors
915 ///
916 /// If this function encounters an error of the kind
917 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
918 /// will continue.
919 ///
920 /// If this function encounters an "end of file" before completely filling
921 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
922 /// The contents of `buf` are unspecified in this case.
923 ///
924 /// If any other read error is encountered then this function immediately
925 /// returns. The contents of `buf` are unspecified in this case.
926 ///
927 /// If this function returns an error, it is unspecified how many bytes it
928 /// has read, but it will never read more than would be necessary to
929 /// completely fill the buffer.
930 ///
931 /// # Examples
932 ///
933 /// [`File`]s implement `Read`:
934 ///
935 /// [`read`]: Read::read
936 /// [`File`]: crate::fs::File
937 ///
938 /// ```no_run
939 /// use std::io;
940 /// use std::io::prelude::*;
941 /// use std::fs::File;
942 ///
943 /// fn main() -> io::Result<()> {
944 /// let mut f = File::open("foo.txt")?;
945 /// let mut buffer = [0; 10];
946 ///
947 /// // read exactly 10 bytes
948 /// f.read_exact(&mut buffer)?;
949 /// Ok(())
950 /// }
951 /// ```
952 #[stable(feature = "read_exact", since = "1.6.0")]
953 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
954 default_read_exact(self, buf)
955 }
956
957 /// Pull some bytes from this source into the specified buffer.
958 ///
959 /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
960 /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
961 ///
962 /// The default implementation delegates to `read`.
963 #[unstable(feature = "read_buf", issue = "78485")]
964 fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<()> {
965 default_read_buf(|b| self.read(b), buf)
966 }
967
968 /// Read the exact number of bytes required to fill `cursor`.
969 ///
970 /// This is similar to the [`read_exact`](Read::read_exact) method, except
971 /// that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
972 /// with uninitialized buffers.
973 ///
974 /// # Errors
975 ///
976 /// If this function encounters an error of the kind [`ErrorKind::Interrupted`]
977 /// then the error is ignored and the operation will continue.
978 ///
979 /// If this function encounters an "end of file" before completely filling
980 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
981 ///
982 /// If any other read error is encountered then this function immediately
983 /// returns.
984 ///
985 /// If this function returns an error, all bytes read will be appended to `cursor`.
986 #[unstable(feature = "read_buf", issue = "78485")]
987 fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> Result<()> {
988 while cursor.capacity() > 0 {
989 let prev_written = cursor.written();
990 match self.read_buf(cursor.reborrow()) {
991 Ok(()) => {}
992 Err(e) if e.is_interrupted() => continue,
993 Err(e) => return Err(e),
994 }
995
996 if cursor.written() == prev_written {
997 return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill buffer"));
998 }
999 }
1000
1001 Ok(())
1002 }
1003
1004 /// Creates a "by reference" adaptor for this instance of `Read`.
1005 ///
1006 /// The returned adapter also implements `Read` and will simply borrow this
1007 /// current reader.
1008 ///
1009 /// # Examples
1010 ///
1011 /// [`File`]s implement `Read`:
1012 ///
1013 /// [`File`]: crate::fs::File
1014 ///
1015 /// ```no_run
1016 /// use std::io;
1017 /// use std::io::Read;
1018 /// use std::fs::File;
1019 ///
1020 /// fn main() -> io::Result<()> {
1021 /// let mut f = File::open("foo.txt")?;
1022 /// let mut buffer = Vec::new();
1023 /// let mut other_buffer = Vec::new();
1024 ///
1025 /// {
1026 /// let reference = f.by_ref();
1027 ///
1028 /// // read at most 5 bytes
1029 /// reference.take(5).read_to_end(&mut buffer)?;
1030 ///
1031 /// } // drop our &mut reference so we can use f again
1032 ///
1033 /// // original file still usable, read the rest
1034 /// f.read_to_end(&mut other_buffer)?;
1035 /// Ok(())
1036 /// }
1037 /// ```
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 fn by_ref(&mut self) -> &mut Self
1040 where
1041 Self: Sized,
1042 {
1043 self
1044 }
1045
1046 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
1047 ///
1048 /// The returned type implements [`Iterator`] where the [`Item`] is
1049 /// <code>[Result]<[u8], [io::Error]></code>.
1050 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
1051 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
1052 ///
1053 /// The default implementation calls `read` for each byte,
1054 /// which can be very inefficient for data that's not in memory,
1055 /// such as [`File`]. Consider using a [`BufReader`] in such cases.
1056 ///
1057 /// # Examples
1058 ///
1059 /// [`File`]s implement `Read`:
1060 ///
1061 /// [`Item`]: Iterator::Item
1062 /// [`File`]: crate::fs::File "fs::File"
1063 /// [Result]: crate::result::Result "Result"
1064 /// [io::Error]: self::Error "io::Error"
1065 ///
1066 /// ```no_run
1067 /// use std::io;
1068 /// use std::io::prelude::*;
1069 /// use std::io::BufReader;
1070 /// use std::fs::File;
1071 ///
1072 /// fn main() -> io::Result<()> {
1073 /// let f = BufReader::new(File::open("foo.txt")?);
1074 ///
1075 /// for byte in f.bytes() {
1076 /// println!("{}", byte.unwrap());
1077 /// }
1078 /// Ok(())
1079 /// }
1080 /// ```
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 fn bytes(self) -> Bytes<Self>
1083 where
1084 Self: Sized,
1085 {
1086 Bytes { inner: self }
1087 }
1088
1089 /// Creates an adapter which will chain this stream with another.
1090 ///
1091 /// The returned `Read` instance will first read all bytes from this object
1092 /// until EOF is encountered. Afterwards the output is equivalent to the
1093 /// output of `next`.
1094 ///
1095 /// # Examples
1096 ///
1097 /// [`File`]s implement `Read`:
1098 ///
1099 /// [`File`]: crate::fs::File
1100 ///
1101 /// ```no_run
1102 /// use std::io;
1103 /// use std::io::prelude::*;
1104 /// use std::fs::File;
1105 ///
1106 /// fn main() -> io::Result<()> {
1107 /// let f1 = File::open("foo.txt")?;
1108 /// let f2 = File::open("bar.txt")?;
1109 ///
1110 /// let mut handle = f1.chain(f2);
1111 /// let mut buffer = String::new();
1112 ///
1113 /// // read the value into a String. We could use any Read method here,
1114 /// // this is just one example.
1115 /// handle.read_to_string(&mut buffer)?;
1116 /// Ok(())
1117 /// }
1118 /// ```
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
1121 where
1122 Self: Sized,
1123 {
1124 Chain { first: self, second: next, done_first: false }
1125 }
1126
1127 /// Creates an adapter which will read at most `limit` bytes from it.
1128 ///
1129 /// This function returns a new instance of `Read` which will read at most
1130 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
1131 /// read errors will not count towards the number of bytes read and future
1132 /// calls to [`read()`] may succeed.
1133 ///
1134 /// # Examples
1135 ///
1136 /// [`File`]s implement `Read`:
1137 ///
1138 /// [`File`]: crate::fs::File
1139 /// [`Ok(0)`]: Ok
1140 /// [`read()`]: Read::read
1141 ///
1142 /// ```no_run
1143 /// use std::io;
1144 /// use std::io::prelude::*;
1145 /// use std::fs::File;
1146 ///
1147 /// fn main() -> io::Result<()> {
1148 /// let f = File::open("foo.txt")?;
1149 /// let mut buffer = [0; 5];
1150 ///
1151 /// // read at most five bytes
1152 /// let mut handle = f.take(5);
1153 ///
1154 /// handle.read(&mut buffer)?;
1155 /// Ok(())
1156 /// }
1157 /// ```
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 fn take(self, limit: u64) -> Take<Self>
1160 where
1161 Self: Sized,
1162 {
1163 Take { inner: self, limit }
1164 }
1165}
1166
1167/// Read all bytes from a [reader][Read] into a new [`String`].
1168///
1169/// This is a convenience function for [`Read::read_to_string`]. Using this
1170/// function avoids having to create a variable first and provides more type
1171/// safety since you can only get the buffer out if there were no errors. (If you
1172/// use [`Read::read_to_string`] you have to remember to check whether the read
1173/// succeeded because otherwise your buffer will be empty or only partially full.)
1174///
1175/// # Performance
1176///
1177/// The downside of this function's increased ease of use and type safety is
1178/// that it gives you less control over performance. For example, you can't
1179/// pre-allocate memory like you can using [`String::with_capacity`] and
1180/// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1181/// occurs while reading.
1182///
1183/// In many cases, this function's performance will be adequate and the ease of use
1184/// and type safety tradeoffs will be worth it. However, there are cases where you
1185/// need more control over performance, and in those cases you should definitely use
1186/// [`Read::read_to_string`] directly.
1187///
1188/// Note that in some special cases, such as when reading files, this function will
1189/// pre-allocate memory based on the size of the input it is reading. In those
1190/// cases, the performance should be as good as if you had used
1191/// [`Read::read_to_string`] with a manually pre-allocated buffer.
1192///
1193/// # Errors
1194///
1195/// This function forces you to handle errors because the output (the `String`)
1196/// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1197/// that can occur. If any error occurs, you will get an [`Err`], so you
1198/// don't have to worry about your buffer being empty or partially full.
1199///
1200/// # Examples
1201///
1202/// ```no_run
1203/// # use std::io;
1204/// fn main() -> io::Result<()> {
1205/// let stdin = io::read_to_string(io::stdin())?;
1206/// println!("Stdin was:");
1207/// println!("{stdin}");
1208/// Ok(())
1209/// }
1210/// ```
1211#[stable(feature = "io_read_to_string", since = "1.65.0")]
1212pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> {
1213 let mut buf: String = String::new();
1214 reader.read_to_string(&mut buf)?;
1215 Ok(buf)
1216}
1217
1218/// A buffer type used with `Read::read_vectored`.
1219///
1220/// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1221/// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1222/// Windows.
1223#[stable(feature = "iovec", since = "1.36.0")]
1224#[repr(transparent)]
1225pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
1226
1227#[stable(feature = "iovec_send_sync", since = "1.44.0")]
1228unsafe impl<'a> Send for IoSliceMut<'a> {}
1229
1230#[stable(feature = "iovec_send_sync", since = "1.44.0")]
1231unsafe impl<'a> Sync for IoSliceMut<'a> {}
1232
1233#[stable(feature = "iovec", since = "1.36.0")]
1234impl<'a> fmt::Debug for IoSliceMut<'a> {
1235 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1236 fmt::Debug::fmt(self.0.as_slice(), f:fmt)
1237 }
1238}
1239
1240impl<'a> IoSliceMut<'a> {
1241 /// Creates a new `IoSliceMut` wrapping a byte slice.
1242 ///
1243 /// # Panics
1244 ///
1245 /// Panics on Windows if the slice is larger than 4GB.
1246 #[stable(feature = "iovec", since = "1.36.0")]
1247 #[inline]
1248 pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
1249 IoSliceMut(sys::io::IoSliceMut::new(buf))
1250 }
1251
1252 /// Advance the internal cursor of the slice.
1253 ///
1254 /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
1255 /// multiple buffers.
1256 ///
1257 /// # Panics
1258 ///
1259 /// Panics when trying to advance beyond the end of the slice.
1260 ///
1261 /// # Examples
1262 ///
1263 /// ```
1264 /// #![feature(io_slice_advance)]
1265 ///
1266 /// use std::io::IoSliceMut;
1267 /// use std::ops::Deref;
1268 ///
1269 /// let mut data = [1; 8];
1270 /// let mut buf = IoSliceMut::new(&mut data);
1271 ///
1272 /// // Mark 3 bytes as read.
1273 /// buf.advance(3);
1274 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1275 /// ```
1276 #[unstable(feature = "io_slice_advance", issue = "62726")]
1277 #[inline]
1278 pub fn advance(&mut self, n: usize) {
1279 self.0.advance(n)
1280 }
1281
1282 /// Advance a slice of slices.
1283 ///
1284 /// Shrinks the slice to remove any `IoSliceMut`s that are fully advanced over.
1285 /// If the cursor ends up in the middle of an `IoSliceMut`, it is modified
1286 /// to start at that cursor.
1287 ///
1288 /// For example, if we have a slice of two 8-byte `IoSliceMut`s, and we advance by 10 bytes,
1289 /// the result will only include the second `IoSliceMut`, advanced by 2 bytes.
1290 ///
1291 /// # Panics
1292 ///
1293 /// Panics when trying to advance beyond the end of the slices.
1294 ///
1295 /// # Examples
1296 ///
1297 /// ```
1298 /// #![feature(io_slice_advance)]
1299 ///
1300 /// use std::io::IoSliceMut;
1301 /// use std::ops::Deref;
1302 ///
1303 /// let mut buf1 = [1; 8];
1304 /// let mut buf2 = [2; 16];
1305 /// let mut buf3 = [3; 8];
1306 /// let mut bufs = &mut [
1307 /// IoSliceMut::new(&mut buf1),
1308 /// IoSliceMut::new(&mut buf2),
1309 /// IoSliceMut::new(&mut buf3),
1310 /// ][..];
1311 ///
1312 /// // Mark 10 bytes as read.
1313 /// IoSliceMut::advance_slices(&mut bufs, 10);
1314 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1315 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1316 /// ```
1317 #[unstable(feature = "io_slice_advance", issue = "62726")]
1318 #[inline]
1319 pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) {
1320 // Number of buffers to remove.
1321 let mut remove = 0;
1322 // Remaining length before reaching n.
1323 let mut left = n;
1324 for buf in bufs.iter() {
1325 if let Some(remainder) = left.checked_sub(buf.len()) {
1326 left = remainder;
1327 remove += 1;
1328 } else {
1329 break;
1330 }
1331 }
1332
1333 *bufs = &mut take(bufs)[remove..];
1334 if bufs.is_empty() {
1335 assert!(left == 0, "advancing io slices beyond their length");
1336 } else {
1337 bufs[0].advance(left);
1338 }
1339 }
1340}
1341
1342#[stable(feature = "iovec", since = "1.36.0")]
1343impl<'a> Deref for IoSliceMut<'a> {
1344 type Target = [u8];
1345
1346 #[inline]
1347 fn deref(&self) -> &[u8] {
1348 self.0.as_slice()
1349 }
1350}
1351
1352#[stable(feature = "iovec", since = "1.36.0")]
1353impl<'a> DerefMut for IoSliceMut<'a> {
1354 #[inline]
1355 fn deref_mut(&mut self) -> &mut [u8] {
1356 self.0.as_mut_slice()
1357 }
1358}
1359
1360/// A buffer type used with `Write::write_vectored`.
1361///
1362/// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be
1363/// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1364/// Windows.
1365#[stable(feature = "iovec", since = "1.36.0")]
1366#[derive(Copy, Clone)]
1367#[repr(transparent)]
1368pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1369
1370#[stable(feature = "iovec_send_sync", since = "1.44.0")]
1371unsafe impl<'a> Send for IoSlice<'a> {}
1372
1373#[stable(feature = "iovec_send_sync", since = "1.44.0")]
1374unsafe impl<'a> Sync for IoSlice<'a> {}
1375
1376#[stable(feature = "iovec", since = "1.36.0")]
1377impl<'a> fmt::Debug for IoSlice<'a> {
1378 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1379 fmt::Debug::fmt(self.0.as_slice(), f:fmt)
1380 }
1381}
1382
1383impl<'a> IoSlice<'a> {
1384 /// Creates a new `IoSlice` wrapping a byte slice.
1385 ///
1386 /// # Panics
1387 ///
1388 /// Panics on Windows if the slice is larger than 4GB.
1389 #[stable(feature = "iovec", since = "1.36.0")]
1390 #[must_use]
1391 #[inline]
1392 pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1393 IoSlice(sys::io::IoSlice::new(buf))
1394 }
1395
1396 /// Advance the internal cursor of the slice.
1397 ///
1398 /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
1399 /// buffers.
1400 ///
1401 /// # Panics
1402 ///
1403 /// Panics when trying to advance beyond the end of the slice.
1404 ///
1405 /// # Examples
1406 ///
1407 /// ```
1408 /// #![feature(io_slice_advance)]
1409 ///
1410 /// use std::io::IoSlice;
1411 /// use std::ops::Deref;
1412 ///
1413 /// let data = [1; 8];
1414 /// let mut buf = IoSlice::new(&data);
1415 ///
1416 /// // Mark 3 bytes as read.
1417 /// buf.advance(3);
1418 /// assert_eq!(buf.deref(), [1; 5].as_ref());
1419 /// ```
1420 #[unstable(feature = "io_slice_advance", issue = "62726")]
1421 #[inline]
1422 pub fn advance(&mut self, n: usize) {
1423 self.0.advance(n)
1424 }
1425
1426 /// Advance a slice of slices.
1427 ///
1428 /// Shrinks the slice to remove any `IoSlice`s that are fully advanced over.
1429 /// If the cursor ends up in the middle of an `IoSlice`, it is modified
1430 /// to start at that cursor.
1431 ///
1432 /// For example, if we have a slice of two 8-byte `IoSlice`s, and we advance by 10 bytes,
1433 /// the result will only include the second `IoSlice`, advanced by 2 bytes.
1434 ///
1435 /// # Panics
1436 ///
1437 /// Panics when trying to advance beyond the end of the slices.
1438 ///
1439 /// # Examples
1440 ///
1441 /// ```
1442 /// #![feature(io_slice_advance)]
1443 ///
1444 /// use std::io::IoSlice;
1445 /// use std::ops::Deref;
1446 ///
1447 /// let buf1 = [1; 8];
1448 /// let buf2 = [2; 16];
1449 /// let buf3 = [3; 8];
1450 /// let mut bufs = &mut [
1451 /// IoSlice::new(&buf1),
1452 /// IoSlice::new(&buf2),
1453 /// IoSlice::new(&buf3),
1454 /// ][..];
1455 ///
1456 /// // Mark 10 bytes as written.
1457 /// IoSlice::advance_slices(&mut bufs, 10);
1458 /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1459 /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1460 #[unstable(feature = "io_slice_advance", issue = "62726")]
1461 #[inline]
1462 pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) {
1463 // Number of buffers to remove.
1464 let mut remove = 0;
1465 // Remaining length before reaching n. This prevents overflow
1466 // that could happen if the length of slices in `bufs` were instead
1467 // accumulated. Those slice may be aliased and, if they are large
1468 // enough, their added length may overflow a `usize`.
1469 let mut left = n;
1470 for buf in bufs.iter() {
1471 if let Some(remainder) = left.checked_sub(buf.len()) {
1472 left = remainder;
1473 remove += 1;
1474 } else {
1475 break;
1476 }
1477 }
1478
1479 *bufs = &mut take(bufs)[remove..];
1480 if bufs.is_empty() {
1481 assert!(left == 0, "advancing io slices beyond their length");
1482 } else {
1483 bufs[0].advance(left);
1484 }
1485 }
1486}
1487
1488#[stable(feature = "iovec", since = "1.36.0")]
1489impl<'a> Deref for IoSlice<'a> {
1490 type Target = [u8];
1491
1492 #[inline]
1493 fn deref(&self) -> &[u8] {
1494 self.0.as_slice()
1495 }
1496}
1497
1498/// A trait for objects which are byte-oriented sinks.
1499///
1500/// Implementors of the `Write` trait are sometimes called 'writers'.
1501///
1502/// Writers are defined by two required methods, [`write`] and [`flush`]:
1503///
1504/// * The [`write`] method will attempt to write some data into the object,
1505/// returning how many bytes were successfully written.
1506///
1507/// * The [`flush`] method is useful for adapters and explicit buffers
1508/// themselves for ensuring that all buffered data has been pushed out to the
1509/// 'true sink'.
1510///
1511/// Writers are intended to be composable with one another. Many implementors
1512/// throughout [`std::io`] take and provide types which implement the `Write`
1513/// trait.
1514///
1515/// [`write`]: Write::write
1516/// [`flush`]: Write::flush
1517/// [`std::io`]: self
1518///
1519/// # Examples
1520///
1521/// ```no_run
1522/// use std::io::prelude::*;
1523/// use std::fs::File;
1524///
1525/// fn main() -> std::io::Result<()> {
1526/// let data = b"some bytes";
1527///
1528/// let mut pos = 0;
1529/// let mut buffer = File::create("foo.txt")?;
1530///
1531/// while pos < data.len() {
1532/// let bytes_written = buffer.write(&data[pos..])?;
1533/// pos += bytes_written;
1534/// }
1535/// Ok(())
1536/// }
1537/// ```
1538///
1539/// The trait also provides convenience methods like [`write_all`], which calls
1540/// `write` in a loop until its entire input has been written.
1541///
1542/// [`write_all`]: Write::write_all
1543#[stable(feature = "rust1", since = "1.0.0")]
1544#[doc(notable_trait)]
1545#[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]
1546pub trait Write {
1547 /// Write a buffer into this writer, returning how many bytes were written.
1548 ///
1549 /// This function will attempt to write the entire contents of `buf`, but
1550 /// the entire write might not succeed, or the write may also generate an
1551 /// error. Typically, a call to `write` represents one attempt to write to
1552 /// any wrapped object.
1553 ///
1554 /// Calls to `write` are not guaranteed to block waiting for data to be
1555 /// written, and a write which would otherwise block can be indicated through
1556 /// an [`Err`] variant.
1557 ///
1558 /// If this method consumed `n > 0` bytes of `buf` it must return [`Ok(n)`].
1559 /// If the return value is `Ok(n)` then `n` must satisfy `n <= buf.len()`.
1560 /// A return value of `Ok(0)` typically means that the underlying object is
1561 /// no longer able to accept bytes and will likely not be able to in the
1562 /// future as well, or that the buffer provided is empty.
1563 ///
1564 /// # Errors
1565 ///
1566 /// Each call to `write` may generate an I/O error indicating that the
1567 /// operation could not be completed. If an error is returned then no bytes
1568 /// in the buffer were written to this writer.
1569 ///
1570 /// It is **not** considered an error if the entire buffer could not be
1571 /// written to this writer.
1572 ///
1573 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1574 /// write operation should be retried if there is nothing else to do.
1575 ///
1576 /// # Examples
1577 ///
1578 /// ```no_run
1579 /// use std::io::prelude::*;
1580 /// use std::fs::File;
1581 ///
1582 /// fn main() -> std::io::Result<()> {
1583 /// let mut buffer = File::create("foo.txt")?;
1584 ///
1585 /// // Writes some prefix of the byte string, not necessarily all of it.
1586 /// buffer.write(b"some bytes")?;
1587 /// Ok(())
1588 /// }
1589 /// ```
1590 ///
1591 /// [`Ok(n)`]: Ok
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 fn write(&mut self, buf: &[u8]) -> Result<usize>;
1594
1595 /// Like [`write`], except that it writes from a slice of buffers.
1596 ///
1597 /// Data is copied from each buffer in order, with the final buffer
1598 /// read from possibly being only partially consumed. This method must
1599 /// behave as a call to [`write`] with the buffers concatenated would.
1600 ///
1601 /// The default implementation calls [`write`] with either the first nonempty
1602 /// buffer provided, or an empty one if none exists.
1603 ///
1604 /// # Examples
1605 ///
1606 /// ```no_run
1607 /// use std::io::IoSlice;
1608 /// use std::io::prelude::*;
1609 /// use std::fs::File;
1610 ///
1611 /// fn main() -> std::io::Result<()> {
1612 /// let data1 = [1; 8];
1613 /// let data2 = [15; 8];
1614 /// let io_slice1 = IoSlice::new(&data1);
1615 /// let io_slice2 = IoSlice::new(&data2);
1616 ///
1617 /// let mut buffer = File::create("foo.txt")?;
1618 ///
1619 /// // Writes some prefix of the byte string, not necessarily all of it.
1620 /// buffer.write_vectored(&[io_slice1, io_slice2])?;
1621 /// Ok(())
1622 /// }
1623 /// ```
1624 ///
1625 /// [`write`]: Write::write
1626 #[stable(feature = "iovec", since = "1.36.0")]
1627 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1628 default_write_vectored(|b| self.write(b), bufs)
1629 }
1630
1631 /// Determines if this `Write`r has an efficient [`write_vectored`]
1632 /// implementation.
1633 ///
1634 /// If a `Write`r does not override the default [`write_vectored`]
1635 /// implementation, code using it may want to avoid the method all together
1636 /// and coalesce writes into a single buffer for higher performance.
1637 ///
1638 /// The default implementation returns `false`.
1639 ///
1640 /// [`write_vectored`]: Write::write_vectored
1641 #[unstable(feature = "can_vector", issue = "69941")]
1642 fn is_write_vectored(&self) -> bool {
1643 false
1644 }
1645
1646 /// Flush this output stream, ensuring that all intermediately buffered
1647 /// contents reach their destination.
1648 ///
1649 /// # Errors
1650 ///
1651 /// It is considered an error if not all bytes could be written due to
1652 /// I/O errors or EOF being reached.
1653 ///
1654 /// # Examples
1655 ///
1656 /// ```no_run
1657 /// use std::io::prelude::*;
1658 /// use std::io::BufWriter;
1659 /// use std::fs::File;
1660 ///
1661 /// fn main() -> std::io::Result<()> {
1662 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
1663 ///
1664 /// buffer.write_all(b"some bytes")?;
1665 /// buffer.flush()?;
1666 /// Ok(())
1667 /// }
1668 /// ```
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 fn flush(&mut self) -> Result<()>;
1671
1672 /// Attempts to write an entire buffer into this writer.
1673 ///
1674 /// This method will continuously call [`write`] until there is no more data
1675 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1676 /// returned. This method will not return until the entire buffer has been
1677 /// successfully written or such an error occurs. The first error that is
1678 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1679 /// returned.
1680 ///
1681 /// If the buffer contains no data, this will never call [`write`].
1682 ///
1683 /// # Errors
1684 ///
1685 /// This function will return the first error of
1686 /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1687 ///
1688 /// [`write`]: Write::write
1689 ///
1690 /// # Examples
1691 ///
1692 /// ```no_run
1693 /// use std::io::prelude::*;
1694 /// use std::fs::File;
1695 ///
1696 /// fn main() -> std::io::Result<()> {
1697 /// let mut buffer = File::create("foo.txt")?;
1698 ///
1699 /// buffer.write_all(b"some bytes")?;
1700 /// Ok(())
1701 /// }
1702 /// ```
1703 #[stable(feature = "rust1", since = "1.0.0")]
1704 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1705 while !buf.is_empty() {
1706 match self.write(buf) {
1707 Ok(0) => {
1708 return Err(error::const_io_error!(
1709 ErrorKind::WriteZero,
1710 "failed to write whole buffer",
1711 ));
1712 }
1713 Ok(n) => buf = &buf[n..],
1714 Err(ref e) if e.is_interrupted() => {}
1715 Err(e) => return Err(e),
1716 }
1717 }
1718 Ok(())
1719 }
1720
1721 /// Attempts to write multiple buffers into this writer.
1722 ///
1723 /// This method will continuously call [`write_vectored`] until there is no
1724 /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1725 /// kind is returned. This method will not return until all buffers have
1726 /// been successfully written or such an error occurs. The first error that
1727 /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1728 /// will be returned.
1729 ///
1730 /// If the buffer contains no data, this will never call [`write_vectored`].
1731 ///
1732 /// # Notes
1733 ///
1734 /// Unlike [`write_vectored`], this takes a *mutable* reference to
1735 /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1736 /// modify the slice to keep track of the bytes already written.
1737 ///
1738 /// Once this function returns, the contents of `bufs` are unspecified, as
1739 /// this depends on how many calls to [`write_vectored`] were necessary. It is
1740 /// best to understand this function as taking ownership of `bufs` and to
1741 /// not use `bufs` afterwards. The underlying buffers, to which the
1742 /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1743 /// can be reused.
1744 ///
1745 /// [`write_vectored`]: Write::write_vectored
1746 ///
1747 /// # Examples
1748 ///
1749 /// ```
1750 /// #![feature(write_all_vectored)]
1751 /// # fn main() -> std::io::Result<()> {
1752 ///
1753 /// use std::io::{Write, IoSlice};
1754 ///
1755 /// let mut writer = Vec::new();
1756 /// let bufs = &mut [
1757 /// IoSlice::new(&[1]),
1758 /// IoSlice::new(&[2, 3]),
1759 /// IoSlice::new(&[4, 5, 6]),
1760 /// ];
1761 ///
1762 /// writer.write_all_vectored(bufs)?;
1763 /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1764 ///
1765 /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1766 /// # Ok(()) }
1767 /// ```
1768 #[unstable(feature = "write_all_vectored", issue = "70436")]
1769 fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1770 // Guarantee that bufs is empty if it contains no data,
1771 // to avoid calling write_vectored if there is no data to be written.
1772 IoSlice::advance_slices(&mut bufs, 0);
1773 while !bufs.is_empty() {
1774 match self.write_vectored(bufs) {
1775 Ok(0) => {
1776 return Err(error::const_io_error!(
1777 ErrorKind::WriteZero,
1778 "failed to write whole buffer",
1779 ));
1780 }
1781 Ok(n) => IoSlice::advance_slices(&mut bufs, n),
1782 Err(ref e) if e.is_interrupted() => {}
1783 Err(e) => return Err(e),
1784 }
1785 }
1786 Ok(())
1787 }
1788
1789 /// Writes a formatted string into this writer, returning any error
1790 /// encountered.
1791 ///
1792 /// This method is primarily used to interface with the
1793 /// [`format_args!()`] macro, and it is rare that this should
1794 /// explicitly be called. The [`write!()`] macro should be favored to
1795 /// invoke this method instead.
1796 ///
1797 /// This function internally uses the [`write_all`] method on
1798 /// this trait and hence will continuously write data so long as no errors
1799 /// are received. This also means that partial writes are not indicated in
1800 /// this signature.
1801 ///
1802 /// [`write_all`]: Write::write_all
1803 ///
1804 /// # Errors
1805 ///
1806 /// This function will return any I/O error reported while formatting.
1807 ///
1808 /// # Examples
1809 ///
1810 /// ```no_run
1811 /// use std::io::prelude::*;
1812 /// use std::fs::File;
1813 ///
1814 /// fn main() -> std::io::Result<()> {
1815 /// let mut buffer = File::create("foo.txt")?;
1816 ///
1817 /// // this call
1818 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1819 /// // turns into this:
1820 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1821 /// Ok(())
1822 /// }
1823 /// ```
1824 #[stable(feature = "rust1", since = "1.0.0")]
1825 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1826 // Create a shim which translates a Write to a fmt::Write and saves
1827 // off I/O errors. instead of discarding them
1828 struct Adapter<'a, T: ?Sized + 'a> {
1829 inner: &'a mut T,
1830 error: Result<()>,
1831 }
1832
1833 impl<T: Write + ?Sized> fmt::Write for Adapter<'_, T> {
1834 fn write_str(&mut self, s: &str) -> fmt::Result {
1835 match self.inner.write_all(s.as_bytes()) {
1836 Ok(()) => Ok(()),
1837 Err(e) => {
1838 self.error = Err(e);
1839 Err(fmt::Error)
1840 }
1841 }
1842 }
1843 }
1844
1845 let mut output = Adapter { inner: self, error: Ok(()) };
1846 match fmt::write(&mut output, fmt) {
1847 Ok(()) => Ok(()),
1848 Err(..) => {
1849 // check if the error came from the underlying `Write` or not
1850 if output.error.is_err() {
1851 output.error
1852 } else {
1853 Err(error::const_io_error!(ErrorKind::Uncategorized, "formatter error"))
1854 }
1855 }
1856 }
1857 }
1858
1859 /// Creates a "by reference" adapter for this instance of `Write`.
1860 ///
1861 /// The returned adapter also implements `Write` and will simply borrow this
1862 /// current writer.
1863 ///
1864 /// # Examples
1865 ///
1866 /// ```no_run
1867 /// use std::io::Write;
1868 /// use std::fs::File;
1869 ///
1870 /// fn main() -> std::io::Result<()> {
1871 /// let mut buffer = File::create("foo.txt")?;
1872 ///
1873 /// let reference = buffer.by_ref();
1874 ///
1875 /// // we can use reference just like our original buffer
1876 /// reference.write_all(b"some bytes")?;
1877 /// Ok(())
1878 /// }
1879 /// ```
1880 #[stable(feature = "rust1", since = "1.0.0")]
1881 fn by_ref(&mut self) -> &mut Self
1882 where
1883 Self: Sized,
1884 {
1885 self
1886 }
1887}
1888
1889/// The `Seek` trait provides a cursor which can be moved within a stream of
1890/// bytes.
1891///
1892/// The stream typically has a fixed size, allowing seeking relative to either
1893/// end or the current offset.
1894///
1895/// # Examples
1896///
1897/// [`File`]s implement `Seek`:
1898///
1899/// [`File`]: crate::fs::File
1900///
1901/// ```no_run
1902/// use std::io;
1903/// use std::io::prelude::*;
1904/// use std::fs::File;
1905/// use std::io::SeekFrom;
1906///
1907/// fn main() -> io::Result<()> {
1908/// let mut f = File::open("foo.txt")?;
1909///
1910/// // move the cursor 42 bytes from the start of the file
1911/// f.seek(SeekFrom::Start(42))?;
1912/// Ok(())
1913/// }
1914/// ```
1915#[stable(feature = "rust1", since = "1.0.0")]
1916#[cfg_attr(not(test), rustc_diagnostic_item = "IoSeek")]
1917pub trait Seek {
1918 /// Seek to an offset, in bytes, in a stream.
1919 ///
1920 /// A seek beyond the end of a stream is allowed, but behavior is defined
1921 /// by the implementation.
1922 ///
1923 /// If the seek operation completed successfully,
1924 /// this method returns the new position from the start of the stream.
1925 /// That position can be used later with [`SeekFrom::Start`].
1926 ///
1927 /// # Errors
1928 ///
1929 /// Seeking can fail, for example because it might involve flushing a buffer.
1930 ///
1931 /// Seeking to a negative offset is considered an error.
1932 #[stable(feature = "rust1", since = "1.0.0")]
1933 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1934
1935 /// Rewind to the beginning of a stream.
1936 ///
1937 /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1938 ///
1939 /// # Errors
1940 ///
1941 /// Rewinding can fail, for example because it might involve flushing a buffer.
1942 ///
1943 /// # Example
1944 ///
1945 /// ```no_run
1946 /// use std::io::{Read, Seek, Write};
1947 /// use std::fs::OpenOptions;
1948 ///
1949 /// let mut f = OpenOptions::new()
1950 /// .write(true)
1951 /// .read(true)
1952 /// .create(true)
1953 /// .open("foo.txt").unwrap();
1954 ///
1955 /// let hello = "Hello!\n";
1956 /// write!(f, "{hello}").unwrap();
1957 /// f.rewind().unwrap();
1958 ///
1959 /// let mut buf = String::new();
1960 /// f.read_to_string(&mut buf).unwrap();
1961 /// assert_eq!(&buf, hello);
1962 /// ```
1963 #[stable(feature = "seek_rewind", since = "1.55.0")]
1964 fn rewind(&mut self) -> Result<()> {
1965 self.seek(SeekFrom::Start(0))?;
1966 Ok(())
1967 }
1968
1969 /// Returns the length of this stream (in bytes).
1970 ///
1971 /// This method is implemented using up to three seek operations. If this
1972 /// method returns successfully, the seek position is unchanged (i.e. the
1973 /// position before calling this method is the same as afterwards).
1974 /// However, if this method returns an error, the seek position is
1975 /// unspecified.
1976 ///
1977 /// If you need to obtain the length of *many* streams and you don't care
1978 /// about the seek position afterwards, you can reduce the number of seek
1979 /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1980 /// return value (it is also the stream length).
1981 ///
1982 /// Note that length of a stream can change over time (for example, when
1983 /// data is appended to a file). So calling this method multiple times does
1984 /// not necessarily return the same length each time.
1985 ///
1986 /// # Example
1987 ///
1988 /// ```no_run
1989 /// #![feature(seek_stream_len)]
1990 /// use std::{
1991 /// io::{self, Seek},
1992 /// fs::File,
1993 /// };
1994 ///
1995 /// fn main() -> io::Result<()> {
1996 /// let mut f = File::open("foo.txt")?;
1997 ///
1998 /// let len = f.stream_len()?;
1999 /// println!("The file is currently {len} bytes long");
2000 /// Ok(())
2001 /// }
2002 /// ```
2003 #[unstable(feature = "seek_stream_len", issue = "59359")]
2004 fn stream_len(&mut self) -> Result<u64> {
2005 let old_pos = self.stream_position()?;
2006 let len = self.seek(SeekFrom::End(0))?;
2007
2008 // Avoid seeking a third time when we were already at the end of the
2009 // stream. The branch is usually way cheaper than a seek operation.
2010 if old_pos != len {
2011 self.seek(SeekFrom::Start(old_pos))?;
2012 }
2013
2014 Ok(len)
2015 }
2016
2017 /// Returns the current seek position from the start of the stream.
2018 ///
2019 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
2020 ///
2021 /// # Example
2022 ///
2023 /// ```no_run
2024 /// use std::{
2025 /// io::{self, BufRead, BufReader, Seek},
2026 /// fs::File,
2027 /// };
2028 ///
2029 /// fn main() -> io::Result<()> {
2030 /// let mut f = BufReader::new(File::open("foo.txt")?);
2031 ///
2032 /// let before = f.stream_position()?;
2033 /// f.read_line(&mut String::new())?;
2034 /// let after = f.stream_position()?;
2035 ///
2036 /// println!("The first line was {} bytes long", after - before);
2037 /// Ok(())
2038 /// }
2039 /// ```
2040 #[stable(feature = "seek_convenience", since = "1.51.0")]
2041 fn stream_position(&mut self) -> Result<u64> {
2042 self.seek(SeekFrom::Current(0))
2043 }
2044
2045 /// Seeks relative to the current position.
2046 ///
2047 /// This is equivalent to `self.seek(SeekFrom::Current(offset))` but
2048 /// doesn't return the new position which can allow some implementations
2049 /// such as [`BufReader`] to perform more efficient seeks.
2050 ///
2051 /// # Example
2052 ///
2053 /// ```no_run
2054 /// #![feature(seek_seek_relative)]
2055 /// use std::{
2056 /// io::{self, Seek},
2057 /// fs::File,
2058 /// };
2059 ///
2060 /// fn main() -> io::Result<()> {
2061 /// let mut f = File::open("foo.txt")?;
2062 /// f.seek_relative(10)?;
2063 /// assert_eq!(f.stream_position()?, 10);
2064 /// Ok(())
2065 /// }
2066 /// ```
2067 ///
2068 /// [`BufReader`]: crate::io::BufReader
2069 #[unstable(feature = "seek_seek_relative", issue = "117374")]
2070 fn seek_relative(&mut self, offset: i64) -> Result<()> {
2071 self.seek(SeekFrom::Current(offset))?;
2072 Ok(())
2073 }
2074}
2075
2076/// Enumeration of possible methods to seek within an I/O object.
2077///
2078/// It is used by the [`Seek`] trait.
2079#[derive(Copy, PartialEq, Eq, Clone, Debug)]
2080#[stable(feature = "rust1", since = "1.0.0")]
2081pub enum SeekFrom {
2082 /// Sets the offset to the provided number of bytes.
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
2085
2086 /// Sets the offset to the size of this object plus the specified number of
2087 /// bytes.
2088 ///
2089 /// It is possible to seek beyond the end of an object, but it's an error to
2090 /// seek before byte 0.
2091 #[stable(feature = "rust1", since = "1.0.0")]
2092 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
2093
2094 /// Sets the offset to the current position plus the specified number of
2095 /// bytes.
2096 ///
2097 /// It is possible to seek beyond the end of an object, but it's an error to
2098 /// seek before byte 0.
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
2101}
2102
2103fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
2104 let mut read = 0;
2105 loop {
2106 let (done, used) = {
2107 let available = match r.fill_buf() {
2108 Ok(n) => n,
2109 Err(ref e) if e.is_interrupted() => continue,
2110 Err(e) => return Err(e),
2111 };
2112 match memchr::memchr(delim, available) {
2113 Some(i) => {
2114 buf.extend_from_slice(&available[..=i]);
2115 (true, i + 1)
2116 }
2117 None => {
2118 buf.extend_from_slice(available);
2119 (false, available.len())
2120 }
2121 }
2122 };
2123 r.consume(used);
2124 read += used;
2125 if done || used == 0 {
2126 return Ok(read);
2127 }
2128 }
2129}
2130
2131fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize> {
2132 let mut read: usize = 0;
2133 loop {
2134 let (done: bool, used: usize) = {
2135 let available: &[u8] = match r.fill_buf() {
2136 Ok(n: &[u8]) => n,
2137 Err(ref e: &Error) if e.kind() == ErrorKind::Interrupted => continue,
2138 Err(e: Error) => return Err(e),
2139 };
2140 match memchr::memchr(needle:delim, haystack:available) {
2141 Some(i: usize) => (true, i + 1),
2142 None => (false, available.len()),
2143 }
2144 };
2145 r.consume(amt:used);
2146 read += used;
2147 if done || used == 0 {
2148 return Ok(read);
2149 }
2150 }
2151}
2152
2153/// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
2154/// to perform extra ways of reading.
2155///
2156/// For example, reading line-by-line is inefficient without using a buffer, so
2157/// if you want to read by line, you'll need `BufRead`, which includes a
2158/// [`read_line`] method as well as a [`lines`] iterator.
2159///
2160/// # Examples
2161///
2162/// A locked standard input implements `BufRead`:
2163///
2164/// ```no_run
2165/// use std::io;
2166/// use std::io::prelude::*;
2167///
2168/// let stdin = io::stdin();
2169/// for line in stdin.lock().lines() {
2170/// println!("{}", line.unwrap());
2171/// }
2172/// ```
2173///
2174/// If you have something that implements [`Read`], you can use the [`BufReader`
2175/// type][`BufReader`] to turn it into a `BufRead`.
2176///
2177/// For example, [`File`] implements [`Read`], but not `BufRead`.
2178/// [`BufReader`] to the rescue!
2179///
2180/// [`File`]: crate::fs::File
2181/// [`read_line`]: BufRead::read_line
2182/// [`lines`]: BufRead::lines
2183///
2184/// ```no_run
2185/// use std::io::{self, BufReader};
2186/// use std::io::prelude::*;
2187/// use std::fs::File;
2188///
2189/// fn main() -> io::Result<()> {
2190/// let f = File::open("foo.txt")?;
2191/// let f = BufReader::new(f);
2192///
2193/// for line in f.lines() {
2194/// println!("{}", line.unwrap());
2195/// }
2196///
2197/// Ok(())
2198/// }
2199/// ```
2200#[stable(feature = "rust1", since = "1.0.0")]
2201pub trait BufRead: Read {
2202 /// Returns the contents of the internal buffer, filling it with more data
2203 /// from the inner reader if it is empty.
2204 ///
2205 /// This function is a lower-level call. It needs to be paired with the
2206 /// [`consume`] method to function properly. When calling this
2207 /// method, none of the contents will be "read" in the sense that later
2208 /// calling `read` may return the same contents. As such, [`consume`] must
2209 /// be called with the number of bytes that are consumed from this buffer to
2210 /// ensure that the bytes are never returned twice.
2211 ///
2212 /// [`consume`]: BufRead::consume
2213 ///
2214 /// An empty buffer returned indicates that the stream has reached EOF.
2215 ///
2216 /// # Errors
2217 ///
2218 /// This function will return an I/O error if the underlying reader was
2219 /// read, but returned an error.
2220 ///
2221 /// # Examples
2222 ///
2223 /// A locked standard input implements `BufRead`:
2224 ///
2225 /// ```no_run
2226 /// use std::io;
2227 /// use std::io::prelude::*;
2228 ///
2229 /// let stdin = io::stdin();
2230 /// let mut stdin = stdin.lock();
2231 ///
2232 /// let buffer = stdin.fill_buf().unwrap();
2233 ///
2234 /// // work with buffer
2235 /// println!("{buffer:?}");
2236 ///
2237 /// // ensure the bytes we worked with aren't returned again later
2238 /// let length = buffer.len();
2239 /// stdin.consume(length);
2240 /// ```
2241 #[stable(feature = "rust1", since = "1.0.0")]
2242 fn fill_buf(&mut self) -> Result<&[u8]>;
2243
2244 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
2245 /// so they should no longer be returned in calls to `read`.
2246 ///
2247 /// This function is a lower-level call. It needs to be paired with the
2248 /// [`fill_buf`] method to function properly. This function does
2249 /// not perform any I/O, it simply informs this object that some amount of
2250 /// its buffer, returned from [`fill_buf`], has been consumed and should
2251 /// no longer be returned. As such, this function may do odd things if
2252 /// [`fill_buf`] isn't called before calling it.
2253 ///
2254 /// The `amt` must be `<=` the number of bytes in the buffer returned by
2255 /// [`fill_buf`].
2256 ///
2257 /// # Examples
2258 ///
2259 /// Since `consume()` is meant to be used with [`fill_buf`],
2260 /// that method's example includes an example of `consume()`.
2261 ///
2262 /// [`fill_buf`]: BufRead::fill_buf
2263 #[stable(feature = "rust1", since = "1.0.0")]
2264 fn consume(&mut self, amt: usize);
2265
2266 /// Check if the underlying `Read` has any data left to be read.
2267 ///
2268 /// This function may fill the buffer to check for data,
2269 /// so this functions returns `Result<bool>`, not `bool`.
2270 ///
2271 /// Default implementation calls `fill_buf` and checks that
2272 /// returned slice is empty (which means that there is no data left,
2273 /// since EOF is reached).
2274 ///
2275 /// Examples
2276 ///
2277 /// ```
2278 /// #![feature(buf_read_has_data_left)]
2279 /// use std::io;
2280 /// use std::io::prelude::*;
2281 ///
2282 /// let stdin = io::stdin();
2283 /// let mut stdin = stdin.lock();
2284 ///
2285 /// while stdin.has_data_left().unwrap() {
2286 /// let mut line = String::new();
2287 /// stdin.read_line(&mut line).unwrap();
2288 /// // work with line
2289 /// println!("{line:?}");
2290 /// }
2291 /// ```
2292 #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
2293 fn has_data_left(&mut self) -> Result<bool> {
2294 self.fill_buf().map(|b| !b.is_empty())
2295 }
2296
2297 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
2298 ///
2299 /// This function will read bytes from the underlying stream until the
2300 /// delimiter or EOF is found. Once found, all bytes up to, and including,
2301 /// the delimiter (if found) will be appended to `buf`.
2302 ///
2303 /// If successful, this function will return the total number of bytes read.
2304 ///
2305 /// This function is blocking and should be used carefully: it is possible for
2306 /// an attacker to continuously send bytes without ever sending the delimiter
2307 /// or EOF.
2308 ///
2309 /// # Errors
2310 ///
2311 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2312 /// will otherwise return any errors returned by [`fill_buf`].
2313 ///
2314 /// If an I/O error is encountered then all bytes read so far will be
2315 /// present in `buf` and its length will have been adjusted appropriately.
2316 ///
2317 /// [`fill_buf`]: BufRead::fill_buf
2318 ///
2319 /// # Examples
2320 ///
2321 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2322 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2323 /// in hyphen delimited segments:
2324 ///
2325 /// ```
2326 /// use std::io::{self, BufRead};
2327 ///
2328 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2329 /// let mut buf = vec![];
2330 ///
2331 /// // cursor is at 'l'
2332 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2333 /// .expect("reading from cursor won't fail");
2334 /// assert_eq!(num_bytes, 6);
2335 /// assert_eq!(buf, b"lorem-");
2336 /// buf.clear();
2337 ///
2338 /// // cursor is at 'i'
2339 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2340 /// .expect("reading from cursor won't fail");
2341 /// assert_eq!(num_bytes, 5);
2342 /// assert_eq!(buf, b"ipsum");
2343 /// buf.clear();
2344 ///
2345 /// // cursor is at EOF
2346 /// let num_bytes = cursor.read_until(b'-', &mut buf)
2347 /// .expect("reading from cursor won't fail");
2348 /// assert_eq!(num_bytes, 0);
2349 /// assert_eq!(buf, b"");
2350 /// ```
2351 #[stable(feature = "rust1", since = "1.0.0")]
2352 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2353 read_until(self, byte, buf)
2354 }
2355
2356 /// Skip all bytes until the delimiter `byte` or EOF is reached.
2357 ///
2358 /// This function will read (and discard) bytes from the underlying stream until the
2359 /// delimiter or EOF is found.
2360 ///
2361 /// If successful, this function will return the total number of bytes read,
2362 /// including the delimiter byte.
2363 ///
2364 /// This is useful for efficiently skipping data such as NUL-terminated strings
2365 /// in binary file formats without buffering.
2366 ///
2367 /// This function is blocking and should be used carefully: it is possible for
2368 /// an attacker to continuously send bytes without ever sending the delimiter
2369 /// or EOF.
2370 ///
2371 /// # Errors
2372 ///
2373 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2374 /// will otherwise return any errors returned by [`fill_buf`].
2375 ///
2376 /// If an I/O error is encountered then all bytes read so far will be
2377 /// present in `buf` and its length will have been adjusted appropriately.
2378 ///
2379 /// [`fill_buf`]: BufRead::fill_buf
2380 ///
2381 /// # Examples
2382 ///
2383 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2384 /// this example, we use [`Cursor`] to read some NUL-terminated information
2385 /// about Ferris from a binary string, skipping the fun fact:
2386 ///
2387 /// ```
2388 /// #![feature(bufread_skip_until)]
2389 ///
2390 /// use std::io::{self, BufRead};
2391 ///
2392 /// let mut cursor = io::Cursor::new(b"Ferris\0Likes long walks on the beach\0Crustacean\0");
2393 ///
2394 /// // read name
2395 /// let mut name = Vec::new();
2396 /// let num_bytes = cursor.read_until(b'\0', &mut name)
2397 /// .expect("reading from cursor won't fail");
2398 /// assert_eq!(num_bytes, 7);
2399 /// assert_eq!(name, b"Ferris\0");
2400 ///
2401 /// // skip fun fact
2402 /// let num_bytes = cursor.skip_until(b'\0')
2403 /// .expect("reading from cursor won't fail");
2404 /// assert_eq!(num_bytes, 30);
2405 ///
2406 /// // read animal type
2407 /// let mut animal = Vec::new();
2408 /// let num_bytes = cursor.read_until(b'\0', &mut animal)
2409 /// .expect("reading from cursor won't fail");
2410 /// assert_eq!(num_bytes, 11);
2411 /// assert_eq!(animal, b"Crustacean\0");
2412 /// ```
2413 #[unstable(feature = "bufread_skip_until", issue = "111735")]
2414 fn skip_until(&mut self, byte: u8) -> Result<usize> {
2415 skip_until(self, byte)
2416 }
2417
2418 /// Read all bytes until a newline (the `0xA` byte) is reached, and append
2419 /// them to the provided `String` buffer.
2420 ///
2421 /// Previous content of the buffer will be preserved. To avoid appending to
2422 /// the buffer, you need to [`clear`] it first.
2423 ///
2424 /// This function will read bytes from the underlying stream until the
2425 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2426 /// up to, and including, the delimiter (if found) will be appended to
2427 /// `buf`.
2428 ///
2429 /// If successful, this function will return the total number of bytes read.
2430 ///
2431 /// If this function returns [`Ok(0)`], the stream has reached EOF.
2432 ///
2433 /// This function is blocking and should be used carefully: it is possible for
2434 /// an attacker to continuously send bytes without ever sending a newline
2435 /// or EOF. You can use [`take`] to limit the maximum number of bytes read.
2436 ///
2437 /// [`Ok(0)`]: Ok
2438 /// [`clear`]: String::clear
2439 /// [`take`]: crate::io::Read::take
2440 ///
2441 /// # Errors
2442 ///
2443 /// This function has the same error semantics as [`read_until`] and will
2444 /// also return an error if the read bytes are not valid UTF-8. If an I/O
2445 /// error is encountered then `buf` may contain some bytes already read in
2446 /// the event that all data read so far was valid UTF-8.
2447 ///
2448 /// [`read_until`]: BufRead::read_until
2449 ///
2450 /// # Examples
2451 ///
2452 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2453 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2454 ///
2455 /// ```
2456 /// use std::io::{self, BufRead};
2457 ///
2458 /// let mut cursor = io::Cursor::new(b"foo\nbar");
2459 /// let mut buf = String::new();
2460 ///
2461 /// // cursor is at 'f'
2462 /// let num_bytes = cursor.read_line(&mut buf)
2463 /// .expect("reading from cursor won't fail");
2464 /// assert_eq!(num_bytes, 4);
2465 /// assert_eq!(buf, "foo\n");
2466 /// buf.clear();
2467 ///
2468 /// // cursor is at 'b'
2469 /// let num_bytes = cursor.read_line(&mut buf)
2470 /// .expect("reading from cursor won't fail");
2471 /// assert_eq!(num_bytes, 3);
2472 /// assert_eq!(buf, "bar");
2473 /// buf.clear();
2474 ///
2475 /// // cursor is at EOF
2476 /// let num_bytes = cursor.read_line(&mut buf)
2477 /// .expect("reading from cursor won't fail");
2478 /// assert_eq!(num_bytes, 0);
2479 /// assert_eq!(buf, "");
2480 /// ```
2481 #[stable(feature = "rust1", since = "1.0.0")]
2482 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2483 // Note that we are not calling the `.read_until` method here, but
2484 // rather our hardcoded implementation. For more details as to why, see
2485 // the comments in `read_to_end`.
2486 unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
2487 }
2488
2489 /// Returns an iterator over the contents of this reader split on the byte
2490 /// `byte`.
2491 ///
2492 /// The iterator returned from this function will return instances of
2493 /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
2494 /// the delimiter byte at the end.
2495 ///
2496 /// This function will yield errors whenever [`read_until`] would have
2497 /// also yielded an error.
2498 ///
2499 /// [io::Result]: self::Result "io::Result"
2500 /// [`read_until`]: BufRead::read_until
2501 ///
2502 /// # Examples
2503 ///
2504 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2505 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2506 /// segments in a byte slice
2507 ///
2508 /// ```
2509 /// use std::io::{self, BufRead};
2510 ///
2511 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2512 ///
2513 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2514 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2515 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2516 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2517 /// assert_eq!(split_iter.next(), None);
2518 /// ```
2519 #[stable(feature = "rust1", since = "1.0.0")]
2520 fn split(self, byte: u8) -> Split<Self>
2521 where
2522 Self: Sized,
2523 {
2524 Split { buf: self, delim: byte }
2525 }
2526
2527 /// Returns an iterator over the lines of this reader.
2528 ///
2529 /// The iterator returned from this function will yield instances of
2530 /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
2531 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2532 ///
2533 /// [io::Result]: self::Result "io::Result"
2534 ///
2535 /// # Examples
2536 ///
2537 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2538 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2539 /// slice.
2540 ///
2541 /// ```
2542 /// use std::io::{self, BufRead};
2543 ///
2544 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2545 ///
2546 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2547 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2548 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2549 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2550 /// assert_eq!(lines_iter.next(), None);
2551 /// ```
2552 ///
2553 /// # Errors
2554 ///
2555 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2556 #[stable(feature = "rust1", since = "1.0.0")]
2557 fn lines(self) -> Lines<Self>
2558 where
2559 Self: Sized,
2560 {
2561 Lines { buf: self }
2562 }
2563}
2564
2565/// Adapter to chain together two readers.
2566///
2567/// This struct is generally created by calling [`chain`] on a reader.
2568/// Please see the documentation of [`chain`] for more details.
2569///
2570/// [`chain`]: Read::chain
2571#[stable(feature = "rust1", since = "1.0.0")]
2572#[derive(Debug)]
2573pub struct Chain<T, U> {
2574 first: T,
2575 second: U,
2576 done_first: bool,
2577}
2578
2579impl<T, U> Chain<T, U> {
2580 /// Consumes the `Chain`, returning the wrapped readers.
2581 ///
2582 /// # Examples
2583 ///
2584 /// ```no_run
2585 /// use std::io;
2586 /// use std::io::prelude::*;
2587 /// use std::fs::File;
2588 ///
2589 /// fn main() -> io::Result<()> {
2590 /// let mut foo_file = File::open("foo.txt")?;
2591 /// let mut bar_file = File::open("bar.txt")?;
2592 ///
2593 /// let chain = foo_file.chain(bar_file);
2594 /// let (foo_file, bar_file) = chain.into_inner();
2595 /// Ok(())
2596 /// }
2597 /// ```
2598 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2599 pub fn into_inner(self) -> (T, U) {
2600 (self.first, self.second)
2601 }
2602
2603 /// Gets references to the underlying readers in this `Chain`.
2604 ///
2605 /// # Examples
2606 ///
2607 /// ```no_run
2608 /// use std::io;
2609 /// use std::io::prelude::*;
2610 /// use std::fs::File;
2611 ///
2612 /// fn main() -> io::Result<()> {
2613 /// let mut foo_file = File::open("foo.txt")?;
2614 /// let mut bar_file = File::open("bar.txt")?;
2615 ///
2616 /// let chain = foo_file.chain(bar_file);
2617 /// let (foo_file, bar_file) = chain.get_ref();
2618 /// Ok(())
2619 /// }
2620 /// ```
2621 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2622 pub fn get_ref(&self) -> (&T, &U) {
2623 (&self.first, &self.second)
2624 }
2625
2626 /// Gets mutable references to the underlying readers in this `Chain`.
2627 ///
2628 /// Care should be taken to avoid modifying the internal I/O state of the
2629 /// underlying readers as doing so may corrupt the internal state of this
2630 /// `Chain`.
2631 ///
2632 /// # Examples
2633 ///
2634 /// ```no_run
2635 /// use std::io;
2636 /// use std::io::prelude::*;
2637 /// use std::fs::File;
2638 ///
2639 /// fn main() -> io::Result<()> {
2640 /// let mut foo_file = File::open("foo.txt")?;
2641 /// let mut bar_file = File::open("bar.txt")?;
2642 ///
2643 /// let mut chain = foo_file.chain(bar_file);
2644 /// let (foo_file, bar_file) = chain.get_mut();
2645 /// Ok(())
2646 /// }
2647 /// ```
2648 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2649 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2650 (&mut self.first, &mut self.second)
2651 }
2652}
2653
2654#[stable(feature = "rust1", since = "1.0.0")]
2655impl<T: Read, U: Read> Read for Chain<T, U> {
2656 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2657 if !self.done_first {
2658 match self.first.read(buf)? {
2659 0 if !buf.is_empty() => self.done_first = true,
2660 n: usize => return Ok(n),
2661 }
2662 }
2663 self.second.read(buf)
2664 }
2665
2666 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2667 if !self.done_first {
2668 match self.first.read_vectored(bufs)? {
2669 0 if bufs.iter().any(|b: &IoSliceMut<'_>| !b.is_empty()) => self.done_first = true,
2670 n: usize => return Ok(n),
2671 }
2672 }
2673 self.second.read_vectored(bufs)
2674 }
2675}
2676
2677#[stable(feature = "chain_bufread", since = "1.9.0")]
2678impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2679 fn fill_buf(&mut self) -> Result<&[u8]> {
2680 if !self.done_first {
2681 match self.first.fill_buf()? {
2682 buf: &[u8] if buf.is_empty() => {
2683 self.done_first = true;
2684 }
2685 buf: &[u8] => return Ok(buf),
2686 }
2687 }
2688 self.second.fill_buf()
2689 }
2690
2691 fn consume(&mut self, amt: usize) {
2692 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2693 }
2694}
2695
2696impl<T, U> SizeHint for Chain<T, U> {
2697 #[inline]
2698 fn lower_bound(&self) -> usize {
2699 SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
2700 }
2701
2702 #[inline]
2703 fn upper_bound(&self) -> Option<usize> {
2704 match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
2705 (Some(first: usize), Some(second: usize)) => first.checked_add(second),
2706 _ => None,
2707 }
2708 }
2709}
2710
2711/// Reader adapter which limits the bytes read from an underlying reader.
2712///
2713/// This struct is generally created by calling [`take`] on a reader.
2714/// Please see the documentation of [`take`] for more details.
2715///
2716/// [`take`]: Read::take
2717#[stable(feature = "rust1", since = "1.0.0")]
2718#[derive(Debug)]
2719pub struct Take<T> {
2720 inner: T,
2721 limit: u64,
2722}
2723
2724impl<T> Take<T> {
2725 /// Returns the number of bytes that can be read before this instance will
2726 /// return EOF.
2727 ///
2728 /// # Note
2729 ///
2730 /// This instance may reach `EOF` after reading fewer bytes than indicated by
2731 /// this method if the underlying [`Read`] instance reaches EOF.
2732 ///
2733 /// # Examples
2734 ///
2735 /// ```no_run
2736 /// use std::io;
2737 /// use std::io::prelude::*;
2738 /// use std::fs::File;
2739 ///
2740 /// fn main() -> io::Result<()> {
2741 /// let f = File::open("foo.txt")?;
2742 ///
2743 /// // read at most five bytes
2744 /// let handle = f.take(5);
2745 ///
2746 /// println!("limit: {}", handle.limit());
2747 /// Ok(())
2748 /// }
2749 /// ```
2750 #[stable(feature = "rust1", since = "1.0.0")]
2751 pub fn limit(&self) -> u64 {
2752 self.limit
2753 }
2754
2755 /// Sets the number of bytes that can be read before this instance will
2756 /// return EOF. This is the same as constructing a new `Take` instance, so
2757 /// the amount of bytes read and the previous limit value don't matter when
2758 /// calling this method.
2759 ///
2760 /// # Examples
2761 ///
2762 /// ```no_run
2763 /// use std::io;
2764 /// use std::io::prelude::*;
2765 /// use std::fs::File;
2766 ///
2767 /// fn main() -> io::Result<()> {
2768 /// let f = File::open("foo.txt")?;
2769 ///
2770 /// // read at most five bytes
2771 /// let mut handle = f.take(5);
2772 /// handle.set_limit(10);
2773 ///
2774 /// assert_eq!(handle.limit(), 10);
2775 /// Ok(())
2776 /// }
2777 /// ```
2778 #[stable(feature = "take_set_limit", since = "1.27.0")]
2779 pub fn set_limit(&mut self, limit: u64) {
2780 self.limit = limit;
2781 }
2782
2783 /// Consumes the `Take`, returning the wrapped reader.
2784 ///
2785 /// # Examples
2786 ///
2787 /// ```no_run
2788 /// use std::io;
2789 /// use std::io::prelude::*;
2790 /// use std::fs::File;
2791 ///
2792 /// fn main() -> io::Result<()> {
2793 /// let mut file = File::open("foo.txt")?;
2794 ///
2795 /// let mut buffer = [0; 5];
2796 /// let mut handle = file.take(5);
2797 /// handle.read(&mut buffer)?;
2798 ///
2799 /// let file = handle.into_inner();
2800 /// Ok(())
2801 /// }
2802 /// ```
2803 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2804 pub fn into_inner(self) -> T {
2805 self.inner
2806 }
2807
2808 /// Gets a reference to the underlying reader.
2809 ///
2810 /// # Examples
2811 ///
2812 /// ```no_run
2813 /// use std::io;
2814 /// use std::io::prelude::*;
2815 /// use std::fs::File;
2816 ///
2817 /// fn main() -> io::Result<()> {
2818 /// let mut file = File::open("foo.txt")?;
2819 ///
2820 /// let mut buffer = [0; 5];
2821 /// let mut handle = file.take(5);
2822 /// handle.read(&mut buffer)?;
2823 ///
2824 /// let file = handle.get_ref();
2825 /// Ok(())
2826 /// }
2827 /// ```
2828 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2829 pub fn get_ref(&self) -> &T {
2830 &self.inner
2831 }
2832
2833 /// Gets a mutable reference to the underlying reader.
2834 ///
2835 /// Care should be taken to avoid modifying the internal I/O state of the
2836 /// underlying reader as doing so may corrupt the internal limit of this
2837 /// `Take`.
2838 ///
2839 /// # Examples
2840 ///
2841 /// ```no_run
2842 /// use std::io;
2843 /// use std::io::prelude::*;
2844 /// use std::fs::File;
2845 ///
2846 /// fn main() -> io::Result<()> {
2847 /// let mut file = File::open("foo.txt")?;
2848 ///
2849 /// let mut buffer = [0; 5];
2850 /// let mut handle = file.take(5);
2851 /// handle.read(&mut buffer)?;
2852 ///
2853 /// let file = handle.get_mut();
2854 /// Ok(())
2855 /// }
2856 /// ```
2857 #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2858 pub fn get_mut(&mut self) -> &mut T {
2859 &mut self.inner
2860 }
2861}
2862
2863#[stable(feature = "rust1", since = "1.0.0")]
2864impl<T: Read> Read for Take<T> {
2865 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2866 // Don't call into inner reader at all at EOF because it may still block
2867 if self.limit == 0 {
2868 return Ok(0);
2869 }
2870
2871 let max = cmp::min(buf.len() as u64, self.limit) as usize;
2872 let n = self.inner.read(&mut buf[..max])?;
2873 assert!(n as u64 <= self.limit, "number of read bytes exceeds limit");
2874 self.limit -= n as u64;
2875 Ok(n)
2876 }
2877
2878 fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> Result<()> {
2879 // Don't call into inner reader at all at EOF because it may still block
2880 if self.limit == 0 {
2881 return Ok(());
2882 }
2883
2884 if self.limit <= buf.capacity() as u64 {
2885 // if we just use an as cast to convert, limit may wrap around on a 32 bit target
2886 let limit = cmp::min(self.limit, usize::MAX as u64) as usize;
2887
2888 let extra_init = cmp::min(limit as usize, buf.init_ref().len());
2889
2890 // SAFETY: no uninit data is written to ibuf
2891 let ibuf = unsafe { &mut buf.as_mut()[..limit] };
2892
2893 let mut sliced_buf: BorrowedBuf<'_> = ibuf.into();
2894
2895 // SAFETY: extra_init bytes of ibuf are known to be initialized
2896 unsafe {
2897 sliced_buf.set_init(extra_init);
2898 }
2899
2900 let mut cursor = sliced_buf.unfilled();
2901 self.inner.read_buf(cursor.reborrow())?;
2902
2903 let new_init = cursor.init_ref().len();
2904 let filled = sliced_buf.len();
2905
2906 // cursor / sliced_buf / ibuf must drop here
2907
2908 unsafe {
2909 // SAFETY: filled bytes have been filled and therefore initialized
2910 buf.advance(filled);
2911 // SAFETY: new_init bytes of buf's unfilled buffer have been initialized
2912 buf.set_init(new_init);
2913 }
2914
2915 self.limit -= filled as u64;
2916 } else {
2917 let written = buf.written();
2918 self.inner.read_buf(buf.reborrow())?;
2919 self.limit -= (buf.written() - written) as u64;
2920 }
2921
2922 Ok(())
2923 }
2924}
2925
2926#[stable(feature = "rust1", since = "1.0.0")]
2927impl<T: BufRead> BufRead for Take<T> {
2928 fn fill_buf(&mut self) -> Result<&[u8]> {
2929 // Don't call into inner reader at all at EOF because it may still block
2930 if self.limit == 0 {
2931 return Ok(&[]);
2932 }
2933
2934 let buf: &[u8] = self.inner.fill_buf()?;
2935 let cap: usize = cmp::min(v1:buf.len() as u64, self.limit) as usize;
2936 Ok(&buf[..cap])
2937 }
2938
2939 fn consume(&mut self, amt: usize) {
2940 // Don't let callers reset the limit by passing an overlarge value
2941 let amt: usize = cmp::min(v1:amt as u64, self.limit) as usize;
2942 self.limit -= amt as u64;
2943 self.inner.consume(amt);
2944 }
2945}
2946
2947impl<T> SizeHint for Take<T> {
2948 #[inline]
2949 fn lower_bound(&self) -> usize {
2950 cmp::min(v1:SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize
2951 }
2952
2953 #[inline]
2954 fn upper_bound(&self) -> Option<usize> {
2955 match SizeHint::upper_bound(&self.inner) {
2956 Some(upper_bound: usize) => Some(cmp::min(v1:upper_bound as u64, self.limit) as usize),
2957 None => self.limit.try_into().ok(),
2958 }
2959 }
2960}
2961
2962/// An iterator over `u8` values of a reader.
2963///
2964/// This struct is generally created by calling [`bytes`] on a reader.
2965/// Please see the documentation of [`bytes`] for more details.
2966///
2967/// [`bytes`]: Read::bytes
2968#[stable(feature = "rust1", since = "1.0.0")]
2969#[derive(Debug)]
2970pub struct Bytes<R> {
2971 inner: R,
2972}
2973
2974#[stable(feature = "rust1", since = "1.0.0")]
2975impl<R: Read> Iterator for Bytes<R> {
2976 type Item = Result<u8>;
2977
2978 // Not `#[inline]`. This function gets inlined even without it, but having
2979 // the inline annotation can result in worse code generation. See #116785.
2980 fn next(&mut self) -> Option<Result<u8>> {
2981 SpecReadByte::spec_read_byte(&mut self.inner)
2982 }
2983
2984 #[inline]
2985 fn size_hint(&self) -> (usize, Option<usize>) {
2986 SizeHint::size_hint(&self.inner)
2987 }
2988}
2989
2990/// For the specialization of `Bytes::next`.
2991trait SpecReadByte {
2992 fn spec_read_byte(&mut self) -> Option<Result<u8>>;
2993}
2994
2995impl<R> SpecReadByte for R
2996where
2997 Self: Read,
2998{
2999 #[inline]
3000 default fn spec_read_byte(&mut self) -> Option<Result<u8>> {
3001 inlined_slow_read_byte(self)
3002 }
3003}
3004
3005/// Read a single byte in a slow, generic way. This is used by the default
3006/// `spec_read_byte`.
3007#[inline]
3008fn inlined_slow_read_byte<R: Read>(reader: &mut R) -> Option<Result<u8>> {
3009 let mut byte: u8 = 0;
3010 loop {
3011 return match reader.read(buf:slice::from_mut(&mut byte)) {
3012 Ok(0) => None,
3013 Ok(..) => Some(Ok(byte)),
3014 Err(ref e: &Error) if e.is_interrupted() => continue,
3015 Err(e: Error) => Some(Err(e)),
3016 };
3017 }
3018}
3019
3020// Used by `BufReader::spec_read_byte`, for which the `inline(ever)` is
3021// important.
3022#[inline(never)]
3023fn uninlined_slow_read_byte<R: Read>(reader: &mut R) -> Option<Result<u8>> {
3024 inlined_slow_read_byte(reader)
3025}
3026
3027trait SizeHint {
3028 fn lower_bound(&self) -> usize;
3029
3030 fn upper_bound(&self) -> Option<usize>;
3031
3032 fn size_hint(&self) -> (usize, Option<usize>) {
3033 (self.lower_bound(), self.upper_bound())
3034 }
3035}
3036
3037impl<T: ?Sized> SizeHint for T {
3038 #[inline]
3039 default fn lower_bound(&self) -> usize {
3040 0
3041 }
3042
3043 #[inline]
3044 default fn upper_bound(&self) -> Option<usize> {
3045 None
3046 }
3047}
3048
3049impl<T> SizeHint for &mut T {
3050 #[inline]
3051 fn lower_bound(&self) -> usize {
3052 SizeHint::lower_bound(*self)
3053 }
3054
3055 #[inline]
3056 fn upper_bound(&self) -> Option<usize> {
3057 SizeHint::upper_bound(*self)
3058 }
3059}
3060
3061impl<T> SizeHint for Box<T> {
3062 #[inline]
3063 fn lower_bound(&self) -> usize {
3064 SizeHint::lower_bound(&**self)
3065 }
3066
3067 #[inline]
3068 fn upper_bound(&self) -> Option<usize> {
3069 SizeHint::upper_bound(&**self)
3070 }
3071}
3072
3073impl SizeHint for &[u8] {
3074 #[inline]
3075 fn lower_bound(&self) -> usize {
3076 self.len()
3077 }
3078
3079 #[inline]
3080 fn upper_bound(&self) -> Option<usize> {
3081 Some(self.len())
3082 }
3083}
3084
3085/// An iterator over the contents of an instance of `BufRead` split on a
3086/// particular byte.
3087///
3088/// This struct is generally created by calling [`split`] on a `BufRead`.
3089/// Please see the documentation of [`split`] for more details.
3090///
3091/// [`split`]: BufRead::split
3092#[stable(feature = "rust1", since = "1.0.0")]
3093#[derive(Debug)]
3094pub struct Split<B> {
3095 buf: B,
3096 delim: u8,
3097}
3098
3099#[stable(feature = "rust1", since = "1.0.0")]
3100impl<B: BufRead> Iterator for Split<B> {
3101 type Item = Result<Vec<u8>>;
3102
3103 fn next(&mut self) -> Option<Result<Vec<u8>>> {
3104 let mut buf: Vec = Vec::new();
3105 match self.buf.read_until(self.delim, &mut buf) {
3106 Ok(0) => None,
3107 Ok(_n: usize) => {
3108 if buf[buf.len() - 1] == self.delim {
3109 buf.pop();
3110 }
3111 Some(Ok(buf))
3112 }
3113 Err(e: Error) => Some(Err(e)),
3114 }
3115 }
3116}
3117
3118/// An iterator over the lines of an instance of `BufRead`.
3119///
3120/// This struct is generally created by calling [`lines`] on a `BufRead`.
3121/// Please see the documentation of [`lines`] for more details.
3122///
3123/// [`lines`]: BufRead::lines
3124#[stable(feature = "rust1", since = "1.0.0")]
3125#[derive(Debug)]
3126#[cfg_attr(not(test), rustc_diagnostic_item = "IoLines")]
3127pub struct Lines<B> {
3128 buf: B,
3129}
3130
3131#[stable(feature = "rust1", since = "1.0.0")]
3132impl<B: BufRead> Iterator for Lines<B> {
3133 type Item = Result<String>;
3134
3135 fn next(&mut self) -> Option<Result<String>> {
3136 let mut buf: String = String::new();
3137 match self.buf.read_line(&mut buf) {
3138 Ok(0) => None,
3139 Ok(_n: usize) => {
3140 if buf.ends_with('\n') {
3141 buf.pop();
3142 if buf.ends_with('\r') {
3143 buf.pop();
3144 }
3145 }
3146 Some(Ok(buf))
3147 }
3148 Err(e: Error) => Some(Err(e)),
3149 }
3150 }
3151}
3152