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