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