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