]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/mod.rs
Update const_forget.rs
[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     /// If the buffer contains no data, this will never call [`write`].
1331     ///
1332     /// # Errors
1333     ///
1334     /// This function will return the first error of
1335     /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1336     ///
1337     /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1338     /// [`write`]: #tymethod.write
1339     ///
1340     /// # Examples
1341     ///
1342     /// ```no_run
1343     /// use std::io::prelude::*;
1344     /// use std::fs::File;
1345     ///
1346     /// fn main() -> std::io::Result<()> {
1347     ///     let mut buffer = File::create("foo.txt")?;
1348     ///
1349     ///     buffer.write_all(b"some bytes")?;
1350     ///     Ok(())
1351     /// }
1352     /// ```
1353     #[stable(feature = "rust1", since = "1.0.0")]
1354     fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1355         while !buf.is_empty() {
1356             match self.write(buf) {
1357                 Ok(0) => {
1358                     return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1359                 }
1360                 Ok(n) => buf = &buf[n..],
1361                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1362                 Err(e) => return Err(e),
1363             }
1364         }
1365         Ok(())
1366     }
1367
1368     /// Writes a formatted string into this writer, returning any error
1369     /// encountered.
1370     ///
1371     /// This method is primarily used to interface with the
1372     /// [`format_args!`][formatargs] macro, but it is rare that this should
1373     /// explicitly be called. The [`write!`][write] macro should be favored to
1374     /// invoke this method instead.
1375     ///
1376     /// [formatargs]: ../macro.format_args.html
1377     /// [write]: ../macro.write.html
1378     ///
1379     /// This function internally uses the [`write_all`][writeall] method on
1380     /// this trait and hence will continuously write data so long as no errors
1381     /// are received. This also means that partial writes are not indicated in
1382     /// this signature.
1383     ///
1384     /// [writeall]: #method.write_all
1385     ///
1386     /// # Errors
1387     ///
1388     /// This function will return any I/O error reported while formatting.
1389     ///
1390     /// # Examples
1391     ///
1392     /// ```no_run
1393     /// use std::io::prelude::*;
1394     /// use std::fs::File;
1395     ///
1396     /// fn main() -> std::io::Result<()> {
1397     ///     let mut buffer = File::create("foo.txt")?;
1398     ///
1399     ///     // this call
1400     ///     write!(buffer, "{:.*}", 2, 1.234567)?;
1401     ///     // turns into this:
1402     ///     buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1403     ///     Ok(())
1404     /// }
1405     /// ```
1406     #[stable(feature = "rust1", since = "1.0.0")]
1407     fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1408         // Create a shim which translates a Write to a fmt::Write and saves
1409         // off I/O errors. instead of discarding them
1410         struct Adaptor<'a, T: ?Sized + 'a> {
1411             inner: &'a mut T,
1412             error: Result<()>,
1413         }
1414
1415         impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1416             fn write_str(&mut self, s: &str) -> fmt::Result {
1417                 match self.inner.write_all(s.as_bytes()) {
1418                     Ok(()) => Ok(()),
1419                     Err(e) => {
1420                         self.error = Err(e);
1421                         Err(fmt::Error)
1422                     }
1423                 }
1424             }
1425         }
1426
1427         let mut output = Adaptor { inner: self, error: Ok(()) };
1428         match fmt::write(&mut output, fmt) {
1429             Ok(()) => Ok(()),
1430             Err(..) => {
1431                 // check if the error came from the underlying `Write` or not
1432                 if output.error.is_err() {
1433                     output.error
1434                 } else {
1435                     Err(Error::new(ErrorKind::Other, "formatter error"))
1436                 }
1437             }
1438         }
1439     }
1440
1441     /// Creates a "by reference" adaptor for this instance of `Write`.
1442     ///
1443     /// The returned adaptor also implements `Write` and will simply borrow this
1444     /// current writer.
1445     ///
1446     /// # Examples
1447     ///
1448     /// ```no_run
1449     /// use std::io::Write;
1450     /// use std::fs::File;
1451     ///
1452     /// fn main() -> std::io::Result<()> {
1453     ///     let mut buffer = File::create("foo.txt")?;
1454     ///
1455     ///     let reference = buffer.by_ref();
1456     ///
1457     ///     // we can use reference just like our original buffer
1458     ///     reference.write_all(b"some bytes")?;
1459     ///     Ok(())
1460     /// }
1461     /// ```
1462     #[stable(feature = "rust1", since = "1.0.0")]
1463     fn by_ref(&mut self) -> &mut Self
1464     where
1465         Self: Sized,
1466     {
1467         self
1468     }
1469 }
1470
1471 /// The `Seek` trait provides a cursor which can be moved within a stream of
1472 /// bytes.
1473 ///
1474 /// The stream typically has a fixed size, allowing seeking relative to either
1475 /// end or the current offset.
1476 ///
1477 /// # Examples
1478 ///
1479 /// [`File`][file]s implement `Seek`:
1480 ///
1481 /// [file]: ../fs/struct.File.html
1482 ///
1483 /// ```no_run
1484 /// use std::io;
1485 /// use std::io::prelude::*;
1486 /// use std::fs::File;
1487 /// use std::io::SeekFrom;
1488 ///
1489 /// fn main() -> io::Result<()> {
1490 ///     let mut f = File::open("foo.txt")?;
1491 ///
1492 ///     // move the cursor 42 bytes from the start of the file
1493 ///     f.seek(SeekFrom::Start(42))?;
1494 ///     Ok(())
1495 /// }
1496 /// ```
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 pub trait Seek {
1499     /// Seek to an offset, in bytes, in a stream.
1500     ///
1501     /// A seek beyond the end of a stream is allowed, but behavior is defined
1502     /// by the implementation.
1503     ///
1504     /// If the seek operation completed successfully,
1505     /// this method returns the new position from the start of the stream.
1506     /// That position can be used later with [`SeekFrom::Start`].
1507     ///
1508     /// # Errors
1509     ///
1510     /// Seeking to a negative offset is considered an error.
1511     ///
1512     /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1513     #[stable(feature = "rust1", since = "1.0.0")]
1514     fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1515
1516     /// Returns the length of this stream (in bytes).
1517     ///
1518     /// This method is implemented using up to three seek operations. If this
1519     /// method returns successfully, the seek position is unchanged (i.e. the
1520     /// position before calling this method is the same as afterwards).
1521     /// However, if this method returns an error, the seek position is
1522     /// unspecified.
1523     ///
1524     /// If you need to obtain the length of *many* streams and you don't care
1525     /// about the seek position afterwards, you can reduce the number of seek
1526     /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1527     /// return value (it is also the stream length).
1528     ///
1529     /// Note that length of a stream can change over time (for example, when
1530     /// data is appended to a file). So calling this method multiple times does
1531     /// not necessarily return the same length each time.
1532     ///
1533     ///
1534     /// # Example
1535     ///
1536     /// ```no_run
1537     /// #![feature(seek_convenience)]
1538     /// use std::{
1539     ///     io::{self, Seek},
1540     ///     fs::File,
1541     /// };
1542     ///
1543     /// fn main() -> io::Result<()> {
1544     ///     let mut f = File::open("foo.txt")?;
1545     ///
1546     ///     let len = f.stream_len()?;
1547     ///     println!("The file is currently {} bytes long", len);
1548     ///     Ok(())
1549     /// }
1550     /// ```
1551     #[unstable(feature = "seek_convenience", issue = "59359")]
1552     fn stream_len(&mut self) -> Result<u64> {
1553         let old_pos = self.stream_position()?;
1554         let len = self.seek(SeekFrom::End(0))?;
1555
1556         // Avoid seeking a third time when we were already at the end of the
1557         // stream. The branch is usually way cheaper than a seek operation.
1558         if old_pos != len {
1559             self.seek(SeekFrom::Start(old_pos))?;
1560         }
1561
1562         Ok(len)
1563     }
1564
1565     /// Returns the current seek position from the start of the stream.
1566     ///
1567     /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1568     ///
1569     ///
1570     /// # Example
1571     ///
1572     /// ```no_run
1573     /// #![feature(seek_convenience)]
1574     /// use std::{
1575     ///     io::{self, BufRead, BufReader, Seek},
1576     ///     fs::File,
1577     /// };
1578     ///
1579     /// fn main() -> io::Result<()> {
1580     ///     let mut f = BufReader::new(File::open("foo.txt")?);
1581     ///
1582     ///     let before = f.stream_position()?;
1583     ///     f.read_line(&mut String::new())?;
1584     ///     let after = f.stream_position()?;
1585     ///
1586     ///     println!("The first line was {} bytes long", after - before);
1587     ///     Ok(())
1588     /// }
1589     /// ```
1590     #[unstable(feature = "seek_convenience", issue = "59359")]
1591     fn stream_position(&mut self) -> Result<u64> {
1592         self.seek(SeekFrom::Current(0))
1593     }
1594 }
1595
1596 /// Enumeration of possible methods to seek within an I/O object.
1597 ///
1598 /// It is used by the [`Seek`] trait.
1599 ///
1600 /// [`Seek`]: trait.Seek.html
1601 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1602 #[stable(feature = "rust1", since = "1.0.0")]
1603 pub enum SeekFrom {
1604     /// Sets the offset to the provided number of bytes.
1605     #[stable(feature = "rust1", since = "1.0.0")]
1606     Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1607
1608     /// Sets the offset to the size of this object plus the specified number of
1609     /// bytes.
1610     ///
1611     /// It is possible to seek beyond the end of an object, but it's an error to
1612     /// seek before byte 0.
1613     #[stable(feature = "rust1", since = "1.0.0")]
1614     End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1615
1616     /// Sets the offset to the current position plus the specified number of
1617     /// bytes.
1618     ///
1619     /// It is possible to seek beyond the end of an object, but it's an error to
1620     /// seek before byte 0.
1621     #[stable(feature = "rust1", since = "1.0.0")]
1622     Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1623 }
1624
1625 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1626     let mut read = 0;
1627     loop {
1628         let (done, used) = {
1629             let available = match r.fill_buf() {
1630                 Ok(n) => n,
1631                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1632                 Err(e) => return Err(e),
1633             };
1634             match memchr::memchr(delim, available) {
1635                 Some(i) => {
1636                     buf.extend_from_slice(&available[..=i]);
1637                     (true, i + 1)
1638                 }
1639                 None => {
1640                     buf.extend_from_slice(available);
1641                     (false, available.len())
1642                 }
1643             }
1644         };
1645         r.consume(used);
1646         read += used;
1647         if done || used == 0 {
1648             return Ok(read);
1649         }
1650     }
1651 }
1652
1653 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1654 /// to perform extra ways of reading.
1655 ///
1656 /// For example, reading line-by-line is inefficient without using a buffer, so
1657 /// if you want to read by line, you'll need `BufRead`, which includes a
1658 /// [`read_line`] method as well as a [`lines`] iterator.
1659 ///
1660 /// # Examples
1661 ///
1662 /// A locked standard input implements `BufRead`:
1663 ///
1664 /// ```no_run
1665 /// use std::io;
1666 /// use std::io::prelude::*;
1667 ///
1668 /// let stdin = io::stdin();
1669 /// for line in stdin.lock().lines() {
1670 ///     println!("{}", line.unwrap());
1671 /// }
1672 /// ```
1673 ///
1674 /// If you have something that implements [`Read`], you can use the [`BufReader`
1675 /// type][`BufReader`] to turn it into a `BufRead`.
1676 ///
1677 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1678 /// [`BufReader`] to the rescue!
1679 ///
1680 /// [`BufReader`]: struct.BufReader.html
1681 /// [`File`]: ../fs/struct.File.html
1682 /// [`read_line`]: #method.read_line
1683 /// [`lines`]: #method.lines
1684 /// [`Read`]: trait.Read.html
1685 ///
1686 /// ```no_run
1687 /// use std::io::{self, BufReader};
1688 /// use std::io::prelude::*;
1689 /// use std::fs::File;
1690 ///
1691 /// fn main() -> io::Result<()> {
1692 ///     let f = File::open("foo.txt")?;
1693 ///     let f = BufReader::new(f);
1694 ///
1695 ///     for line in f.lines() {
1696 ///         println!("{}", line.unwrap());
1697 ///     }
1698 ///
1699 ///     Ok(())
1700 /// }
1701 /// ```
1702 ///
1703 #[stable(feature = "rust1", since = "1.0.0")]
1704 pub trait BufRead: Read {
1705     /// Returns the contents of the internal buffer, filling it with more data
1706     /// from the inner reader if it is empty.
1707     ///
1708     /// This function is a lower-level call. It needs to be paired with the
1709     /// [`consume`] method to function properly. When calling this
1710     /// method, none of the contents will be "read" in the sense that later
1711     /// calling `read` may return the same contents. As such, [`consume`] must
1712     /// be called with the number of bytes that are consumed from this buffer to
1713     /// ensure that the bytes are never returned twice.
1714     ///
1715     /// [`consume`]: #tymethod.consume
1716     ///
1717     /// An empty buffer returned indicates that the stream has reached EOF.
1718     ///
1719     /// # Errors
1720     ///
1721     /// This function will return an I/O error if the underlying reader was
1722     /// read, but returned an error.
1723     ///
1724     /// # Examples
1725     ///
1726     /// A locked standard input implements `BufRead`:
1727     ///
1728     /// ```no_run
1729     /// use std::io;
1730     /// use std::io::prelude::*;
1731     ///
1732     /// let stdin = io::stdin();
1733     /// let mut stdin = stdin.lock();
1734     ///
1735     /// let buffer = stdin.fill_buf().unwrap();
1736     ///
1737     /// // work with buffer
1738     /// println!("{:?}", buffer);
1739     ///
1740     /// // ensure the bytes we worked with aren't returned again later
1741     /// let length = buffer.len();
1742     /// stdin.consume(length);
1743     /// ```
1744     #[stable(feature = "rust1", since = "1.0.0")]
1745     fn fill_buf(&mut self) -> Result<&[u8]>;
1746
1747     /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1748     /// so they should no longer be returned in calls to `read`.
1749     ///
1750     /// This function is a lower-level call. It needs to be paired with the
1751     /// [`fill_buf`] method to function properly. This function does
1752     /// not perform any I/O, it simply informs this object that some amount of
1753     /// its buffer, returned from [`fill_buf`], has been consumed and should
1754     /// no longer be returned. As such, this function may do odd things if
1755     /// [`fill_buf`] isn't called before calling it.
1756     ///
1757     /// The `amt` must be `<=` the number of bytes in the buffer returned by
1758     /// [`fill_buf`].
1759     ///
1760     /// # Examples
1761     ///
1762     /// Since `consume()` is meant to be used with [`fill_buf`],
1763     /// that method's example includes an example of `consume()`.
1764     ///
1765     /// [`fill_buf`]: #tymethod.fill_buf
1766     #[stable(feature = "rust1", since = "1.0.0")]
1767     fn consume(&mut self, amt: usize);
1768
1769     /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1770     ///
1771     /// This function will read bytes from the underlying stream until the
1772     /// delimiter or EOF is found. Once found, all bytes up to, and including,
1773     /// the delimiter (if found) will be appended to `buf`.
1774     ///
1775     /// If successful, this function will return the total number of bytes read.
1776     ///
1777     /// # Errors
1778     ///
1779     /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1780     /// will otherwise return any errors returned by [`fill_buf`].
1781     ///
1782     /// If an I/O error is encountered then all bytes read so far will be
1783     /// present in `buf` and its length will have been adjusted appropriately.
1784     ///
1785     /// [`fill_buf`]: #tymethod.fill_buf
1786     /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1787     ///
1788     /// # Examples
1789     ///
1790     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1791     /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1792     /// in hyphen delimited segments:
1793     ///
1794     /// [`Cursor`]: struct.Cursor.html
1795     ///
1796     /// ```
1797     /// use std::io::{self, BufRead};
1798     ///
1799     /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1800     /// let mut buf = vec![];
1801     ///
1802     /// // cursor is at 'l'
1803     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1804     ///     .expect("reading from cursor won't fail");
1805     /// assert_eq!(num_bytes, 6);
1806     /// assert_eq!(buf, b"lorem-");
1807     /// buf.clear();
1808     ///
1809     /// // cursor is at 'i'
1810     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1811     ///     .expect("reading from cursor won't fail");
1812     /// assert_eq!(num_bytes, 5);
1813     /// assert_eq!(buf, b"ipsum");
1814     /// buf.clear();
1815     ///
1816     /// // cursor is at EOF
1817     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1818     ///     .expect("reading from cursor won't fail");
1819     /// assert_eq!(num_bytes, 0);
1820     /// assert_eq!(buf, b"");
1821     /// ```
1822     #[stable(feature = "rust1", since = "1.0.0")]
1823     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1824         read_until(self, byte, buf)
1825     }
1826
1827     /// Read all bytes until a newline (the 0xA byte) is reached, and append
1828     /// them to the provided buffer.
1829     ///
1830     /// This function will read bytes from the underlying stream until the
1831     /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1832     /// up to, and including, the delimiter (if found) will be appended to
1833     /// `buf`.
1834     ///
1835     /// If successful, this function will return the total number of bytes read.
1836     ///
1837     /// If this function returns `Ok(0)`, the stream has reached EOF.
1838     ///
1839     /// # Errors
1840     ///
1841     /// This function has the same error semantics as [`read_until`] and will
1842     /// also return an error if the read bytes are not valid UTF-8. If an I/O
1843     /// error is encountered then `buf` may contain some bytes already read in
1844     /// the event that all data read so far was valid UTF-8.
1845     ///
1846     /// [`read_until`]: #method.read_until
1847     ///
1848     /// # Examples
1849     ///
1850     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1851     /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1852     ///
1853     /// [`Cursor`]: struct.Cursor.html
1854     ///
1855     /// ```
1856     /// use std::io::{self, BufRead};
1857     ///
1858     /// let mut cursor = io::Cursor::new(b"foo\nbar");
1859     /// let mut buf = String::new();
1860     ///
1861     /// // cursor is at 'f'
1862     /// let num_bytes = cursor.read_line(&mut buf)
1863     ///     .expect("reading from cursor won't fail");
1864     /// assert_eq!(num_bytes, 4);
1865     /// assert_eq!(buf, "foo\n");
1866     /// buf.clear();
1867     ///
1868     /// // cursor is at 'b'
1869     /// let num_bytes = cursor.read_line(&mut buf)
1870     ///     .expect("reading from cursor won't fail");
1871     /// assert_eq!(num_bytes, 3);
1872     /// assert_eq!(buf, "bar");
1873     /// buf.clear();
1874     ///
1875     /// // cursor is at EOF
1876     /// let num_bytes = cursor.read_line(&mut buf)
1877     ///     .expect("reading from cursor won't fail");
1878     /// assert_eq!(num_bytes, 0);
1879     /// assert_eq!(buf, "");
1880     /// ```
1881     #[stable(feature = "rust1", since = "1.0.0")]
1882     fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1883         // Note that we are not calling the `.read_until` method here, but
1884         // rather our hardcoded implementation. For more details as to why, see
1885         // the comments in `read_to_end`.
1886         append_to_string(buf, |b| read_until(self, b'\n', b))
1887     }
1888
1889     /// Returns an iterator over the contents of this reader split on the byte
1890     /// `byte`.
1891     ///
1892     /// The iterator returned from this function will return instances of
1893     /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1894     /// the delimiter byte at the end.
1895     ///
1896     /// This function will yield errors whenever [`read_until`] would have
1897     /// also yielded an error.
1898     ///
1899     /// [`io::Result`]: type.Result.html
1900     /// [`Vec<u8>`]: ../vec/struct.Vec.html
1901     /// [`read_until`]: #method.read_until
1902     ///
1903     /// # Examples
1904     ///
1905     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1906     /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1907     /// segments in a byte slice
1908     ///
1909     /// [`Cursor`]: struct.Cursor.html
1910     ///
1911     /// ```
1912     /// use std::io::{self, BufRead};
1913     ///
1914     /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1915     ///
1916     /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1917     /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1918     /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1919     /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1920     /// assert_eq!(split_iter.next(), None);
1921     /// ```
1922     #[stable(feature = "rust1", since = "1.0.0")]
1923     fn split(self, byte: u8) -> Split<Self>
1924     where
1925         Self: Sized,
1926     {
1927         Split { buf: self, delim: byte }
1928     }
1929
1930     /// Returns an iterator over the lines of this reader.
1931     ///
1932     /// The iterator returned from this function will yield instances of
1933     /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1934     /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1935     ///
1936     /// [`io::Result`]: type.Result.html
1937     /// [`String`]: ../string/struct.String.html
1938     ///
1939     /// # Examples
1940     ///
1941     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1942     /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1943     /// slice.
1944     ///
1945     /// [`Cursor`]: struct.Cursor.html
1946     ///
1947     /// ```
1948     /// use std::io::{self, BufRead};
1949     ///
1950     /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1951     ///
1952     /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1953     /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1954     /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1955     /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1956     /// assert_eq!(lines_iter.next(), None);
1957     /// ```
1958     ///
1959     /// # Errors
1960     ///
1961     /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1962     ///
1963     /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1964     #[stable(feature = "rust1", since = "1.0.0")]
1965     fn lines(self) -> Lines<Self>
1966     where
1967         Self: Sized,
1968     {
1969         Lines { buf: self }
1970     }
1971 }
1972
1973 /// Adaptor to chain together two readers.
1974 ///
1975 /// This struct is generally created by calling [`chain`] on a reader.
1976 /// Please see the documentation of [`chain`] for more details.
1977 ///
1978 /// [`chain`]: trait.Read.html#method.chain
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 pub struct Chain<T, U> {
1981     first: T,
1982     second: U,
1983     done_first: bool,
1984 }
1985
1986 impl<T, U> Chain<T, U> {
1987     /// Consumes the `Chain`, returning the wrapped readers.
1988     ///
1989     /// # Examples
1990     ///
1991     /// ```no_run
1992     /// use std::io;
1993     /// use std::io::prelude::*;
1994     /// use std::fs::File;
1995     ///
1996     /// fn main() -> io::Result<()> {
1997     ///     let mut foo_file = File::open("foo.txt")?;
1998     ///     let mut bar_file = File::open("bar.txt")?;
1999     ///
2000     ///     let chain = foo_file.chain(bar_file);
2001     ///     let (foo_file, bar_file) = chain.into_inner();
2002     ///     Ok(())
2003     /// }
2004     /// ```
2005     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2006     pub fn into_inner(self) -> (T, U) {
2007         (self.first, self.second)
2008     }
2009
2010     /// Gets references to the underlying readers in this `Chain`.
2011     ///
2012     /// # Examples
2013     ///
2014     /// ```no_run
2015     /// use std::io;
2016     /// use std::io::prelude::*;
2017     /// use std::fs::File;
2018     ///
2019     /// fn main() -> io::Result<()> {
2020     ///     let mut foo_file = File::open("foo.txt")?;
2021     ///     let mut bar_file = File::open("bar.txt")?;
2022     ///
2023     ///     let chain = foo_file.chain(bar_file);
2024     ///     let (foo_file, bar_file) = chain.get_ref();
2025     ///     Ok(())
2026     /// }
2027     /// ```
2028     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2029     pub fn get_ref(&self) -> (&T, &U) {
2030         (&self.first, &self.second)
2031     }
2032
2033     /// Gets mutable references to the underlying readers in this `Chain`.
2034     ///
2035     /// Care should be taken to avoid modifying the internal I/O state of the
2036     /// underlying readers as doing so may corrupt the internal state of this
2037     /// `Chain`.
2038     ///
2039     /// # Examples
2040     ///
2041     /// ```no_run
2042     /// use std::io;
2043     /// use std::io::prelude::*;
2044     /// use std::fs::File;
2045     ///
2046     /// fn main() -> io::Result<()> {
2047     ///     let mut foo_file = File::open("foo.txt")?;
2048     ///     let mut bar_file = File::open("bar.txt")?;
2049     ///
2050     ///     let mut chain = foo_file.chain(bar_file);
2051     ///     let (foo_file, bar_file) = chain.get_mut();
2052     ///     Ok(())
2053     /// }
2054     /// ```
2055     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2056     pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2057         (&mut self.first, &mut self.second)
2058     }
2059 }
2060
2061 #[stable(feature = "std_debug", since = "1.16.0")]
2062 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
2063     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2064         f.debug_struct("Chain").field("t", &self.first).field("u", &self.second).finish()
2065     }
2066 }
2067
2068 #[stable(feature = "rust1", since = "1.0.0")]
2069 impl<T: Read, U: Read> Read for Chain<T, U> {
2070     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2071         if !self.done_first {
2072             match self.first.read(buf)? {
2073                 0 if !buf.is_empty() => self.done_first = true,
2074                 n => return Ok(n),
2075             }
2076         }
2077         self.second.read(buf)
2078     }
2079
2080     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2081         if !self.done_first {
2082             match self.first.read_vectored(bufs)? {
2083                 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2084                 n => return Ok(n),
2085             }
2086         }
2087         self.second.read_vectored(bufs)
2088     }
2089
2090     unsafe fn initializer(&self) -> Initializer {
2091         let initializer = self.first.initializer();
2092         if initializer.should_initialize() { initializer } else { self.second.initializer() }
2093     }
2094 }
2095
2096 #[stable(feature = "chain_bufread", since = "1.9.0")]
2097 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2098     fn fill_buf(&mut self) -> Result<&[u8]> {
2099         if !self.done_first {
2100             match self.first.fill_buf()? {
2101                 buf if buf.is_empty() => {
2102                     self.done_first = true;
2103                 }
2104                 buf => return Ok(buf),
2105             }
2106         }
2107         self.second.fill_buf()
2108     }
2109
2110     fn consume(&mut self, amt: usize) {
2111         if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2112     }
2113 }
2114
2115 /// Reader adaptor which limits the bytes read from an underlying reader.
2116 ///
2117 /// This struct is generally created by calling [`take`] on a reader.
2118 /// Please see the documentation of [`take`] for more details.
2119 ///
2120 /// [`take`]: trait.Read.html#method.take
2121 #[stable(feature = "rust1", since = "1.0.0")]
2122 #[derive(Debug)]
2123 pub struct Take<T> {
2124     inner: T,
2125     limit: u64,
2126 }
2127
2128 impl<T> Take<T> {
2129     /// Returns the number of bytes that can be read before this instance will
2130     /// return EOF.
2131     ///
2132     /// # Note
2133     ///
2134     /// This instance may reach `EOF` after reading fewer bytes than indicated by
2135     /// this method if the underlying [`Read`] instance reaches EOF.
2136     ///
2137     /// [`Read`]: ../../std/io/trait.Read.html
2138     ///
2139     /// # Examples
2140     ///
2141     /// ```no_run
2142     /// use std::io;
2143     /// use std::io::prelude::*;
2144     /// use std::fs::File;
2145     ///
2146     /// fn main() -> io::Result<()> {
2147     ///     let f = File::open("foo.txt")?;
2148     ///
2149     ///     // read at most five bytes
2150     ///     let handle = f.take(5);
2151     ///
2152     ///     println!("limit: {}", handle.limit());
2153     ///     Ok(())
2154     /// }
2155     /// ```
2156     #[stable(feature = "rust1", since = "1.0.0")]
2157     pub fn limit(&self) -> u64 {
2158         self.limit
2159     }
2160
2161     /// Sets the number of bytes that can be read before this instance will
2162     /// return EOF. This is the same as constructing a new `Take` instance, so
2163     /// the amount of bytes read and the previous limit value don't matter when
2164     /// calling this method.
2165     ///
2166     /// # Examples
2167     ///
2168     /// ```no_run
2169     /// use std::io;
2170     /// use std::io::prelude::*;
2171     /// use std::fs::File;
2172     ///
2173     /// fn main() -> io::Result<()> {
2174     ///     let f = File::open("foo.txt")?;
2175     ///
2176     ///     // read at most five bytes
2177     ///     let mut handle = f.take(5);
2178     ///     handle.set_limit(10);
2179     ///
2180     ///     assert_eq!(handle.limit(), 10);
2181     ///     Ok(())
2182     /// }
2183     /// ```
2184     #[stable(feature = "take_set_limit", since = "1.27.0")]
2185     pub fn set_limit(&mut self, limit: u64) {
2186         self.limit = limit;
2187     }
2188
2189     /// Consumes the `Take`, returning the wrapped reader.
2190     ///
2191     /// # Examples
2192     ///
2193     /// ```no_run
2194     /// use std::io;
2195     /// use std::io::prelude::*;
2196     /// use std::fs::File;
2197     ///
2198     /// fn main() -> io::Result<()> {
2199     ///     let mut file = File::open("foo.txt")?;
2200     ///
2201     ///     let mut buffer = [0; 5];
2202     ///     let mut handle = file.take(5);
2203     ///     handle.read(&mut buffer)?;
2204     ///
2205     ///     let file = handle.into_inner();
2206     ///     Ok(())
2207     /// }
2208     /// ```
2209     #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2210     pub fn into_inner(self) -> T {
2211         self.inner
2212     }
2213
2214     /// Gets a reference to the underlying reader.
2215     ///
2216     /// # Examples
2217     ///
2218     /// ```no_run
2219     /// use std::io;
2220     /// use std::io::prelude::*;
2221     /// use std::fs::File;
2222     ///
2223     /// fn main() -> io::Result<()> {
2224     ///     let mut file = File::open("foo.txt")?;
2225     ///
2226     ///     let mut buffer = [0; 5];
2227     ///     let mut handle = file.take(5);
2228     ///     handle.read(&mut buffer)?;
2229     ///
2230     ///     let file = handle.get_ref();
2231     ///     Ok(())
2232     /// }
2233     /// ```
2234     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2235     pub fn get_ref(&self) -> &T {
2236         &self.inner
2237     }
2238
2239     /// Gets a mutable reference to the underlying reader.
2240     ///
2241     /// Care should be taken to avoid modifying the internal I/O state of the
2242     /// underlying reader as doing so may corrupt the internal limit of this
2243     /// `Take`.
2244     ///
2245     /// # Examples
2246     ///
2247     /// ```no_run
2248     /// use std::io;
2249     /// use std::io::prelude::*;
2250     /// use std::fs::File;
2251     ///
2252     /// fn main() -> io::Result<()> {
2253     ///     let mut file = File::open("foo.txt")?;
2254     ///
2255     ///     let mut buffer = [0; 5];
2256     ///     let mut handle = file.take(5);
2257     ///     handle.read(&mut buffer)?;
2258     ///
2259     ///     let file = handle.get_mut();
2260     ///     Ok(())
2261     /// }
2262     /// ```
2263     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2264     pub fn get_mut(&mut self) -> &mut T {
2265         &mut self.inner
2266     }
2267 }
2268
2269 #[stable(feature = "rust1", since = "1.0.0")]
2270 impl<T: Read> Read for Take<T> {
2271     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2272         // Don't call into inner reader at all at EOF because it may still block
2273         if self.limit == 0 {
2274             return Ok(0);
2275         }
2276
2277         let max = cmp::min(buf.len() as u64, self.limit) as usize;
2278         let n = self.inner.read(&mut buf[..max])?;
2279         self.limit -= n as u64;
2280         Ok(n)
2281     }
2282
2283     unsafe fn initializer(&self) -> Initializer {
2284         self.inner.initializer()
2285     }
2286
2287     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2288         // Pass in a reservation_size closure that respects the current value
2289         // of limit for each read. If we hit the read limit, this prevents the
2290         // final zero-byte read from allocating again.
2291         read_to_end_with_reservation(self, buf, |self_| cmp::min(self_.limit, 32) as usize)
2292     }
2293 }
2294
2295 #[stable(feature = "rust1", since = "1.0.0")]
2296 impl<T: BufRead> BufRead for Take<T> {
2297     fn fill_buf(&mut self) -> Result<&[u8]> {
2298         // Don't call into inner reader at all at EOF because it may still block
2299         if self.limit == 0 {
2300             return Ok(&[]);
2301         }
2302
2303         let buf = self.inner.fill_buf()?;
2304         let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2305         Ok(&buf[..cap])
2306     }
2307
2308     fn consume(&mut self, amt: usize) {
2309         // Don't let callers reset the limit by passing an overlarge value
2310         let amt = cmp::min(amt as u64, self.limit) as usize;
2311         self.limit -= amt as u64;
2312         self.inner.consume(amt);
2313     }
2314 }
2315
2316 /// An iterator over `u8` values of a reader.
2317 ///
2318 /// This struct is generally created by calling [`bytes`] on a reader.
2319 /// Please see the documentation of [`bytes`] for more details.
2320 ///
2321 /// [`bytes`]: trait.Read.html#method.bytes
2322 #[stable(feature = "rust1", since = "1.0.0")]
2323 #[derive(Debug)]
2324 pub struct Bytes<R> {
2325     inner: R,
2326 }
2327
2328 #[stable(feature = "rust1", since = "1.0.0")]
2329 impl<R: Read> Iterator for Bytes<R> {
2330     type Item = Result<u8>;
2331
2332     fn next(&mut self) -> Option<Result<u8>> {
2333         let mut byte = 0;
2334         loop {
2335             return match self.inner.read(slice::from_mut(&mut byte)) {
2336                 Ok(0) => None,
2337                 Ok(..) => Some(Ok(byte)),
2338                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2339                 Err(e) => Some(Err(e)),
2340             };
2341         }
2342     }
2343 }
2344
2345 /// An iterator over the contents of an instance of `BufRead` split on a
2346 /// particular byte.
2347 ///
2348 /// This struct is generally created by calling [`split`] on a `BufRead`.
2349 /// Please see the documentation of [`split`] for more details.
2350 ///
2351 /// [`split`]: trait.BufRead.html#method.split
2352 #[stable(feature = "rust1", since = "1.0.0")]
2353 #[derive(Debug)]
2354 pub struct Split<B> {
2355     buf: B,
2356     delim: u8,
2357 }
2358
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 impl<B: BufRead> Iterator for Split<B> {
2361     type Item = Result<Vec<u8>>;
2362
2363     fn next(&mut self) -> Option<Result<Vec<u8>>> {
2364         let mut buf = Vec::new();
2365         match self.buf.read_until(self.delim, &mut buf) {
2366             Ok(0) => None,
2367             Ok(_n) => {
2368                 if buf[buf.len() - 1] == self.delim {
2369                     buf.pop();
2370                 }
2371                 Some(Ok(buf))
2372             }
2373             Err(e) => Some(Err(e)),
2374         }
2375     }
2376 }
2377
2378 /// An iterator over the lines of an instance of `BufRead`.
2379 ///
2380 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2381 /// Please see the documentation of [`lines`] for more details.
2382 ///
2383 /// [`lines`]: trait.BufRead.html#method.lines
2384 #[stable(feature = "rust1", since = "1.0.0")]
2385 #[derive(Debug)]
2386 pub struct Lines<B> {
2387     buf: B,
2388 }
2389
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 impl<B: BufRead> Iterator for Lines<B> {
2392     type Item = Result<String>;
2393
2394     fn next(&mut self) -> Option<Result<String>> {
2395         let mut buf = String::new();
2396         match self.buf.read_line(&mut buf) {
2397             Ok(0) => None,
2398             Ok(_n) => {
2399                 if buf.ends_with('\n') {
2400                     buf.pop();
2401                     if buf.ends_with('\r') {
2402                         buf.pop();
2403                     }
2404                 }
2405                 Some(Ok(buf))
2406             }
2407             Err(e) => Some(Err(e)),
2408         }
2409     }
2410 }
2411
2412 #[cfg(test)]
2413 mod tests {
2414     use super::{repeat, Cursor, SeekFrom};
2415     use crate::cmp;
2416     use crate::io::prelude::*;
2417     use crate::io::{self, IoSlice, IoSliceMut};
2418     use crate::ops::Deref;
2419
2420     #[test]
2421     #[cfg_attr(target_os = "emscripten", ignore)]
2422     fn read_until() {
2423         let mut buf = Cursor::new(&b"12"[..]);
2424         let mut v = Vec::new();
2425         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2426         assert_eq!(v, b"12");
2427
2428         let mut buf = Cursor::new(&b"1233"[..]);
2429         let mut v = Vec::new();
2430         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2431         assert_eq!(v, b"123");
2432         v.truncate(0);
2433         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2434         assert_eq!(v, b"3");
2435         v.truncate(0);
2436         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2437         assert_eq!(v, []);
2438     }
2439
2440     #[test]
2441     fn split() {
2442         let buf = Cursor::new(&b"12"[..]);
2443         let mut s = buf.split(b'3');
2444         assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2445         assert!(s.next().is_none());
2446
2447         let buf = Cursor::new(&b"1233"[..]);
2448         let mut s = buf.split(b'3');
2449         assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2450         assert_eq!(s.next().unwrap().unwrap(), vec![]);
2451         assert!(s.next().is_none());
2452     }
2453
2454     #[test]
2455     fn read_line() {
2456         let mut buf = Cursor::new(&b"12"[..]);
2457         let mut v = String::new();
2458         assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2459         assert_eq!(v, "12");
2460
2461         let mut buf = Cursor::new(&b"12\n\n"[..]);
2462         let mut v = String::new();
2463         assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2464         assert_eq!(v, "12\n");
2465         v.truncate(0);
2466         assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2467         assert_eq!(v, "\n");
2468         v.truncate(0);
2469         assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2470         assert_eq!(v, "");
2471     }
2472
2473     #[test]
2474     fn lines() {
2475         let buf = Cursor::new(&b"12\r"[..]);
2476         let mut s = buf.lines();
2477         assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2478         assert!(s.next().is_none());
2479
2480         let buf = Cursor::new(&b"12\r\n\n"[..]);
2481         let mut s = buf.lines();
2482         assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2483         assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2484         assert!(s.next().is_none());
2485     }
2486
2487     #[test]
2488     fn read_to_end() {
2489         let mut c = Cursor::new(&b""[..]);
2490         let mut v = Vec::new();
2491         assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2492         assert_eq!(v, []);
2493
2494         let mut c = Cursor::new(&b"1"[..]);
2495         let mut v = Vec::new();
2496         assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2497         assert_eq!(v, b"1");
2498
2499         let cap = 1024 * 1024;
2500         let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2501         let mut v = Vec::new();
2502         let (a, b) = data.split_at(data.len() / 2);
2503         assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2504         assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2505         assert_eq!(v, data);
2506     }
2507
2508     #[test]
2509     fn read_to_string() {
2510         let mut c = Cursor::new(&b""[..]);
2511         let mut v = String::new();
2512         assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2513         assert_eq!(v, "");
2514
2515         let mut c = Cursor::new(&b"1"[..]);
2516         let mut v = String::new();
2517         assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2518         assert_eq!(v, "1");
2519
2520         let mut c = Cursor::new(&b"\xff"[..]);
2521         let mut v = String::new();
2522         assert!(c.read_to_string(&mut v).is_err());
2523     }
2524
2525     #[test]
2526     fn read_exact() {
2527         let mut buf = [0; 4];
2528
2529         let mut c = Cursor::new(&b""[..]);
2530         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2531
2532         let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2533         c.read_exact(&mut buf).unwrap();
2534         assert_eq!(&buf, b"1234");
2535         c.read_exact(&mut buf).unwrap();
2536         assert_eq!(&buf, b"5678");
2537         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2538     }
2539
2540     #[test]
2541     fn read_exact_slice() {
2542         let mut buf = [0; 4];
2543
2544         let mut c = &b""[..];
2545         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2546
2547         let mut c = &b"123"[..];
2548         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
2549         // make sure the optimized (early returning) method is being used
2550         assert_eq!(&buf, &[0; 4]);
2551
2552         let mut c = &b"1234"[..];
2553         c.read_exact(&mut buf).unwrap();
2554         assert_eq!(&buf, b"1234");
2555
2556         let mut c = &b"56789"[..];
2557         c.read_exact(&mut buf).unwrap();
2558         assert_eq!(&buf, b"5678");
2559         assert_eq!(c, b"9");
2560     }
2561
2562     #[test]
2563     fn take_eof() {
2564         struct R;
2565
2566         impl Read for R {
2567             fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2568                 Err(io::Error::new(io::ErrorKind::Other, ""))
2569             }
2570         }
2571         impl BufRead for R {
2572             fn fill_buf(&mut self) -> io::Result<&[u8]> {
2573                 Err(io::Error::new(io::ErrorKind::Other, ""))
2574             }
2575             fn consume(&mut self, _amt: usize) {}
2576         }
2577
2578         let mut buf = [0; 1];
2579         assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2580         assert_eq!(b"", R.take(0).fill_buf().unwrap());
2581     }
2582
2583     fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2584         let mut cat = Vec::new();
2585         loop {
2586             let consume = {
2587                 let buf1 = br1.fill_buf().unwrap();
2588                 let buf2 = br2.fill_buf().unwrap();
2589                 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2590                 assert_eq!(buf1[..minlen], buf2[..minlen]);
2591                 cat.extend_from_slice(&buf1[..minlen]);
2592                 minlen
2593             };
2594             if consume == 0 {
2595                 break;
2596             }
2597             br1.consume(consume);
2598             br2.consume(consume);
2599         }
2600         assert_eq!(br1.fill_buf().unwrap().len(), 0);
2601         assert_eq!(br2.fill_buf().unwrap().len(), 0);
2602         assert_eq!(&cat[..], &exp[..])
2603     }
2604
2605     #[test]
2606     fn chain_bufread() {
2607         let testdata = b"ABCDEFGHIJKL";
2608         let chain1 =
2609             (&testdata[..3]).chain(&testdata[3..6]).chain(&testdata[6..9]).chain(&testdata[9..]);
2610         let chain2 = (&testdata[..4]).chain(&testdata[4..8]).chain(&testdata[8..]);
2611         cmp_bufread(chain1, chain2, &testdata[..]);
2612     }
2613
2614     #[test]
2615     fn chain_zero_length_read_is_not_eof() {
2616         let a = b"A";
2617         let b = b"B";
2618         let mut s = String::new();
2619         let mut chain = (&a[..]).chain(&b[..]);
2620         chain.read(&mut []).unwrap();
2621         chain.read_to_string(&mut s).unwrap();
2622         assert_eq!("AB", s);
2623     }
2624
2625     #[bench]
2626     #[cfg_attr(target_os = "emscripten", ignore)]
2627     fn bench_read_to_end(b: &mut test::Bencher) {
2628         b.iter(|| {
2629             let mut lr = repeat(1).take(10000000);
2630             let mut vec = Vec::with_capacity(1024);
2631             super::read_to_end(&mut lr, &mut vec)
2632         });
2633     }
2634
2635     #[test]
2636     fn seek_len() -> io::Result<()> {
2637         let mut c = Cursor::new(vec![0; 15]);
2638         assert_eq!(c.stream_len()?, 15);
2639
2640         c.seek(SeekFrom::End(0))?;
2641         let old_pos = c.stream_position()?;
2642         assert_eq!(c.stream_len()?, 15);
2643         assert_eq!(c.stream_position()?, old_pos);
2644
2645         c.seek(SeekFrom::Start(7))?;
2646         c.seek(SeekFrom::Current(2))?;
2647         let old_pos = c.stream_position()?;
2648         assert_eq!(c.stream_len()?, 15);
2649         assert_eq!(c.stream_position()?, old_pos);
2650
2651         Ok(())
2652     }
2653
2654     #[test]
2655     fn seek_position() -> io::Result<()> {
2656         // All `asserts` are duplicated here to make sure the method does not
2657         // change anything about the seek state.
2658         let mut c = Cursor::new(vec![0; 15]);
2659         assert_eq!(c.stream_position()?, 0);
2660         assert_eq!(c.stream_position()?, 0);
2661
2662         c.seek(SeekFrom::End(0))?;
2663         assert_eq!(c.stream_position()?, 15);
2664         assert_eq!(c.stream_position()?, 15);
2665
2666         c.seek(SeekFrom::Start(7))?;
2667         c.seek(SeekFrom::Current(2))?;
2668         assert_eq!(c.stream_position()?, 9);
2669         assert_eq!(c.stream_position()?, 9);
2670
2671         c.seek(SeekFrom::End(-3))?;
2672         c.seek(SeekFrom::Current(1))?;
2673         c.seek(SeekFrom::Current(-5))?;
2674         assert_eq!(c.stream_position()?, 8);
2675         assert_eq!(c.stream_position()?, 8);
2676
2677         Ok(())
2678     }
2679
2680     // A simple example reader which uses the default implementation of
2681     // read_to_end.
2682     struct ExampleSliceReader<'a> {
2683         slice: &'a [u8],
2684     }
2685
2686     impl<'a> Read for ExampleSliceReader<'a> {
2687         fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2688             let len = cmp::min(self.slice.len(), buf.len());
2689             buf[..len].copy_from_slice(&self.slice[..len]);
2690             self.slice = &self.slice[len..];
2691             Ok(len)
2692         }
2693     }
2694
2695     #[test]
2696     fn test_read_to_end_capacity() -> io::Result<()> {
2697         let input = &b"foo"[..];
2698
2699         // read_to_end() generally needs to over-allocate, both for efficiency
2700         // and so that it can distinguish EOF. Assert that this is the case
2701         // with this simple ExampleSliceReader struct, which uses the default
2702         // implementation of read_to_end. Even though vec1 is allocated with
2703         // exactly enough capacity for the read, read_to_end will allocate more
2704         // space here.
2705         let mut vec1 = Vec::with_capacity(input.len());
2706         ExampleSliceReader { slice: input }.read_to_end(&mut vec1)?;
2707         assert_eq!(vec1.len(), input.len());
2708         assert!(vec1.capacity() > input.len(), "allocated more");
2709
2710         // However, std::io::Take includes an implementation of read_to_end
2711         // that will not allocate when the limit has already been reached. In
2712         // this case, vec2 never grows.
2713         let mut vec2 = Vec::with_capacity(input.len());
2714         ExampleSliceReader { slice: input }.take(input.len() as u64).read_to_end(&mut vec2)?;
2715         assert_eq!(vec2.len(), input.len());
2716         assert_eq!(vec2.capacity(), input.len(), "did not allocate more");
2717
2718         Ok(())
2719     }
2720
2721     #[test]
2722     fn io_slice_mut_advance() {
2723         let mut buf1 = [1; 8];
2724         let mut buf2 = [2; 16];
2725         let mut buf3 = [3; 8];
2726         let mut bufs = &mut [
2727             IoSliceMut::new(&mut buf1),
2728             IoSliceMut::new(&mut buf2),
2729             IoSliceMut::new(&mut buf3),
2730         ][..];
2731
2732         // Only in a single buffer..
2733         bufs = IoSliceMut::advance(bufs, 1);
2734         assert_eq!(bufs[0].deref(), [1; 7].as_ref());
2735         assert_eq!(bufs[1].deref(), [2; 16].as_ref());
2736         assert_eq!(bufs[2].deref(), [3; 8].as_ref());
2737
2738         // Removing a buffer, leaving others as is.
2739         bufs = IoSliceMut::advance(bufs, 7);
2740         assert_eq!(bufs[0].deref(), [2; 16].as_ref());
2741         assert_eq!(bufs[1].deref(), [3; 8].as_ref());
2742
2743         // Removing a buffer and removing from the next buffer.
2744         bufs = IoSliceMut::advance(bufs, 18);
2745         assert_eq!(bufs[0].deref(), [3; 6].as_ref());
2746     }
2747
2748     #[test]
2749     fn io_slice_mut_advance_empty_slice() {
2750         let empty_bufs = &mut [][..];
2751         // Shouldn't panic.
2752         IoSliceMut::advance(empty_bufs, 1);
2753     }
2754
2755     #[test]
2756     fn io_slice_mut_advance_beyond_total_length() {
2757         let mut buf1 = [1; 8];
2758         let mut bufs = &mut [IoSliceMut::new(&mut buf1)][..];
2759
2760         // Going beyond the total length should be ok.
2761         bufs = IoSliceMut::advance(bufs, 9);
2762         assert!(bufs.is_empty());
2763     }
2764
2765     #[test]
2766     fn io_slice_advance() {
2767         let buf1 = [1; 8];
2768         let buf2 = [2; 16];
2769         let buf3 = [3; 8];
2770         let mut bufs = &mut [IoSlice::new(&buf1), IoSlice::new(&buf2), IoSlice::new(&buf3)][..];
2771
2772         // Only in a single buffer..
2773         bufs = IoSlice::advance(bufs, 1);
2774         assert_eq!(bufs[0].deref(), [1; 7].as_ref());
2775         assert_eq!(bufs[1].deref(), [2; 16].as_ref());
2776         assert_eq!(bufs[2].deref(), [3; 8].as_ref());
2777
2778         // Removing a buffer, leaving others as is.
2779         bufs = IoSlice::advance(bufs, 7);
2780         assert_eq!(bufs[0].deref(), [2; 16].as_ref());
2781         assert_eq!(bufs[1].deref(), [3; 8].as_ref());
2782
2783         // Removing a buffer and removing from the next buffer.
2784         bufs = IoSlice::advance(bufs, 18);
2785         assert_eq!(bufs[0].deref(), [3; 6].as_ref());
2786     }
2787
2788     #[test]
2789     fn io_slice_advance_empty_slice() {
2790         let empty_bufs = &mut [][..];
2791         // Shouldn't panic.
2792         IoSlice::advance(empty_bufs, 1);
2793     }
2794
2795     #[test]
2796     fn io_slice_advance_beyond_total_length() {
2797         let buf1 = [1; 8];
2798         let mut bufs = &mut [IoSlice::new(&buf1)][..];
2799
2800         // Going beyond the total length should be ok.
2801         bufs = IoSlice::advance(bufs, 9);
2802         assert!(bufs.is_empty());
2803     }
2804 }