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