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