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