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