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