]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/mod.rs
Auto merge of #29858 - fhahn:abort-if-path-has-spaces, r=brson
[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     /// #![feature(read_exact)]
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     #[unstable(feature = "read_exact", reason = "recently added", issue = "27585")]
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     fn tee<W: Write>(self, out: W) -> Tee<Self, W> where Self: Sized {
842         Tee { reader: self, writer: out }
843     }
844 }
845
846 /// A trait for objects which are byte-oriented sinks.
847 ///
848 /// Implementors of the `Write` trait are sometimes called 'writers'.
849 ///
850 /// Writers are defined by two required methods, `write()` and `flush()`:
851 ///
852 /// * The `write()` method will attempt to write some data into the object,
853 ///   returning how many bytes were successfully written.
854 ///
855 /// * The `flush()` method is useful for adaptors and explicit buffers
856 ///   themselves for ensuring that all buffered data has been pushed out to the
857 ///   'true sink'.
858 ///
859 /// Writers are intended to be composable with one another. Many implementors
860 /// throughout `std::io` take and provide types which implement the `Write`
861 /// trait.
862 ///
863 /// # Examples
864 ///
865 /// ```
866 /// use std::io::prelude::*;
867 /// use std::fs::File;
868 ///
869 /// # fn foo() -> std::io::Result<()> {
870 /// let mut buffer = try!(File::create("foo.txt"));
871 ///
872 /// try!(buffer.write(b"some bytes"));
873 /// # Ok(())
874 /// # }
875 /// ```
876 #[stable(feature = "rust1", since = "1.0.0")]
877 pub trait Write {
878     /// Write a buffer into this object, returning how many bytes were written.
879     ///
880     /// This function will attempt to write the entire contents of `buf`, but
881     /// the entire write may not succeed, or the write may also generate an
882     /// error. A call to `write` represents *at most one* attempt to write to
883     /// any wrapped object.
884     ///
885     /// Calls to `write` are not guaranteed to block waiting for data to be
886     /// written, and a write which would otherwise block can be indicated through
887     /// an `Err` variant.
888     ///
889     /// If the return value is `Ok(n)` then it must be guaranteed that
890     /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
891     /// underlying object is no longer able to accept bytes and will likely not
892     /// be able to in the future as well, or that the buffer provided is empty.
893     ///
894     /// # Errors
895     ///
896     /// Each call to `write` may generate an I/O error indicating that the
897     /// operation could not be completed. If an error is returned then no bytes
898     /// in the buffer were written to this writer.
899     ///
900     /// It is **not** considered an error if the entire buffer could not be
901     /// written to this writer.
902     ///
903     /// # Examples
904     ///
905     /// ```
906     /// use std::io::prelude::*;
907     /// use std::fs::File;
908     ///
909     /// # fn foo() -> std::io::Result<()> {
910     /// let mut buffer = try!(File::create("foo.txt"));
911     ///
912     /// try!(buffer.write(b"some bytes"));
913     /// # Ok(())
914     /// # }
915     /// ```
916     #[stable(feature = "rust1", since = "1.0.0")]
917     fn write(&mut self, buf: &[u8]) -> Result<usize>;
918
919     /// Flush this output stream, ensuring that all intermediately buffered
920     /// contents reach their destination.
921     ///
922     /// # Errors
923     ///
924     /// It is considered an error if not all bytes could be written due to
925     /// I/O errors or EOF being reached.
926     ///
927     /// # Examples
928     ///
929     /// ```
930     /// use std::io::prelude::*;
931     /// use std::io::BufWriter;
932     /// use std::fs::File;
933     ///
934     /// # fn foo() -> std::io::Result<()> {
935     /// let mut buffer = BufWriter::new(try!(File::create("foo.txt")));
936     ///
937     /// try!(buffer.write(b"some bytes"));
938     /// try!(buffer.flush());
939     /// # Ok(())
940     /// # }
941     /// ```
942     #[stable(feature = "rust1", since = "1.0.0")]
943     fn flush(&mut self) -> Result<()>;
944
945     /// Attempts to write an entire buffer into this write.
946     ///
947     /// This method will continuously call `write` while there is more data to
948     /// write. This method will not return until the entire buffer has been
949     /// successfully written or an error occurs. The first error generated from
950     /// this method will be returned.
951     ///
952     /// # Errors
953     ///
954     /// This function will return the first error that `write` returns.
955     ///
956     /// # Examples
957     ///
958     /// ```
959     /// use std::io::prelude::*;
960     /// use std::fs::File;
961     ///
962     /// # fn foo() -> std::io::Result<()> {
963     /// let mut buffer = try!(File::create("foo.txt"));
964     ///
965     /// try!(buffer.write_all(b"some bytes"));
966     /// # Ok(())
967     /// # }
968     /// ```
969     #[stable(feature = "rust1", since = "1.0.0")]
970     fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
971         while !buf.is_empty() {
972             match self.write(buf) {
973                 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
974                                                "failed to write whole buffer")),
975                 Ok(n) => buf = &buf[n..],
976                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
977                 Err(e) => return Err(e),
978             }
979         }
980         Ok(())
981     }
982
983     /// Writes a formatted string into this writer, returning any error
984     /// encountered.
985     ///
986     /// This method is primarily used to interface with the
987     /// [`format_args!`][formatargs] macro, but it is rare that this should
988     /// explicitly be called. The [`write!`][write] macro should be favored to
989     /// invoke this method instead.
990     ///
991     /// [formatargs]: ../std/macro.format_args!.html
992     /// [write]: ../std/macro.write!.html
993     ///
994     /// This function internally uses the [`write_all`][writeall] method on
995     /// this trait and hence will continuously write data so long as no errors
996     /// are received. This also means that partial writes are not indicated in
997     /// this signature.
998     ///
999     /// [writeall]: #method.write_all
1000     ///
1001     /// # Errors
1002     ///
1003     /// This function will return any I/O error reported while formatting.
1004     ///
1005     /// # Examples
1006     ///
1007     /// ```
1008     /// use std::io::prelude::*;
1009     /// use std::fs::File;
1010     ///
1011     /// # fn foo() -> std::io::Result<()> {
1012     /// let mut buffer = try!(File::create("foo.txt"));
1013     ///
1014     /// // this call
1015     /// try!(write!(buffer, "{:.*}", 2, 1.234567));
1016     /// // turns into this:
1017     /// try!(buffer.write_fmt(format_args!("{:.*}", 2, 1.234567)));
1018     /// # Ok(())
1019     /// # }
1020     /// ```
1021     #[stable(feature = "rust1", since = "1.0.0")]
1022     fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1023         // Create a shim which translates a Write to a fmt::Write and saves
1024         // off I/O errors. instead of discarding them
1025         struct Adaptor<'a, T: ?Sized + 'a> {
1026             inner: &'a mut T,
1027             error: Result<()>,
1028         }
1029
1030         impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1031             fn write_str(&mut self, s: &str) -> fmt::Result {
1032                 match self.inner.write_all(s.as_bytes()) {
1033                     Ok(()) => Ok(()),
1034                     Err(e) => {
1035                         self.error = Err(e);
1036                         Err(fmt::Error)
1037                     }
1038                 }
1039             }
1040         }
1041
1042         let mut output = Adaptor { inner: self, error: Ok(()) };
1043         match fmt::write(&mut output, fmt) {
1044             Ok(()) => Ok(()),
1045             Err(..) => output.error
1046         }
1047     }
1048
1049     /// Creates a "by reference" adaptor for this instance of `Write`.
1050     ///
1051     /// The returned adaptor also implements `Write` and will simply borrow this
1052     /// current writer.
1053     ///
1054     /// # Examples
1055     ///
1056     /// ```
1057     /// use std::io::Write;
1058     /// use std::fs::File;
1059     ///
1060     /// # fn foo() -> std::io::Result<()> {
1061     /// let mut buffer = try!(File::create("foo.txt"));
1062     ///
1063     /// let reference = buffer.by_ref();
1064     ///
1065     /// // we can use reference just like our original buffer
1066     /// try!(reference.write_all(b"some bytes"));
1067     /// # Ok(())
1068     /// # }
1069     /// ```
1070     #[stable(feature = "rust1", since = "1.0.0")]
1071     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1072
1073     /// Creates a new writer which will write all data to both this writer and
1074     /// another writer.
1075     ///
1076     /// All data written to the returned writer will both be written to `self`
1077     /// as well as `other`. Note that the error semantics of the current
1078     /// implementation do not precisely track where errors happen. For example
1079     /// an error on the second call to `write` will not report that the first
1080     /// call to `write` succeeded.
1081     ///
1082     /// # Examples
1083     ///
1084     /// ```
1085     /// #![feature(io)]
1086     /// use std::io::prelude::*;
1087     /// use std::fs::File;
1088     ///
1089     /// # fn foo() -> std::io::Result<()> {
1090     /// let mut buffer1 = try!(File::create("foo.txt"));
1091     /// let mut buffer2 = Vec::new();
1092     ///
1093     /// // write the output to buffer1 as we read
1094     /// let mut handle = buffer1.broadcast(&mut buffer2);
1095     ///
1096     /// try!(handle.write(b"some bytes"));
1097     /// # Ok(())
1098     /// # }
1099     /// ```
1100     #[unstable(feature = "io", reason = "the semantics of a partial read/write \
1101                                          of where errors happen is currently \
1102                                          unclear and may change",
1103                issue = "27802")]
1104     fn broadcast<W: Write>(self, other: W) -> Broadcast<Self, W>
1105         where Self: Sized
1106     {
1107         Broadcast { first: self, second: other }
1108     }
1109 }
1110
1111 /// The `Seek` trait provides a cursor which can be moved within a stream of
1112 /// bytes.
1113 ///
1114 /// The stream typically has a fixed size, allowing seeking relative to either
1115 /// end or the current offset.
1116 ///
1117 /// # Examples
1118 ///
1119 /// [`File`][file]s implement `Seek`:
1120 ///
1121 /// [file]: ../std/fs/struct.File.html
1122 ///
1123 /// ```
1124 /// use std::io;
1125 /// use std::io::prelude::*;
1126 /// use std::fs::File;
1127 /// use std::io::SeekFrom;
1128 ///
1129 /// # fn foo() -> io::Result<()> {
1130 /// let mut f = try!(File::open("foo.txt"));
1131 ///
1132 /// // move the cursor 42 bytes from the start of the file
1133 /// try!(f.seek(SeekFrom::Start(42)));
1134 /// # Ok(())
1135 /// # }
1136 /// ```
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 pub trait Seek {
1139     /// Seek to an offset, in bytes, in a stream.
1140     ///
1141     /// A seek beyond the end of a stream is allowed, but implementation
1142     /// defined.
1143     ///
1144     /// If the seek operation completed successfully,
1145     /// this method returns the new position from the start of the stream.
1146     /// That position can be used later with `SeekFrom::Start`.
1147     ///
1148     /// # Errors
1149     ///
1150     /// Seeking to a negative offset is considered an error.
1151     #[stable(feature = "rust1", since = "1.0.0")]
1152     fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1153 }
1154
1155 /// Enumeration of possible methods to seek within an I/O object.
1156 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 pub enum SeekFrom {
1159     /// Set the offset to the provided number of bytes.
1160     #[stable(feature = "rust1", since = "1.0.0")]
1161     Start(u64),
1162
1163     /// Set the offset to the size of this object plus the specified number of
1164     /// bytes.
1165     ///
1166     /// It is possible to seek beyond the end of an object, but is an error to
1167     /// seek before byte 0.
1168     #[stable(feature = "rust1", since = "1.0.0")]
1169     End(i64),
1170
1171     /// Set the offset to the current position plus the specified number of
1172     /// bytes.
1173     ///
1174     /// It is possible to seek beyond the end of an object, but is an error to
1175     /// seek before byte 0.
1176     #[stable(feature = "rust1", since = "1.0.0")]
1177     Current(i64),
1178 }
1179
1180 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1181                                    -> Result<usize> {
1182     let mut read = 0;
1183     loop {
1184         let (done, used) = {
1185             let available = match r.fill_buf() {
1186                 Ok(n) => n,
1187                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1188                 Err(e) => return Err(e)
1189             };
1190             match available.iter().position(|x| *x == delim) {
1191                 Some(i) => {
1192                     buf.push_all(&available[..i + 1]);
1193                     (true, i + 1)
1194                 }
1195                 None => {
1196                     buf.push_all(available);
1197                     (false, available.len())
1198                 }
1199             }
1200         };
1201         r.consume(used);
1202         read += used;
1203         if done || used == 0 {
1204             return Ok(read);
1205         }
1206     }
1207 }
1208
1209 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1210 /// to perform extra ways of reading.
1211 ///
1212 /// For example, reading line-by-line is inefficient without using a buffer, so
1213 /// if you want to read by line, you'll need `BufRead`, which includes a
1214 /// [`read_line()`][readline] method as well as a [`lines()`][lines] iterator.
1215 ///
1216 /// [readline]: #method.read_line
1217 /// [lines]: #method.lines
1218 ///
1219 /// # Examples
1220 ///
1221 /// A locked standard input implements `BufRead`:
1222 ///
1223 /// ```
1224 /// use std::io;
1225 /// use std::io::prelude::*;
1226 ///
1227 /// let stdin = io::stdin();
1228 /// for line in stdin.lock().lines() {
1229 ///     println!("{}", line.unwrap());
1230 /// }
1231 /// ```
1232 ///
1233 /// If you have something that implements `Read`, you can use the [`BufReader`
1234 /// type][bufreader] to turn it into a `BufRead`.
1235 ///
1236 /// For example, [`File`][file] implements `Read`, but not `BufRead`.
1237 /// `BufReader` to the rescue!
1238 ///
1239 /// [bufreader]: struct.BufReader.html
1240 /// [file]: ../fs/struct.File.html
1241 ///
1242 /// ```
1243 /// use std::io::{self, BufReader};
1244 /// use std::io::prelude::*;
1245 /// use std::fs::File;
1246 ///
1247 /// # fn foo() -> io::Result<()> {
1248 /// let f = try!(File::open("foo.txt"));
1249 /// let f = BufReader::new(f);
1250 ///
1251 /// for line in f.lines() {
1252 ///     println!("{}", line.unwrap());
1253 /// }
1254 ///
1255 /// # Ok(())
1256 /// # }
1257 /// ```
1258 ///
1259 #[stable(feature = "rust1", since = "1.0.0")]
1260 pub trait BufRead: Read {
1261     /// Fills the internal buffer of this object, returning the buffer contents.
1262     ///
1263     /// This function is a lower-level call. It needs to be paired with the
1264     /// [`consume`][consume] method to function properly. When calling this
1265     /// method, none of the contents will be "read" in the sense that later
1266     /// calling `read` may return the same contents. As such, `consume` must be
1267     /// called with the number of bytes that are consumed from this buffer to
1268     /// ensure that the bytes are never returned twice.
1269     ///
1270     /// [consume]: #tymethod.consume
1271     ///
1272     /// An empty buffer returned indicates that the stream has reached EOF.
1273     ///
1274     /// # Errors
1275     ///
1276     /// This function will return an I/O error if the underlying reader was
1277     /// read, but returned an error.
1278     ///
1279     /// # Examples
1280     ///
1281     /// A locked standard input implements `BufRead`:
1282     ///
1283     /// ```
1284     /// use std::io;
1285     /// use std::io::prelude::*;
1286     ///
1287     /// let stdin = io::stdin();
1288     /// let mut stdin = stdin.lock();
1289     ///
1290     /// // we can't have two `&mut` references to `stdin`, so use a block
1291     /// // to end the borrow early.
1292     /// let length = {
1293     ///     let buffer = stdin.fill_buf().unwrap();
1294     ///
1295     ///     // work with buffer
1296     ///     println!("{:?}", buffer);
1297     ///
1298     ///     buffer.len()
1299     /// };
1300     ///
1301     /// // ensure the bytes we worked with aren't returned again later
1302     /// stdin.consume(length);
1303     /// ```
1304     #[stable(feature = "rust1", since = "1.0.0")]
1305     fn fill_buf(&mut self) -> Result<&[u8]>;
1306
1307     /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1308     /// so they should no longer be returned in calls to `read`.
1309     ///
1310     /// This function is a lower-level call. It needs to be paired with the
1311     /// [`fill_buf`][fillbuf] method to function properly. This function does
1312     /// not perform any I/O, it simply informs this object that some amount of
1313     /// its buffer, returned from `fill_buf`, has been consumed and should no
1314     /// longer be returned. As such, this function may do odd things if
1315     /// `fill_buf` isn't called before calling it.
1316     ///
1317     /// [fillbuf]: #tymethod.fill_buff
1318     ///
1319     /// The `amt` must be `<=` the number of bytes in the buffer returned by
1320     /// `fill_buf`.
1321     ///
1322     /// # Examples
1323     ///
1324     /// Since `consume()` is meant to be used with [`fill_buf()`][fillbuf],
1325     /// that method's example includes an example of `consume()`.
1326     #[stable(feature = "rust1", since = "1.0.0")]
1327     fn consume(&mut self, amt: usize);
1328
1329     /// Read all bytes into `buf` until the delimiter `byte` is reached.
1330     ///
1331     /// This function will read bytes from the underlying stream until the
1332     /// delimiter or EOF is found. Once found, all bytes up to, and including,
1333     /// the delimiter (if found) will be appended to `buf`.
1334     ///
1335     /// If this reader is currently at EOF then this function will not modify
1336     /// `buf` and will return `Ok(n)` where `n` is the number of bytes which
1337     /// were read.
1338     ///
1339     /// # Errors
1340     ///
1341     /// This function will ignore all instances of `ErrorKind::Interrupted` and
1342     /// will otherwise return any errors returned by `fill_buf`.
1343     ///
1344     /// If an I/O error is encountered then all bytes read so far will be
1345     /// present in `buf` and its length will have been adjusted appropriately.
1346     ///
1347     /// # Examples
1348     ///
1349     /// A locked standard input implements `BufRead`. In this example, we'll
1350     /// read from standard input until we see an `a` byte.
1351     ///
1352     /// ```
1353     /// use std::io;
1354     /// use std::io::prelude::*;
1355     ///
1356     /// fn foo() -> io::Result<()> {
1357     /// let stdin = io::stdin();
1358     /// let mut stdin = stdin.lock();
1359     /// let mut buffer = Vec::new();
1360     ///
1361     /// try!(stdin.read_until(b'a', &mut buffer));
1362     ///
1363     /// println!("{:?}", buffer);
1364     /// # Ok(())
1365     /// # }
1366     /// ```
1367     #[stable(feature = "rust1", since = "1.0.0")]
1368     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1369         read_until(self, byte, buf)
1370     }
1371
1372     /// Read all bytes until a newline (the 0xA byte) is reached, and append
1373     /// them to the provided buffer.
1374     ///
1375     /// This function will read bytes from the underlying stream until the
1376     /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1377     /// up to, and including, the delimiter (if found) will be appended to
1378     /// `buf`.
1379     ///
1380     /// If this reader is currently at EOF then this function will not modify
1381     /// `buf` and will return `Ok(n)` where `n` is the number of bytes which
1382     /// were read.
1383     ///
1384     /// # Errors
1385     ///
1386     /// This function has the same error semantics as `read_until` and will also
1387     /// return an error if the read bytes are not valid UTF-8. If an I/O error
1388     /// is encountered then `buf` may contain some bytes already read in the
1389     /// event that all data read so far was valid UTF-8.
1390     ///
1391     /// # Examples
1392     ///
1393     /// A locked standard input implements `BufRead`. In this example, we'll
1394     /// read all of the lines from standard input. If we were to do this in
1395     /// an actual project, the [`lines()`][lines] method would be easier, of
1396     /// course.
1397     ///
1398     /// [lines]: #method.lines
1399     ///
1400     /// ```
1401     /// use std::io;
1402     /// use std::io::prelude::*;
1403     ///
1404     /// let stdin = io::stdin();
1405     /// let mut stdin = stdin.lock();
1406     /// let mut buffer = String::new();
1407     ///
1408     /// while stdin.read_line(&mut buffer).unwrap() > 0 {
1409     ///     // work with buffer
1410     ///     println!("{:?}", buffer);
1411     ///
1412     ///     buffer.clear();
1413     /// }
1414     /// ```
1415     #[stable(feature = "rust1", since = "1.0.0")]
1416     fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1417         // Note that we are not calling the `.read_until` method here, but
1418         // rather our hardcoded implementation. For more details as to why, see
1419         // the comments in `read_to_end`.
1420         append_to_string(buf, |b| read_until(self, b'\n', b))
1421     }
1422
1423     /// Returns an iterator over the contents of this reader split on the byte
1424     /// `byte`.
1425     ///
1426     /// The iterator returned from this function will return instances of
1427     /// `io::Result<Vec<u8>>`. Each vector returned will *not* have the
1428     /// delimiter byte at the end.
1429     ///
1430     /// This function will yield errors whenever `read_until` would have also
1431     /// yielded an error.
1432     ///
1433     /// # Examples
1434     ///
1435     /// A locked standard input implements `BufRead`. In this example, we'll
1436     /// read some input from standard input, splitting on commas.
1437     ///
1438     /// ```
1439     /// use std::io;
1440     /// use std::io::prelude::*;
1441     ///
1442     /// let stdin = io::stdin();
1443     ///
1444     /// for content in stdin.lock().split(b',') {
1445     ///     println!("{:?}", content.unwrap());
1446     /// }
1447     /// ```
1448     #[stable(feature = "rust1", since = "1.0.0")]
1449     fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1450         Split { buf: self, delim: byte }
1451     }
1452
1453     /// Returns an iterator over the lines of this reader.
1454     ///
1455     /// The iterator returned from this function will yield instances of
1456     /// `io::Result<String>`. Each string returned will *not* have a newline
1457     /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1458     ///
1459     /// # Examples
1460     ///
1461     /// A locked standard input implements `BufRead`:
1462     ///
1463     /// ```
1464     /// use std::io;
1465     /// use std::io::prelude::*;
1466     ///
1467     /// let stdin = io::stdin();
1468     ///
1469     /// for line in stdin.lock().lines() {
1470     ///     println!("{}", line.unwrap());
1471     /// }
1472     /// ```
1473     #[stable(feature = "rust1", since = "1.0.0")]
1474     fn lines(self) -> Lines<Self> where Self: Sized {
1475         Lines { buf: self }
1476     }
1477 }
1478
1479 /// A `Write` adaptor which will write data to multiple locations.
1480 ///
1481 /// This struct is generally created by calling [`broadcast()`][broadcast] on a
1482 /// writer. Please see the documentation of `broadcast()` for more details.
1483 ///
1484 /// [broadcast]: trait.Write.html#method.broadcast
1485 #[unstable(feature = "io", reason = "awaiting stability of Write::broadcast",
1486            issue = "27802")]
1487 pub struct Broadcast<T, U> {
1488     first: T,
1489     second: U,
1490 }
1491
1492 #[unstable(feature = "io", reason = "awaiting stability of Write::broadcast",
1493            issue = "27802")]
1494 impl<T: Write, U: Write> Write for Broadcast<T, U> {
1495     fn write(&mut self, data: &[u8]) -> Result<usize> {
1496         let n = try!(self.first.write(data));
1497         // FIXME: what if the write fails? (we wrote something)
1498         try!(self.second.write_all(&data[..n]));
1499         Ok(n)
1500     }
1501
1502     fn flush(&mut self) -> Result<()> {
1503         self.first.flush().and(self.second.flush())
1504     }
1505 }
1506
1507 /// Adaptor to chain together two readers.
1508 ///
1509 /// This struct is generally created by calling [`chain()`][chain] on a reader.
1510 /// Please see the documentation of `chain()` for more details.
1511 ///
1512 /// [chain]: trait.Read.html#method.chain
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 pub struct Chain<T, U> {
1515     first: T,
1516     second: U,
1517     done_first: bool,
1518 }
1519
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<T: Read, U: Read> Read for Chain<T, U> {
1522     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1523         if !self.done_first {
1524             match try!(self.first.read(buf)) {
1525                 0 => { self.done_first = true; }
1526                 n => return Ok(n),
1527             }
1528         }
1529         self.second.read(buf)
1530     }
1531 }
1532
1533 /// Reader adaptor which limits the bytes read from an underlying reader.
1534 ///
1535 /// This struct is generally created by calling [`take()`][take] on a reader.
1536 /// Please see the documentation of `take()` for more details.
1537 ///
1538 /// [take]: trait.Read.html#method.take
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 pub struct Take<T> {
1541     inner: T,
1542     limit: u64,
1543 }
1544
1545 impl<T> Take<T> {
1546     /// Returns the number of bytes that can be read before this instance will
1547     /// return EOF.
1548     ///
1549     /// # Note
1550     ///
1551     /// This instance may reach EOF after reading fewer bytes than indicated by
1552     /// this method if the underlying `Read` instance reaches EOF.
1553     #[stable(feature = "rust1", since = "1.0.0")]
1554     pub fn limit(&self) -> u64 { self.limit }
1555 }
1556
1557 #[stable(feature = "rust1", since = "1.0.0")]
1558 impl<T: Read> Read for Take<T> {
1559     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1560         // Don't call into inner reader at all at EOF because it may still block
1561         if self.limit == 0 {
1562             return Ok(0);
1563         }
1564
1565         let max = cmp::min(buf.len() as u64, self.limit) as usize;
1566         let n = try!(self.inner.read(&mut buf[..max]));
1567         self.limit -= n as u64;
1568         Ok(n)
1569     }
1570 }
1571
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 impl<T: BufRead> BufRead for Take<T> {
1574     fn fill_buf(&mut self) -> Result<&[u8]> {
1575         let buf = try!(self.inner.fill_buf());
1576         let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1577         Ok(&buf[..cap])
1578     }
1579
1580     fn consume(&mut self, amt: usize) {
1581         // Don't let callers reset the limit by passing an overlarge value
1582         let amt = cmp::min(amt as u64, self.limit) as usize;
1583         self.limit -= amt as u64;
1584         self.inner.consume(amt);
1585     }
1586 }
1587
1588 /// An adaptor which will emit all read data to a specified writer as well.
1589 ///
1590 /// This struct is generally created by calling [`tee()`][tee] on a reader.
1591 /// Please see the documentation of `tee()` for more details.
1592 ///
1593 /// [tee]: trait.Read.html#method.tee
1594 #[unstable(feature = "io", reason = "awaiting stability of Read::tee",
1595            issue = "27802")]
1596 pub struct Tee<R, W> {
1597     reader: R,
1598     writer: W,
1599 }
1600
1601 #[unstable(feature = "io", reason = "awaiting stability of Read::tee",
1602            issue = "27802")]
1603 impl<R: Read, W: Write> Read for Tee<R, W> {
1604     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1605         let n = try!(self.reader.read(buf));
1606         // FIXME: what if the write fails? (we read something)
1607         try!(self.writer.write_all(&buf[..n]));
1608         Ok(n)
1609     }
1610 }
1611
1612 /// An iterator over `u8` values of a reader.
1613 ///
1614 /// This struct is generally created by calling [`bytes()`][bytes] on a reader.
1615 /// Please see the documentation of `bytes()` for more details.
1616 ///
1617 /// [bytes]: trait.Read.html#method.bytes
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 pub struct Bytes<R> {
1620     inner: R,
1621 }
1622
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl<R: Read> Iterator for Bytes<R> {
1625     type Item = Result<u8>;
1626
1627     fn next(&mut self) -> Option<Result<u8>> {
1628         let mut buf = [0];
1629         match self.inner.read(&mut buf) {
1630             Ok(0) => None,
1631             Ok(..) => Some(Ok(buf[0])),
1632             Err(e) => Some(Err(e)),
1633         }
1634     }
1635 }
1636
1637 /// An iterator over the `char`s of a reader.
1638 ///
1639 /// This struct is generally created by calling [`chars()`][chars] on a reader.
1640 /// Please see the documentation of `chars()` for more details.
1641 ///
1642 /// [chars]: trait.Read.html#method.chars
1643 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1644            issue = "27802")]
1645 pub struct Chars<R> {
1646     inner: R,
1647 }
1648
1649 /// An enumeration of possible errors that can be generated from the `Chars`
1650 /// adapter.
1651 #[derive(Debug)]
1652 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1653            issue = "27802")]
1654 pub enum CharsError {
1655     /// Variant representing that the underlying stream was read successfully
1656     /// but it did not contain valid utf8 data.
1657     NotUtf8,
1658
1659     /// Variant representing that an I/O error occurred.
1660     Other(Error),
1661 }
1662
1663 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1664            issue = "27802")]
1665 impl<R: Read> Iterator for Chars<R> {
1666     type Item = result::Result<char, CharsError>;
1667
1668     fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1669         let mut buf = [0];
1670         let first_byte = match self.inner.read(&mut buf) {
1671             Ok(0) => return None,
1672             Ok(..) => buf[0],
1673             Err(e) => return Some(Err(CharsError::Other(e))),
1674         };
1675         let width = core_str::utf8_char_width(first_byte);
1676         if width == 1 { return Some(Ok(first_byte as char)) }
1677         if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1678         let mut buf = [first_byte, 0, 0, 0];
1679         {
1680             let mut start = 1;
1681             while start < width {
1682                 match self.inner.read(&mut buf[start..width]) {
1683                     Ok(0) => return Some(Err(CharsError::NotUtf8)),
1684                     Ok(n) => start += n,
1685                     Err(e) => return Some(Err(CharsError::Other(e))),
1686                 }
1687             }
1688         }
1689         Some(match str::from_utf8(&buf[..width]).ok() {
1690             Some(s) => Ok(s.char_at(0)),
1691             None => Err(CharsError::NotUtf8),
1692         })
1693     }
1694 }
1695
1696 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1697            issue = "27802")]
1698 impl std_error::Error for CharsError {
1699     fn description(&self) -> &str {
1700         match *self {
1701             CharsError::NotUtf8 => "invalid utf8 encoding",
1702             CharsError::Other(ref e) => std_error::Error::description(e),
1703         }
1704     }
1705     fn cause(&self) -> Option<&std_error::Error> {
1706         match *self {
1707             CharsError::NotUtf8 => None,
1708             CharsError::Other(ref e) => e.cause(),
1709         }
1710     }
1711 }
1712
1713 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1714            issue = "27802")]
1715 impl fmt::Display for CharsError {
1716     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1717         match *self {
1718             CharsError::NotUtf8 => {
1719                 "byte stream did not contain valid utf8".fmt(f)
1720             }
1721             CharsError::Other(ref e) => e.fmt(f),
1722         }
1723     }
1724 }
1725
1726 /// An iterator over the contents of an instance of `BufRead` split on a
1727 /// particular byte.
1728 ///
1729 /// This struct is generally created by calling [`split()`][split] on a
1730 /// `BufRead`. Please see the documentation of `split()` for more details.
1731 ///
1732 /// [split]: trait.BufRead.html#method.split
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 pub struct Split<B> {
1735     buf: B,
1736     delim: u8,
1737 }
1738
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 impl<B: BufRead> Iterator for Split<B> {
1741     type Item = Result<Vec<u8>>;
1742
1743     fn next(&mut self) -> Option<Result<Vec<u8>>> {
1744         let mut buf = Vec::new();
1745         match self.buf.read_until(self.delim, &mut buf) {
1746             Ok(0) => None,
1747             Ok(_n) => {
1748                 if buf[buf.len() - 1] == self.delim {
1749                     buf.pop();
1750                 }
1751                 Some(Ok(buf))
1752             }
1753             Err(e) => Some(Err(e))
1754         }
1755     }
1756 }
1757
1758 /// An iterator over the lines of an instance of `BufRead`.
1759 ///
1760 /// This struct is generally created by calling [`lines()`][lines] on a
1761 /// `BufRead`. Please see the documentation of `lines()` for more details.
1762 ///
1763 /// [lines]: trait.BufRead.html#method.lines
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 pub struct Lines<B> {
1766     buf: B,
1767 }
1768
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 impl<B: BufRead> Iterator for Lines<B> {
1771     type Item = Result<String>;
1772
1773     fn next(&mut self) -> Option<Result<String>> {
1774         let mut buf = String::new();
1775         match self.buf.read_line(&mut buf) {
1776             Ok(0) => None,
1777             Ok(_n) => {
1778                 if buf.ends_with("\n") {
1779                     buf.pop();
1780                     if buf.ends_with("\r") {
1781                         buf.pop();
1782                     }
1783                 }
1784                 Some(Ok(buf))
1785             }
1786             Err(e) => Some(Err(e))
1787         }
1788     }
1789 }
1790
1791 #[cfg(test)]
1792 mod tests {
1793     use prelude::v1::*;
1794     use io::prelude::*;
1795     use io;
1796     use super::Cursor;
1797     use test;
1798     use super::repeat;
1799
1800     #[test]
1801     fn read_until() {
1802         let mut buf = Cursor::new(&b"12"[..]);
1803         let mut v = Vec::new();
1804         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
1805         assert_eq!(v, b"12");
1806
1807         let mut buf = Cursor::new(&b"1233"[..]);
1808         let mut v = Vec::new();
1809         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
1810         assert_eq!(v, b"123");
1811         v.truncate(0);
1812         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
1813         assert_eq!(v, b"3");
1814         v.truncate(0);
1815         assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
1816         assert_eq!(v, []);
1817     }
1818
1819     #[test]
1820     fn split() {
1821         let buf = Cursor::new(&b"12"[..]);
1822         let mut s = buf.split(b'3');
1823         assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1824         assert!(s.next().is_none());
1825
1826         let buf = Cursor::new(&b"1233"[..]);
1827         let mut s = buf.split(b'3');
1828         assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1829         assert_eq!(s.next().unwrap().unwrap(), vec![]);
1830         assert!(s.next().is_none());
1831     }
1832
1833     #[test]
1834     fn read_line() {
1835         let mut buf = Cursor::new(&b"12"[..]);
1836         let mut v = String::new();
1837         assert_eq!(buf.read_line(&mut v).unwrap(), 2);
1838         assert_eq!(v, "12");
1839
1840         let mut buf = Cursor::new(&b"12\n\n"[..]);
1841         let mut v = String::new();
1842         assert_eq!(buf.read_line(&mut v).unwrap(), 3);
1843         assert_eq!(v, "12\n");
1844         v.truncate(0);
1845         assert_eq!(buf.read_line(&mut v).unwrap(), 1);
1846         assert_eq!(v, "\n");
1847         v.truncate(0);
1848         assert_eq!(buf.read_line(&mut v).unwrap(), 0);
1849         assert_eq!(v, "");
1850     }
1851
1852     #[test]
1853     fn lines() {
1854         let buf = Cursor::new(&b"12\r"[..]);
1855         let mut s = buf.lines();
1856         assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
1857         assert!(s.next().is_none());
1858
1859         let buf = Cursor::new(&b"12\r\n\n"[..]);
1860         let mut s = buf.lines();
1861         assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
1862         assert_eq!(s.next().unwrap().unwrap(), "".to_string());
1863         assert!(s.next().is_none());
1864     }
1865
1866     #[test]
1867     fn read_to_end() {
1868         let mut c = Cursor::new(&b""[..]);
1869         let mut v = Vec::new();
1870         assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
1871         assert_eq!(v, []);
1872
1873         let mut c = Cursor::new(&b"1"[..]);
1874         let mut v = Vec::new();
1875         assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
1876         assert_eq!(v, b"1");
1877
1878         let cap = 1024 * 1024;
1879         let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
1880         let mut v = Vec::new();
1881         let (a, b) = data.split_at(data.len() / 2);
1882         assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
1883         assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
1884         assert_eq!(v, data);
1885     }
1886
1887     #[test]
1888     fn read_to_string() {
1889         let mut c = Cursor::new(&b""[..]);
1890         let mut v = String::new();
1891         assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
1892         assert_eq!(v, "");
1893
1894         let mut c = Cursor::new(&b"1"[..]);
1895         let mut v = String::new();
1896         assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
1897         assert_eq!(v, "1");
1898
1899         let mut c = Cursor::new(&b"\xff"[..]);
1900         let mut v = String::new();
1901         assert!(c.read_to_string(&mut v).is_err());
1902     }
1903
1904     #[test]
1905     fn read_exact() {
1906         let mut buf = [0; 4];
1907
1908         let mut c = Cursor::new(&b""[..]);
1909         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1910                    io::ErrorKind::UnexpectedEOF);
1911
1912         let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
1913         c.read_exact(&mut buf).unwrap();
1914         assert_eq!(&buf, b"1234");
1915         c.read_exact(&mut buf).unwrap();
1916         assert_eq!(&buf, b"5678");
1917         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1918                    io::ErrorKind::UnexpectedEOF);
1919     }
1920
1921     #[test]
1922     fn read_exact_slice() {
1923         let mut buf = [0; 4];
1924
1925         let mut c = &b""[..];
1926         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1927                    io::ErrorKind::UnexpectedEOF);
1928
1929         let mut c = &b"123"[..];
1930         assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1931                    io::ErrorKind::UnexpectedEOF);
1932         // make sure the optimized (early returning) method is being used
1933         assert_eq!(&buf, &[0; 4]);
1934
1935         let mut c = &b"1234"[..];
1936         c.read_exact(&mut buf).unwrap();
1937         assert_eq!(&buf, b"1234");
1938
1939         let mut c = &b"56789"[..];
1940         c.read_exact(&mut buf).unwrap();
1941         assert_eq!(&buf, b"5678");
1942         assert_eq!(c, b"9");
1943     }
1944
1945     #[test]
1946     fn take_eof() {
1947         struct R;
1948
1949         impl Read for R {
1950             fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1951                 Err(io::Error::new(io::ErrorKind::Other, ""))
1952             }
1953         }
1954
1955         let mut buf = [0; 1];
1956         assert_eq!(0, R.take(0).read(&mut buf).unwrap());
1957     }
1958
1959     #[bench]
1960     fn bench_read_to_end(b: &mut test::Bencher) {
1961         b.iter(|| {
1962             let mut lr = repeat(1).take(10000000);
1963             let mut vec = Vec::with_capacity(1024);
1964             super::read_to_end(&mut lr, &mut vec);
1965         });
1966     }
1967 }