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