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