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