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