1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Traits, helpers, and type definitions for core I/O functionality.
13 //! The `std::io` module contains a number of common things you'll need
14 //! when doing input and output. The most core part of this module is
15 //! the [`Read`] and [`Write`] traits, which provide the
16 //! most general interface for reading and writing input and output.
20 //! Because they are traits, [`Read`] and [`Write`] are implemented by a number
21 //! of other types, and you can implement them for your types too. As such,
22 //! you'll see a few different types of I/O throughout the documentation in
23 //! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
24 //! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
29 //! use std::io::prelude::*;
30 //! use std::fs::File;
32 //! # fn foo() -> io::Result<()> {
33 //! let mut f = File::open("foo.txt")?;
34 //! let mut buffer = [0; 10];
36 //! // read up to 10 bytes
37 //! f.read(&mut buffer)?;
39 //! println!("The bytes: {:?}", buffer);
44 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
45 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
46 //! of 'a type that implements the [`Read`] trait'. Much easier!
48 //! ## Seek and BufRead
50 //! Beyond that, there are two important traits that are provided: [`Seek`]
51 //! and [`BufRead`]. Both of these build on top of a reader to control
52 //! how the reading happens. [`Seek`] lets you control where the next byte is
57 //! use std::io::prelude::*;
58 //! use std::io::SeekFrom;
59 //! use std::fs::File;
61 //! # fn foo() -> io::Result<()> {
62 //! let mut f = File::open("foo.txt")?;
63 //! let mut buffer = [0; 10];
65 //! // skip to the last 10 bytes of the file
66 //! f.seek(SeekFrom::End(-10))?;
68 //! // read up to 10 bytes
69 //! f.read(&mut buffer)?;
71 //! println!("The bytes: {:?}", buffer);
76 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
77 //! to show it off, we'll need to talk about buffers in general. Keep reading!
79 //! ## BufReader and BufWriter
81 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
82 //! making near-constant calls to the operating system. To help with this,
83 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
84 //! readers and writers. The wrapper uses a buffer, reducing the number of
85 //! calls and providing nicer methods for accessing exactly what you want.
87 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
88 //! methods to any reader:
92 //! use std::io::prelude::*;
93 //! use std::io::BufReader;
94 //! use std::fs::File;
96 //! # fn foo() -> io::Result<()> {
97 //! let f = File::open("foo.txt")?;
98 //! let mut reader = BufReader::new(f);
99 //! let mut buffer = String::new();
101 //! // read a line into buffer
102 //! reader.read_line(&mut buffer)?;
104 //! println!("{}", buffer);
109 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
110 //! to [`write`][`Write::write`]:
114 //! use std::io::prelude::*;
115 //! use std::io::BufWriter;
116 //! use std::fs::File;
118 //! # fn foo() -> io::Result<()> {
119 //! let f = File::create("foo.txt")?;
121 //! let mut writer = BufWriter::new(f);
123 //! // write a byte to the buffer
124 //! writer.write(&[42])?;
126 //! } // the buffer is flushed once writer goes out of scope
132 //! ## Standard input and output
134 //! A very common source of input is standard input:
139 //! # fn foo() -> io::Result<()> {
140 //! let mut input = String::new();
142 //! io::stdin().read_line(&mut input)?;
144 //! println!("You typed: {}", input.trim());
149 //! Note that you cannot use the `?` operator in functions that do not return
150 //! a `Result<T, E>` (e.g. `main`). Instead, you can call `.unwrap()` or `match`
151 //! on the return value to catch any possible errors:
156 //! let mut input = String::new();
158 //! io::stdin().read_line(&mut input).unwrap();
161 //! And a very common source of output is standard output:
165 //! use std::io::prelude::*;
167 //! # fn foo() -> io::Result<()> {
168 //! io::stdout().write(&[42])?;
173 //! Of course, using [`io::stdout`] directly is less common than something like
176 //! ## Iterator types
178 //! A large number of the structures provided by `std::io` are for various
179 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
184 //! use std::io::prelude::*;
185 //! use std::io::BufReader;
186 //! use std::fs::File;
188 //! # fn foo() -> io::Result<()> {
189 //! let f = File::open("foo.txt")?;
190 //! let reader = BufReader::new(f);
192 //! for line in reader.lines() {
193 //! println!("{}", line?);
202 //! There are a number of [functions][functions-list] that offer access to various
203 //! features. For example, we can use three of these functions to copy everything
204 //! from standard input to standard output:
209 //! # fn foo() -> io::Result<()> {
210 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
215 //! [functions-list]: #functions-1
219 //! Last, but certainly not least, is [`io::Result`]. This type is used
220 //! as the return type of many `std::io` functions that can cause an error, and
221 //! can be returned from your own functions as well. Many of the examples in this
222 //! module use the [`?` operator]:
227 //! fn read_input() -> io::Result<()> {
228 //! let mut input = String::new();
230 //! io::stdin().read_line(&mut input)?;
232 //! println!("You typed: {}", input.trim());
238 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
239 //! common type for functions which don't have a 'real' return value, but do want to
240 //! return errors if they happen. In this case, the only purpose of this function is
241 //! to read the line and print it, so we use `()`.
243 //! ## Platform-specific behavior
245 //! Many I/O functions throughout the standard library are documented to indicate
246 //! what various library or syscalls they are delegated to. This is done to help
247 //! applications both understand what's happening under the hood as well as investigate
248 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
249 //! contract. The implementation of many of these functions are subject to change over
250 //! time and may call fewer or more syscalls/library functions.
252 //! [`Read`]: trait.Read.html
253 //! [`Write`]: trait.Write.html
254 //! [`Seek`]: trait.Seek.html
255 //! [`BufRead`]: trait.BufRead.html
256 //! [`File`]: ../fs/struct.File.html
257 //! [`TcpStream`]: ../net/struct.TcpStream.html
258 //! [`Vec<T>`]: ../vec/struct.Vec.html
259 //! [`BufReader`]: struct.BufReader.html
260 //! [`BufWriter`]: struct.BufWriter.html
261 //! [`Write::write`]: trait.Write.html#tymethod.write
262 //! [`io::stdout`]: fn.stdout.html
263 //! [`println!`]: ../macro.println.html
264 //! [`Lines`]: struct.Lines.html
265 //! [`io::Result`]: type.Result.html
266 //! [`?` operator]: ../../book/syntax-index.html
267 //! [`Read::read`]: trait.Read.html#tymethod.read
269 #![stable(feature = "rust1", since = "1.0.0")]
272 use core::str as core_str;
273 use error as std_error;
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::buffered::{BufReader, BufWriter, LineWriter};
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::buffered::IntoInnerError;
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub use self::cursor::Cursor;
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub use self::error::{Result, Error, ErrorKind};
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
293 #[unstable(feature = "libstd_io_internals", issue = "0")]
294 #[doc(no_inline, hidden)]
295 pub use self::stdio::{set_panic, set_print};
306 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
308 // A few methods below (read_to_string, read_line) will append data into a
309 // `String` buffer, but we need to be pretty careful when doing this. The
310 // implementation will just call `.as_mut_vec()` and then delegate to a
311 // byte-oriented reading method, but we must ensure that when returning we never
312 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
314 // To this end, we use an RAII guard (to protect against panics) which updates
315 // the length of the string when it is dropped. This guard initially truncates
316 // the string to the prior length and only after we've validated that the
317 // new contents are valid UTF-8 do we allow it to set a longer length.
319 // The unsafety in this function is twofold:
321 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
323 // 2. We're passing a raw buffer to the function `f`, and it is expected that
324 // the function only *appends* bytes to the buffer. We'll get undefined
325 // behavior if existing bytes are overwritten to have non-UTF-8 data.
326 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
327 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
329 struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
330 impl<'a> Drop for Guard<'a> {
332 unsafe { self.s.set_len(self.len); }
337 let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
339 if str::from_utf8(&g.s[g.len..]).is_err() {
341 Err(Error::new(ErrorKind::InvalidData,
342 "stream did not contain valid UTF-8"))
351 // This uses an adaptive system to extend the vector when it fills. We want to
352 // avoid paying to allocate and zero a huge chunk of memory if the reader only
353 // has 4 bytes while still making large reads if the reader does have a ton
354 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
355 // time is 4,500 times (!) slower than this if the reader has a very small
356 // amount of data to return.
357 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
358 let start_len = buf.len();
359 let mut len = start_len;
360 let mut new_write_size = 16;
363 if len == buf.len() {
364 if new_write_size < DEFAULT_BUF_SIZE {
367 buf.resize(len + new_write_size, 0);
370 match r.read(&mut buf[len..]) {
372 ret = Ok(len - start_len);
376 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
388 /// The `Read` trait allows for reading bytes from a source.
390 /// Implementors of the `Read` trait are sometimes called 'readers'.
392 /// Readers are defined by one required method, `read()`. Each call to `read`
393 /// will attempt to pull bytes from this source into a provided buffer. A
394 /// number of other methods are implemented in terms of `read()`, giving
395 /// implementors a number of ways to read bytes while only needing to implement
398 /// Readers are intended to be composable with one another. Many implementors
399 /// throughout `std::io` take and provide types which implement the `Read`
402 /// Please note that each call to `read` may involve a system call, and
403 /// therefore, using something that implements [`BufRead`][bufread], such as
404 /// [`BufReader`][bufreader], will be more efficient.
406 /// [bufread]: trait.BufRead.html
407 /// [bufreader]: struct.BufReader.html
411 /// [`File`][file]s implement `Read`:
413 /// [file]: ../fs/struct.File.html
417 /// use std::io::prelude::*;
418 /// use std::fs::File;
420 /// # fn foo() -> io::Result<()> {
421 /// let mut f = File::open("foo.txt")?;
422 /// let mut buffer = [0; 10];
424 /// // read up to 10 bytes
425 /// f.read(&mut buffer)?;
427 /// let mut buffer = vec![0; 10];
428 /// // read the whole file
429 /// f.read_to_end(&mut buffer)?;
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)?;
435 /// // and more! See the other methods for more details.
439 #[stable(feature = "rust1", since = "1.0.0")]
441 /// Pull some bytes from this source into the specified buffer, returning
442 /// how many bytes were read.
444 /// This function does not provide any guarantees about whether it blocks
445 /// waiting for data, but if an object needs to block for a read but cannot
446 /// it will typically signal this via an `Err` return value.
448 /// If the return value of this method is `Ok(n)`, then it must be
449 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
450 /// that the buffer `buf` has been filled in with `n` bytes of data from this
451 /// source. If `n` is `0`, then it can indicate one of two scenarios:
453 /// 1. This reader has reached its "end of file" and will likely no longer
454 /// be able to produce bytes. Note that this does not mean that the
455 /// reader will *always* no longer be able to produce bytes.
456 /// 2. The buffer specified was 0 bytes in length.
458 /// No guarantees are provided about the contents of `buf` when this
459 /// function is called, implementations cannot rely on any property of the
460 /// contents of `buf` being true. It is recommended that implementations
461 /// only write data to `buf` instead of reading its contents.
465 /// If this function encounters any form of I/O or other error, an error
466 /// variant will be returned. If an error is returned then it must be
467 /// guaranteed that no bytes were read.
469 /// An error of the `ErrorKind::Interrupted` kind is non-fatal and the read
470 /// operation should be retried if there is nothing else to do.
474 /// [`File`][file]s implement `Read`:
476 /// [file]: ../fs/struct.File.html
480 /// use std::io::prelude::*;
481 /// use std::fs::File;
483 /// # fn foo() -> io::Result<()> {
484 /// let mut f = File::open("foo.txt")?;
485 /// let mut buffer = [0; 10];
487 /// // read up to 10 bytes
488 /// f.read(&mut buffer[..])?;
492 #[stable(feature = "rust1", since = "1.0.0")]
493 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
495 /// Read all bytes until EOF in this source, placing them into `buf`.
497 /// All bytes read from this source will be appended to the specified buffer
498 /// `buf`. This function will continuously call `read` to append more data to
499 /// `buf` until `read` returns either `Ok(0)` or an error of
500 /// non-`ErrorKind::Interrupted` kind.
502 /// If successful, this function will return the total number of bytes read.
506 /// If this function encounters an error of the kind
507 /// `ErrorKind::Interrupted` then the error is ignored and the operation
510 /// If any other read error is encountered then this function immediately
511 /// returns. Any bytes which have already been read will be appended to
516 /// [`File`][file]s implement `Read`:
518 /// [file]: ../fs/struct.File.html
522 /// use std::io::prelude::*;
523 /// use std::fs::File;
525 /// # fn foo() -> io::Result<()> {
526 /// let mut f = File::open("foo.txt")?;
527 /// let mut buffer = Vec::new();
529 /// // read the whole file
530 /// f.read_to_end(&mut buffer)?;
534 #[stable(feature = "rust1", since = "1.0.0")]
535 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
536 read_to_end(self, buf)
539 /// Read all bytes until EOF in this source, placing them into `buf`.
541 /// If successful, this function returns the number of bytes which were read
542 /// and appended to `buf`.
546 /// If the data in this stream is *not* valid UTF-8 then an error is
547 /// returned and `buf` is unchanged.
549 /// See [`read_to_end`][readtoend] for other error semantics.
551 /// [readtoend]: #method.read_to_end
555 /// [`File`][file]s implement `Read`:
557 /// [file]: ../fs/struct.File.html
561 /// use std::io::prelude::*;
562 /// use std::fs::File;
564 /// # fn foo() -> io::Result<()> {
565 /// let mut f = File::open("foo.txt")?;
566 /// let mut buffer = String::new();
568 /// f.read_to_string(&mut buffer)?;
572 #[stable(feature = "rust1", since = "1.0.0")]
573 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
574 // Note that we do *not* call `.read_to_end()` here. We are passing
575 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
576 // method to fill it up. An arbitrary implementation could overwrite the
577 // entire contents of the vector, not just append to it (which is what
578 // we are expecting).
580 // To prevent extraneously checking the UTF-8-ness of the entire buffer
581 // we pass it to our hardcoded `read_to_end` implementation which we
582 // know is guaranteed to only read data into the end of the buffer.
583 append_to_string(buf, |b| read_to_end(self, b))
586 /// Read the exact number of bytes required to fill `buf`.
588 /// This function reads as many bytes as necessary to completely fill the
589 /// specified buffer `buf`.
591 /// No guarantees are provided about the contents of `buf` when this
592 /// function is called, implementations cannot rely on any property of the
593 /// contents of `buf` being true. It is recommended that implementations
594 /// only write data to `buf` instead of reading its contents.
598 /// If this function encounters an error of the kind
599 /// `ErrorKind::Interrupted` then the error is ignored and the operation
602 /// If this function encounters an "end of file" before completely filling
603 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
604 /// The contents of `buf` are unspecified in this case.
606 /// If any other read error is encountered then this function immediately
607 /// returns. The contents of `buf` are unspecified in this case.
609 /// If this function returns an error, it is unspecified how many bytes it
610 /// has read, but it will never read more than would be necessary to
611 /// completely fill the buffer.
615 /// [`File`][file]s implement `Read`:
617 /// [file]: ../fs/struct.File.html
621 /// use std::io::prelude::*;
622 /// use std::fs::File;
624 /// # fn foo() -> io::Result<()> {
625 /// let mut f = File::open("foo.txt")?;
626 /// let mut buffer = [0; 10];
628 /// // read exactly 10 bytes
629 /// f.read_exact(&mut buffer)?;
633 #[stable(feature = "read_exact", since = "1.6.0")]
634 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
635 while !buf.is_empty() {
636 match self.read(buf) {
638 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
639 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
640 Err(e) => return Err(e),
644 Err(Error::new(ErrorKind::UnexpectedEof,
645 "failed to fill whole buffer"))
651 /// Creates a "by reference" adaptor for this instance of `Read`.
653 /// The returned adaptor also implements `Read` and will simply borrow this
658 /// [`File`][file]s implement `Read`:
660 /// [file]: ../fs/struct.File.html
664 /// use std::io::Read;
665 /// use std::fs::File;
667 /// # fn foo() -> io::Result<()> {
668 /// let mut f = File::open("foo.txt")?;
669 /// let mut buffer = Vec::new();
670 /// let mut other_buffer = Vec::new();
673 /// let reference = f.by_ref();
675 /// // read at most 5 bytes
676 /// reference.take(5).read_to_end(&mut buffer)?;
678 /// } // drop our &mut reference so we can use f again
680 /// // original file still usable, read the rest
681 /// f.read_to_end(&mut other_buffer)?;
685 #[stable(feature = "rust1", since = "1.0.0")]
686 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
688 /// Transforms this `Read` instance to an `Iterator` over its bytes.
690 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
691 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
692 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
697 /// [`File`][file]s implement `Read`:
699 /// [file]: ../fs/struct.File.html
703 /// use std::io::prelude::*;
704 /// use std::fs::File;
706 /// # fn foo() -> io::Result<()> {
707 /// let mut f = File::open("foo.txt")?;
709 /// for byte in f.bytes() {
710 /// println!("{}", byte.unwrap());
715 #[stable(feature = "rust1", since = "1.0.0")]
716 fn bytes(self) -> Bytes<Self> where Self: Sized {
717 Bytes { inner: self }
720 /// Transforms this `Read` instance to an `Iterator` over `char`s.
722 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
723 /// sequence of characters. The returned iterator will return `None` once
724 /// EOF is reached for this reader. Otherwise each element yielded will be a
725 /// `Result<char, E>` where `E` may contain information about what I/O error
726 /// occurred or where decoding failed.
728 /// Currently this adaptor will discard intermediate data read, and should
729 /// be avoided if this is not desired.
733 /// [`File`][file]s implement `Read`:
735 /// [file]: ../fs/struct.File.html
740 /// use std::io::prelude::*;
741 /// use std::fs::File;
743 /// # fn foo() -> io::Result<()> {
744 /// let mut f = File::open("foo.txt")?;
746 /// for c in f.chars() {
747 /// println!("{}", c.unwrap());
752 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
753 of where errors happen is currently \
754 unclear and may change",
756 fn chars(self) -> Chars<Self> where Self: Sized {
757 Chars { inner: self }
760 /// Creates an adaptor which will chain this stream with another.
762 /// The returned `Read` instance will first read all bytes from this object
763 /// until EOF is encountered. Afterwards the output is equivalent to the
764 /// output of `next`.
768 /// [`File`][file]s implement `Read`:
770 /// [file]: ../fs/struct.File.html
774 /// use std::io::prelude::*;
775 /// use std::fs::File;
777 /// # fn foo() -> io::Result<()> {
778 /// let mut f1 = File::open("foo.txt")?;
779 /// let mut f2 = File::open("bar.txt")?;
781 /// let mut handle = f1.chain(f2);
782 /// let mut buffer = String::new();
784 /// // read the value into a String. We could use any Read method here,
785 /// // this is just one example.
786 /// handle.read_to_string(&mut buffer)?;
790 #[stable(feature = "rust1", since = "1.0.0")]
791 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
792 Chain { first: self, second: next, done_first: false }
795 /// Creates an adaptor which will read at most `limit` bytes from it.
797 /// This function returns a new instance of `Read` which will read at most
798 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
799 /// read errors will not count towards the number of bytes read and future
800 /// calls to `read` may succeed.
804 /// [`File`][file]s implement `Read`:
806 /// [file]: ../fs/struct.File.html
810 /// use std::io::prelude::*;
811 /// use std::fs::File;
813 /// # fn foo() -> io::Result<()> {
814 /// let mut f = File::open("foo.txt")?;
815 /// let mut buffer = [0; 5];
817 /// // read at most five bytes
818 /// let mut handle = f.take(5);
820 /// handle.read(&mut buffer)?;
824 #[stable(feature = "rust1", since = "1.0.0")]
825 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
826 Take { inner: self, limit: limit }
830 /// A trait for objects which are byte-oriented sinks.
832 /// Implementors of the `Write` trait are sometimes called 'writers'.
834 /// Writers are defined by two required methods, [`write`] and [`flush`]:
836 /// * The [`write`] method will attempt to write some data into the object,
837 /// returning how many bytes were successfully written.
839 /// * The [`flush`] method is useful for adaptors and explicit buffers
840 /// themselves for ensuring that all buffered data has been pushed out to the
843 /// Writers are intended to be composable with one another. Many implementors
844 /// throughout [`std::io`] take and provide types which implement the `Write`
847 /// [`write`]: #tymethod.write
848 /// [`flush`]: #tymethod.flush
849 /// [`std::io`]: index.html
854 /// use std::io::prelude::*;
855 /// use std::fs::File;
857 /// # fn foo() -> std::io::Result<()> {
858 /// let mut buffer = File::create("foo.txt")?;
860 /// buffer.write(b"some bytes")?;
864 #[stable(feature = "rust1", since = "1.0.0")]
866 /// Write a buffer into this object, returning how many bytes were written.
868 /// This function will attempt to write the entire contents of `buf`, but
869 /// the entire write may not succeed, or the write may also generate an
870 /// error. A call to `write` represents *at most one* attempt to write to
871 /// any wrapped object.
873 /// Calls to `write` are not guaranteed to block waiting for data to be
874 /// written, and a write which would otherwise block can be indicated through
875 /// an `Err` variant.
877 /// If the return value is `Ok(n)` then it must be guaranteed that
878 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
879 /// underlying object is no longer able to accept bytes and will likely not
880 /// be able to in the future as well, or that the buffer provided is empty.
884 /// Each call to `write` may generate an I/O error indicating that the
885 /// operation could not be completed. If an error is returned then no bytes
886 /// in the buffer were written to this writer.
888 /// It is **not** considered an error if the entire buffer could not be
889 /// written to this writer.
891 /// An error of the `ErrorKind::Interrupted` kind is non-fatal and the
892 /// write operation should be retried if there is nothing else to do.
897 /// use std::io::prelude::*;
898 /// use std::fs::File;
900 /// # fn foo() -> std::io::Result<()> {
901 /// let mut buffer = File::create("foo.txt")?;
903 /// // Writes some prefix of the byte string, not necessarily all of it.
904 /// buffer.write(b"some bytes")?;
908 #[stable(feature = "rust1", since = "1.0.0")]
909 fn write(&mut self, buf: &[u8]) -> Result<usize>;
911 /// Flush this output stream, ensuring that all intermediately buffered
912 /// contents reach their destination.
916 /// It is considered an error if not all bytes could be written due to
917 /// I/O errors or EOF being reached.
922 /// use std::io::prelude::*;
923 /// use std::io::BufWriter;
924 /// use std::fs::File;
926 /// # fn foo() -> std::io::Result<()> {
927 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
929 /// buffer.write(b"some bytes")?;
934 #[stable(feature = "rust1", since = "1.0.0")]
935 fn flush(&mut self) -> Result<()>;
937 /// Attempts to write an entire buffer into this write.
939 /// This method will continuously call `write` until there is no more data
940 /// to be written or an error of non-`ErrorKind::Interrupted` kind is
941 /// returned. This method will not return until the entire buffer has been
942 /// successfully written or such an error occurs. The first error that is
943 /// not of `ErrorKind::Interrupted` kind generated from this method will be
948 /// This function will return the first error of
949 /// non-`ErrorKind::Interrupted` kind that `write` returns.
954 /// use std::io::prelude::*;
955 /// use std::fs::File;
957 /// # fn foo() -> std::io::Result<()> {
958 /// let mut buffer = File::create("foo.txt")?;
960 /// buffer.write_all(b"some bytes")?;
964 #[stable(feature = "rust1", since = "1.0.0")]
965 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
966 while !buf.is_empty() {
967 match self.write(buf) {
968 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
969 "failed to write whole buffer")),
970 Ok(n) => buf = &buf[n..],
971 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
972 Err(e) => return Err(e),
978 /// Writes a formatted string into this writer, returning any error
981 /// This method is primarily used to interface with the
982 /// [`format_args!`][formatargs] macro, but it is rare that this should
983 /// explicitly be called. The [`write!`][write] macro should be favored to
984 /// invoke this method instead.
986 /// [formatargs]: ../macro.format_args.html
987 /// [write]: ../macro.write.html
989 /// This function internally uses the [`write_all`][writeall] method on
990 /// this trait and hence will continuously write data so long as no errors
991 /// are received. This also means that partial writes are not indicated in
994 /// [writeall]: #method.write_all
998 /// This function will return any I/O error reported while formatting.
1003 /// use std::io::prelude::*;
1004 /// use std::fs::File;
1006 /// # fn foo() -> std::io::Result<()> {
1007 /// let mut buffer = File::create("foo.txt")?;
1010 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1011 /// // turns into this:
1012 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1018 // Create a shim which translates a Write to a fmt::Write and saves
1019 // off I/O errors. instead of discarding them
1020 struct Adaptor<'a, T: ?Sized + 'a> {
1025 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1026 fn write_str(&mut self, s: &str) -> fmt::Result {
1027 match self.inner.write_all(s.as_bytes()) {
1030 self.error = Err(e);
1037 let mut output = Adaptor { inner: self, error: Ok(()) };
1038 match fmt::write(&mut output, fmt) {
1041 // check if the error came from the underlying `Write` or not
1042 if output.error.is_err() {
1045 Err(Error::new(ErrorKind::Other, "formatter error"))
1051 /// Creates a "by reference" adaptor for this instance of `Write`.
1053 /// The returned adaptor also implements `Write` and will simply borrow this
1059 /// use std::io::Write;
1060 /// use std::fs::File;
1062 /// # fn foo() -> std::io::Result<()> {
1063 /// let mut buffer = File::create("foo.txt")?;
1065 /// let reference = buffer.by_ref();
1067 /// // we can use reference just like our original buffer
1068 /// reference.write_all(b"some bytes")?;
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1076 /// The `Seek` trait provides a cursor which can be moved within a stream of
1079 /// The stream typically has a fixed size, allowing seeking relative to either
1080 /// end or the current offset.
1084 /// [`File`][file]s implement `Seek`:
1086 /// [file]: ../fs/struct.File.html
1090 /// use std::io::prelude::*;
1091 /// use std::fs::File;
1092 /// use std::io::SeekFrom;
1094 /// # fn foo() -> io::Result<()> {
1095 /// let mut f = File::open("foo.txt")?;
1097 /// // move the cursor 42 bytes from the start of the file
1098 /// f.seek(SeekFrom::Start(42))?;
1102 #[stable(feature = "rust1", since = "1.0.0")]
1104 /// Seek to an offset, in bytes, in a stream.
1106 /// A seek beyond the end of a stream is allowed, but implementation
1109 /// If the seek operation completed successfully,
1110 /// this method returns the new position from the start of the stream.
1111 /// That position can be used later with [`SeekFrom::Start`].
1115 /// Seeking to a negative offset is considered an error.
1117 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1122 /// Enumeration of possible methods to seek within an I/O object.
1124 /// It is used by the [`Seek`] trait.
1126 /// [`Seek`]: trait.Seek.html
1127 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1128 #[stable(feature = "rust1", since = "1.0.0")]
1130 /// Set the offset to the provided number of bytes.
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1134 /// Set the offset to the size of this object plus the specified number of
1137 /// It is possible to seek beyond the end of an object, but it's an error to
1138 /// seek before byte 0.
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1142 /// Set the offset to the current position plus the specified number of
1145 /// It is possible to seek beyond the end of an object, but it's an error to
1146 /// seek before byte 0.
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1151 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1155 let (done, used) = {
1156 let available = match r.fill_buf() {
1158 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1159 Err(e) => return Err(e)
1161 match memchr::memchr(delim, available) {
1163 buf.extend_from_slice(&available[..i + 1]);
1167 buf.extend_from_slice(available);
1168 (false, available.len())
1174 if done || used == 0 {
1180 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1181 /// to perform extra ways of reading.
1183 /// For example, reading line-by-line is inefficient without using a buffer, so
1184 /// if you want to read by line, you'll need `BufRead`, which includes a
1185 /// [`read_line`] method as well as a [`lines`] iterator.
1189 /// A locked standard input implements `BufRead`:
1193 /// use std::io::prelude::*;
1195 /// let stdin = io::stdin();
1196 /// for line in stdin.lock().lines() {
1197 /// println!("{}", line.unwrap());
1201 /// If you have something that implements [`Read`], you can use the [`BufReader`
1202 /// type][`BufReader`] to turn it into a `BufRead`.
1204 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1205 /// [`BufReader`] to the rescue!
1207 /// [`BufReader`]: struct.BufReader.html
1208 /// [`File`]: ../fs/struct.File.html
1209 /// [`read_line`]: #method.read_line
1210 /// [`lines`]: #method.lines
1211 /// [`Read`]: trait.Read.html
1214 /// use std::io::{self, BufReader};
1215 /// use std::io::prelude::*;
1216 /// use std::fs::File;
1218 /// # fn foo() -> io::Result<()> {
1219 /// let f = File::open("foo.txt")?;
1220 /// let f = BufReader::new(f);
1222 /// for line in f.lines() {
1223 /// println!("{}", line.unwrap());
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 pub trait BufRead: Read {
1232 /// Fills the internal buffer of this object, returning the buffer contents.
1234 /// This function is a lower-level call. It needs to be paired with the
1235 /// [`consume`] method to function properly. When calling this
1236 /// method, none of the contents will be "read" in the sense that later
1237 /// calling `read` may return the same contents. As such, [`consume`] must
1238 /// be called with the number of bytes that are consumed from this buffer to
1239 /// ensure that the bytes are never returned twice.
1241 /// [`consume`]: #tymethod.consume
1243 /// An empty buffer returned indicates that the stream has reached EOF.
1247 /// This function will return an I/O error if the underlying reader was
1248 /// read, but returned an error.
1252 /// A locked standard input implements `BufRead`:
1256 /// use std::io::prelude::*;
1258 /// let stdin = io::stdin();
1259 /// let mut stdin = stdin.lock();
1261 /// // we can't have two `&mut` references to `stdin`, so use a block
1262 /// // to end the borrow early.
1264 /// let buffer = stdin.fill_buf().unwrap();
1266 /// // work with buffer
1267 /// println!("{:?}", buffer);
1272 /// // ensure the bytes we worked with aren't returned again later
1273 /// stdin.consume(length);
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 fn fill_buf(&mut self) -> Result<&[u8]>;
1278 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1279 /// so they should no longer be returned in calls to `read`.
1281 /// This function is a lower-level call. It needs to be paired with the
1282 /// [`fill_buf`] method to function properly. This function does
1283 /// not perform any I/O, it simply informs this object that some amount of
1284 /// its buffer, returned from [`fill_buf`], has been consumed and should
1285 /// no longer be returned. As such, this function may do odd things if
1286 /// [`fill_buf`] isn't called before calling it.
1288 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1293 /// Since `consume()` is meant to be used with [`fill_buf`],
1294 /// that method's example includes an example of `consume()`.
1296 /// [`fill_buf`]: #tymethod.fill_buf
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 fn consume(&mut self, amt: usize);
1300 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1302 /// This function will read bytes from the underlying stream until the
1303 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1304 /// the delimiter (if found) will be appended to `buf`.
1306 /// If successful, this function will return the total number of bytes read.
1310 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1311 /// will otherwise return any errors returned by [`fill_buf`].
1313 /// If an I/O error is encountered then all bytes read so far will be
1314 /// present in `buf` and its length will have been adjusted appropriately.
1316 /// [`fill_buf`]: #tymethod.fill_buf
1317 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1321 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1322 /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1323 /// in hyphen delimited segments:
1325 /// [`Cursor`]: struct.Cursor.html
1328 /// use std::io::{self, BufRead};
1330 /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1331 /// let mut buf = vec![];
1333 /// // cursor is at 'l'
1334 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1335 /// .expect("reading from cursor won't fail");
1336 /// assert_eq!(num_bytes, 6);
1337 /// assert_eq!(buf, b"lorem-");
1340 /// // cursor is at 'i'
1341 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1342 /// .expect("reading from cursor won't fail");
1343 /// assert_eq!(num_bytes, 5);
1344 /// assert_eq!(buf, b"ipsum");
1347 /// // cursor is at EOF
1348 /// let num_bytes = cursor.read_until(b'-', &mut buf)
1349 /// .expect("reading from cursor won't fail");
1350 /// assert_eq!(num_bytes, 0);
1351 /// assert_eq!(buf, b"");
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1355 read_until(self, byte, buf)
1358 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1359 /// them to the provided buffer.
1361 /// This function will read bytes from the underlying stream until the
1362 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1363 /// up to, and including, the delimiter (if found) will be appended to
1366 /// If successful, this function will return the total number of bytes read.
1370 /// This function has the same error semantics as [`read_until`] and will
1371 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1372 /// error is encountered then `buf` may contain some bytes already read in
1373 /// the event that all data read so far was valid UTF-8.
1377 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1378 /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1380 /// [`Cursor`]: struct.Cursor.html
1383 /// use std::io::{self, BufRead};
1385 /// let mut cursor = io::Cursor::new(b"foo\nbar");
1386 /// let mut buf = String::new();
1388 /// // cursor is at 'f'
1389 /// let num_bytes = cursor.read_line(&mut buf)
1390 /// .expect("reading from cursor won't fail");
1391 /// assert_eq!(num_bytes, 4);
1392 /// assert_eq!(buf, "foo\n");
1395 /// // cursor is at 'b'
1396 /// let num_bytes = cursor.read_line(&mut buf)
1397 /// .expect("reading from cursor won't fail");
1398 /// assert_eq!(num_bytes, 3);
1399 /// assert_eq!(buf, "bar");
1402 /// // cursor is at EOF
1403 /// let num_bytes = cursor.read_line(&mut buf)
1404 /// .expect("reading from cursor won't fail");
1405 /// assert_eq!(num_bytes, 0);
1406 /// assert_eq!(buf, "");
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1410 // Note that we are not calling the `.read_until` method here, but
1411 // rather our hardcoded implementation. For more details as to why, see
1412 // the comments in `read_to_end`.
1413 append_to_string(buf, |b| read_until(self, b'\n', b))
1416 /// Returns an iterator over the contents of this reader split on the byte
1419 /// The iterator returned from this function will return instances of
1420 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1421 /// the delimiter byte at the end.
1423 /// This function will yield errors whenever [`read_until`] would have
1424 /// also yielded an error.
1426 /// [`io::Result`]: type.Result.html
1427 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1428 /// [`read_until`]: #method.read_until
1432 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1433 /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1434 /// segments in a byte slice
1436 /// [`Cursor`]: struct.Cursor.html
1439 /// use std::io::{self, BufRead};
1441 /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1443 /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
1444 /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
1445 /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
1446 /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
1447 /// assert_eq!(split_iter.next(), None);
1449 #[stable(feature = "rust1", since = "1.0.0")]
1450 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1451 Split { buf: self, delim: byte }
1454 /// Returns an iterator over the lines of this reader.
1456 /// The iterator returned from this function will yield instances of
1457 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1458 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1460 /// [`io::Result`]: type.Result.html
1461 /// [`String`]: ../string/struct.String.html
1465 /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1466 /// this example, we use [`Cursor`] to iterate over all the lines in a byte
1469 /// [`Cursor`]: struct.Cursor.html
1472 /// use std::io::{self, BufRead};
1474 /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
1476 /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
1477 /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
1478 /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
1479 /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
1480 /// assert_eq!(lines_iter.next(), None);
1485 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1487 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 fn lines(self) -> Lines<Self> where Self: Sized {
1494 /// Adaptor to chain together two readers.
1496 /// This struct is generally created by calling [`chain`] on a reader.
1497 /// Please see the documentation of [`chain`] for more details.
1499 /// [`chain`]: trait.Read.html#method.chain
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 pub struct Chain<T, U> {
1507 impl<T, U> Chain<T, U> {
1508 /// Consumes the `Chain`, returning the wrapped readers.
1513 /// #![feature(more_io_inner_methods)]
1516 /// use std::io::prelude::*;
1517 /// use std::fs::File;
1519 /// # fn foo() -> io::Result<()> {
1520 /// let mut foo_file = File::open("foo.txt")?;
1521 /// let mut bar_file = File::open("bar.txt")?;
1523 /// let chain = foo_file.chain(bar_file);
1524 /// let (foo_file, bar_file) = chain.into_inner();
1528 #[unstable(feature = "more_io_inner_methods", issue="41519")]
1529 pub fn into_inner(self) -> (T, U) {
1530 (self.first, self.second)
1533 /// Gets references to the underlying readers in this `Chain`.
1538 /// #![feature(more_io_inner_methods)]
1541 /// use std::io::prelude::*;
1542 /// use std::fs::File;
1544 /// # fn foo() -> io::Result<()> {
1545 /// let mut foo_file = File::open("foo.txt")?;
1546 /// let mut bar_file = File::open("bar.txt")?;
1548 /// let chain = foo_file.chain(bar_file);
1549 /// let (foo_file, bar_file) = chain.get_ref();
1553 #[unstable(feature = "more_io_inner_methods", issue="41519")]
1554 pub fn get_ref(&self) -> (&T, &U) {
1555 (&self.first, &self.second)
1558 /// Gets mutable references to the underlying readers in this `Chain`.
1560 /// Care should be taken to avoid modifying the internal I/O state of the
1561 /// underlying readers as doing so may corrupt the internal state of this
1567 /// #![feature(more_io_inner_methods)]
1570 /// use std::io::prelude::*;
1571 /// use std::fs::File;
1573 /// # fn foo() -> io::Result<()> {
1574 /// let mut foo_file = File::open("foo.txt")?;
1575 /// let mut bar_file = File::open("bar.txt")?;
1577 /// let mut chain = foo_file.chain(bar_file);
1578 /// let (foo_file, bar_file) = chain.get_mut();
1582 #[unstable(feature = "more_io_inner_methods", issue="41519")]
1583 pub fn get_mut(&mut self) -> (&mut T, &mut U) {
1584 (&mut self.first, &mut self.second)
1588 #[stable(feature = "std_debug", since = "1.16.0")]
1589 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1590 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1591 f.debug_struct("Chain")
1592 .field("t", &self.first)
1593 .field("u", &self.second)
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 impl<T: Read, U: Read> Read for Chain<T, U> {
1600 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1601 if !self.done_first {
1602 match self.first.read(buf)? {
1603 0 if buf.len() != 0 => { self.done_first = true; }
1607 self.second.read(buf)
1611 #[stable(feature = "chain_bufread", since = "1.9.0")]
1612 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1613 fn fill_buf(&mut self) -> Result<&[u8]> {
1614 if !self.done_first {
1615 match self.first.fill_buf()? {
1616 buf if buf.len() == 0 => { self.done_first = true; }
1617 buf => return Ok(buf),
1620 self.second.fill_buf()
1623 fn consume(&mut self, amt: usize) {
1624 if !self.done_first {
1625 self.first.consume(amt)
1627 self.second.consume(amt)
1632 /// Reader adaptor which limits the bytes read from an underlying reader.
1634 /// This struct is generally created by calling [`take`] on a reader.
1635 /// Please see the documentation of [`take`] for more details.
1637 /// [`take`]: trait.Read.html#method.take
1638 #[stable(feature = "rust1", since = "1.0.0")]
1640 pub struct Take<T> {
1646 /// Returns the number of bytes that can be read before this instance will
1651 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1652 /// this method if the underlying [`Read`] instance reaches EOF.
1654 /// [`Read`]: ../../std/io/trait.Read.html
1660 /// use std::io::prelude::*;
1661 /// use std::fs::File;
1663 /// # fn foo() -> io::Result<()> {
1664 /// let f = File::open("foo.txt")?;
1666 /// // read at most five bytes
1667 /// let handle = f.take(5);
1669 /// println!("limit: {}", handle.limit());
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 pub fn limit(&self) -> u64 { self.limit }
1676 /// Consumes the `Take`, returning the wrapped reader.
1682 /// use std::io::prelude::*;
1683 /// use std::fs::File;
1685 /// # fn foo() -> io::Result<()> {
1686 /// let mut file = File::open("foo.txt")?;
1688 /// let mut buffer = [0; 5];
1689 /// let mut handle = file.take(5);
1690 /// handle.read(&mut buffer)?;
1692 /// let file = handle.into_inner();
1696 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1697 pub fn into_inner(self) -> T {
1701 /// Gets a reference to the underlying reader.
1706 /// #![feature(more_io_inner_methods)]
1709 /// use std::io::prelude::*;
1710 /// use std::fs::File;
1712 /// # fn foo() -> io::Result<()> {
1713 /// let mut file = File::open("foo.txt")?;
1715 /// let mut buffer = [0; 5];
1716 /// let mut handle = file.take(5);
1717 /// handle.read(&mut buffer)?;
1719 /// let file = handle.get_ref();
1723 #[unstable(feature = "more_io_inner_methods", issue="41519")]
1724 pub fn get_ref(&self) -> &T {
1728 /// Gets a mutable reference to the underlying reader.
1730 /// Care should be taken to avoid modifying the internal I/O state of the
1731 /// underlying reader as doing so may corrupt the internal limit of this
1737 /// #![feature(more_io_inner_methods)]
1740 /// use std::io::prelude::*;
1741 /// use std::fs::File;
1743 /// # fn foo() -> io::Result<()> {
1744 /// let mut file = File::open("foo.txt")?;
1746 /// let mut buffer = [0; 5];
1747 /// let mut handle = file.take(5);
1748 /// handle.read(&mut buffer)?;
1750 /// let file = handle.get_mut();
1754 #[unstable(feature = "more_io_inner_methods", issue="41519")]
1755 pub fn get_mut(&mut self) -> &mut T {
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 impl<T: Read> Read for Take<T> {
1762 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1763 // Don't call into inner reader at all at EOF because it may still block
1764 if self.limit == 0 {
1768 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1769 let n = self.inner.read(&mut buf[..max])?;
1770 self.limit -= n as u64;
1775 #[stable(feature = "rust1", since = "1.0.0")]
1776 impl<T: BufRead> BufRead for Take<T> {
1777 fn fill_buf(&mut self) -> Result<&[u8]> {
1778 // Don't call into inner reader at all at EOF because it may still block
1779 if self.limit == 0 {
1783 let buf = self.inner.fill_buf()?;
1784 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1788 fn consume(&mut self, amt: usize) {
1789 // Don't let callers reset the limit by passing an overlarge value
1790 let amt = cmp::min(amt as u64, self.limit) as usize;
1791 self.limit -= amt as u64;
1792 self.inner.consume(amt);
1796 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1799 return match reader.read(&mut buf) {
1801 Ok(..) => Some(Ok(buf[0])),
1802 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1803 Err(e) => Some(Err(e)),
1808 /// An iterator over `u8` values of a reader.
1810 /// This struct is generally created by calling [`bytes`] on a reader.
1811 /// Please see the documentation of [`bytes`] for more details.
1813 /// [`bytes`]: trait.Read.html#method.bytes
1814 #[stable(feature = "rust1", since = "1.0.0")]
1816 pub struct Bytes<R> {
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 impl<R: Read> Iterator for Bytes<R> {
1822 type Item = Result<u8>;
1824 fn next(&mut self) -> Option<Result<u8>> {
1825 read_one_byte(&mut self.inner)
1829 /// An iterator over the `char`s of a reader.
1831 /// This struct is generally created by calling [`chars`][chars] on a reader.
1832 /// Please see the documentation of `chars()` for more details.
1834 /// [chars]: trait.Read.html#method.chars
1835 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1838 pub struct Chars<R> {
1842 /// An enumeration of possible errors that can be generated from the `Chars`
1845 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1847 pub enum CharsError {
1848 /// Variant representing that the underlying stream was read successfully
1849 /// but it did not contain valid utf8 data.
1852 /// Variant representing that an I/O error occurred.
1856 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1858 impl<R: Read> Iterator for Chars<R> {
1859 type Item = result::Result<char, CharsError>;
1861 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1862 let first_byte = match read_one_byte(&mut self.inner) {
1863 None => return None,
1865 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1867 let width = core_str::utf8_char_width(first_byte);
1868 if width == 1 { return Some(Ok(first_byte as char)) }
1869 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1870 let mut buf = [first_byte, 0, 0, 0];
1873 while start < width {
1874 match self.inner.read(&mut buf[start..width]) {
1875 Ok(0) => return Some(Err(CharsError::NotUtf8)),
1876 Ok(n) => start += n,
1877 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1878 Err(e) => return Some(Err(CharsError::Other(e))),
1882 Some(match str::from_utf8(&buf[..width]).ok() {
1883 Some(s) => Ok(s.chars().next().unwrap()),
1884 None => Err(CharsError::NotUtf8),
1889 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1891 impl std_error::Error for CharsError {
1892 fn description(&self) -> &str {
1894 CharsError::NotUtf8 => "invalid utf8 encoding",
1895 CharsError::Other(ref e) => std_error::Error::description(e),
1898 fn cause(&self) -> Option<&std_error::Error> {
1900 CharsError::NotUtf8 => None,
1901 CharsError::Other(ref e) => e.cause(),
1906 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1908 impl fmt::Display for CharsError {
1909 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1911 CharsError::NotUtf8 => {
1912 "byte stream did not contain valid utf8".fmt(f)
1914 CharsError::Other(ref e) => e.fmt(f),
1919 /// An iterator over the contents of an instance of `BufRead` split on a
1920 /// particular byte.
1922 /// This struct is generally created by calling [`split`][split] on a
1923 /// `BufRead`. Please see the documentation of `split()` for more details.
1925 /// [split]: trait.BufRead.html#method.split
1926 #[stable(feature = "rust1", since = "1.0.0")]
1928 pub struct Split<B> {
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 impl<B: BufRead> Iterator for Split<B> {
1935 type Item = Result<Vec<u8>>;
1937 fn next(&mut self) -> Option<Result<Vec<u8>>> {
1938 let mut buf = Vec::new();
1939 match self.buf.read_until(self.delim, &mut buf) {
1942 if buf[buf.len() - 1] == self.delim {
1947 Err(e) => Some(Err(e))
1952 /// An iterator over the lines of an instance of `BufRead`.
1954 /// This struct is generally created by calling [`lines`][lines] on a
1955 /// `BufRead`. Please see the documentation of `lines()` for more details.
1957 /// [lines]: trait.BufRead.html#method.lines
1958 #[stable(feature = "rust1", since = "1.0.0")]
1960 pub struct Lines<B> {
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 impl<B: BufRead> Iterator for Lines<B> {
1966 type Item = Result<String>;
1968 fn next(&mut self) -> Option<Result<String>> {
1969 let mut buf = String::new();
1970 match self.buf.read_line(&mut buf) {
1973 if buf.ends_with("\n") {
1975 if buf.ends_with("\r") {
1981 Err(e) => Some(Err(e))
1995 #[cfg_attr(target_os = "emscripten", ignore)]
1997 let mut buf = Cursor::new(&b"12"[..]);
1998 let mut v = Vec::new();
1999 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
2000 assert_eq!(v, b"12");
2002 let mut buf = Cursor::new(&b"1233"[..]);
2003 let mut v = Vec::new();
2004 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
2005 assert_eq!(v, b"123");
2007 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
2008 assert_eq!(v, b"3");
2010 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
2016 let buf = Cursor::new(&b"12"[..]);
2017 let mut s = buf.split(b'3');
2018 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2019 assert!(s.next().is_none());
2021 let buf = Cursor::new(&b"1233"[..]);
2022 let mut s = buf.split(b'3');
2023 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
2024 assert_eq!(s.next().unwrap().unwrap(), vec![]);
2025 assert!(s.next().is_none());
2030 let mut buf = Cursor::new(&b"12"[..]);
2031 let mut v = String::new();
2032 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
2033 assert_eq!(v, "12");
2035 let mut buf = Cursor::new(&b"12\n\n"[..]);
2036 let mut v = String::new();
2037 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
2038 assert_eq!(v, "12\n");
2040 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
2041 assert_eq!(v, "\n");
2043 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
2049 let buf = Cursor::new(&b"12\r"[..]);
2050 let mut s = buf.lines();
2051 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
2052 assert!(s.next().is_none());
2054 let buf = Cursor::new(&b"12\r\n\n"[..]);
2055 let mut s = buf.lines();
2056 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
2057 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
2058 assert!(s.next().is_none());
2063 let mut c = Cursor::new(&b""[..]);
2064 let mut v = Vec::new();
2065 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
2068 let mut c = Cursor::new(&b"1"[..]);
2069 let mut v = Vec::new();
2070 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
2071 assert_eq!(v, b"1");
2073 let cap = 1024 * 1024;
2074 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
2075 let mut v = Vec::new();
2076 let (a, b) = data.split_at(data.len() / 2);
2077 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
2078 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
2079 assert_eq!(v, data);
2083 fn read_to_string() {
2084 let mut c = Cursor::new(&b""[..]);
2085 let mut v = String::new();
2086 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
2089 let mut c = Cursor::new(&b"1"[..]);
2090 let mut v = String::new();
2091 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
2094 let mut c = Cursor::new(&b"\xff"[..]);
2095 let mut v = String::new();
2096 assert!(c.read_to_string(&mut v).is_err());
2101 let mut buf = [0; 4];
2103 let mut c = Cursor::new(&b""[..]);
2104 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2105 io::ErrorKind::UnexpectedEof);
2107 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
2108 c.read_exact(&mut buf).unwrap();
2109 assert_eq!(&buf, b"1234");
2110 c.read_exact(&mut buf).unwrap();
2111 assert_eq!(&buf, b"5678");
2112 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2113 io::ErrorKind::UnexpectedEof);
2117 fn read_exact_slice() {
2118 let mut buf = [0; 4];
2120 let mut c = &b""[..];
2121 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2122 io::ErrorKind::UnexpectedEof);
2124 let mut c = &b"123"[..];
2125 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
2126 io::ErrorKind::UnexpectedEof);
2127 // make sure the optimized (early returning) method is being used
2128 assert_eq!(&buf, &[0; 4]);
2130 let mut c = &b"1234"[..];
2131 c.read_exact(&mut buf).unwrap();
2132 assert_eq!(&buf, b"1234");
2134 let mut c = &b"56789"[..];
2135 c.read_exact(&mut buf).unwrap();
2136 assert_eq!(&buf, b"5678");
2137 assert_eq!(c, b"9");
2145 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2146 Err(io::Error::new(io::ErrorKind::Other, ""))
2149 impl BufRead for R {
2150 fn fill_buf(&mut self) -> io::Result<&[u8]> {
2151 Err(io::Error::new(io::ErrorKind::Other, ""))
2153 fn consume(&mut self, _amt: usize) { }
2156 let mut buf = [0; 1];
2157 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
2158 assert_eq!(b"", R.take(0).fill_buf().unwrap());
2161 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
2162 let mut cat = Vec::new();
2165 let buf1 = br1.fill_buf().unwrap();
2166 let buf2 = br2.fill_buf().unwrap();
2167 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
2168 assert_eq!(buf1[..minlen], buf2[..minlen]);
2169 cat.extend_from_slice(&buf1[..minlen]);
2175 br1.consume(consume);
2176 br2.consume(consume);
2178 assert_eq!(br1.fill_buf().unwrap().len(), 0);
2179 assert_eq!(br2.fill_buf().unwrap().len(), 0);
2180 assert_eq!(&cat[..], &exp[..])
2184 fn chain_bufread() {
2185 let testdata = b"ABCDEFGHIJKL";
2186 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2187 .chain(&testdata[6..9])
2188 .chain(&testdata[9..]);
2189 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2190 .chain(&testdata[8..]);
2191 cmp_bufread(chain1, chain2, &testdata[..]);
2195 fn chain_zero_length_read_is_not_eof() {
2198 let mut s = String::new();
2199 let mut chain = (&a[..]).chain(&b[..]);
2200 chain.read(&mut []).unwrap();
2201 chain.read_to_string(&mut s).unwrap();
2202 assert_eq!("AB", s);
2206 #[cfg_attr(target_os = "emscripten", ignore)]
2207 fn bench_read_to_end(b: &mut test::Bencher) {
2209 let mut lr = repeat(1).take(10000000);
2210 let mut vec = Vec::with_capacity(1024);
2211 super::read_to_end(&mut lr, &mut vec)