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