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