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