Skip to main content

relibc/io/
mod.rs

1// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! Traits, helpers, and type definitions for core I/O functionality.
12//!
13//! The `std::io` module contains a number of common things you'll need
14//! when doing input and output. The most core part of this module is
15//! the [`Read`] and [`Write`] traits, which provide the
16//! most general interface for reading and writing input and output.
17//!
18//! # Read and Write
19//!
20//! Because they are traits, [`Read`] and [`Write`] are implemented by a number
21//! of other types, and you can implement them for your types too. As such,
22//! you'll see a few different types of I/O throughout the documentation in
23//! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
24//! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
25//! [`File`]s:
26//!
27//! ```no_run
28//! use std::io;
29//! use std::io::prelude::*;
30//! use std::fs::File;
31//!
32//! fn main() -> io::Result<()> {
33//!     let mut f = File::open("foo.txt")?;
34//!     let mut buffer = [0; 10];
35//!
36//!     // read up to 10 bytes
37//!     f.read(&mut buffer)?;
38//!
39//!     println!("The bytes: {:?}", buffer);
40//!     Ok(())
41//! }
42//! ```
43//!
44//! [`Read`] and [`Write`] are so important, implementors of the two traits have a
45//! nickname: readers and writers. So you'll sometimes see 'a reader' instead
46//! of 'a type that implements the [`Read`] trait'. Much easier!
47//!
48//! ## Seek and BufRead
49//!
50//! Beyond that, there are two important traits that are provided: [`Seek`]
51//! and [`BufRead`]. Both of these build on top of a reader to control
52//! how the reading happens. [`Seek`] lets you control where the next byte is
53//! coming from:
54//!
55//! ```no_run
56//! use std::io;
57//! use std::io::prelude::*;
58//! use std::io::SeekFrom;
59//! use std::fs::File;
60//!
61//! fn main() -> io::Result<()> {
62//!     let mut f = File::open("foo.txt")?;
63//!     let mut buffer = [0; 10];
64//!
65//!     // skip to the last 10 bytes of the file
66//!     f.seek(SeekFrom::End(-10))?;
67//!
68//!     // read up to 10 bytes
69//!     f.read(&mut buffer)?;
70//!
71//!     println!("The bytes: {:?}", buffer);
72//!     Ok(())
73//! }
74//! ```
75//!
76//! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
77//! to show it off, we'll need to talk about buffers in general. Keep reading!
78//!
79//! ## BufReader and BufWriter
80//!
81//! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
82//! making near-constant calls to the operating system. To help with this,
83//! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
84//! readers and writers. The wrapper uses a buffer, reducing the number of
85//! calls and providing nicer methods for accessing exactly what you want.
86//!
87//! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
88//! methods to any reader:
89//!
90//! ```no_run
91//! use std::io;
92//! use std::io::prelude::*;
93//! use std::io::BufReader;
94//! use std::fs::File;
95//!
96//! fn main() -> io::Result<()> {
97//!     let f = File::open("foo.txt")?;
98//!     let mut reader = BufReader::new(f);
99//!     let mut buffer = String::new();
100//!
101//!     // read a line into buffer
102//!     reader.read_line(&mut buffer)?;
103//!
104//!     println!("{}", buffer);
105//!     Ok(())
106//! }
107//! ```
108//!
109//! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
110//! to [`write`][`Write::write`]:
111//!
112//! ```no_run
113//! use std::io;
114//! use std::io::prelude::*;
115//! use std::io::BufWriter;
116//! use std::fs::File;
117//!
118//! fn main() -> io::Result<()> {
119//!     let f = File::create("foo.txt")?;
120//!     {
121//!         let mut writer = BufWriter::new(f);
122//!
123//!         // write a byte to the buffer
124//!         writer.write(&[42])?;
125//!
126//!     } // the buffer is flushed once writer goes out of scope
127//!
128//!     Ok(())
129//! }
130//! ```
131//!
132//! ## Standard input and output
133//!
134//! A very common source of input is standard input:
135//!
136//! ```no_run
137//! use std::io;
138//!
139//! fn main() -> io::Result<()> {
140//!     let mut input = String::new();
141//!
142//!     io::stdin().read_line(&mut input)?;
143//!
144//!     println!("You typed: {}", input.trim());
145//!     Ok(())
146//! }
147//! ```
148//!
149//! Note that you cannot use the [`?` operator] in functions that do not return
150//! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]
151//! or `match` on the return value to catch any possible errors:
152//!
153//! ```no_run
154//! use std::io;
155//!
156//! let mut input = String::new();
157//!
158//! io::stdin().read_line(&mut input).unwrap();
159//! ```
160//!
161//! And a very common source of output is standard output:
162//!
163//! ```no_run
164//! use std::io;
165//! use std::io::prelude::*;
166//!
167//! fn main() -> io::Result<()> {
168//!     io::stdout().write(&[42])?;
169//!     Ok(())
170//! }
171//! ```
172//!
173//! Of course, using [`io::stdout`] directly is less common than something like
174//! [`println!`].
175//!
176//! ## Iterator types
177//!
178//! A large number of the structures provided by `std::io` are for various
179//! ways of iterating over I/O. For example, [`Lines`] is used to split over
180//! lines:
181//!
182//! ```no_run
183//! use std::io;
184//! use std::io::prelude::*;
185//! use std::io::BufReader;
186//! use std::fs::File;
187//!
188//! fn main() -> io::Result<()> {
189//!     let f = File::open("foo.txt")?;
190//!     let reader = BufReader::new(f);
191//!
192//!     for line in reader.lines() {
193//!         println!("{}", line?);
194//!     }
195//!     Ok(())
196//! }
197//! ```
198//!
199//! ## Functions
200//!
201//! There are a number of [functions][functions-list] that offer access to various
202//! features. For example, we can use three of these functions to copy everything
203//! from standard input to standard output:
204//!
205//! ```no_run
206//! use std::io;
207//!
208//! fn main() -> io::Result<()> {
209//!     io::copy(&mut io::stdin(), &mut io::stdout())?;
210//!     Ok(())
211//! }
212//! ```
213//!
214//! [functions-list]: #functions-1
215//!
216//! ## io::Result
217//!
218//! Last, but certainly not least, is [`io::Result`]. This type is used
219//! as the return type of many `std::io` functions that can cause an error, and
220//! can be returned from your own functions as well. Many of the examples in this
221//! module use the [`?` operator]:
222//!
223//! ```
224//! use std::io;
225//!
226//! fn read_input() -> io::Result<()> {
227//!     let mut input = String::new();
228//!
229//!     io::stdin().read_line(&mut input)?;
230//!
231//!     println!("You typed: {}", input.trim());
232//!
233//!     Ok(())
234//! }
235//! ```
236//!
237//! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
238//! common type for functions which don't have a 'real' return value, but do want to
239//! return errors if they happen. In this case, the only purpose of this function is
240//! to read the line and print it, so we use `()`.
241//!
242//! ## Platform-specific behavior
243//!
244//! Many I/O functions throughout the standard library are documented to indicate
245//! what various library or syscalls they are delegated to. This is done to help
246//! applications both understand what's happening under the hood as well as investigate
247//! any possibly unclear semantics. Note, however, that this is informative, not a binding
248//! contract. The implementation of many of these functions are subject to change over
249//! time and may call fewer or more syscalls/library functions.
250//!
251//! [`Read`]: trait.Read.html
252//! [`Write`]: trait.Write.html
253//! [`Seek`]: trait.Seek.html
254//! [`BufRead`]: trait.BufRead.html
255//! [`File`]: ../fs/struct.File.html
256//! [`TcpStream`]: ../net/struct.TcpStream.html
257//! [`Vec<T>`]: ../vec/struct.Vec.html
258//! [`BufReader`]: struct.BufReader.html
259//! [`BufWriter`]: struct.BufWriter.html
260//! [`Write::write`]: trait.Write.html#tymethod.write
261//! [`io::stdout`]: fn.stdout.html
262//! [`println!`]: ../macro.println.html
263//! [`Lines`]: struct.Lines.html
264//! [`io::Result`]: type.Result.html
265//! [`?` operator]: ../../book/first-edition/syntax-index.html
266//! [`Read::read`]: trait.Read.html#tymethod.read
267//! [`Result`]: ../result/enum.Result.html
268//! [`.unwrap()`]: ../result/enum.Result.html#method.unwrap
269
270pub mod buffered;
271pub mod cursor;
272pub mod error;
273mod impls;
274pub mod prelude;
275
276use crate::out::Out;
277
278pub use self::{buffered::*, cursor::*, error::*};
279
280use self::prelude::*;
281
282use alloc::string::String;
283use core::{cmp, fmt, ptr, str};
284
285const DEFAULT_BUF_SIZE: usize = 8 * 1024;
286
287#[inline]
288pub fn last_os_error() -> Error {
289    Error::last_os_error()
290}
291
292struct Guard<'a> {
293    buf: &'a mut Vec<u8>,
294    len: usize,
295}
296
297impl<'a> Drop for Guard<'a> {
298    fn drop(&mut self) {
299        unsafe {
300            self.buf.set_len(self.len);
301        }
302    }
303}
304
305// A few methods below (read_to_string, read_line) will append data into a
306// `String` buffer, but we need to be pretty careful when doing this. The
307// implementation will just call `.as_mut_vec()` and then delegate to a
308// byte-oriented reading method, but we must ensure that when returning we never
309// leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
310//
311// To this end, we use an RAII guard (to protect against panics) which updates
312// the length of the string when it is dropped. This guard initially truncates
313// the string to the prior length and only after we've validated that the
314// new contents are valid UTF-8 do we allow it to set a longer length.
315//
316// The unsafety in this function is twofold:
317//
318// 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
319//    checks.
320// 2. We're passing a raw buffer to the function `f`, and it is expected that
321//    the function only *appends* bytes to the buffer. We'll get undefined
322//    behavior if existing bytes are overwritten to have non-UTF-8 data.
323fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
324where
325    F: FnOnce(&mut Vec<u8>) -> Result<usize>,
326{
327    unsafe {
328        let mut g = Guard {
329            len: buf.len(),
330            buf: buf.as_mut_vec(),
331        };
332        let ret = f(g.buf);
333        if str::from_utf8(&g.buf[g.len..]).is_err() {
334            ret.and_then(|_| {
335                Err(Error::new(
336                    ErrorKind::InvalidData,
337                    "stream did not contain valid UTF-8",
338                ))
339            })
340        } else {
341            g.len = g.buf.len();
342            ret
343        }
344    }
345}
346
347// This uses an adaptive system to extend the vector when it fills. We want to
348// avoid paying to allocate and zero a huge chunk of memory if the reader only
349// has 4 bytes while still making large reads if the reader does have a ton
350// of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
351// time is 4,500 times (!) slower than a default reservation size of 32 if the
352// reader has a very small amount of data to return.
353//
354// Because we're extending the buffer with uninitialized data for trusted
355// readers, we need to make sure to truncate that if any of this panics.
356fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
357    read_to_end_with_reservation(r, buf, 32)
358}
359
360fn read_to_end_with_reservation<R: Read + ?Sized>(
361    r: &mut R,
362    buf: &mut Vec<u8>,
363    reservation_size: usize,
364) -> Result<usize> {
365    let start_len = buf.len();
366    let mut g = Guard {
367        len: buf.len(),
368        buf,
369    };
370    let ret;
371    loop {
372        if g.len == g.buf.len() {
373            unsafe {
374                g.buf.reserve(reservation_size);
375                let capacity = g.buf.capacity();
376                g.buf.set_len(capacity);
377                r.initializer().initialize(&mut g.buf[g.len..]);
378            }
379        }
380
381        match r.read(&mut g.buf[g.len..]) {
382            Ok(0) => {
383                ret = Ok(g.len - start_len);
384                break;
385            }
386            Ok(n) => g.len += n,
387            Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
388            Err(e) => {
389                ret = Err(e);
390                break;
391            }
392        }
393    }
394
395    ret
396}
397
398fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
399    let mut read = 0;
400    loop {
401        let (done, used) = {
402            let available = match r.fill_buf() {
403                Ok(n) => n,
404                Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
405                Err(e) => return Err(e),
406            };
407            match memchr::memchr(delim, available) {
408                Some(i) => {
409                    buf.extend_from_slice(&available[..i + 1]);
410                    (true, i + 1)
411                }
412                None => {
413                    buf.extend_from_slice(available);
414                    (false, available.len())
415                }
416            }
417        };
418        r.consume(used);
419        read += used;
420        if done || used == 0 {
421            return Ok(read);
422        }
423    }
424}
425
426/// The `Read` trait allows for reading bytes from a source.
427///
428/// Implementors of the `Read` trait are called 'readers'.
429///
430/// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
431/// will attempt to pull bytes from this source into a provided buffer. A
432/// number of other methods are implemented in terms of [`read()`], giving
433/// implementors a number of ways to read bytes while only needing to implement
434/// a single method.
435///
436/// Readers are intended to be composable with one another. Many implementors
437/// throughout [`std::io`] take and provide types which implement the `Read`
438/// trait.
439///
440/// Please note that each call to [`read()`] may involve a system call, and
441/// therefore, using something that implements [`BufRead`], such as
442/// [`BufReader`], will be more efficient.
443///
444/// # Examples
445///
446/// [`File`]s implement `Read`:
447///
448/// ```no_run
449/// use std::io;
450/// use std::io::prelude::*;
451/// use std::fs::File;
452///
453/// fn main() -> io::Result<()> {
454///     let mut f = File::open("foo.txt")?;
455///     let mut buffer = [0; 10];
456///
457///     // read up to 10 bytes
458///     f.read(&mut buffer)?;
459///
460///     let mut buffer = vec![0; 10];
461///     // read the whole file
462///     f.read_to_end(&mut buffer)?;
463///
464///     // read into a String, so that you don't need to do the conversion.
465///     let mut buffer = String::new();
466///     f.read_to_string(&mut buffer)?;
467///
468///     // and more! See the other methods for more details.
469///     Ok(())
470/// }
471/// ```
472///
473/// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
474///
475/// ```no_run
476/// # use std::io;
477/// use std::io::prelude::*;
478///
479/// fn main() -> io::Result<()> {
480///     let mut b = "This string will be read".as_bytes();
481///     let mut buffer = [0; 10];
482///
483///     // read up to 10 bytes
484///     b.read(&mut buffer)?;
485///
486///     // etc... it works exactly as a File does!
487///     Ok(())
488/// }
489/// ```
490///
491/// [`read()`]: trait.Read.html#tymethod.read
492/// [`std::io`]: ../../std/io/index.html
493/// [`File`]: ../fs/struct.File.html
494/// [`BufRead`]: trait.BufRead.html
495/// [`BufReader`]: struct.BufReader.html
496/// [`&str`]: ../../std/primitive.str.html
497/// [slice]: ../../std/primitive.slice.html
498pub trait Read {
499    /// Pull some bytes from this source into the specified buffer, returning
500    /// how many bytes were read.
501    ///
502    /// This function does not provide any guarantees about whether it blocks
503    /// waiting for data, but if an object needs to block for a read but cannot
504    /// it will typically signal this via an [`Err`] return value.
505    ///
506    /// If the return value of this method is [`Ok(n)`], then it must be
507    /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
508    /// that the buffer `buf` has been filled in with `n` bytes of data from this
509    /// source. If `n` is `0`, then it can indicate one of two scenarios:
510    ///
511    /// 1. This reader has reached its "end of file" and will likely no longer
512    ///    be able to produce bytes. Note that this does not mean that the
513    ///    reader will *always* no longer be able to produce bytes.
514    /// 2. The buffer specified was 0 bytes in length.
515    ///
516    /// No guarantees are provided about the contents of `buf` when this
517    /// function is called, implementations cannot rely on any property of the
518    /// contents of `buf` being true. It is recommended that implementations
519    /// only write data to `buf` instead of reading its contents.
520    ///
521    /// # Errors
522    ///
523    /// If this function encounters any form of I/O or other error, an error
524    /// variant will be returned. If an error is returned then it must be
525    /// guaranteed that no bytes were read.
526    ///
527    /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
528    /// operation should be retried if there is nothing else to do.
529    ///
530    /// # Examples
531    ///
532    /// [`File`]s implement `Read`:
533    ///
534    /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
535    /// [`Ok(n)`]: ../../std/result/enum.Result.html#variant.Ok
536    /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
537    /// [`File`]: ../fs/struct.File.html
538    ///
539    /// ```no_run
540    /// use std::io;
541    /// use std::io::prelude::*;
542    /// use std::fs::File;
543    ///
544    /// fn main() -> io::Result<()> {
545    ///     let mut f = File::open("foo.txt")?;
546    ///     let mut buffer = [0; 10];
547    ///
548    ///     // read up to 10 bytes
549    ///     f.read(&mut buffer.as_slice())?;
550    ///     Ok(())
551    /// }
552    /// ```
553    fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
554
555    fn read_out(&mut self, mut out: Out<[u8]>) -> Result<usize> {
556        // XXX: Technically incorrect but hopefully not UB
557        let slice: &mut [u8] = unsafe { &mut *out.as_mut_ptr() };
558        self.read(slice)
559    }
560
561    /// Determines if this `Read`er can work with buffers of uninitialized
562    /// memory.
563    ///
564    /// The default implementation returns an initializer which will zero
565    /// buffers.
566    ///
567    /// If a `Read`er guarantees that it can work properly with uninitialized
568    /// memory, it should call [`Initializer::nop()`]. See the documentation for
569    /// [`Initializer`] for details.
570    ///
571    /// The behavior of this method must be independent of the state of the
572    /// `Read`er - the method only takes `&self` so that it can be used through
573    /// trait objects.
574    ///
575    /// # Safety
576    ///
577    /// This method is unsafe because a `Read`er could otherwise return a
578    /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
579    /// block.
580    ///
581    /// [`Initializer::nop()`]: ../../std/io/struct.Initializer.html#method.nop
582    /// [`Initializer`]: ../../std/io/struct.Initializer.html
583    #[inline]
584    unsafe fn initializer(&self) -> Initializer {
585        Initializer::zeroing()
586    }
587
588    /// Read all bytes until EOF in this source, placing them into `buf`.
589    ///
590    /// All bytes read from this source will be appended to the specified buffer
591    /// `buf`. This function will continuously call [`read()`] to append more data to
592    /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
593    /// non-[`ErrorKind::Interrupted`] kind.
594    ///
595    /// If successful, this function will return the total number of bytes read.
596    ///
597    /// # Errors
598    ///
599    /// If this function encounters an error of the kind
600    /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
601    /// will continue.
602    ///
603    /// If any other read error is encountered then this function immediately
604    /// returns. Any bytes which have already been read will be appended to
605    /// `buf`.
606    ///
607    /// # Examples
608    ///
609    /// [`File`]s implement `Read`:
610    ///
611    /// [`read()`]: trait.Read.html#tymethod.read
612    /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
613    /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
614    /// [`File`]: ../fs/struct.File.html
615    ///
616    /// ```no_run
617    /// use std::io;
618    /// use std::io::prelude::*;
619    /// use std::fs::File;
620    ///
621    /// fn main() -> io::Result<()> {
622    ///     let mut f = File::open("foo.txt")?;
623    ///     let mut buffer = Vec::new();
624    ///
625    ///     // read the whole file
626    ///     f.read_to_end(&mut buffer)?;
627    ///     Ok(())
628    /// }
629    /// ```
630    ///
631    /// (See also the [`std::fs::read`] convenience function for reading from a
632    /// file.)
633    ///
634    /// [`std::fs::read`]: ../fs/fn.read.html
635    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
636        read_to_end(self, buf)
637    }
638
639    /// Read all bytes until EOF in this source, appending them to `buf`.
640    ///
641    /// If successful, this function returns the number of bytes which were read
642    /// and appended to `buf`.
643    ///
644    /// # Errors
645    ///
646    /// If the data in this stream is *not* valid UTF-8 then an error is
647    /// returned and `buf` is unchanged.
648    ///
649    /// See [`read_to_end`][readtoend] for other error semantics.
650    ///
651    /// [readtoend]: #method.read_to_end
652    ///
653    /// # Examples
654    ///
655    /// [`File`][file]s implement `Read`:
656    ///
657    /// [file]: ../fs/struct.File.html
658    ///
659    /// ```no_run
660    /// use std::io;
661    /// use std::io::prelude::*;
662    /// use std::fs::File;
663    ///
664    /// fn main() -> io::Result<()> {
665    ///     let mut f = File::open("foo.txt")?;
666    ///     let mut buffer = String::new();
667    ///
668    ///     f.read_to_string(&mut buffer)?;
669    ///     Ok(())
670    /// }
671    /// ```
672    ///
673    /// (See also the [`std::fs::read_to_string`] convenience function for
674    /// reading from a file.)
675    ///
676    /// [`std::fs::read_to_string`]: ../fs/fn.read_to_string.html
677    fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
678        // Note that we do *not* call `.read_to_end()` here. We are passing
679        // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
680        // method to fill it up. An arbitrary implementation could overwrite the
681        // entire contents of the vector, not just append to it (which is what
682        // we are expecting).
683        //
684        // To prevent extraneously checking the UTF-8-ness of the entire buffer
685        // we pass it to our hardcoded `read_to_end` implementation which we
686        // know is guaranteed to only read data into the end of the buffer.
687        append_to_string(buf, |b| read_to_end(self, b))
688    }
689
690    /// Read the exact number of bytes required to fill `buf`.
691    ///
692    /// This function reads as many bytes as necessary to completely fill the
693    /// specified buffer `buf`.
694    ///
695    /// No guarantees are provided about the contents of `buf` when this
696    /// function is called, implementations cannot rely on any property of the
697    /// contents of `buf` being true. It is recommended that implementations
698    /// only write data to `buf` instead of reading its contents.
699    ///
700    /// # Errors
701    ///
702    /// If this function encounters an error of the kind
703    /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
704    /// will continue.
705    ///
706    /// If this function encounters an "end of file" before completely filling
707    /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
708    /// The contents of `buf` are unspecified in this case.
709    ///
710    /// If any other read error is encountered then this function immediately
711    /// returns. The contents of `buf` are unspecified in this case.
712    ///
713    /// If this function returns an error, it is unspecified how many bytes it
714    /// has read, but it will never read more than would be necessary to
715    /// completely fill the buffer.
716    ///
717    /// # Examples
718    ///
719    /// [`File`]s implement `Read`:
720    ///
721    /// [`File`]: ../fs/struct.File.html
722    /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
723    /// [`ErrorKind::UnexpectedEof`]: ../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
724    ///
725    /// ```no_run
726    /// use std::io;
727    /// use std::io::prelude::*;
728    /// use std::fs::File;
729    ///
730    /// fn main() -> io::Result<()> {
731    ///     let mut f = File::open("foo.txt")?;
732    ///     let mut buffer = [0; 10];
733    ///
734    ///     // read exactly 10 bytes
735    ///     f.read_exact(&mut buffer)?;
736    ///     Ok(())
737    /// }
738    /// ```
739    fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
740        while !buf.is_empty() {
741            match self.read(buf) {
742                Ok(0) => break,
743                Ok(n) => {
744                    let tmp = buf;
745                    buf = &mut tmp[n..];
746                }
747                Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
748                Err(e) => return Err(e),
749            }
750        }
751        if !buf.is_empty() {
752            Err(Error::new(
753                ErrorKind::UnexpectedEof,
754                "failed to fill whole buffer",
755            ))
756        } else {
757            Ok(())
758        }
759    }
760
761    /// Creates a "by reference" adaptor for this instance of `Read`.
762    ///
763    /// The returned adaptor also implements `Read` and will simply borrow this
764    /// current reader.
765    ///
766    /// # Examples
767    ///
768    /// [`File`][file]s implement `Read`:
769    ///
770    /// [file]: ../fs/struct.File.html
771    ///
772    /// ```no_run
773    /// use std::io;
774    /// use std::io::Read;
775    /// use std::fs::File;
776    ///
777    /// fn main() -> io::Result<()> {
778    ///     let mut f = File::open("foo.txt")?;
779    ///     let mut buffer = Vec::new();
780    ///     let mut other_buffer = Vec::new();
781    ///
782    ///     {
783    ///         let reference = f.by_ref();
784    ///
785    ///         // read at most 5 bytes
786    ///         reference.take(5).read_to_end(&mut buffer)?;
787    ///
788    ///     } // drop our &mut reference so we can use f again
789    ///
790    ///     // original file still usable, read the rest
791    ///     f.read_to_end(&mut other_buffer)?;
792    ///     Ok(())
793    /// }
794    /// ```
795    fn by_ref(&mut self) -> &mut Self
796    where
797        Self: Sized,
798    {
799        self
800    }
801
802    /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
803    ///
804    /// The returned type implements [`Iterator`] where the `Item` is
805    /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
806    /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
807    /// otherwise. EOF is mapped to returning [`None`] from this iterator.
808    ///
809    /// # Examples
810    ///
811    /// [`File`][file]s implement `Read`:
812    ///
813    /// [file]: ../fs/struct.File.html
814    /// [`Iterator`]: ../../std/iter/trait.Iterator.html
815    /// [`Result`]: ../../std/result/enum.Result.html
816    /// [`io::Error`]: ../../std/io/struct.Error.html
817    /// [`u8`]: ../../std/primitive.u8.html
818    /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
819    /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
820    /// [`None`]: ../../std/option/enum.Option.html#variant.None
821    ///
822    /// ```no_run
823    /// use std::io;
824    /// use std::io::prelude::*;
825    /// use std::fs::File;
826    ///
827    /// fn main() -> io::Result<()> {
828    ///     let mut f = File::open("foo.txt")?;
829    ///
830    ///     for byte in f.bytes() {
831    ///         println!("{}", byte.unwrap());
832    ///     }
833    ///     Ok(())
834    /// }
835    /// ```
836    fn bytes(self) -> Bytes<Self>
837    where
838        Self: Sized,
839    {
840        Bytes { inner: self }
841    }
842
843    /// Creates an adaptor which will chain this stream with another.
844    ///
845    /// The returned `Read` instance will first read all bytes from this object
846    /// until EOF is encountered. Afterwards the output is equivalent to the
847    /// output of `next`.
848    ///
849    /// # Examples
850    ///
851    /// [`File`][file]s implement `Read`:
852    ///
853    /// [file]: ../fs/struct.File.html
854    ///
855    /// ```no_run
856    /// use std::io;
857    /// use std::io::prelude::*;
858    /// use std::fs::File;
859    ///
860    /// fn main() -> io::Result<()> {
861    ///     let mut f1 = File::open("foo.txt")?;
862    ///     let mut f2 = File::open("bar.txt")?;
863    ///
864    ///     let mut handle = f1.chain(f2);
865    ///     let mut buffer = String::new();
866    ///
867    ///     // read the value into a String. We could use any Read method here,
868    ///     // this is just one example.
869    ///     handle.read_to_string(&mut buffer)?;
870    ///     Ok(())
871    /// }
872    /// ```
873    fn chain<R: Read>(self, next: R) -> Chain<Self, R>
874    where
875        Self: Sized,
876    {
877        Chain {
878            first: self,
879            second: next,
880            done_first: false,
881        }
882    }
883
884    /// Creates an adaptor which will read at most `limit` bytes from it.
885    ///
886    /// This function returns a new instance of `Read` which will read at most
887    /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
888    /// read errors will not count towards the number of bytes read and future
889    /// calls to [`read()`] may succeed.
890    ///
891    /// # Examples
892    ///
893    /// [`File`]s implement `Read`:
894    ///
895    /// [`File`]: ../fs/struct.File.html
896    /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
897    /// [`read()`]: trait.Read.html#tymethod.read
898    ///
899    /// ```no_run
900    /// use std::io;
901    /// use std::io::prelude::*;
902    /// use std::fs::File;
903    ///
904    /// fn main() -> io::Result<()> {
905    ///     let mut f = File::open("foo.txt")?;
906    ///     let mut buffer = [0; 5];
907    ///
908    ///     // read at most five bytes
909    ///     let mut handle = f.take(5);
910    ///
911    ///     handle.read(&mut buffer)?;
912    ///     Ok(())
913    /// }
914    /// ```
915    fn take(self, limit: u64) -> Take<Self>
916    where
917        Self: Sized,
918    {
919        Take { inner: self, limit }
920    }
921}
922
923fn read_one_byte(reader: &mut dyn Read) -> Option<Result<u8>> {
924    let mut buf = [0];
925    loop {
926        return match reader.read(&mut buf) {
927            Ok(0) => None,
928            Ok(..) => Some(Ok(buf[0])),
929            Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
930            Err(e) => Some(Err(e)),
931        };
932    }
933}
934
935/// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
936/// to perform extra ways of reading.
937///
938/// For example, reading line-by-line is inefficient without using a buffer, so
939/// if you want to read by line, you'll need `BufRead`, which includes a
940/// [`read_line`] method as well as a [`lines`] iterator.
941///
942/// # Examples
943///
944/// A locked standard input implements `BufRead`:
945///
946/// ```no_run
947/// use std::io;
948/// use std::io::prelude::*;
949///
950/// let stdin = io::stdin();
951/// for line in stdin.lock().lines() {
952///     println!("{}", line.unwrap());
953/// }
954/// ```
955///
956/// If you have something that implements [`Read`], you can use the [`BufReader`
957/// type][`BufReader`] to turn it into a `BufRead`.
958///
959/// For example, [`File`] implements [`Read`], but not `BufRead`.
960/// [`BufReader`] to the rescue!
961///
962/// [`BufReader`]: struct.BufReader.html
963/// [`File`]: ../fs/struct.File.html
964/// [`read_line`]: #method.read_line
965/// [`lines`]: #method.lines
966/// [`Read`]: trait.Read.html
967///
968/// ```no_run
969/// use std::io::{self, BufReader};
970/// use std::io::prelude::*;
971/// use std::fs::File;
972///
973/// fn main() -> io::Result<()> {
974///     let f = File::open("foo.txt")?;
975///     let f = BufReader::new(f);
976///
977///     for line in f.lines() {
978///         println!("{}", line.unwrap());
979///     }
980///
981///     Ok(())
982/// }
983/// ```
984///
985pub trait BufRead: Read {
986    /// Returns the contents of the internal buffer, filling it with more data
987    /// from the inner reader if it is empty.
988    ///
989    /// This function is a lower-level call. It needs to be paired with the
990    /// [`consume`] method to function properly. When calling this
991    /// method, none of the contents will be "read" in the sense that later
992    /// calling `read` may return the same contents. As such, [`consume`] must
993    /// be called with the number of bytes that are consumed from this buffer to
994    /// ensure that the bytes are never returned twice.
995    ///
996    /// [`consume`]: #tymethod.consume
997    ///
998    /// An empty buffer returned indicates that the stream has reached EOF.
999    ///
1000    /// # Errors
1001    ///
1002    /// This function will return an I/O error if the underlying reader was
1003    /// read, but returned an error.
1004    ///
1005    /// # Examples
1006    ///
1007    /// A locked standard input implements `BufRead`:
1008    ///
1009    /// ```no_run
1010    /// use std::io;
1011    /// use std::io::prelude::*;
1012    ///
1013    /// let stdin = io::stdin();
1014    /// let mut stdin = stdin.lock();
1015    ///
1016    /// // we can't have two `&mut` references to `stdin`, so use a block
1017    /// // to end the borrow early.
1018    /// let length = {
1019    ///     let buffer = stdin.fill_buf().unwrap();
1020    ///
1021    ///     // work with buffer
1022    ///     println!("{:?}", buffer);
1023    ///
1024    ///     buffer.len()
1025    /// };
1026    ///
1027    /// // ensure the bytes we worked with aren't returned again later
1028    /// stdin.consume(length);
1029    /// ```
1030    fn fill_buf(&mut self) -> Result<&[u8]>;
1031
1032    /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1033    /// so they should no longer be returned in calls to `read`.
1034    ///
1035    /// This function is a lower-level call. It needs to be paired with the
1036    /// [`fill_buf`] method to function properly. This function does
1037    /// not perform any I/O, it simply informs this object that some amount of
1038    /// its buffer, returned from [`fill_buf`], has been consumed and should
1039    /// no longer be returned. As such, this function may do odd things if
1040    /// [`fill_buf`] isn't called before calling it.
1041    ///
1042    /// The `amt` must be `<=` the number of bytes in the buffer returned by
1043    /// [`fill_buf`].
1044    ///
1045    /// # Examples
1046    ///
1047    /// Since `consume()` is meant to be used with [`fill_buf`],
1048    /// that method's example includes an example of `consume()`.
1049    ///
1050    /// [`fill_buf`]: #tymethod.fill_buf
1051    fn consume(&mut self, amt: usize);
1052
1053    /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1054    ///
1055    /// This function will read bytes from the underlying stream until the
1056    /// delimiter or EOF is found. Once found, all bytes up to, and including,
1057    /// the delimiter (if found) will be appended to `buf`.
1058    ///
1059    /// If successful, this function will return the total number of bytes read.
1060    ///
1061    /// # Errors
1062    ///
1063    /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1064    /// will otherwise return any errors returned by [`fill_buf`].
1065    ///
1066    /// If an I/O error is encountered then all bytes read so far will be
1067    /// present in `buf` and its length will have been adjusted appropriately.
1068    ///
1069    /// [`fill_buf`]: #tymethod.fill_buf
1070    /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1071    ///
1072    /// # Examples
1073    ///
1074    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1075    /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1076    /// in hyphen delimited segments:
1077    ///
1078    /// [`Cursor`]: struct.Cursor.html
1079    ///
1080    /// ```
1081    /// use std::io::{self, BufRead};
1082    ///
1083    /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1084    /// let mut buf = vec![];
1085    ///
1086    /// // cursor is at 'l'
1087    /// let num_bytes = cursor.read_until(b'-', &mut buf)
1088    ///     .expect("reading from cursor won't fail");
1089    /// assert_eq!(num_bytes, 6);
1090    /// assert_eq!(buf, b"lorem-");
1091    /// buf.clear();
1092    ///
1093    /// // cursor is at 'i'
1094    /// let num_bytes = cursor.read_until(b'-', &mut buf)
1095    ///     .expect("reading from cursor won't fail");
1096    /// assert_eq!(num_bytes, 5);
1097    /// assert_eq!(buf, b"ipsum");
1098    /// buf.clear();
1099    ///
1100    /// // cursor is at EOF
1101    /// let num_bytes = cursor.read_until(b'-', &mut buf)
1102    ///     .expect("reading from cursor won't fail");
1103    /// assert_eq!(num_bytes, 0);
1104    /// assert_eq!(buf, b"");
1105    /// ```
1106    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1107        read_until(self, byte, buf)
1108    }
1109
1110    /// Read all bytes until a newline (the 0xA byte) is reached, and append
1111    /// them to the provided buffer.
1112    ///
1113    /// This function will read bytes from the underlying stream until the
1114    /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1115    /// up to, and including, the delimiter (if found) will be appended to
1116    /// `buf`.
1117    ///
1118    /// If successful, this function will return the total number of bytes read.
1119    ///
1120    /// An empty buffer returned indicates that the stream has reached EOF.
1121    ///
1122    /// # Errors
1123    ///
1124    /// This function has the same error semantics as [`read_until`] and will
1125    /// also return an error if the read bytes are not valid UTF-8. If an I/O
1126    /// error is encountered then `buf` may contain some bytes already read in
1127    /// the event that all data read so far was valid UTF-8.
1128    ///
1129    /// [`read_until`]: #method.read_until
1130    ///
1131    /// # Examples
1132    ///
1133    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1134    /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1135    ///
1136    /// [`Cursor`]: struct.Cursor.html
1137    ///
1138    /// ```
1139    /// use std::io::{self, BufRead};
1140    ///
1141    /// let mut cursor = io::Cursor::new(b"foo\nbar");
1142    /// let mut buf = String::new();
1143    ///
1144    /// // cursor is at 'f'
1145    /// let num_bytes = cursor.read_line(&mut buf)
1146    ///     .expect("reading from cursor won't fail");
1147    /// assert_eq!(num_bytes, 4);
1148    /// assert_eq!(buf, "foo\n");
1149    /// buf.clear();
1150    ///
1151    /// // cursor is at 'b'
1152    /// let num_bytes = cursor.read_line(&mut buf)
1153    ///     .expect("reading from cursor won't fail");
1154    /// assert_eq!(num_bytes, 3);
1155    /// assert_eq!(buf, "bar");
1156    /// buf.clear();
1157    ///
1158    /// // cursor is at EOF
1159    /// let num_bytes = cursor.read_line(&mut buf)
1160    ///     .expect("reading from cursor won't fail");
1161    /// assert_eq!(num_bytes, 0);
1162    /// assert_eq!(buf, "");
1163    /// ```
1164    fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1165        // Note that we are not calling the `.read_until` method here, but
1166        // rather our hardcoded implementation. For more details as to why, see
1167        // the comments in `read_to_end`.
1168        append_to_string(buf, |b| read_until(self, b'\n', b))
1169    }
1170
1171    /// Returns an iterator over the contents of this reader split on the byte
1172    /// `byte`.
1173    ///
1174    /// The iterator returned from this function will return instances of
1175    /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1176    /// the delimiter byte at the end.
1177    ///
1178    /// This function will yield errors whenever [`read_until`] would have
1179    /// also yielded an error.
1180    ///
1181    /// [`io::Result`]: type.Result.html
1182    /// [`Vec<u8>`]: ../vec/struct.Vec.html
1183    /// [`read_until`]: #method.read_until
1184    ///
1185    /// # Examples
1186    ///
1187    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1188    /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1189    /// segments in a byte slice
1190    ///
1191    /// [`Cursor`]: struct.Cursor.html
1192    ///
1193    /// ```
1194    /// use std::io::{self, BufRead};
1195    ///
1196    /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1197    ///
1198    /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1199    /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1200    /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1201    /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1202    /// assert_eq!(split_iter.next(), None);
1203    /// ```
1204    fn split(self, byte: u8) -> Split<Self>
1205    where
1206        Self: Sized,
1207    {
1208        Split {
1209            buf: self,
1210            delim: byte,
1211        }
1212    }
1213
1214    /// Returns an iterator over the lines of this reader.
1215    ///
1216    /// The iterator returned from this function will yield instances of
1217    /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1218    /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1219    ///
1220    /// [`io::Result`]: type.Result.html
1221    /// [`String`]: ../string/struct.String.html
1222    ///
1223    /// # Examples
1224    ///
1225    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1226    /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1227    /// slice.
1228    ///
1229    /// [`Cursor`]: struct.Cursor.html
1230    ///
1231    /// ```
1232    /// use std::io::{self, BufRead};
1233    ///
1234    /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1235    ///
1236    /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1237    /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1238    /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1239    /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1240    /// assert_eq!(lines_iter.next(), None);
1241    /// ```
1242    ///
1243    /// # Errors
1244    ///
1245    /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1246    ///
1247    /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1248    fn lines(self) -> Lines<Self>
1249    where
1250        Self: Sized,
1251    {
1252        Lines { buf: self }
1253    }
1254}
1255
1256/// A type used to conditionally initialize buffers passed to `Read` methods.
1257#[derive(Debug)]
1258pub struct Initializer(bool);
1259
1260impl Initializer {
1261    /// Returns a new `Initializer` which will zero out buffers.
1262    #[inline]
1263    pub fn zeroing() -> Initializer {
1264        Initializer(true)
1265    }
1266
1267    /// Returns a new `Initializer` which will not zero out buffers.
1268    ///
1269    /// # Safety
1270    ///
1271    /// This may only be called by `Read`ers which guarantee that they will not
1272    /// read from buffers passed to `Read` methods, and that the return value of
1273    /// the method accurately reflects the number of bytes that have been
1274    /// written to the head of the buffer.
1275    #[inline]
1276    pub unsafe fn nop() -> Initializer {
1277        Initializer(false)
1278    }
1279
1280    /// Indicates if a buffer should be initialized.
1281    #[inline]
1282    pub fn should_initialize(&self) -> bool {
1283        self.0
1284    }
1285
1286    /// Initializes a buffer if necessary.
1287    #[inline]
1288    pub fn initialize(&self, buf: &mut [u8]) {
1289        if self.should_initialize() {
1290            unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1291        }
1292    }
1293}
1294
1295/// Adaptor to chain together two readers.
1296///
1297/// This struct is generally created by calling [`chain`] on a reader.
1298/// Please see the documentation of [`chain`] for more details.
1299///
1300/// [`chain`]: trait.Read.html#method.chain
1301pub struct Chain<T, U> {
1302    first: T,
1303    second: U,
1304    done_first: bool,
1305}
1306
1307impl<T, U> Chain<T, U> {
1308    /// Consumes the `Chain`, returning the wrapped readers.
1309    ///
1310    /// # Examples
1311    ///
1312    /// ```no_run
1313    /// use std::io;
1314    /// use std::io::prelude::*;
1315    /// use std::fs::File;
1316    ///
1317    /// fn main() -> io::Result<()> {
1318    ///     let mut foo_file = File::open("foo.txt")?;
1319    ///     let mut bar_file = File::open("bar.txt")?;
1320    ///
1321    ///     let chain = foo_file.chain(bar_file);
1322    ///     let (foo_file, bar_file) = chain.into_inner();
1323    ///     Ok(())
1324    /// }
1325    /// ```
1326    pub fn into_inner(self) -> (T, U) {
1327        (self.first, self.second)
1328    }
1329
1330    /// Gets references to the underlying readers in this `Chain`.
1331    ///
1332    /// # Examples
1333    ///
1334    /// ```no_run
1335    /// use std::io;
1336    /// use std::io::prelude::*;
1337    /// use std::fs::File;
1338    ///
1339    /// fn main() -> io::Result<()> {
1340    ///     let mut foo_file = File::open("foo.txt")?;
1341    ///     let mut bar_file = File::open("bar.txt")?;
1342    ///
1343    ///     let chain = foo_file.chain(bar_file);
1344    ///     let (foo_file, bar_file) = chain.get_ref();
1345    ///     Ok(())
1346    /// }
1347    /// ```
1348    pub fn get_ref(&self) -> (&T, &U) {
1349        (&self.first, &self.second)
1350    }
1351
1352    /// Gets mutable references to the underlying readers in this `Chain`.
1353    ///
1354    /// Care should be taken to avoid modifying the internal I/O state of the
1355    /// underlying readers as doing so may corrupt the internal state of this
1356    /// `Chain`.
1357    ///
1358    /// # Examples
1359    ///
1360    /// ```no_run
1361    /// use std::io;
1362    /// use std::io::prelude::*;
1363    /// use std::fs::File;
1364    ///
1365    /// fn main() -> io::Result<()> {
1366    ///     let mut foo_file = File::open("foo.txt")?;
1367    ///     let mut bar_file = File::open("bar.txt")?;
1368    ///
1369    ///     let mut chain = foo_file.chain(bar_file);
1370    ///     let (foo_file, bar_file) = chain.get_mut();
1371    ///     Ok(())
1372    /// }
1373    /// ```
1374    pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1375        (&mut self.first, &mut self.second)
1376    }
1377}
1378
1379impl<T: Read, U: Read> Read for Chain<T, U> {
1380    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1381        if !self.done_first {
1382            match self.first.read(buf)? {
1383                0 if !buf.is_empty() => {
1384                    self.done_first = true;
1385                }
1386                n => return Ok(n),
1387            }
1388        }
1389        self.second.read(buf)
1390    }
1391
1392    unsafe fn initializer(&self) -> Initializer {
1393        let initializer = unsafe { self.first.initializer() };
1394        if initializer.should_initialize() {
1395            initializer
1396        } else {
1397            unsafe { self.second.initializer() }
1398        }
1399    }
1400}
1401
1402impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1403    fn fill_buf(&mut self) -> Result<&[u8]> {
1404        if !self.done_first {
1405            match self.first.fill_buf()? {
1406                [] => {
1407                    self.done_first = true;
1408                }
1409                buf => return Ok(buf),
1410            }
1411        }
1412        self.second.fill_buf()
1413    }
1414
1415    fn consume(&mut self, amt: usize) {
1416        if !self.done_first {
1417            self.first.consume(amt)
1418        } else {
1419            self.second.consume(amt)
1420        }
1421    }
1422}
1423
1424/// Reader adaptor which limits the bytes read from an underlying reader.
1425///
1426/// This struct is generally created by calling [`take`] on a reader.
1427/// Please see the documentation of [`take`] for more details.
1428///
1429/// [`take`]: trait.Read.html#method.take
1430#[derive(Debug)]
1431pub struct Take<T> {
1432    inner: T,
1433    limit: u64,
1434}
1435
1436impl<T> Take<T> {
1437    /// Returns the number of bytes that can be read before this instance will
1438    /// return EOF.
1439    ///
1440    /// # Note
1441    ///
1442    /// This instance may reach `EOF` after reading fewer bytes than indicated by
1443    /// this method if the underlying [`Read`] instance reaches EOF.
1444    ///
1445    /// [`Read`]: ../../std/io/trait.Read.html
1446    ///
1447    /// # Examples
1448    ///
1449    /// ```no_run
1450    /// use std::io;
1451    /// use std::io::prelude::*;
1452    /// use std::fs::File;
1453    ///
1454    /// fn main() -> io::Result<()> {
1455    ///     let f = File::open("foo.txt")?;
1456    ///
1457    ///     // read at most five bytes
1458    ///     let handle = f.take(5);
1459    ///
1460    ///     println!("limit: {}", handle.limit());
1461    ///     Ok(())
1462    /// }
1463    /// ```
1464    pub fn limit(&self) -> u64 {
1465        self.limit
1466    }
1467
1468    /// Sets the number of bytes that can be read before this instance will
1469    /// return EOF. This is the same as constructing a new `Take` instance, so
1470    /// the amount of bytes read and the previous limit value don't matter when
1471    /// calling this method.
1472    ///
1473    /// # Examples
1474    ///
1475    /// ```no_run
1476    /// use std::io;
1477    /// use std::io::prelude::*;
1478    /// use std::fs::File;
1479    ///
1480    /// fn main() -> io::Result<()> {
1481    ///     let f = File::open("foo.txt")?;
1482    ///
1483    ///     // read at most five bytes
1484    ///     let mut handle = f.take(5);
1485    ///     handle.set_limit(10);
1486    ///
1487    ///     assert_eq!(handle.limit(), 10);
1488    ///     Ok(())
1489    /// }
1490    /// ```
1491    pub fn set_limit(&mut self, limit: u64) {
1492        self.limit = limit;
1493    }
1494
1495    /// Consumes the `Take`, returning the wrapped reader.
1496    ///
1497    /// # Examples
1498    ///
1499    /// ```no_run
1500    /// use std::io;
1501    /// use std::io::prelude::*;
1502    /// use std::fs::File;
1503    ///
1504    /// fn main() -> io::Result<()> {
1505    ///     let mut file = File::open("foo.txt")?;
1506    ///
1507    ///     let mut buffer = [0; 5];
1508    ///     let mut handle = file.take(5);
1509    ///     handle.read(&mut buffer)?;
1510    ///
1511    ///     let file = handle.into_inner();
1512    ///     Ok(())
1513    /// }
1514    /// ```
1515    pub fn into_inner(self) -> T {
1516        self.inner
1517    }
1518
1519    /// Gets a reference to the underlying reader.
1520    ///
1521    /// # Examples
1522    ///
1523    /// ```no_run
1524    /// use std::io;
1525    /// use std::io::prelude::*;
1526    /// use std::fs::File;
1527    ///
1528    /// fn main() -> io::Result<()> {
1529    ///     let mut file = File::open("foo.txt")?;
1530    ///
1531    ///     let mut buffer = [0; 5];
1532    ///     let mut handle = file.take(5);
1533    ///     handle.read(&mut buffer)?;
1534    ///
1535    ///     let file = handle.get_ref();
1536    ///     Ok(())
1537    /// }
1538    /// ```
1539    pub fn get_ref(&self) -> &T {
1540        &self.inner
1541    }
1542
1543    /// Gets a mutable reference to the underlying reader.
1544    ///
1545    /// Care should be taken to avoid modifying the internal I/O state of the
1546    /// underlying reader as doing so may corrupt the internal limit of this
1547    /// `Take`.
1548    ///
1549    /// # Examples
1550    ///
1551    /// ```no_run
1552    /// use std::io;
1553    /// use std::io::prelude::*;
1554    /// use std::fs::File;
1555    ///
1556    /// fn main() -> io::Result<()> {
1557    ///     let mut file = File::open("foo.txt")?;
1558    ///
1559    ///     let mut buffer = [0; 5];
1560    ///     let mut handle = file.take(5);
1561    ///     handle.read(&mut buffer)?;
1562    ///
1563    ///     let file = handle.get_mut();
1564    ///     Ok(())
1565    /// }
1566    /// ```
1567    pub fn get_mut(&mut self) -> &mut T {
1568        &mut self.inner
1569    }
1570}
1571
1572impl<T: Read> Read for Take<T> {
1573    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1574        // Don't call into inner reader at all at EOF because it may still block
1575        if self.limit == 0 {
1576            return Ok(0);
1577        }
1578
1579        let max = cmp::min(buf.len() as u64, self.limit) as usize;
1580        let n = self.inner.read(&mut buf[..max])?;
1581        self.limit -= n as u64;
1582        Ok(n)
1583    }
1584
1585    unsafe fn initializer(&self) -> Initializer {
1586        unsafe { self.inner.initializer() }
1587    }
1588
1589    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
1590        let reservation_size = cmp::min(self.limit, 32) as usize;
1591
1592        read_to_end_with_reservation(self, buf, reservation_size)
1593    }
1594}
1595
1596impl<T: BufRead> BufRead for Take<T> {
1597    fn fill_buf(&mut self) -> Result<&[u8]> {
1598        // Don't call into inner reader at all at EOF because it may still block
1599        if self.limit == 0 {
1600            return Ok(&[]);
1601        }
1602
1603        let buf = self.inner.fill_buf()?;
1604        let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1605        Ok(&buf[..cap])
1606    }
1607
1608    fn consume(&mut self, amt: usize) {
1609        // Don't let callers reset the limit by passing an overlarge value
1610        let amt = cmp::min(amt as u64, self.limit) as usize;
1611        self.limit -= amt as u64;
1612        self.inner.consume(amt);
1613    }
1614}
1615
1616/// A trait for objects which are byte-oriented sinks.
1617///
1618/// Implementors of the `Write` trait are sometimes called 'writers'.
1619///
1620/// Writers are defined by two required methods, [`write`] and [`flush`]:
1621///
1622/// * The [`write`] method will attempt to write some data into the object,
1623///   returning how many bytes were successfully written.
1624///
1625/// * The [`flush`] method is useful for adaptors and explicit buffers
1626///   themselves for ensuring that all buffered data has been pushed out to the
1627///   'true sink'.
1628///
1629/// Writers are intended to be composable with one another. Many implementors
1630/// throughout [`std::io`] take and provide types which implement the `Write`
1631/// trait.
1632///
1633/// [`write`]: #tymethod.write
1634/// [`flush`]: #tymethod.flush
1635/// [`std::io`]: index.html
1636///
1637/// # Examples
1638///
1639/// ```no_run
1640/// use std::io::prelude::*;
1641/// use std::fs::File;
1642///
1643/// fn main() -> std::io::Result<()> {
1644///     let mut buffer = File::create("foo.txt")?;
1645///
1646///     buffer.write(b"some bytes")?;
1647///     Ok(())
1648/// }
1649/// ```
1650pub trait Write {
1651    /// Write a buffer into this object, returning how many bytes were written.
1652    ///
1653    /// This function will attempt to write the entire contents of `buf`, but
1654    /// the entire write may not succeed, or the write may also generate an
1655    /// error. A call to `write` represents *at most one* attempt to write to
1656    /// any wrapped object.
1657    ///
1658    /// Calls to `write` are not guaranteed to block waiting for data to be
1659    /// written, and a write which would otherwise block can be indicated through
1660    /// an [`Err`] variant.
1661    ///
1662    /// If the return value is [`Ok(n)`] then it must be guaranteed that
1663    /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
1664    /// underlying object is no longer able to accept bytes and will likely not
1665    /// be able to in the future as well, or that the buffer provided is empty.
1666    ///
1667    /// # Errors
1668    ///
1669    /// Each call to `write` may generate an I/O error indicating that the
1670    /// operation could not be completed. If an error is returned then no bytes
1671    /// in the buffer were written to this writer.
1672    ///
1673    /// It is **not** considered an error if the entire buffer could not be
1674    /// written to this writer.
1675    ///
1676    /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1677    /// write operation should be retried if there is nothing else to do.
1678    ///
1679    /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1680    /// [`Ok(n)`]:  ../../std/result/enum.Result.html#variant.Ok
1681    /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1682    ///
1683    /// # Examples
1684    ///
1685    /// ```no_run
1686    /// use std::io::prelude::*;
1687    /// use std::fs::File;
1688    ///
1689    /// fn main() -> std::io::Result<()> {
1690    ///     let mut buffer = File::create("foo.txt")?;
1691    ///
1692    ///     // Writes some prefix of the byte string, not necessarily all of it.
1693    ///     buffer.write(b"some bytes")?;
1694    ///     Ok(())
1695    /// }
1696    /// ```
1697    fn write(&mut self, buf: &[u8]) -> Result<usize>;
1698
1699    /// Flush this output stream, ensuring that all intermediately buffered
1700    /// contents reach their destination.
1701    ///
1702    /// # Errors
1703    ///
1704    /// It is considered an error if not all bytes could be written due to
1705    /// I/O errors or EOF being reached.
1706    ///
1707    /// # Examples
1708    ///
1709    /// ```no_run
1710    /// use std::io::prelude::*;
1711    /// use std::io::BufWriter;
1712    /// use std::fs::File;
1713    ///
1714    /// fn main() -> std::io::Result<()> {
1715    ///     let mut buffer = BufWriter::new(File::create("foo.txt")?);
1716    ///
1717    ///     buffer.write(b"some bytes")?;
1718    ///     buffer.flush()?;
1719    ///     Ok(())
1720    /// }
1721    /// ```
1722    fn flush(&mut self) -> Result<()>;
1723
1724    /// Attempts to write an entire buffer into this write.
1725    ///
1726    /// This method will continuously call [`write`] until there is no more data
1727    /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1728    /// returned. This method will not return until the entire buffer has been
1729    /// successfully written or such an error occurs. The first error that is
1730    /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1731    /// returned.
1732    ///
1733    /// # Errors
1734    ///
1735    /// This function will return the first error of
1736    /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1737    ///
1738    /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
1739    /// [`write`]: #tymethod.write
1740    ///
1741    /// # Examples
1742    ///
1743    /// ```no_run
1744    /// use std::io::prelude::*;
1745    /// use std::fs::File;
1746    ///
1747    /// fn main() -> std::io::Result<()> {
1748    ///     let mut buffer = File::create("foo.txt")?;
1749    ///
1750    ///     buffer.write_all(b"some bytes")?;
1751    ///     Ok(())
1752    /// }
1753    /// ```
1754    fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1755        while !buf.is_empty() {
1756            match self.write(buf) {
1757                Ok(0) => {
1758                    return Err(Error::new(
1759                        ErrorKind::WriteZero,
1760                        "failed to write whole buffer",
1761                    ));
1762                }
1763                Ok(n) => buf = &buf[n..],
1764                Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1765                Err(e) => return Err(e),
1766            }
1767        }
1768        Ok(())
1769    }
1770
1771    /// Writes a formatted string into this writer, returning any error
1772    /// encountered.
1773    ///
1774    /// This method is primarily used to interface with the
1775    /// [`format_args!`][formatargs] macro, but it is rare that this should
1776    /// explicitly be called. The [`write!`][write] macro should be favored to
1777    /// invoke this method instead.
1778    ///
1779    /// [formatargs]: ../macro.format_args.html
1780    /// [write]: ../macro.write.html
1781    ///
1782    /// This function internally uses the [`write_all`][writeall] method on
1783    /// this trait and hence will continuously write data so long as no errors
1784    /// are received. This also means that partial writes are not indicated in
1785    /// this signature.
1786    ///
1787    /// [writeall]: #method.write_all
1788    ///
1789    /// # Errors
1790    ///
1791    /// This function will return any I/O error reported while formatting.
1792    ///
1793    /// # Examples
1794    ///
1795    /// ```no_run
1796    /// use std::io::prelude::*;
1797    /// use std::fs::File;
1798    ///
1799    /// fn main() -> std::io::Result<()> {
1800    ///     let mut buffer = File::create("foo.txt")?;
1801    ///
1802    ///     // this call
1803    ///     write!(buffer, "{:.*}", 2, 1.234567)?;
1804    ///     // turns into this:
1805    ///     buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1806    ///     Ok(())
1807    /// }
1808    /// ```
1809    fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1810        // Create a shim which translates a Write to a fmt::Write and saves
1811        // off I/O errors. instead of discarding them
1812        struct Adaptor<'a, T: ?Sized + 'a> {
1813            inner: &'a mut T,
1814            error: Result<()>,
1815        }
1816
1817        impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1818            fn write_str(&mut self, s: &str) -> fmt::Result {
1819                match self.inner.write_all(s.as_bytes()) {
1820                    Ok(()) => Ok(()),
1821                    Err(e) => {
1822                        self.error = Err(e);
1823                        Err(fmt::Error)
1824                    }
1825                }
1826            }
1827        }
1828
1829        let mut output = Adaptor {
1830            inner: self,
1831            error: Ok(()),
1832        };
1833        match fmt::write(&mut output, fmt) {
1834            Ok(()) => Ok(()),
1835            Err(..) => {
1836                // check if the error came from the underlying `Write` or not
1837                if output.error.is_err() {
1838                    output.error
1839                } else {
1840                    Err(Error::new(ErrorKind::Other, "formatter error"))
1841                }
1842            }
1843        }
1844    }
1845
1846    /// Creates a "by reference" adaptor for this instance of `Write`.
1847    ///
1848    /// The returned adaptor also implements `Write` and will simply borrow this
1849    /// current writer.
1850    ///
1851    /// # Examples
1852    ///
1853    /// ```no_run
1854    /// use std::io::Write;
1855    /// use std::fs::File;
1856    ///
1857    /// fn main() -> std::io::Result<()> {
1858    ///     let mut buffer = File::create("foo.txt")?;
1859    ///
1860    ///     let reference = buffer.by_ref();
1861    ///
1862    ///     // we can use reference just like our original buffer
1863    ///     reference.write_all(b"some bytes")?;
1864    ///     Ok(())
1865    /// }
1866    /// ```
1867    fn by_ref(&mut self) -> &mut Self
1868    where
1869        Self: Sized,
1870    {
1871        self
1872    }
1873}
1874
1875/// The `Seek` trait provides a cursor which can be moved within a stream of
1876/// bytes.
1877///
1878/// The stream typically has a fixed size, allowing seeking relative to either
1879/// end or the current offset.
1880///
1881/// # Examples
1882///
1883/// [`File`][file]s implement `Seek`:
1884///
1885/// [file]: ../fs/struct.File.html
1886///
1887/// ```no_run
1888/// use std::io;
1889/// use std::io::prelude::*;
1890/// use std::fs::File;
1891/// use std::io::SeekFrom;
1892///
1893/// fn main() -> io::Result<()> {
1894///     let mut f = File::open("foo.txt")?;
1895///
1896///     // move the cursor 42 bytes from the start of the file
1897///     f.seek(SeekFrom::Start(42))?;
1898///     Ok(())
1899/// }
1900/// ```
1901pub trait Seek {
1902    /// Seek to an offset, in bytes, in a stream.
1903    ///
1904    /// A seek beyond the end of a stream is allowed, but behavior is defined
1905    /// by the implementation.
1906    ///
1907    /// If the seek operation completed successfully,
1908    /// this method returns the new position from the start of the stream.
1909    /// That position can be used later with [`SeekFrom::Start`].
1910    ///
1911    /// # Errors
1912    ///
1913    /// Seeking to a negative offset is considered an error.
1914    ///
1915    /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1916    fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1917}
1918
1919/// Enumeration of possible methods to seek within an I/O object.
1920///
1921/// It is used by the [`Seek`] trait.
1922///
1923/// [`Seek`]: trait.Seek.html
1924#[derive(Copy, PartialEq, Eq, Clone, Debug)]
1925pub enum SeekFrom {
1926    /// Set the offset to the provided number of bytes.
1927    Start(u64),
1928
1929    /// Set the offset to the size of this object plus the specified number of
1930    /// bytes.
1931    ///
1932    /// It is possible to seek beyond the end of an object, but it's an error to
1933    /// seek before byte 0.
1934    End(i64),
1935
1936    /// Set the offset to the current position plus the specified number of
1937    /// bytes.
1938    ///
1939    /// It is possible to seek beyond the end of an object, but it's an error to
1940    /// seek before byte 0.
1941    Current(i64),
1942}
1943
1944/// An iterator over `u8` values of a reader.
1945///
1946/// This struct is generally created by calling [`bytes`] on a reader.
1947/// Please see the documentation of [`bytes`] for more details.
1948///
1949/// [`bytes`]: trait.Read.html#method.bytes
1950#[derive(Debug)]
1951pub struct Bytes<R> {
1952    inner: R,
1953}
1954
1955impl<R: Read> Iterator for Bytes<R> {
1956    type Item = Result<u8>;
1957
1958    fn next(&mut self) -> Option<Result<u8>> {
1959        read_one_byte(&mut self.inner)
1960    }
1961}
1962
1963/// An iterator over the contents of an instance of `BufRead` split on a
1964/// particular byte.
1965///
1966/// This struct is generally created by calling [`split`][split] on a
1967/// `BufRead`. Please see the documentation of `split()` for more details.
1968///
1969/// [split]: trait.BufRead.html#method.split
1970#[derive(Debug)]
1971pub struct Split<B> {
1972    buf: B,
1973    delim: u8,
1974}
1975
1976impl<B: BufRead> Iterator for Split<B> {
1977    type Item = Result<Vec<u8>>;
1978
1979    fn next(&mut self) -> Option<Result<Vec<u8>>> {
1980        let mut buf = Vec::new();
1981        match self.buf.read_until(self.delim, &mut buf) {
1982            Ok(0) => None,
1983            Ok(_n) => {
1984                if buf[buf.len() - 1] == self.delim {
1985                    buf.pop();
1986                }
1987                Some(Ok(buf))
1988            }
1989            Err(e) => Some(Err(e)),
1990        }
1991    }
1992}
1993
1994/// An iterator over the lines of an instance of `BufRead`.
1995///
1996/// This struct is generally created by calling [`lines`][lines] on a
1997/// `BufRead`. Please see the documentation of `lines()` for more details.
1998///
1999/// [lines]: trait.BufRead.html#method.lines
2000#[derive(Debug)]
2001pub struct Lines<B> {
2002    buf: B,
2003}
2004
2005impl<B: BufRead> Iterator for Lines<B> {
2006    type Item = Result<String>;
2007
2008    fn next(&mut self) -> Option<Result<String>> {
2009        let mut buf = String::new();
2010        match self.buf.read_line(&mut buf) {
2011            Ok(0) => None,
2012            Ok(_n) => {
2013                if buf.ends_with("\n") {
2014                    buf.pop();
2015                    if buf.ends_with("\r") {
2016                        buf.pop();
2017                    }
2018                }
2019                Some(Ok(buf))
2020            }
2021            Err(e) => Some(Err(e)),
2022        }
2023    }
2024}
2025
2026#[cfg(test)]
2027mod tests {
2028    use alloc::string::String;
2029
2030    use crate::io::{self, cursor::Cursor, prelude::*};
2031
2032    #[test]
2033    #[cfg_attr(target_os = "emscripten", ignore)]
2034    fn read_until() {
2035        let mut buf = Cursor::new(b"12".as_slice());
2036        let mut v = Vec::new();
2037        assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2038        assert_eq!(v, b"12");
2039
2040        let mut buf = Cursor::new(b"1233".as_slice());
2041        let mut v = Vec::new();
2042        assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2043        assert_eq!(v, b"123");
2044        v.truncate(0);
2045        assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2046        assert_eq!(v, b"3");
2047        v.truncate(0);
2048        assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2049        assert_eq!(v, []);
2050    }
2051
2052    #[test]
2053    fn split() {
2054        let buf = Cursor::new(b"12".as_slice());
2055        let mut s = buf.split(b'3');
2056        assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2057        assert!(s.next().is_none());
2058
2059        let buf = Cursor::new(b"1233".as_slice());
2060        let mut s = buf.split(b'3');
2061        assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2062        assert_eq!(s.next().unwrap().unwrap(), vec![]);
2063        assert!(s.next().is_none());
2064    }
2065
2066    #[test]
2067    fn read_line() {
2068        let mut buf = Cursor::new(b"12".as_slice());
2069        let mut v = String::new();
2070        assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2071        assert_eq!(v, "12");
2072
2073        let mut buf = Cursor::new(b"12\n\n".as_slice());
2074        let mut v = String::new();
2075        assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2076        assert_eq!(v, "12\n");
2077        v.truncate(0);
2078        assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2079        assert_eq!(v, "\n");
2080        v.truncate(0);
2081        assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2082        assert_eq!(v, "");
2083    }
2084
2085    // #[test]
2086    // fn lines() {
2087    //     let buf = Cursor::new(b"12\r".as_slice());
2088    //     let mut s = buf.lines();
2089    //     assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2090    //     assert!(s.next().is_none());
2091
2092    //     let buf = Cursor::new(b"12\r\n\n".as_slice());
2093    //     let mut s = buf.lines();
2094    //     assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2095    //     assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2096    //     assert!(s.next().is_none());
2097    // }
2098
2099    #[test]
2100    fn read_to_end() {
2101        let mut c = Cursor::new(b"".as_slice());
2102        let mut v = Vec::new();
2103        assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2104        assert_eq!(v, []);
2105
2106        let mut c = Cursor::new(b"1".as_slice());
2107        let mut v = Vec::new();
2108        assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2109        assert_eq!(v, b"1");
2110
2111        let cap = 1024 * 1024;
2112        let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2113        let mut v = Vec::new();
2114        let (a, b) = data.split_at(data.len() / 2);
2115        assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2116        assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2117        assert_eq!(v, data);
2118    }
2119
2120    #[test]
2121    fn read_to_string() {
2122        let mut c = Cursor::new(b"".as_slice());
2123        let mut v = String::new();
2124        assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2125        assert_eq!(v, "");
2126
2127        let mut c = Cursor::new(b"1".as_slice());
2128        let mut v = String::new();
2129        assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2130        assert_eq!(v, "1");
2131
2132        let mut c = Cursor::new(b"\xff".as_slice());
2133        let mut v = String::new();
2134        assert!(c.read_to_string(&mut v).is_err());
2135    }
2136
2137    #[test]
2138    fn read_exact() {
2139        let mut buf = [0; 4];
2140
2141        let mut c = Cursor::new(b"".as_slice());
2142        assert_eq!(
2143            c.read_exact(&mut buf).unwrap_err().kind(),
2144            io::ErrorKind::UnexpectedEof
2145        );
2146
2147        let mut c = Cursor::new(b"123".as_slice()).chain(Cursor::new(b"456789".as_slice()));
2148        c.read_exact(&mut buf).unwrap();
2149        assert_eq!(buf, *b"1234");
2150        c.read_exact(&mut buf).unwrap();
2151        assert_eq!(buf, *b"5678");
2152        assert_eq!(
2153            c.read_exact(&mut buf).unwrap_err().kind(),
2154            io::ErrorKind::UnexpectedEof
2155        );
2156    }
2157
2158    #[test]
2159    fn read_exact_slice() {
2160        let mut buf = [0; 4];
2161
2162        let mut c = b"".as_slice();
2163        assert_eq!(
2164            c.read_exact(&mut buf).unwrap_err().kind(),
2165            io::ErrorKind::UnexpectedEof
2166        );
2167
2168        let mut c = b"123".as_slice();
2169        assert_eq!(
2170            c.read_exact(&mut buf).unwrap_err().kind(),
2171            io::ErrorKind::UnexpectedEof
2172        );
2173        // make sure the optimized (early returning) method is being used
2174        assert_eq!(buf, [0; 4]);
2175
2176        let mut c = b"1234".as_slice();
2177        c.read_exact(&mut buf).unwrap();
2178        assert_eq!(buf, *b"1234");
2179
2180        let mut c = b"56789".as_slice();
2181        c.read_exact(&mut buf).unwrap();
2182        assert_eq!(buf, *b"5678");
2183        assert_eq!(c, b"9");
2184    }
2185
2186    #[test]
2187    fn take_eof() {
2188        struct R;
2189
2190        impl Read for R {
2191            fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2192                Err(io::Error::new(io::ErrorKind::Other, ""))
2193            }
2194        }
2195        impl BufRead for R {
2196            fn fill_buf(&mut self) -> io::Result<&[u8]> {
2197                Err(io::Error::new(io::ErrorKind::Other, ""))
2198            }
2199            fn consume(&mut self, _amt: usize) {}
2200        }
2201
2202        let mut buf = [0; 1];
2203        assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2204        assert_eq!(b"", R.take(0).fill_buf().unwrap());
2205    }
2206
2207    fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2208        let mut cat = Vec::new();
2209        loop {
2210            let consume = {
2211                let buf1 = br1.fill_buf().unwrap();
2212                let buf2 = br2.fill_buf().unwrap();
2213                let minlen = if buf1.len() < buf2.len() {
2214                    buf1.len()
2215                } else {
2216                    buf2.len()
2217                };
2218                assert_eq!(buf1[..minlen], buf2[..minlen]);
2219                cat.extend_from_slice(&buf1[..minlen]);
2220                minlen
2221            };
2222            if consume == 0 {
2223                break;
2224            }
2225            br1.consume(consume);
2226            br2.consume(consume);
2227        }
2228        assert_eq!(br1.fill_buf().unwrap().len(), 0);
2229        assert_eq!(br2.fill_buf().unwrap().len(), 0);
2230        assert_eq!(&cat, &exp)
2231    }
2232
2233    #[test]
2234    fn chain_bufread() {
2235        let testdata = b"ABCDEFGHIJKL";
2236        let chain1 = (&testdata[..3])
2237            .chain(&testdata[3..6])
2238            .chain(&testdata[6..9])
2239            .chain(&testdata[9..]);
2240        let chain2 = (&testdata[..4])
2241            .chain(&testdata[4..8])
2242            .chain(&testdata[8..]);
2243        cmp_bufread(chain1, chain2, testdata.as_slice());
2244    }
2245
2246    #[test]
2247    fn chain_zero_length_read_is_not_eof() {
2248        let a = b"A";
2249        let b = b"B";
2250        let mut s = String::new();
2251        let mut chain = a.chain(b.as_slice());
2252        chain.read(&mut []).unwrap();
2253        chain.read_to_string(&mut s).unwrap();
2254        assert_eq!("AB", s);
2255    }
2256
2257    // #[bench]
2258    // #[cfg_attr(target_os = "emscripten", ignore)]
2259    // fn bench_read_to_end(b: &mut test::Bencher) {
2260    //     b.iter(|| {
2261    //         let mut lr = repeat(1).take(10000000);
2262    //         let mut vec = Vec::with_capacity(1024);
2263    //         super::read_to_end(&mut lr, &mut vec)
2264    //     });
2265    // }
2266}