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