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
302#[unstable(feature = "raw_os_error_ty", issue = "107792")]
303pub use alloc_crate::io::RawOsError;
304#[doc(hidden)]
305#[unstable(feature = "io_const_error_internals", issue = "none")]
306pub use alloc_crate::io::SimpleMessage;
307#[unstable(feature = "io_const_error", issue = "133448")]
308pub use alloc_crate::io::const_error;
309#[allow(unused_imports, reason = "only used by certain platforms")]
310pub(crate) use alloc_crate::io::default_write_vectored;
311#[unstable(feature = "read_buf", issue = "78485")]
312pub use alloc_crate::io::{BorrowedBuf, BorrowedCursor};
313#[stable(feature = "rust1", since = "1.0.0")]
314pub use alloc_crate::io::{
315 Chain, Empty, Error, ErrorKind, Repeat, Result, Seek, SeekFrom, Sink, Take, Write, empty,
316 repeat, sink,
317};
318pub(crate) use alloc_crate::io::{IoHandle, stream_len_default};
319#[stable(feature = "iovec", since = "1.36.0")]
320pub use alloc_crate::io::{IoSlice, IoSliceMut};
321use alloc_crate::io::{OsFunctions, SizeHint};
322
323#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
324pub use self::buffered::WriterPanicked;
325#[stable(feature = "anonymous_pipe", since = "1.87.0")]
326pub use self::pipe::{PipeReader, PipeWriter, pipe};
327#[stable(feature = "is_terminal", since = "1.70.0")]
328pub use self::stdio::IsTerminal;
329pub(crate) use self::stdio::attempt_print_to_stderr;
330#[unstable(feature = "print_internals", issue = "none")]
331#[doc(hidden)]
332pub use self::stdio::{_eprint, _print};
333#[unstable(feature = "internal_output_capture", issue = "none")]
334#[doc(no_inline, hidden)]
335pub use self::stdio::{set_output_capture, try_set_output_capture};
336#[stable(feature = "rust1", since = "1.0.0")]
337pub use self::{
338 buffered::{BufReader, BufWriter, IntoInnerError, LineWriter},
339 copy::copy,
340 cursor::Cursor,
341 stdio::{Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock, stderr, stdin, stdout},
342};
343use crate::mem::MaybeUninit;
344use crate::{cmp, slice, str};
345
346mod buffered;
347pub(crate) mod copy;
348mod cursor;
349mod error;
350mod impls;
351mod pipe;
352pub mod prelude;
353mod stdio;
354mod util;
355
356const DEFAULT_BUF_SIZE: usize = crate::sys::io::DEFAULT_BUF_SIZE;
357
358pub(crate) use stdio::cleanup;
359
360struct Guard<'a> {
361 buf: &'a mut Vec<u8>,
362 len: usize,
363}
364
365impl Drop for Guard<'_> {
366 fn drop(&mut self) {
367 unsafe {
368 self.buf.set_len(self.len);
369 }
370 }
371}
372
373// Several `read_to_string` and `read_line` methods in the standard library will
374// append data into a `String` buffer, but we need to be pretty careful when
375// doing this. The implementation will just call `.as_mut_vec()` and then
376// delegate to a byte-oriented reading method, but we must ensure that when
377// returning we never leave `buf` in a state such that it contains invalid UTF-8
378// in its bounds.
379//
380// To this end, we use an RAII guard (to protect against panics) which updates
381// the length of the string when it is dropped. This guard initially truncates
382// the string to the prior length and only after we've validated that the
383// new contents are valid UTF-8 do we allow it to set a longer length.
384//
385// The unsafety in this function is twofold:
386//
387// 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
388// checks.
389// 2. We're passing a raw buffer to the function `f`, and it is expected that
390// the function only *appends* bytes to the buffer. We'll get undefined
391// behavior if existing bytes are overwritten to have non-UTF-8 data.
392pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
393where
394 F: FnOnce(&mut Vec<u8>) -> Result<usize>,
395{
396 let mut g = Guard { len: buf.len(), buf: unsafe { buf.as_mut_vec() } };
397 let ret = f(g.buf);
398
399 // SAFETY: the caller promises to only append data to `buf`
400 let appended = unsafe { g.buf.get_unchecked(g.len..) };
401 if str::from_utf8(appended).is_err() {
402 ret.and_then(|_| Err(Error::INVALID_UTF8))
403 } else {
404 g.len = g.buf.len();
405 ret
406 }
407}
408
409// Here we must serve many masters with conflicting goals:
410//
411// - avoid allocating unless necessary
412// - avoid overallocating if we know the exact size (#89165)
413// - avoid passing large buffers to readers that always initialize the free capacity if they perform short reads (#23815, #23820)
414// - pass large buffers to readers that do not initialize the spare capacity. this can amortize per-call overheads
415// - and finally pass not-too-small and not-too-large buffers to Windows read APIs because they manage to suffer from both problems
416// at the same time, i.e. small reads suffer from syscall overhead, all reads incur costs proportional to buffer size (#110650)
417//
418pub(crate) fn default_read_to_end<R: Read + ?Sized>(
419 r: &mut R,
420 buf: &mut Vec<u8>,
421 size_hint: Option<usize>,
422) -> Result<usize> {
423 let start_len = buf.len();
424 let start_cap = buf.capacity();
425 // Optionally limit the maximum bytes read on each iteration.
426 // This adds an arbitrary fiddle factor to allow for more data than we expect.
427 let mut max_read_size = size_hint
428 .and_then(|s| s.checked_add(1024)?.checked_next_multiple_of(DEFAULT_BUF_SIZE))
429 .unwrap_or(DEFAULT_BUF_SIZE);
430
431 const PROBE_SIZE: usize = 32;
432
433 fn small_probe_read<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
434 let mut probe = [0u8; PROBE_SIZE];
435
436 loop {
437 match r.read(&mut probe) {
438 Ok(n) => {
439 // there is no way to recover from allocation failure here
440 // because the data has already been read.
441 buf.extend_from_slice(&probe[..n]);
442 return Ok(n);
443 }
444 Err(ref e) if e.is_interrupted() => continue,
445 Err(e) => return Err(e),
446 }
447 }
448 }
449
450 // avoid inflating empty/small vecs before we have determined that there's anything to read
451 if (size_hint.is_none() || size_hint == Some(0)) && buf.capacity() - buf.len() < PROBE_SIZE {
452 let read = small_probe_read(r, buf)?;
453
454 if read == 0 {
455 return Ok(0);
456 }
457 }
458
459 loop {
460 if buf.len() == buf.capacity() && buf.capacity() == start_cap {
461 // The buffer might be an exact fit. Let's read into a probe buffer
462 // and see if it returns `Ok(0)`. If so, we've avoided an
463 // unnecessary doubling of the capacity. But if not, append the
464 // probe buffer to the primary buffer and let its capacity grow.
465 let read = small_probe_read(r, buf)?;
466
467 if read == 0 {
468 return Ok(buf.len() - start_len);
469 }
470 }
471
472 if buf.len() == buf.capacity() {
473 // buf is full, need more space
474 buf.try_reserve(PROBE_SIZE)?;
475 }
476
477 let mut spare = buf.spare_capacity_mut();
478 let buf_len = cmp::min(spare.len(), max_read_size);
479 spare = &mut spare[..buf_len];
480 let mut read_buf: BorrowedBuf<'_, u8> = spare.into();
481
482 // Note that we don't track already initialized bytes here, but this is fine
483 // because we explicitly limit the read size
484 let mut cursor = read_buf.unfilled();
485 let result = loop {
486 match r.read_buf(cursor.reborrow()) {
487 Err(e) if e.is_interrupted() => continue,
488 // Do not stop now in case of error: we might have received both data
489 // and an error
490 res => break res,
491 }
492 };
493
494 let bytes_read = cursor.written();
495 let is_init = read_buf.is_init();
496
497 // SAFETY: BorrowedBuf's invariants mean this much memory is initialized.
498 unsafe {
499 let new_len = bytes_read + buf.len();
500 buf.set_len(new_len);
501 }
502
503 // Now that all data is pushed to the vector, we can fail without data loss
504 result?;
505
506 if bytes_read == 0 {
507 return Ok(buf.len() - start_len);
508 }
509
510 // Use heuristics to determine the max read size if no initial size hint was provided
511 if size_hint.is_none() {
512 // The reader is returning short reads but it doesn't call ensure_init().
513 // In that case we no longer need to restrict read sizes to avoid
514 // initialization costs.
515 // When reading from disk we usually don't get any short reads except at EOF.
516 // So we wait for at least 2 short reads before uncapping the read buffer;
517 // this helps with the Windows issue.
518 if !is_init {
519 max_read_size = usize::MAX;
520 }
521 // we have passed a larger buffer than previously and the
522 // reader still hasn't returned a short read
523 else if buf_len >= max_read_size && bytes_read == buf_len {
524 max_read_size = max_read_size.saturating_mul(2);
525 }
526 }
527 }
528}
529
530pub(crate) fn default_read_to_string<R: Read + ?Sized>(
531 r: &mut R,
532 buf: &mut String,
533 size_hint: Option<usize>,
534) -> Result<usize> {
535 // Note that we do *not* call `r.read_to_end()` here. We are passing
536 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
537 // method to fill it up. An arbitrary implementation could overwrite the
538 // entire contents of the vector, not just append to it (which is what
539 // we are expecting).
540 //
541 // To prevent extraneously checking the UTF-8-ness of the entire buffer
542 // we pass it to our hardcoded `default_read_to_end` implementation which
543 // we know is guaranteed to only read data into the end of the buffer.
544 unsafe { append_to_string(buf, |b| default_read_to_end(r, b, size_hint)) }
545}
546
547pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
548where
549 F: FnOnce(&mut [u8]) -> Result<usize>,
550{
551 let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
552 read(buf)
553}
554
555pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
556 while !buf.is_empty() {
557 match this.read(buf) {
558 Ok(0) => break,
559 Ok(n) => {
560 buf = &mut buf[n..];
561 }
562 Err(ref e) if e.is_interrupted() => {}
563 Err(e) => return Err(e),
564 }
565 }
566 if !buf.is_empty() { Err(Error::READ_EXACT_EOF) } else { Ok(()) }
567}
568
569pub(crate) fn default_read_buf<F>(read: F, mut cursor: BorrowedCursor<'_, u8>) -> Result<()>
570where
571 F: FnOnce(&mut [u8]) -> Result<usize>,
572{
573 let n = read(cursor.ensure_init())?;
574 cursor.advance_checked(n);
575 Ok(())
576}
577
578pub(crate) fn default_read_buf_exact<R: Read + ?Sized>(
579 this: &mut R,
580 mut cursor: BorrowedCursor<'_, u8>,
581) -> Result<()> {
582 while cursor.capacity() > 0 {
583 let prev_written = cursor.written();
584 match this.read_buf(cursor.reborrow()) {
585 Ok(()) => {}
586 Err(e) if e.is_interrupted() => continue,
587 Err(e) => return Err(e),
588 }
589
590 if cursor.written() == prev_written {
591 return Err(Error::READ_EXACT_EOF);
592 }
593 }
594
595 Ok(())
596}
597
598/// The `Read` trait allows for reading bytes from a source.
599///
600/// Implementors of the `Read` trait are called 'readers'.
601///
602/// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
603/// will attempt to pull bytes from this source into a provided buffer. A
604/// number of other methods are implemented in terms of [`read()`], giving
605/// implementors a number of ways to read bytes while only needing to implement
606/// a single method.
607///
608/// Readers are intended to be composable with one another. Many implementors
609/// throughout [`std::io`] take and provide types which implement the `Read`
610/// trait.
611///
612/// Please note that each call to [`read()`] may involve a system call, and
613/// therefore, using something that implements [`BufRead`], such as
614/// [`BufReader`], will be more efficient.
615///
616/// Repeated calls to the reader use the same cursor, so for example
617/// calling `read_to_end` twice on a [`File`] will only return the file's
618/// contents once. It's recommended to first call `rewind()` in that case.
619///
620/// # Examples
621///
622/// [`File`]s implement `Read`:
623///
624/// ```no_run
625/// use std::io;
626/// use std::io::prelude::*;
627/// use std::fs::File;
628///
629/// fn main() -> io::Result<()> {
630/// let mut f = File::open("foo.txt")?;
631/// let mut buffer = [0; 10];
632///
633/// // read up to 10 bytes
634/// f.read(&mut buffer)?;
635///
636/// let mut buffer = Vec::new();
637/// // read the whole file
638/// f.read_to_end(&mut buffer)?;
639///
640/// // read into a String, so that you don't need to do the conversion.
641/// let mut buffer = String::new();
642/// f.read_to_string(&mut buffer)?;
643///
644/// // and more! See the other methods for more details.
645/// Ok(())
646/// }
647/// ```
648///
649/// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
650///
651/// ```no_run
652/// # use std::io;
653/// use std::io::prelude::*;
654///
655/// fn main() -> io::Result<()> {
656/// let mut b = "This string will be read".as_bytes();
657/// let mut buffer = [0; 10];
658///
659/// // read up to 10 bytes
660/// b.read(&mut buffer)?;
661///
662/// // etc... it works exactly as a File does!
663/// Ok(())
664/// }
665/// ```
666///
667/// [`read()`]: Read::read
668/// [`&str`]: prim@str
669/// [`std::io`]: self
670/// [`File`]: crate::fs::File
671#[stable(feature = "rust1", since = "1.0.0")]
672#[doc(notable_trait)]
673#[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
674pub trait Read {
675 /// Pull some bytes from this source into the specified buffer, returning
676 /// how many bytes were read.
677 ///
678 /// This function does not provide any guarantees about whether it blocks
679 /// waiting for data, but if an object needs to block for a read and cannot,
680 /// it will typically signal this via an [`Err`] return value.
681 ///
682 /// If the return value of this method is [`Ok(n)`], then implementations must
683 /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
684 /// that the buffer `buf` has been filled in with `n` bytes of data from this
685 /// source. If `n` is `0`, then it can indicate one of two scenarios:
686 ///
687 /// 1. This reader has reached its "end of file" and will likely no longer
688 /// be able to produce bytes. Note that this does not mean that the
689 /// reader will *always* no longer be able to produce bytes. As an example,
690 /// on Linux, this method will call the `recv` syscall for a [`TcpStream`],
691 /// where returning zero indicates the connection was shut down correctly. While
692 /// for [`File`], it is possible to reach the end of file and get zero as result,
693 /// but if more data is appended to the file, future calls to `read` will return
694 /// more data.
695 /// 2. The buffer specified was 0 bytes in length.
696 ///
697 /// It is not an error if the returned value `n` is smaller than the buffer size,
698 /// even when the reader is not at the end of the stream yet.
699 /// This may happen for example because fewer bytes are actually available right now
700 /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
701 ///
702 /// As this trait is safe to implement, callers in unsafe code cannot rely on
703 /// `n <= buf.len()` for safety.
704 /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
705 /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
706 /// `n > buf.len()`.
707 ///
708 /// *Implementations* of this method can make no assumptions about the contents of `buf` when
709 /// this function is called. It is recommended that implementations only write data to `buf`
710 /// instead of reading its contents.
711 ///
712 /// Correspondingly, however, *callers* of this method in unsafe code must not assume
713 /// any guarantees about how the implementation uses `buf`. The trait is safe to implement,
714 /// so it is possible that the code that's supposed to write to the buffer might also read
715 /// from it. It is your responsibility to make sure that `buf` is initialized
716 /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
717 /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
718 ///
719 /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
720 ///
721 /// # Errors
722 ///
723 /// If this function encounters any form of I/O or other error, an error
724 /// variant will be returned. If an error is returned then it must be
725 /// guaranteed that no bytes were read.
726 ///
727 /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
728 /// operation should be retried if there is nothing else to do.
729 ///
730 /// # Examples
731 ///
732 /// [`File`]s implement `Read`:
733 ///
734 /// [`Ok(n)`]: Ok
735 /// [`File`]: crate::fs::File
736 /// [`TcpStream`]: crate::net::TcpStream
737 ///
738 /// ```no_run
739 /// use std::io;
740 /// use std::io::prelude::*;
741 /// use std::fs::File;
742 ///
743 /// fn main() -> io::Result<()> {
744 /// let mut f = File::open("foo.txt")?;
745 /// let mut buffer = [0; 10];
746 ///
747 /// // read up to 10 bytes
748 /// let n = f.read(&mut buffer[..])?;
749 ///
750 /// println!("The bytes: {:?}", &buffer[..n]);
751 /// Ok(())
752 /// }
753 /// ```
754 #[stable(feature = "rust1", since = "1.0.0")]
755 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
756
757 /// Like `read`, except that it reads into a slice of buffers.
758 ///
759 /// Data is copied to fill each buffer in order, with the final buffer
760 /// written to possibly being only partially filled. This method must
761 /// behave equivalently to a single call to `read` with concatenated
762 /// buffers.
763 ///
764 /// The default implementation calls `read` with either the first nonempty
765 /// buffer provided, or an empty one if none exists.
766 #[stable(feature = "iovec", since = "1.36.0")]
767 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
768 default_read_vectored(|b| self.read(b), bufs)
769 }
770
771 /// Determines if this `Read`er has an efficient `read_vectored`
772 /// implementation.
773 ///
774 /// If a `Read`er does not override the default `read_vectored`
775 /// implementation, code using it may want to avoid the method all together
776 /// and coalesce writes into a single buffer for higher performance.
777 ///
778 /// The default implementation returns `false`.
779 #[unstable(feature = "can_vector", issue = "69941")]
780 fn is_read_vectored(&self) -> bool {
781 false
782 }
783
784 /// Reads all bytes until EOF in this source, placing them into `buf`.
785 ///
786 /// All bytes read from this source will be appended to the specified buffer
787 /// `buf`. This function will continuously call [`read()`] to append more data to
788 /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
789 /// non-[`ErrorKind::Interrupted`] kind.
790 ///
791 /// If successful, this function will return the total number of bytes read.
792 ///
793 /// # Errors
794 ///
795 /// If this function encounters an error of the kind
796 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
797 /// will continue.
798 ///
799 /// If any other read error is encountered then this function immediately
800 /// returns. Any bytes which have already been read will be appended to
801 /// `buf`.
802 ///
803 /// # Examples
804 ///
805 /// [`File`]s implement `Read`:
806 ///
807 /// [`read()`]: Read::read
808 /// [`Ok(0)`]: Ok
809 /// [`File`]: crate::fs::File
810 ///
811 /// ```no_run
812 /// use std::io;
813 /// use std::io::prelude::*;
814 /// use std::fs::File;
815 ///
816 /// fn main() -> io::Result<()> {
817 /// let mut f = File::open("foo.txt")?;
818 /// let mut buffer = Vec::new();
819 ///
820 /// // read the whole file
821 /// f.read_to_end(&mut buffer)?;
822 /// Ok(())
823 /// }
824 /// ```
825 ///
826 /// (See also the [`std::fs::read`] convenience function for reading from a
827 /// file.)
828 ///
829 /// [`std::fs::read`]: crate::fs::read
830 ///
831 /// ## Implementing `read_to_end`
832 ///
833 /// When implementing the `io::Read` trait, it is recommended to allocate
834 /// memory using [`Vec::try_reserve`]. However, this behavior is not guaranteed
835 /// by all implementations, and `read_to_end` may not handle out-of-memory
836 /// situations gracefully.
837 ///
838 /// ```no_run
839 /// # use std::io::{self, BufRead};
840 /// # struct Example { example_datasource: io::Empty } impl Example {
841 /// # fn get_some_data_for_the_example(&self) -> &'static [u8] { &[] }
842 /// fn read_to_end(&mut self, dest_vec: &mut Vec<u8>) -> io::Result<usize> {
843 /// let initial_vec_len = dest_vec.len();
844 /// loop {
845 /// let src_buf = self.example_datasource.fill_buf()?;
846 /// if src_buf.is_empty() {
847 /// break;
848 /// }
849 /// dest_vec.try_reserve(src_buf.len())?;
850 /// dest_vec.extend_from_slice(src_buf);
851 ///
852 /// // Any irreversible side effects should happen after `try_reserve` succeeds,
853 /// // to avoid losing data on allocation error.
854 /// let read = src_buf.len();
855 /// self.example_datasource.consume(read);
856 /// }
857 /// Ok(dest_vec.len() - initial_vec_len)
858 /// }
859 /// # }
860 /// ```
861 ///
862 /// # Usage Notes
863 ///
864 /// `read_to_end` attempts to read a source until EOF, but many sources are continuous streams
865 /// that do not send EOF. In these cases, `read_to_end` will block indefinitely. Standard input
866 /// is one such stream which may be finite if piped, but is typically continuous. For example,
867 /// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
868 /// Reading user input or running programs that remain open indefinitely will never terminate
869 /// the stream with `EOF` (e.g. `yes | my-rust-program`).
870 ///
871 /// Using `.lines()` with a [`BufReader`] or using [`read`] can provide a better solution
872 ///
873 ///[`read`]: Read::read
874 ///
875 /// [`Vec::try_reserve`]: crate::vec::Vec::try_reserve
876 #[stable(feature = "rust1", since = "1.0.0")]
877 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
878 default_read_to_end(self, buf, None)
879 }
880
881 /// Reads all bytes until EOF in this source, appending them to `buf`.
882 ///
883 /// If successful, this function returns the number of bytes which were read
884 /// and appended to `buf`.
885 ///
886 /// # Errors
887 ///
888 /// If the data in this stream is *not* valid UTF-8 then an error is
889 /// returned and `buf` is unchanged.
890 ///
891 /// See [`read_to_end`] for other error semantics.
892 ///
893 /// [`read_to_end`]: Read::read_to_end
894 ///
895 /// # Examples
896 ///
897 /// [`File`]s implement `Read`:
898 ///
899 /// [`File`]: crate::fs::File
900 ///
901 /// ```no_run
902 /// use std::io;
903 /// use std::io::prelude::*;
904 /// use std::fs::File;
905 ///
906 /// fn main() -> io::Result<()> {
907 /// let mut f = File::open("foo.txt")?;
908 /// let mut buffer = String::new();
909 ///
910 /// f.read_to_string(&mut buffer)?;
911 /// Ok(())
912 /// }
913 /// ```
914 ///
915 /// (See also the [`std::fs::read_to_string`] convenience function for
916 /// reading from a file.)
917 ///
918 /// # Usage Notes
919 ///
920 /// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams
921 /// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input
922 /// is one such stream which may be finite if piped, but is typically continuous. For example,
923 /// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
924 /// Reading user input or running programs that remain open indefinitely will never terminate
925 /// the stream with `EOF` (e.g. `yes | my-rust-program`).
926 ///
927 /// Using `.lines()` with a [`BufReader`] or using [`read`] can provide a better solution
928 ///
929 ///[`read`]: Read::read
930 ///
931 /// [`std::fs::read_to_string`]: crate::fs::read_to_string
932 #[stable(feature = "rust1", since = "1.0.0")]
933 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
934 default_read_to_string(self, buf, None)
935 }
936
937 /// Reads the exact number of bytes required to fill `buf`.
938 ///
939 /// This function reads as many bytes as necessary to completely fill the
940 /// specified buffer `buf`.
941 ///
942 /// *Implementations* of this method can make no assumptions about the contents of `buf` when
943 /// this function is called. It is recommended that implementations only write data to `buf`
944 /// instead of reading its contents. The documentation on [`read`] has a more detailed
945 /// explanation of this subject.
946 ///
947 /// # Errors
948 ///
949 /// If this function encounters an error of the kind
950 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
951 /// will continue.
952 ///
953 /// If this function encounters an "end of file" before completely filling
954 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
955 /// The contents of `buf` are unspecified in this case.
956 ///
957 /// If any other read error is encountered then this function immediately
958 /// returns. The contents of `buf` are unspecified in this case.
959 ///
960 /// If this function returns an error, it is unspecified how many bytes it
961 /// has read, but it will never read more than would be necessary to
962 /// completely fill the buffer.
963 ///
964 /// # Examples
965 ///
966 /// [`File`]s implement `Read`:
967 ///
968 /// [`read`]: Read::read
969 /// [`File`]: crate::fs::File
970 ///
971 /// ```no_run
972 /// use std::io;
973 /// use std::io::prelude::*;
974 /// use std::fs::File;
975 ///
976 /// fn main() -> io::Result<()> {
977 /// let mut f = File::open("foo.txt")?;
978 /// let mut buffer = [0; 10];
979 ///
980 /// // read exactly 10 bytes
981 /// f.read_exact(&mut buffer)?;
982 /// Ok(())
983 /// }
984 /// ```
985 #[stable(feature = "read_exact", since = "1.6.0")]
986 fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
987 default_read_exact(self, buf)
988 }
989
990 /// Pull some bytes from this source into the specified buffer.
991 ///
992 /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
993 /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
994 ///
995 /// The default implementation delegates to `read`.
996 ///
997 /// This method makes it possible to return both data and an error but it is advised against.
998 #[unstable(feature = "read_buf", issue = "78485")]
999 fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<()> {
1000 default_read_buf(|b| self.read(b), buf)
1001 }
1002
1003 /// Reads the exact number of bytes required to fill `cursor`.
1004 ///
1005 /// This is similar to the [`read_exact`](Read::read_exact) method, except
1006 /// that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
1007 /// with uninitialized buffers.
1008 ///
1009 /// # Errors
1010 ///
1011 /// If this function encounters an error of the kind [`ErrorKind::Interrupted`]
1012 /// then the error is ignored and the operation will continue.
1013 ///
1014 /// If this function encounters an "end of file" before completely filling
1015 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
1016 ///
1017 /// If any other read error is encountered then this function immediately
1018 /// returns.
1019 ///
1020 /// If this function returns an error, all bytes read will be appended to `cursor`.
1021 #[unstable(feature = "read_buf", issue = "78485")]
1022 fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> Result<()> {
1023 default_read_buf_exact(self, cursor)
1024 }
1025
1026 /// Creates a "by reference" adapter for this instance of `Read`.
1027 ///
1028 /// The returned adapter also implements `Read` and will simply borrow this
1029 /// current reader.
1030 ///
1031 /// # Examples
1032 ///
1033 /// [`File`]s implement `Read`:
1034 ///
1035 /// [`File`]: crate::fs::File
1036 ///
1037 /// ```no_run
1038 /// use std::io;
1039 /// use std::io::Read;
1040 /// use std::fs::File;
1041 ///
1042 /// fn main() -> io::Result<()> {
1043 /// let mut f = File::open("foo.txt")?;
1044 /// let mut buffer = Vec::new();
1045 /// let mut other_buffer = Vec::new();
1046 ///
1047 /// {
1048 /// let reference = f.by_ref();
1049 ///
1050 /// // read at most 5 bytes
1051 /// reference.take(5).read_to_end(&mut buffer)?;
1052 ///
1053 /// } // drop our &mut reference so we can use f again
1054 ///
1055 /// // original file still usable, read the rest
1056 /// f.read_to_end(&mut other_buffer)?;
1057 /// Ok(())
1058 /// }
1059 /// ```
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 fn by_ref(&mut self) -> &mut Self
1062 where
1063 Self: Sized,
1064 {
1065 self
1066 }
1067
1068 /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
1069 ///
1070 /// The returned type implements [`Iterator`] where the [`Item`] is
1071 /// <code>[Result]<[u8], [io::Error]></code>.
1072 /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
1073 /// otherwise. EOF is mapped to returning [`None`] from this iterator.
1074 ///
1075 /// The default implementation calls `read` for each byte,
1076 /// which can be very inefficient for data that's not in memory,
1077 /// such as [`File`]. Consider using a [`BufReader`] in such cases.
1078 ///
1079 /// # Examples
1080 ///
1081 /// [`File`]s implement `Read`:
1082 ///
1083 /// [`Item`]: Iterator::Item
1084 /// [`File`]: crate::fs::File "fs::File"
1085 /// [Result]: crate::result::Result "Result"
1086 /// [io::Error]: self::Error "io::Error"
1087 ///
1088 /// ```no_run
1089 /// use std::io;
1090 /// use std::io::prelude::*;
1091 /// use std::io::BufReader;
1092 /// use std::fs::File;
1093 ///
1094 /// fn main() -> io::Result<()> {
1095 /// let f = BufReader::new(File::open("foo.txt")?);
1096 ///
1097 /// for byte in f.bytes() {
1098 /// println!("{}", byte?);
1099 /// }
1100 /// Ok(())
1101 /// }
1102 /// ```
1103 #[stable(feature = "rust1", since = "1.0.0")]
1104 fn bytes(self) -> Bytes<Self>
1105 where
1106 Self: Sized,
1107 {
1108 Bytes { inner: self }
1109 }
1110
1111 /// Creates an adapter which will chain this stream with another.
1112 ///
1113 /// The returned `Read` instance will first read all bytes from this object
1114 /// until EOF is encountered. Afterwards the output is equivalent to the
1115 /// output of `next`.
1116 ///
1117 /// # Examples
1118 ///
1119 /// [`File`]s implement `Read`:
1120 ///
1121 /// [`File`]: crate::fs::File
1122 ///
1123 /// ```no_run
1124 /// use std::io;
1125 /// use std::io::prelude::*;
1126 /// use std::fs::File;
1127 ///
1128 /// fn main() -> io::Result<()> {
1129 /// let f1 = File::open("foo.txt")?;
1130 /// let f2 = File::open("bar.txt")?;
1131 ///
1132 /// let mut handle = f1.chain(f2);
1133 /// let mut buffer = String::new();
1134 ///
1135 /// // read the value into a String. We could use any Read method here,
1136 /// // this is just one example.
1137 /// handle.read_to_string(&mut buffer)?;
1138 /// Ok(())
1139 /// }
1140 /// ```
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 fn chain<R: Read>(self, next: R) -> Chain<Self, R>
1143 where
1144 Self: Sized,
1145 {
1146 core::io::chain(self, next)
1147 }
1148
1149 /// Creates an adapter which will read at most `limit` bytes from it.
1150 ///
1151 /// This function returns a new instance of `Read` which will read at most
1152 /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
1153 /// read errors will not count towards the number of bytes read and future
1154 /// calls to [`read()`] may succeed.
1155 ///
1156 /// # Examples
1157 ///
1158 /// [`File`]s implement `Read`:
1159 ///
1160 /// [`File`]: crate::fs::File
1161 /// [`Ok(0)`]: Ok
1162 /// [`read()`]: Read::read
1163 ///
1164 /// ```no_run
1165 /// use std::io;
1166 /// use std::io::prelude::*;
1167 /// use std::fs::File;
1168 ///
1169 /// fn main() -> io::Result<()> {
1170 /// let f = File::open("foo.txt")?;
1171 /// let mut buffer = [0; 5];
1172 ///
1173 /// // read at most five bytes
1174 /// let mut handle = f.take(5);
1175 ///
1176 /// handle.read(&mut buffer)?;
1177 /// Ok(())
1178 /// }
1179 /// ```
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 fn take(self, limit: u64) -> Take<Self>
1182 where
1183 Self: Sized,
1184 {
1185 core::io::take(self, limit)
1186 }
1187
1188 /// Read and return a fixed array of bytes from this source.
1189 ///
1190 /// This function uses an array sized based on a const generic size known at compile time. You
1191 /// can specify the size with turbofish (`reader.read_array::<8>()`), or let type inference
1192 /// determine the number of bytes needed based on how the return value gets used. For instance,
1193 /// this function works well with functions like [`u64::from_le_bytes`] to turn an array of
1194 /// bytes into an integer of the same size.
1195 ///
1196 /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
1197 /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
1198 ///
1199 /// ```
1200 /// #![feature(read_array)]
1201 /// use std::io::Cursor;
1202 /// use std::io::prelude::*;
1203 ///
1204 /// fn main() -> std::io::Result<()> {
1205 /// let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
1206 /// let x = u64::from_le_bytes(buf.read_array()?);
1207 /// let y = u32::from_be_bytes(buf.read_array()?);
1208 /// let z = u16::from_be_bytes(buf.read_array()?);
1209 /// assert_eq!(x, 0x807060504030201);
1210 /// assert_eq!(y, 0x9080706);
1211 /// assert_eq!(z, 0x504);
1212 /// Ok(())
1213 /// }
1214 /// ```
1215 #[unstable(feature = "read_array", issue = "148848")]
1216 fn read_array<const N: usize>(&mut self) -> Result<[u8; N]>
1217 where
1218 Self: Sized,
1219 {
1220 let mut buf = [MaybeUninit::uninit(); N];
1221 let mut borrowed_buf = BorrowedBuf::from(buf.as_mut_slice());
1222 self.read_buf_exact(borrowed_buf.unfilled())?;
1223 // Guard against incorrect `read_buf_exact` implementations.
1224 assert_eq!(borrowed_buf.len(), N);
1225 Ok(unsafe { MaybeUninit::array_assume_init(buf) })
1226 }
1227
1228 /// Read and return a type (e.g. an integer) in little-endian order.
1229 ///
1230 /// You can specify the type with turbofish (`reader.read_le::<u64>()`), or let type inference
1231 /// determine the type based on how the return value gets used.
1232 ///
1233 /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
1234 /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
1235 ///
1236 /// ```
1237 /// #![feature(read_le)]
1238 /// use std::io::Cursor;
1239 /// use std::io::prelude::*;
1240 ///
1241 /// fn main() -> std::io::Result<()> {
1242 /// let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
1243 /// let x: u64 = buf.read_le()?;
1244 /// let y: u32 = buf.read_le()?;
1245 /// let z = buf.read_le::<u16>()?;
1246 /// assert_eq!(x, 0x807060504030201);
1247 /// assert_eq!(y, 0x6070809);
1248 /// assert_eq!(z, 0x405);
1249 /// Ok(())
1250 /// }
1251 /// ```
1252 #[unstable(feature = "read_le", issue = "156984")]
1253 #[inline]
1254 fn read_le<T: FromEndianBytes>(&mut self) -> Result<T>
1255 where
1256 Self: Sized,
1257 {
1258 T::read_le_from(self)
1259 }
1260
1261 /// Read and return a type (e.g. an integer) in big-endian order.
1262 ///
1263 /// You can specify the type with turbofish (`reader.read_be::<u64>()`), or let type inference
1264 /// determine the type based on how the return value gets used.
1265 ///
1266 /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
1267 /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
1268 ///
1269 /// ```
1270 /// #![feature(read_le)]
1271 /// use std::io::Cursor;
1272 /// use std::io::prelude::*;
1273 ///
1274 /// fn main() -> std::io::Result<()> {
1275 /// let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
1276 /// let x: u64 = buf.read_be()?;
1277 /// let y: u32 = buf.read_be()?;
1278 /// let z = buf.read_be::<u16>()?;
1279 /// assert_eq!(x, 0x102030405060708);
1280 /// assert_eq!(y, 0x9080706);
1281 /// assert_eq!(z, 0x504);
1282 /// Ok(())
1283 /// }
1284 /// ```
1285 #[unstable(feature = "read_le", issue = "156984")]
1286 #[inline]
1287 fn read_be<T: FromEndianBytes>(&mut self) -> Result<T>
1288 where
1289 Self: Sized,
1290 {
1291 T::read_be_from(self)
1292 }
1293}
1294
1295/// Reads all bytes from a [reader][Read] into a new [`String`].
1296///
1297/// This is a convenience function for [`Read::read_to_string`]. Using this
1298/// function avoids having to create a variable first and provides more type
1299/// safety since you can only get the buffer out if there were no errors. (If you
1300/// use [`Read::read_to_string`] you have to remember to check whether the read
1301/// succeeded because otherwise your buffer will be empty or only partially full.)
1302///
1303/// # Performance
1304///
1305/// The downside of this function's increased ease of use and type safety is
1306/// that it gives you less control over performance. For example, you can't
1307/// pre-allocate memory like you can using [`String::with_capacity`] and
1308/// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1309/// occurs while reading.
1310///
1311/// In many cases, this function's performance will be adequate and the ease of use
1312/// and type safety tradeoffs will be worth it. However, there are cases where you
1313/// need more control over performance, and in those cases you should definitely use
1314/// [`Read::read_to_string`] directly.
1315///
1316/// Note that in some special cases, such as when reading files, this function will
1317/// pre-allocate memory based on the size of the input it is reading. In those
1318/// cases, the performance should be as good as if you had used
1319/// [`Read::read_to_string`] with a manually pre-allocated buffer.
1320///
1321/// # Errors
1322///
1323/// This function forces you to handle errors because the output (the `String`)
1324/// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1325/// that can occur. If any error occurs, you will get an [`Err`], so you
1326/// don't have to worry about your buffer being empty or partially full.
1327///
1328/// # Examples
1329///
1330/// ```no_run
1331/// # use std::io;
1332/// fn main() -> io::Result<()> {
1333/// let stdin = io::read_to_string(io::stdin())?;
1334/// println!("Stdin was:");
1335/// println!("{stdin}");
1336/// Ok(())
1337/// }
1338/// ```
1339///
1340/// # Usage Notes
1341///
1342/// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams
1343/// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input
1344/// is one such stream which may be finite if piped, but is typically continuous. For example,
1345/// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
1346/// Reading user input or running programs that remain open indefinitely will never terminate
1347/// the stream with `EOF` (e.g. `yes | my-rust-program`).
1348///
1349/// Using `.lines()` with a [`BufReader`] or using [`read`] can provide a better solution
1350///
1351///[`read`]: Read::read
1352///
1353#[stable(feature = "io_read_to_string", since = "1.65.0")]
1354pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> {
1355 let mut buf = String::new();
1356 reader.read_to_string(&mut buf)?;
1357 Ok(buf)
1358}
1359
1360fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1361 let mut read = 0;
1362 loop {
1363 let (done, used) = {
1364 let available = match r.fill_buf() {
1365 Ok(n) => n,
1366 Err(ref e) if e.is_interrupted() => continue,
1367 Err(e) => return Err(e),
1368 };
1369 match memchr::memchr(delim, available) {
1370 Some(i) => {
1371 buf.extend_from_slice(&available[..=i]);
1372 (true, i + 1)
1373 }
1374 None => {
1375 buf.extend_from_slice(available);
1376 (false, available.len())
1377 }
1378 }
1379 };
1380 r.consume(used);
1381 read += used;
1382 if done || used == 0 {
1383 return Ok(read);
1384 }
1385 }
1386}
1387
1388fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize> {
1389 let mut read = 0;
1390 loop {
1391 let (done, used) = {
1392 let available = match r.fill_buf() {
1393 Ok(n) => n,
1394 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1395 Err(e) => return Err(e),
1396 };
1397 match memchr::memchr(delim, available) {
1398 Some(i) => (true, i + 1),
1399 None => (false, available.len()),
1400 }
1401 };
1402 r.consume(used);
1403 read += used;
1404 if done || used == 0 {
1405 return Ok(read);
1406 }
1407 }
1408}
1409
1410/// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1411/// to perform extra ways of reading.
1412///
1413/// For example, reading line-by-line is inefficient without using a buffer, so
1414/// if you want to read by line, you'll need `BufRead`, which includes a
1415/// [`read_line`] method as well as a [`lines`] iterator.
1416///
1417/// # Examples
1418///
1419/// A locked standard input implements `BufRead`:
1420///
1421/// ```no_run
1422/// use std::io;
1423/// use std::io::prelude::*;
1424///
1425/// let stdin = io::stdin();
1426/// for line in stdin.lock().lines() {
1427/// println!("{}", line?);
1428/// }
1429/// # std::io::Result::Ok(())
1430/// ```
1431///
1432/// If you have something that implements [`Read`], you can use the [`BufReader`
1433/// type][`BufReader`] to turn it into a `BufRead`.
1434///
1435/// For example, [`File`] implements [`Read`], but not `BufRead`.
1436/// [`BufReader`] to the rescue!
1437///
1438/// [`File`]: crate::fs::File
1439/// [`read_line`]: BufRead::read_line
1440/// [`lines`]: BufRead::lines
1441///
1442/// ```no_run
1443/// use std::io::{self, BufReader};
1444/// use std::io::prelude::*;
1445/// use std::fs::File;
1446///
1447/// fn main() -> io::Result<()> {
1448/// let f = File::open("foo.txt")?;
1449/// let f = BufReader::new(f);
1450///
1451/// for line in f.lines() {
1452/// let line = line?;
1453/// println!("{line}");
1454/// }
1455///
1456/// Ok(())
1457/// }
1458/// ```
1459#[stable(feature = "rust1", since = "1.0.0")]
1460#[cfg_attr(not(test), rustc_diagnostic_item = "IoBufRead")]
1461pub trait BufRead: Read {
1462 /// Returns the contents of the internal buffer, filling it with more data, via `Read` methods, if empty.
1463 ///
1464 /// This is a lower-level method and is meant to be used together with [`consume`],
1465 /// which can be used to mark bytes that should not be returned by subsequent calls to `read`.
1466 ///
1467 /// [`consume`]: BufRead::consume
1468 ///
1469 /// Returns an empty buffer when the stream has reached EOF.
1470 ///
1471 /// # Errors
1472 ///
1473 /// This function will return an I/O error if a `Read` method was called, but returned an error.
1474 ///
1475 /// # Examples
1476 ///
1477 /// A locked standard input implements `BufRead`:
1478 ///
1479 /// ```no_run
1480 /// use std::io;
1481 /// use std::io::prelude::*;
1482 ///
1483 /// let stdin = io::stdin();
1484 /// let mut stdin = stdin.lock();
1485 ///
1486 /// let buffer = stdin.fill_buf()?;
1487 ///
1488 /// // work with buffer
1489 /// println!("{buffer:?}");
1490 ///
1491 /// // mark the bytes we worked with as read
1492 /// let length = buffer.len();
1493 /// stdin.consume(length);
1494 /// # std::io::Result::Ok(())
1495 /// ```
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 fn fill_buf(&mut self) -> Result<&[u8]>;
1498
1499 /// Marks the given `amount` of additional bytes from the internal buffer as having been read.
1500 /// Subsequent calls to `read` only return bytes that have not been marked as read.
1501 ///
1502 /// This is a lower-level method and is meant to be used together with [`fill_buf`],
1503 /// which can be used to fill the internal buffer via `Read` methods.
1504 ///
1505 /// It is a logic error if `amount` exceeds the number of unread bytes in the internal buffer, which is returned by [`fill_buf`].
1506 ///
1507 /// # Examples
1508 ///
1509 /// Since `consume()` is meant to be used with [`fill_buf`],
1510 /// that method's example includes an example of `consume()`.
1511 ///
1512 /// [`fill_buf`]: BufRead::fill_buf
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 fn consume(&mut self, amount: usize);
1515
1516 /// Checks if there is any data left to be `read`.
1517 ///
1518 /// This function may fill the buffer to check for data,
1519 /// so this function returns `Result<bool>`, not `bool`.
1520 ///
1521 /// The default implementation calls `fill_buf` and checks that the
1522 /// returned slice is empty (which means that there is no data left,
1523 /// since EOF is reached).
1524 ///
1525 /// # Errors
1526 ///
1527 /// This function will return an I/O error if a `Read` method was called, but returned an error.
1528 ///
1529 /// Examples
1530 ///
1531 /// ```
1532 /// #![feature(buf_read_has_data_left)]
1533 /// use std::io;
1534 /// use std::io::prelude::*;
1535 ///
1536 /// let stdin = io::stdin();
1537 /// let mut stdin = stdin.lock();
1538 ///
1539 /// while stdin.has_data_left()? {
1540 /// let mut line = String::new();
1541 /// stdin.read_line(&mut line)?;
1542 /// // work with line
1543 /// println!("{line:?}");
1544 /// }
1545 /// # std::io::Result::Ok(())
1546 /// ```
1547 #[unstable(feature = "buf_read_has_data_left", issue = "86423")]
1548 fn has_data_left(&mut self) -> Result<bool> {
1549 self.fill_buf().map(|b| !b.is_empty())
1550 }
1551
1552 /// Reads all bytes into `buf` until the delimiter `byte` or EOF is reached.
1553 ///
1554 /// This function will read bytes from the underlying stream until the
1555 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1556 /// the delimiter (if found) will be appended to `buf`.
1557 ///
1558 /// If successful, this function will return the total number of bytes read.
1559 ///
1560 /// This function is blocking and should be used carefully: it is possible for
1561 /// an attacker to continuously send bytes without ever sending the delimiter
1562 /// or EOF.
1563 ///
1564 /// # Errors
1565 ///
1566 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1567 /// will otherwise return any errors returned by [`fill_buf`].
1568 ///
1569 /// If an I/O error is encountered then all bytes read so far will be
1570 /// present in `buf` and its length will have been adjusted appropriately.
1571 ///
1572 /// [`fill_buf`]: BufRead::fill_buf
1573 ///
1574 /// # Examples
1575 ///
1576 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1577 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1578 /// in hyphen delimited segments:
1579 ///
1580 /// ```
1581 /// use std::io::{self, BufRead};
1582 ///
1583 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1584 /// let mut buf = vec![];
1585 ///
1586 /// // cursor is at 'l'
1587 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1588 /// .expect("reading from cursor won't fail");
1589 /// assert_eq!(num_bytes, 6);
1590 /// assert_eq!(buf, b"lorem-");
1591 /// buf.clear();
1592 ///
1593 /// // cursor is at 'i'
1594 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1595 /// .expect("reading from cursor won't fail");
1596 /// assert_eq!(num_bytes, 5);
1597 /// assert_eq!(buf, b"ipsum");
1598 /// buf.clear();
1599 ///
1600 /// // cursor is at EOF
1601 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1602 /// .expect("reading from cursor won't fail");
1603 /// assert_eq!(num_bytes, 0);
1604 /// assert_eq!(buf, b"");
1605 /// ```
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1608 read_until(self, byte, buf)
1609 }
1610
1611 /// Skips all bytes until the delimiter `byte` or EOF is reached.
1612 ///
1613 /// This function will read (and discard) bytes from the underlying stream until the
1614 /// delimiter or EOF is found.
1615 ///
1616 /// If successful, this function will return the total number of bytes read,
1617 /// including the delimiter byte if found.
1618 ///
1619 /// This is useful for efficiently skipping data such as NUL-terminated strings
1620 /// in binary file formats without buffering.
1621 ///
1622 /// This function is blocking and should be used carefully: it is possible for
1623 /// an attacker to continuously send bytes without ever sending the delimiter
1624 /// or EOF.
1625 ///
1626 /// # Errors
1627 ///
1628 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1629 /// will otherwise return any errors returned by [`fill_buf`].
1630 ///
1631 /// If an I/O error is encountered then all bytes read so far will be
1632 /// present in `buf` and its length will have been adjusted appropriately.
1633 ///
1634 /// [`fill_buf`]: BufRead::fill_buf
1635 ///
1636 /// # Examples
1637 ///
1638 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1639 /// this example, we use [`Cursor`] to read some NUL-terminated information
1640 /// about Ferris from a binary string, skipping the fun fact:
1641 ///
1642 /// ```
1643 /// use std::io::{self, BufRead};
1644 ///
1645 /// let mut cursor = io::Cursor::new(b"Ferris\0Likes long walks on the beach\0Crustacean\0!");
1646 ///
1647 /// // read name
1648 /// let mut name = Vec::new();
1649 /// let num_bytes = cursor.read_until(b'\0', &mut name)
1650 /// .expect("reading from cursor won't fail");
1651 /// assert_eq!(num_bytes, 7);
1652 /// assert_eq!(name, b"Ferris\0");
1653 ///
1654 /// // skip fun fact
1655 /// let num_bytes = cursor.skip_until(b'\0')
1656 /// .expect("reading from cursor won't fail");
1657 /// assert_eq!(num_bytes, 30);
1658 ///
1659 /// // read animal type
1660 /// let mut animal = Vec::new();
1661 /// let num_bytes = cursor.read_until(b'\0', &mut animal)
1662 /// .expect("reading from cursor won't fail");
1663 /// assert_eq!(num_bytes, 11);
1664 /// assert_eq!(animal, b"Crustacean\0");
1665 ///
1666 /// // reach EOF
1667 /// let num_bytes = cursor.skip_until(b'\0')
1668 /// .expect("reading from cursor won't fail");
1669 /// assert_eq!(num_bytes, 1);
1670 /// ```
1671 #[stable(feature = "bufread_skip_until", since = "1.83.0")]
1672 fn skip_until(&mut self, byte: u8) -> Result<usize> {
1673 skip_until(self, byte)
1674 }
1675
1676 /// Reads all bytes until a newline (the `0xA` byte) is reached, and append
1677 /// them to the provided `String` buffer.
1678 ///
1679 /// Previous content of the buffer will be preserved. To avoid appending to
1680 /// the buffer, you need to [`clear`] it first.
1681 ///
1682 /// This function will read bytes from the underlying stream until the
1683 /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
1684 /// up to, and including, the delimiter (if found) will be appended to
1685 /// `buf`.
1686 ///
1687 /// If successful, this function will return the total number of bytes read.
1688 ///
1689 /// If this function returns [`Ok(0)`], the stream has reached EOF.
1690 ///
1691 /// This function is blocking and should be used carefully: it is possible for
1692 /// an attacker to continuously send bytes without ever sending a newline
1693 /// or EOF. You can use [`take`] to limit the maximum number of bytes read.
1694 ///
1695 /// [`Ok(0)`]: Ok
1696 /// [`clear`]: String::clear
1697 /// [`take`]: crate::io::Read::take
1698 ///
1699 /// # Errors
1700 ///
1701 /// This function has the same error semantics as [`read_until`] and will
1702 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1703 /// error is encountered then `buf` may contain some bytes already read in
1704 /// the event that all data read so far was valid UTF-8.
1705 ///
1706 /// [`read_until`]: BufRead::read_until
1707 ///
1708 /// # Examples
1709 ///
1710 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1711 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1712 ///
1713 /// ```
1714 /// use std::io::{self, BufRead};
1715 ///
1716 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1717 /// let mut buf = String::new();
1718 ///
1719 /// // cursor is at 'f'
1720 /// let num_bytes = cursor.read_line(&mut buf)
1721 /// .expect("reading from cursor won't fail");
1722 /// assert_eq!(num_bytes, 4);
1723 /// assert_eq!(buf, "foo\n");
1724 /// buf.clear();
1725 ///
1726 /// // cursor is at 'b'
1727 /// let num_bytes = cursor.read_line(&mut buf)
1728 /// .expect("reading from cursor won't fail");
1729 /// assert_eq!(num_bytes, 3);
1730 /// assert_eq!(buf, "bar");
1731 /// buf.clear();
1732 ///
1733 /// // cursor is at EOF
1734 /// let num_bytes = cursor.read_line(&mut buf)
1735 /// .expect("reading from cursor won't fail");
1736 /// assert_eq!(num_bytes, 0);
1737 /// assert_eq!(buf, "");
1738 /// ```
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1741 // Note that we are not calling the `.read_until` method here, but
1742 // rather our hardcoded implementation. For more details as to why, see
1743 // the comments in `default_read_to_string`.
1744 unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
1745 }
1746
1747 /// Returns an iterator over the contents of this reader split on the byte
1748 /// `byte`.
1749 ///
1750 /// The iterator returned from this function will return instances of
1751 /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
1752 /// the delimiter byte at the end.
1753 ///
1754 /// This function will yield errors whenever [`read_until`] would have
1755 /// also yielded an error.
1756 ///
1757 /// [io::Result]: self::Result "io::Result"
1758 /// [`read_until`]: BufRead::read_until
1759 ///
1760 /// # Examples
1761 ///
1762 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1763 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1764 /// segments in a byte slice
1765 ///
1766 /// ```
1767 /// use std::io::{self, BufRead};
1768 ///
1769 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1770 ///
1771 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1772 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1773 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1774 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1775 /// assert_eq!(split_iter.next(), None);
1776 /// ```
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 fn split(self, byte: u8) -> Split<Self>
1779 where
1780 Self: Sized,
1781 {
1782 Split { buf: self, delim: byte }
1783 }
1784
1785 /// Returns an iterator over the lines of this reader.
1786 ///
1787 /// The iterator returned from this function will yield instances of
1788 /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
1789 /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
1790 ///
1791 /// [io::Result]: self::Result "io::Result"
1792 ///
1793 /// # Examples
1794 ///
1795 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1796 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1797 /// slice.
1798 ///
1799 /// ```
1800 /// use std::io::{self, BufRead};
1801 ///
1802 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1803 ///
1804 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1805 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1806 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1807 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1808 /// assert_eq!(lines_iter.next(), None);
1809 /// ```
1810 ///
1811 /// # Errors
1812 ///
1813 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 fn lines(self) -> Lines<Self>
1816 where
1817 Self: Sized,
1818 {
1819 Lines { buf: self }
1820 }
1821}
1822
1823#[stable(feature = "rust1", since = "1.0.0")]
1824impl<T: Read, U: Read> Read for Chain<T, U> {
1825 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1826 if !self.done_first {
1827 match self.first.read(buf)? {
1828 0 if !buf.is_empty() => self.done_first = true,
1829 n => return Ok(n),
1830 }
1831 }
1832 self.second.read(buf)
1833 }
1834
1835 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
1836 if !self.done_first {
1837 match self.first.read_vectored(bufs)? {
1838 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
1839 n => return Ok(n),
1840 }
1841 }
1842 self.second.read_vectored(bufs)
1843 }
1844
1845 #[inline]
1846 fn is_read_vectored(&self) -> bool {
1847 self.first.is_read_vectored() || self.second.is_read_vectored()
1848 }
1849
1850 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
1851 let mut read = 0;
1852 if !self.done_first {
1853 read += self.first.read_to_end(buf)?;
1854 self.done_first = true;
1855 }
1856 read += self.second.read_to_end(buf)?;
1857 Ok(read)
1858 }
1859
1860 // We don't override `read_to_string` here because an UTF-8 sequence could
1861 // be split between the two parts of the chain
1862
1863 fn read_buf(&mut self, mut buf: BorrowedCursor<'_, u8>) -> Result<()> {
1864 if buf.capacity() == 0 {
1865 return Ok(());
1866 }
1867
1868 if !self.done_first {
1869 let old_len = buf.written();
1870 self.first.read_buf(buf.reborrow())?;
1871
1872 if buf.written() != old_len {
1873 return Ok(());
1874 } else {
1875 self.done_first = true;
1876 }
1877 }
1878 self.second.read_buf(buf)
1879 }
1880}
1881
1882#[stable(feature = "chain_bufread", since = "1.9.0")]
1883impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1884 fn fill_buf(&mut self) -> Result<&[u8]> {
1885 if !self.done_first {
1886 match self.first.fill_buf()? {
1887 buf if buf.is_empty() => self.done_first = true,
1888 buf => return Ok(buf),
1889 }
1890 }
1891 self.second.fill_buf()
1892 }
1893
1894 fn consume(&mut self, amt: usize) {
1895 if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
1896 }
1897
1898 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1899 let mut read = 0;
1900 if !self.done_first {
1901 let n = self.first.read_until(byte, buf)?;
1902 read += n;
1903
1904 match buf.last() {
1905 Some(b) if *b == byte && n != 0 => return Ok(read),
1906 _ => self.done_first = true,
1907 }
1908 }
1909 read += self.second.read_until(byte, buf)?;
1910 Ok(read)
1911 }
1912
1913 // We don't override `read_line` here because an UTF-8 sequence could be
1914 // split between the two parts of the chain
1915}
1916
1917#[stable(feature = "rust1", since = "1.0.0")]
1918impl<T: Read> Read for Take<T> {
1919 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1920 // Don't call into inner reader at all at EOF because it may still block
1921 if self.limit == 0 {
1922 return Ok(0);
1923 }
1924
1925 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1926 let n = self.inner.read(&mut buf[..max])?;
1927 assert!(n as u64 <= self.limit, "number of read bytes exceeds limit");
1928 self.limit -= n as u64;
1929 Ok(n)
1930 }
1931
1932 fn read_buf(&mut self, mut buf: BorrowedCursor<'_, u8>) -> Result<()> {
1933 // Don't call into inner reader at all at EOF because it may still block
1934 if self.limit == 0 {
1935 return Ok(());
1936 }
1937
1938 if self.limit < buf.capacity() as u64 {
1939 // The condition above guarantees that `self.limit` fits in `usize`.
1940 let limit = self.limit as usize;
1941
1942 let is_init = buf.is_init();
1943
1944 // SAFETY: no uninit data is written to ibuf
1945 let mut sliced_buf = BorrowedBuf::from(unsafe { &mut buf.as_mut()[..limit] });
1946
1947 if is_init {
1948 // SAFETY: `sliced_buf` is a subslice of `buf`, so if `buf` was initialized then
1949 // `sliced_buf` is.
1950 unsafe { sliced_buf.set_init() };
1951 }
1952
1953 let result = self.inner.read_buf(sliced_buf.unfilled());
1954
1955 let did_init_up_to_limit = sliced_buf.is_init();
1956 let filled = sliced_buf.len();
1957
1958 // sliced_buf must drop here
1959
1960 // Avoid accidentally quadratic behaviour by initializing the whole
1961 // cursor if only part of it was initialized.
1962 if did_init_up_to_limit && !is_init {
1963 // SAFETY: No uninit data will be written.
1964 let unfilled_before_advance = unsafe { buf.as_mut() };
1965
1966 unfilled_before_advance[limit..].write_filled(0);
1967
1968 // SAFETY: `unfilled_before_advance[..limit]` was initialized by `T::read_buf`, and
1969 // `unfilled_before_advance[limit..]` was just initialized.
1970 unsafe { buf.set_init() };
1971 }
1972
1973 unsafe {
1974 // SAFETY: filled bytes have been filled
1975 buf.advance(filled);
1976 }
1977
1978 self.limit -= filled as u64;
1979
1980 result
1981 } else {
1982 let written = buf.written();
1983 let result = self.inner.read_buf(buf.reborrow());
1984 self.limit -= (buf.written() - written) as u64;
1985 result
1986 }
1987 }
1988}
1989
1990#[stable(feature = "rust1", since = "1.0.0")]
1991impl<T: BufRead> BufRead for Take<T> {
1992 fn fill_buf(&mut self) -> Result<&[u8]> {
1993 // Don't call into inner reader at all at EOF because it may still block
1994 if self.limit == 0 {
1995 return Ok(&[]);
1996 }
1997
1998 let buf = self.inner.fill_buf()?;
1999 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2000 Ok(&buf[..cap])
2001 }
2002
2003 fn consume(&mut self, amt: usize) {
2004 // Don't let callers reset the limit by passing an overlarge value
2005 let amt = cmp::min(amt as u64, self.limit) as usize;
2006 self.limit -= amt as u64;
2007 self.inner.consume(amt);
2008 }
2009}
2010
2011/// An iterator over `u8` values of a reader.
2012///
2013/// This struct is generally created by calling [`bytes`] on a reader.
2014/// Please see the documentation of [`bytes`] for more details.
2015///
2016/// [`bytes`]: Read::bytes
2017#[stable(feature = "rust1", since = "1.0.0")]
2018#[derive(Debug)]
2019pub struct Bytes<R> {
2020 inner: R,
2021}
2022
2023#[stable(feature = "rust1", since = "1.0.0")]
2024impl<R: Read> Iterator for Bytes<R> {
2025 type Item = Result<u8>;
2026
2027 // Not `#[inline]`. This function gets inlined even without it, but having
2028 // the inline annotation can result in worse code generation. See #116785.
2029 fn next(&mut self) -> Option<Result<u8>> {
2030 SpecReadByte::spec_read_byte(&mut self.inner)
2031 }
2032
2033 #[inline]
2034 fn size_hint(&self) -> (usize, Option<usize>) {
2035 SizeHint::size_hint(&self.inner)
2036 }
2037}
2038
2039/// For the specialization of `Bytes::next`.
2040trait SpecReadByte {
2041 fn spec_read_byte(&mut self) -> Option<Result<u8>>;
2042}
2043
2044impl<R> SpecReadByte for R
2045where
2046 Self: Read,
2047{
2048 #[inline]
2049 default fn spec_read_byte(&mut self) -> Option<Result<u8>> {
2050 inlined_slow_read_byte(self)
2051 }
2052}
2053
2054/// Reads a single byte in a slow, generic way. This is used by the default
2055/// `spec_read_byte`.
2056#[inline]
2057fn inlined_slow_read_byte<R: Read>(reader: &mut R) -> Option<Result<u8>> {
2058 let mut byte = 0;
2059 loop {
2060 return match reader.read(slice::from_mut(&mut byte)) {
2061 Ok(0) => None,
2062 Ok(..) => Some(Ok(byte)),
2063 Err(ref e) if e.is_interrupted() => continue,
2064 Err(e) => Some(Err(e)),
2065 };
2066 }
2067}
2068
2069// Used by `BufReader::spec_read_byte`, for which the `inline(never)` is
2070// important.
2071#[inline(never)]
2072fn uninlined_slow_read_byte<R: Read>(reader: &mut R) -> Option<Result<u8>> {
2073 inlined_slow_read_byte(reader)
2074}
2075
2076/// An iterator over the contents of an instance of `BufRead` split on a
2077/// particular byte.
2078///
2079/// This struct is generally created by calling [`split`] on a `BufRead`.
2080/// Please see the documentation of [`split`] for more details.
2081///
2082/// [`split`]: BufRead::split
2083#[stable(feature = "rust1", since = "1.0.0")]
2084#[derive(Debug)]
2085#[cfg_attr(not(test), rustc_diagnostic_item = "IoSplit")]
2086pub struct Split<B> {
2087 buf: B,
2088 delim: u8,
2089}
2090
2091#[stable(feature = "rust1", since = "1.0.0")]
2092impl<B: BufRead> Iterator for Split<B> {
2093 type Item = Result<Vec<u8>>;
2094
2095 fn next(&mut self) -> Option<Result<Vec<u8>>> {
2096 let mut buf = Vec::new();
2097 match self.buf.read_until(self.delim, &mut buf) {
2098 Ok(0) => None,
2099 Ok(_n) => {
2100 if buf[buf.len() - 1] == self.delim {
2101 buf.pop();
2102 }
2103 Some(Ok(buf))
2104 }
2105 Err(e) => Some(Err(e)),
2106 }
2107 }
2108}
2109
2110/// An iterator over the lines of an instance of `BufRead`.
2111///
2112/// This struct is generally created by calling [`lines`] on a `BufRead`.
2113/// Please see the documentation of [`lines`] for more details.
2114///
2115/// [`lines`]: BufRead::lines
2116#[stable(feature = "rust1", since = "1.0.0")]
2117#[derive(Debug)]
2118#[cfg_attr(not(test), rustc_diagnostic_item = "IoLines")]
2119pub struct Lines<B> {
2120 buf: B,
2121}
2122
2123#[stable(feature = "rust1", since = "1.0.0")]
2124impl<B: BufRead> Iterator for Lines<B> {
2125 type Item = Result<String>;
2126
2127 fn next(&mut self) -> Option<Result<String>> {
2128 let mut buf = String::new();
2129 match self.buf.read_line(&mut buf) {
2130 Ok(0) => None,
2131 Ok(_n) => {
2132 if buf.ends_with('\n') {
2133 buf.pop();
2134 if buf.ends_with('\r') {
2135 buf.pop();
2136 }
2137 }
2138 Some(Ok(buf))
2139 }
2140 Err(e) => Some(Err(e)),
2141 }
2142 }
2143}
2144
2145/// Trait for types that can be converted from a fixed-size byte array with a specified endianness
2146#[unstable(feature = "read_le_be_internals", reason = "internals", issue = "none")]
2147// Once we can use associated consts in the types of method parameters, rewrite this to have
2148// `from_le_bytes` and `from_be_bytes` methods, move it to `core`, and make it public.
2149pub trait FromEndianBytes: crate::sealed::Sealed + Sized {
2150 #[doc(hidden)]
2151 fn read_le_from(r: &mut impl Read) -> Result<Self>;
2152
2153 #[doc(hidden)]
2154 fn read_be_from(r: &mut impl Read) -> Result<Self>;
2155}
2156
2157macro_rules! impl_from_endian_bytes {
2158 ($($t:ty),*$(,)?) => {$(
2159 #[unstable(feature = "read_le_be_internals", reason = "internals", issue = "none")]
2160 impl FromEndianBytes for $t {
2161 #[inline]
2162 fn read_le_from(r: &mut impl Read) -> Result<Self> {
2163 Ok(<$t>::from_le_bytes(r.read_array()?))
2164 }
2165
2166 #[inline]
2167 fn read_be_from(r: &mut impl Read) -> Result<Self> {
2168 Ok(<$t>::from_be_bytes(r.read_array()?))
2169 }
2170 }
2171 )*};
2172}
2173
2174impl_from_endian_bytes!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64);