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