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