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