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