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