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