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`] method, which we can use on `File`s:
28 //! use std::io::prelude::*;
29 //! use std::fs::File;
31 //! # fn foo() -> io::Result<()> {
32 //! let mut f = File::open("foo.txt")?;
33 //! let mut buffer = [0; 10];
35 //! // read up to 10 bytes
36 //! f.read(&mut buffer)?;
38 //! println!("The bytes: {:?}", buffer);
43 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
44 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
45 //! of 'a type that implements the [`Read`] trait'. Much easier!
47 //! ## Seek and BufRead
49 //! Beyond that, there are two important traits that are provided: [`Seek`]
50 //! and [`BufRead`]. Both of these build on top of a reader to control
51 //! how the reading happens. [`Seek`] lets you control where the next byte is
56 //! use std::io::prelude::*;
57 //! use std::io::SeekFrom;
58 //! use std::fs::File;
60 //! # fn foo() -> io::Result<()> {
61 //! let mut f = File::open("foo.txt")?;
62 //! let mut buffer = [0; 10];
64 //! // skip to the last 10 bytes of the file
65 //! f.seek(SeekFrom::End(-10))?;
67 //! // read up to 10 bytes
68 //! f.read(&mut buffer)?;
70 //! println!("The bytes: {:?}", buffer);
75 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
76 //! to show it off, we'll need to talk about buffers in general. Keep reading!
78 //! ## BufReader and BufWriter
80 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
81 //! making near-constant calls to the operating system. To help with this,
82 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
83 //! readers and writers. The wrapper uses a buffer, reducing the number of
84 //! calls and providing nicer methods for accessing exactly what you want.
86 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
87 //! methods to any reader:
91 //! use std::io::prelude::*;
92 //! use std::io::BufReader;
93 //! use std::fs::File;
95 //! # fn foo() -> io::Result<()> {
96 //! let f = File::open("foo.txt")?;
97 //! let mut reader = BufReader::new(f);
98 //! let mut buffer = String::new();
100 //! // read a line into buffer
101 //! reader.read_line(&mut buffer)?;
103 //! println!("{}", buffer);
108 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
113 //! use std::io::prelude::*;
114 //! use std::io::BufWriter;
115 //! use std::fs::File;
117 //! # fn foo() -> io::Result<()> {
118 //! let f = File::create("foo.txt")?;
120 //! let mut writer = BufWriter::new(f);
122 //! // write a byte to the buffer
123 //! writer.write(&[42])?;
125 //! } // the buffer is flushed once writer goes out of scope
131 //! ## Standard input and output
133 //! A very common source of input is standard input:
138 //! # fn foo() -> io::Result<()> {
139 //! let mut input = String::new();
141 //! io::stdin().read_line(&mut input)?;
143 //! println!("You typed: {}", input.trim());
148 //! And a very common source of output is standard output:
152 //! use std::io::prelude::*;
154 //! # fn foo() -> io::Result<()> {
155 //! io::stdout().write(&[42])?;
160 //! Of course, using [`io::stdout`] directly is less common than something like
163 //! ## Iterator types
165 //! A large number of the structures provided by `std::io` are for various
166 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
171 //! use std::io::prelude::*;
172 //! use std::io::BufReader;
173 //! use std::fs::File;
175 //! # fn foo() -> io::Result<()> {
176 //! let f = File::open("foo.txt")?;
177 //! let reader = BufReader::new(f);
179 //! for line in reader.lines() {
180 //! println!("{}", line?);
189 //! There are a number of [functions][functions-list] that offer access to various
190 //! features. For example, we can use three of these functions to copy everything
191 //! from standard input to standard output:
196 //! # fn foo() -> io::Result<()> {
197 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
202 //! [functions-list]: #functions-1
206 //! Last, but certainly not least, is [`io::Result`]. This type is used
207 //! as the return type of many `std::io` functions that can cause an error, and
208 //! can be returned from your own functions as well. Many of the examples in this
209 //! module use the [`?` operator]:
214 //! fn read_input() -> io::Result<()> {
215 //! let mut input = String::new();
217 //! io::stdin().read_line(&mut input)?;
219 //! println!("You typed: {}", input.trim());
225 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
226 //! common type for functions which don't have a 'real' return value, but do want to
227 //! return errors if they happen. In this case, the only purpose of this function is
228 //! to read the line and print it, so we use `()`.
230 //! ## Platform-specific behavior
232 //! Many I/O functions throughout the standard library are documented to indicate
233 //! what various library or syscalls they are delegated to. This is done to help
234 //! applications both understand what's happening under the hood as well as investigate
235 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
236 //! contract. The implementation of many of these functions are subject to change over
237 //! time and may call fewer or more syscalls/library functions.
239 //! [`Read`]: trait.Read.html
240 //! [`Write`]: trait.Write.html
241 //! [`Seek`]: trait.Seek.html
242 //! [`BufRead`]: trait.BufRead.html
243 //! [`File`]: ../fs/struct.File.html
244 //! [`TcpStream`]: ../net/struct.TcpStream.html
245 //! [`Vec<T>`]: ../vec/struct.Vec.html
246 //! [`BufReader`]: struct.BufReader.html
247 //! [`BufWriter`]: struct.BufWriter.html
248 //! [`write`]: trait.Write.html#tymethod.write
249 //! [`io::stdout`]: fn.stdout.html
250 //! [`println!`]: ../macro.println.html
251 //! [`Lines`]: struct.Lines.html
252 //! [`io::Result`]: type.Result.html
253 //! [`?` operator]: ../../book/syntax-index.html
254 //! [`read`]: trait.Read.html#tymethod.read
256 #![stable(feature = "rust1", since = "1.0.0")]
259 use core::str as core_str;
260 use error as std_error;
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub use self::buffered::{BufReader, BufWriter, LineWriter};
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub use self::buffered::IntoInnerError;
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub use self::cursor::Cursor;
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub use self::error::{Result, Error, ErrorKind};
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
280 #[unstable(feature = "libstd_io_internals", issue = "0")]
281 #[doc(no_inline, hidden)]
282 pub use self::stdio::{set_panic, set_print};
293 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
295 // A few methods below (read_to_string, read_line) will append data into a
296 // `String` buffer, but we need to be pretty careful when doing this. The
297 // implementation will just call `.as_mut_vec()` and then delegate to a
298 // byte-oriented reading method, but we must ensure that when returning we never
299 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
301 // To this end, we use an RAII guard (to protect against panics) which updates
302 // the length of the string when it is dropped. This guard initially truncates
303 // the string to the prior length and only after we've validated that the
304 // new contents are valid UTF-8 do we allow it to set a longer length.
306 // The unsafety in this function is twofold:
308 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
310 // 2. We're passing a raw buffer to the function `f`, and it is expected that
311 // the function only *appends* bytes to the buffer. We'll get undefined
312 // behavior if existing bytes are overwritten to have non-UTF-8 data.
313 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
314 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
316 struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
317 impl<'a> Drop for Guard<'a> {
319 unsafe { self.s.set_len(self.len); }
324 let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
326 if str::from_utf8(&g.s[g.len..]).is_err() {
328 Err(Error::new(ErrorKind::InvalidData,
329 "stream did not contain valid UTF-8"))
338 // This uses an adaptive system to extend the vector when it fills. We want to
339 // avoid paying to allocate and zero a huge chunk of memory if the reader only
340 // has 4 bytes while still making large reads if the reader does have a ton
341 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
342 // time is 4,500 times (!) slower than this if the reader has a very small
343 // amount of data to return.
344 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
345 let start_len = buf.len();
346 let mut len = start_len;
347 let mut new_write_size = 16;
350 if len == buf.len() {
351 if new_write_size < DEFAULT_BUF_SIZE {
354 buf.resize(len + new_write_size, 0);
357 match r.read(&mut buf[len..]) {
359 ret = Ok(len - start_len);
363 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
375 /// The `Read` trait allows for reading bytes from a source.
377 /// Implementors of the `Read` trait are sometimes called 'readers'.
379 /// Readers are defined by one required method, `read()`. Each call to `read`
380 /// will attempt to pull bytes from this source into a provided buffer. A
381 /// number of other methods are implemented in terms of `read()`, giving
382 /// implementors a number of ways to read bytes while only needing to implement
385 /// Readers are intended to be composable with one another. Many implementors
386 /// throughout `std::io` take and provide types which implement the `Read`
389 /// Please note that each call to `read` may involve a system call, and
390 /// therefore, using something that implements [`BufRead`][bufread], such as
391 /// [`BufReader`][bufreader], will be more efficient.
393 /// [bufread]: trait.BufRead.html
394 /// [bufreader]: struct.BufReader.html
398 /// [`File`][file]s implement `Read`:
400 /// [file]: ../fs/struct.File.html
404 /// use std::io::prelude::*;
405 /// use std::fs::File;
407 /// # fn foo() -> io::Result<()> {
408 /// let mut f = File::open("foo.txt")?;
409 /// let mut buffer = [0; 10];
411 /// // read up to 10 bytes
412 /// f.read(&mut buffer)?;
414 /// let mut buffer = vec![0; 10];
415 /// // read the whole file
416 /// f.read_to_end(&mut buffer)?;
418 /// // read into a String, so that you don't need to do the conversion.
419 /// let mut buffer = String::new();
420 /// f.read_to_string(&mut buffer)?;
422 /// // and more! See the other methods for more details.
426 #[stable(feature = "rust1", since = "1.0.0")]
428 /// Pull some bytes from this source into the specified buffer, returning
429 /// how many bytes were read.
431 /// This function does not provide any guarantees about whether it blocks
432 /// waiting for data, but if an object needs to block for a read but cannot
433 /// it will typically signal this via an `Err` return value.
435 /// If the return value of this method is `Ok(n)`, then it must be
436 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
437 /// that the buffer `buf` has been filled in with `n` bytes of data from this
438 /// source. If `n` is `0`, then it can indicate one of two scenarios:
440 /// 1. This reader has reached its "end of file" and will likely no longer
441 /// be able to produce bytes. Note that this does not mean that the
442 /// reader will *always* no longer be able to produce bytes.
443 /// 2. The buffer specified was 0 bytes in length.
445 /// No guarantees are provided about the contents of `buf` when this
446 /// function is called, implementations cannot rely on any property of the
447 /// contents of `buf` being true. It is recommended that implementations
448 /// only write data to `buf` instead of reading its contents.
452 /// If this function encounters any form of I/O or other error, an error
453 /// variant will be returned. If an error is returned then it must be
454 /// guaranteed that no bytes were read.
458 /// [`File`][file]s implement `Read`:
460 /// [file]: ../fs/struct.File.html
464 /// use std::io::prelude::*;
465 /// use std::fs::File;
467 /// # fn foo() -> io::Result<()> {
468 /// let mut f = File::open("foo.txt")?;
469 /// let mut buffer = [0; 10];
472 /// f.read(&mut buffer[..])?;
476 #[stable(feature = "rust1", since = "1.0.0")]
477 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
479 /// Read all bytes until EOF in this source, placing them into `buf`.
481 /// All bytes read from this source will be appended to the specified buffer
482 /// `buf`. This function will continuously call `read` to append more data to
483 /// `buf` until `read` returns either `Ok(0)` or an error of
484 /// non-`ErrorKind::Interrupted` kind.
486 /// If successful, this function will return the total number of bytes read.
490 /// If this function encounters an error of the kind
491 /// `ErrorKind::Interrupted` then the error is ignored and the operation
494 /// If any other read error is encountered then this function immediately
495 /// returns. Any bytes which have already been read will be appended to
500 /// [`File`][file]s implement `Read`:
502 /// [file]: ../fs/struct.File.html
506 /// use std::io::prelude::*;
507 /// use std::fs::File;
509 /// # fn foo() -> io::Result<()> {
510 /// let mut f = File::open("foo.txt")?;
511 /// let mut buffer = Vec::new();
513 /// // read the whole file
514 /// f.read_to_end(&mut buffer)?;
518 #[stable(feature = "rust1", since = "1.0.0")]
519 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
520 read_to_end(self, buf)
523 /// Read all bytes until EOF in this source, placing them into `buf`.
525 /// If successful, this function returns the number of bytes which were read
526 /// and appended to `buf`.
530 /// If the data in this stream is *not* valid UTF-8 then an error is
531 /// returned and `buf` is unchanged.
533 /// See [`read_to_end`][readtoend] for other error semantics.
535 /// [readtoend]: #method.read_to_end
539 /// [`File`][file]s implement `Read`:
541 /// [file]: ../fs/struct.File.html
545 /// use std::io::prelude::*;
546 /// use std::fs::File;
548 /// # fn foo() -> io::Result<()> {
549 /// let mut f = File::open("foo.txt")?;
550 /// let mut buffer = String::new();
552 /// f.read_to_string(&mut buffer)?;
556 #[stable(feature = "rust1", since = "1.0.0")]
557 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
558 // Note that we do *not* call `.read_to_end()` here. We are passing
559 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
560 // method to fill it up. An arbitrary implementation could overwrite the
561 // entire contents of the vector, not just append to it (which is what
562 // we are expecting).
564 // To prevent extraneously checking the UTF-8-ness of the entire buffer
565 // we pass it to our hardcoded `read_to_end` implementation which we
566 // know is guaranteed to only read data into the end of the buffer.
567 append_to_string(buf, |b| read_to_end(self, b))
570 /// Read the exact number of bytes required to fill `buf`.
572 /// This function reads as many bytes as necessary to completely fill the
573 /// specified buffer `buf`.
575 /// No guarantees are provided about the contents of `buf` when this
576 /// function is called, implementations cannot rely on any property of the
577 /// contents of `buf` being true. It is recommended that implementations
578 /// only write data to `buf` instead of reading its contents.
582 /// If this function encounters an error of the kind
583 /// `ErrorKind::Interrupted` then the error is ignored and the operation
586 /// If this function encounters an "end of file" before completely filling
587 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
588 /// The contents of `buf` are unspecified in this case.
590 /// If any other read error is encountered then this function immediately
591 /// returns. The contents of `buf` are unspecified in this case.
593 /// If this function returns an error, it is unspecified how many bytes it
594 /// has read, but it will never read more than would be necessary to
595 /// completely fill the buffer.
599 /// [`File`][file]s implement `Read`:
601 /// [file]: ../fs/struct.File.html
605 /// use std::io::prelude::*;
606 /// use std::fs::File;
608 /// # fn foo() -> io::Result<()> {
609 /// let mut f = File::open("foo.txt")?;
610 /// let mut buffer = [0; 10];
612 /// // read exactly 10 bytes
613 /// f.read_exact(&mut buffer)?;
617 #[stable(feature = "read_exact", since = "1.6.0")]
618 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
619 while !buf.is_empty() {
620 match self.read(buf) {
622 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
623 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
624 Err(e) => return Err(e),
628 Err(Error::new(ErrorKind::UnexpectedEof,
629 "failed to fill whole buffer"))
635 /// Creates a "by reference" adaptor for this instance of `Read`.
637 /// The returned adaptor also implements `Read` and will simply borrow this
642 /// [`File`][file]s implement `Read`:
644 /// [file]: ../fs/struct.File.html
648 /// use std::io::Read;
649 /// use std::fs::File;
651 /// # fn foo() -> io::Result<()> {
652 /// let mut f = File::open("foo.txt")?;
653 /// let mut buffer = Vec::new();
654 /// let mut other_buffer = Vec::new();
657 /// let reference = f.by_ref();
659 /// // read at most 5 bytes
660 /// reference.take(5).read_to_end(&mut buffer)?;
662 /// } // drop our &mut reference so we can use f again
664 /// // original file still usable, read the rest
665 /// f.read_to_end(&mut other_buffer)?;
669 #[stable(feature = "rust1", since = "1.0.0")]
670 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
672 /// Transforms this `Read` instance to an `Iterator` over its bytes.
674 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
675 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
676 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
681 /// [`File`][file]s implement `Read`:
683 /// [file]: ../fs/struct.File.html
687 /// use std::io::prelude::*;
688 /// use std::fs::File;
690 /// # fn foo() -> io::Result<()> {
691 /// let mut f = File::open("foo.txt")?;
693 /// for byte in f.bytes() {
694 /// println!("{}", byte.unwrap());
699 #[stable(feature = "rust1", since = "1.0.0")]
700 fn bytes(self) -> Bytes<Self> where Self: Sized {
701 Bytes { inner: self }
704 /// Transforms this `Read` instance to an `Iterator` over `char`s.
706 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
707 /// sequence of characters. The returned iterator will return `None` once
708 /// EOF is reached for this reader. Otherwise each element yielded will be a
709 /// `Result<char, E>` where `E` may contain information about what I/O error
710 /// occurred or where decoding failed.
712 /// Currently this adaptor will discard intermediate data read, and should
713 /// be avoided if this is not desired.
717 /// [`File`][file]s implement `Read`:
719 /// [file]: ../fs/struct.File.html
724 /// use std::io::prelude::*;
725 /// use std::fs::File;
727 /// # fn foo() -> io::Result<()> {
728 /// let mut f = File::open("foo.txt")?;
730 /// for c in f.chars() {
731 /// println!("{}", c.unwrap());
736 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
737 of where errors happen is currently \
738 unclear and may change",
740 fn chars(self) -> Chars<Self> where Self: Sized {
741 Chars { inner: self }
744 /// Creates an adaptor which will chain this stream with another.
746 /// The returned `Read` instance will first read all bytes from this object
747 /// until EOF is encountered. Afterwards the output is equivalent to the
748 /// output of `next`.
752 /// [`File`][file]s implement `Read`:
754 /// [file]: ../fs/struct.File.html
758 /// use std::io::prelude::*;
759 /// use std::fs::File;
761 /// # fn foo() -> io::Result<()> {
762 /// let mut f1 = File::open("foo.txt")?;
763 /// let mut f2 = File::open("bar.txt")?;
765 /// let mut handle = f1.chain(f2);
766 /// let mut buffer = String::new();
768 /// // read the value into a String. We could use any Read method here,
769 /// // this is just one example.
770 /// handle.read_to_string(&mut buffer)?;
774 #[stable(feature = "rust1", since = "1.0.0")]
775 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
776 Chain { first: self, second: next, done_first: false }
779 /// Creates an adaptor which will read at most `limit` bytes from it.
781 /// This function returns a new instance of `Read` which will read at most
782 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
783 /// read errors will not count towards the number of bytes read and future
784 /// calls to `read` may succeed.
788 /// [`File`][file]s implement `Read`:
790 /// [file]: ../fs/struct.File.html
794 /// use std::io::prelude::*;
795 /// use std::fs::File;
797 /// # fn foo() -> io::Result<()> {
798 /// let mut f = File::open("foo.txt")?;
799 /// let mut buffer = [0; 5];
801 /// // read at most five bytes
802 /// let mut handle = f.take(5);
804 /// handle.read(&mut buffer)?;
808 #[stable(feature = "rust1", since = "1.0.0")]
809 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
810 Take { inner: self, limit: limit }
814 /// A trait for objects which are byte-oriented sinks.
816 /// Implementors of the `Write` trait are sometimes called 'writers'.
818 /// Writers are defined by two required methods, [`write`] and [`flush`]:
820 /// * The [`write`] method will attempt to write some data into the object,
821 /// returning how many bytes were successfully written.
823 /// * The [`flush`] method is useful for adaptors and explicit buffers
824 /// themselves for ensuring that all buffered data has been pushed out to the
827 /// Writers are intended to be composable with one another. Many implementors
828 /// throughout [`std::io`] take and provide types which implement the `Write`
831 /// [`write`]: #tymethod.write
832 /// [`flush`]: #tymethod.flush
833 /// [`std::io`]: index.html
838 /// use std::io::prelude::*;
839 /// use std::fs::File;
841 /// # fn foo() -> std::io::Result<()> {
842 /// let mut buffer = File::create("foo.txt")?;
844 /// buffer.write(b"some bytes")?;
848 #[stable(feature = "rust1", since = "1.0.0")]
850 /// Write a buffer into this object, returning how many bytes were written.
852 /// This function will attempt to write the entire contents of `buf`, but
853 /// the entire write may not succeed, or the write may also generate an
854 /// error. A call to `write` represents *at most one* attempt to write to
855 /// any wrapped object.
857 /// Calls to `write` are not guaranteed to block waiting for data to be
858 /// written, and a write which would otherwise block can be indicated through
859 /// an `Err` variant.
861 /// If the return value is `Ok(n)` then it must be guaranteed that
862 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
863 /// underlying object is no longer able to accept bytes and will likely not
864 /// be able to in the future as well, or that the buffer provided is empty.
868 /// Each call to `write` may generate an I/O error indicating that the
869 /// operation could not be completed. If an error is returned then no bytes
870 /// in the buffer were written to this writer.
872 /// It is **not** considered an error if the entire buffer could not be
873 /// written to this writer.
878 /// use std::io::prelude::*;
879 /// use std::fs::File;
881 /// # fn foo() -> std::io::Result<()> {
882 /// let mut buffer = File::create("foo.txt")?;
884 /// buffer.write(b"some bytes")?;
888 #[stable(feature = "rust1", since = "1.0.0")]
889 fn write(&mut self, buf: &[u8]) -> Result<usize>;
891 /// Flush this output stream, ensuring that all intermediately buffered
892 /// contents reach their destination.
896 /// It is considered an error if not all bytes could be written due to
897 /// I/O errors or EOF being reached.
902 /// use std::io::prelude::*;
903 /// use std::io::BufWriter;
904 /// use std::fs::File;
906 /// # fn foo() -> std::io::Result<()> {
907 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
909 /// buffer.write(b"some bytes")?;
914 #[stable(feature = "rust1", since = "1.0.0")]
915 fn flush(&mut self) -> Result<()>;
917 /// Attempts to write an entire buffer into this write.
919 /// This method will continuously call `write` while there is more data to
920 /// write. This method will not return until the entire buffer has been
921 /// successfully written or an error occurs. The first error generated from
922 /// this method will be returned.
926 /// This function will return the first error that `write` returns.
931 /// use std::io::prelude::*;
932 /// use std::fs::File;
934 /// # fn foo() -> std::io::Result<()> {
935 /// let mut buffer = File::create("foo.txt")?;
937 /// buffer.write_all(b"some bytes")?;
941 #[stable(feature = "rust1", since = "1.0.0")]
942 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
943 while !buf.is_empty() {
944 match self.write(buf) {
945 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
946 "failed to write whole buffer")),
947 Ok(n) => buf = &buf[n..],
948 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
949 Err(e) => return Err(e),
955 /// Writes a formatted string into this writer, returning any error
958 /// This method is primarily used to interface with the
959 /// [`format_args!`][formatargs] macro, but it is rare that this should
960 /// explicitly be called. The [`write!`][write] macro should be favored to
961 /// invoke this method instead.
963 /// [formatargs]: ../macro.format_args.html
964 /// [write]: ../macro.write.html
966 /// This function internally uses the [`write_all`][writeall] method on
967 /// this trait and hence will continuously write data so long as no errors
968 /// are received. This also means that partial writes are not indicated in
971 /// [writeall]: #method.write_all
975 /// This function will return any I/O error reported while formatting.
980 /// use std::io::prelude::*;
981 /// use std::fs::File;
983 /// # fn foo() -> std::io::Result<()> {
984 /// let mut buffer = File::create("foo.txt")?;
987 /// write!(buffer, "{:.*}", 2, 1.234567)?;
988 /// // turns into this:
989 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
993 #[stable(feature = "rust1", since = "1.0.0")]
994 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
995 // Create a shim which translates a Write to a fmt::Write and saves
996 // off I/O errors. instead of discarding them
997 struct Adaptor<'a, T: ?Sized + 'a> {
1002 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1003 fn write_str(&mut self, s: &str) -> fmt::Result {
1004 match self.inner.write_all(s.as_bytes()) {
1007 self.error = Err(e);
1014 let mut output = Adaptor { inner: self, error: Ok(()) };
1015 match fmt::write(&mut output, fmt) {
1018 // check if the error came from the underlying `Write` or not
1019 if output.error.is_err() {
1022 Err(Error::new(ErrorKind::Other, "formatter error"))
1028 /// Creates a "by reference" adaptor for this instance of `Write`.
1030 /// The returned adaptor also implements `Write` and will simply borrow this
1036 /// use std::io::Write;
1037 /// use std::fs::File;
1039 /// # fn foo() -> std::io::Result<()> {
1040 /// let mut buffer = File::create("foo.txt")?;
1042 /// let reference = buffer.by_ref();
1044 /// // we can use reference just like our original buffer
1045 /// reference.write_all(b"some bytes")?;
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1053 /// The `Seek` trait provides a cursor which can be moved within a stream of
1056 /// The stream typically has a fixed size, allowing seeking relative to either
1057 /// end or the current offset.
1061 /// [`File`][file]s implement `Seek`:
1063 /// [file]: ../fs/struct.File.html
1067 /// use std::io::prelude::*;
1068 /// use std::fs::File;
1069 /// use std::io::SeekFrom;
1071 /// # fn foo() -> io::Result<()> {
1072 /// let mut f = File::open("foo.txt")?;
1074 /// // move the cursor 42 bytes from the start of the file
1075 /// f.seek(SeekFrom::Start(42))?;
1079 #[stable(feature = "rust1", since = "1.0.0")]
1081 /// Seek to an offset, in bytes, in a stream.
1083 /// A seek beyond the end of a stream is allowed, but implementation
1086 /// If the seek operation completed successfully,
1087 /// this method returns the new position from the start of the stream.
1088 /// That position can be used later with [`SeekFrom::Start`].
1092 /// Seeking to a negative offset is considered an error.
1094 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1099 /// Enumeration of possible methods to seek within an I/O object.
1101 /// It is used by the [`Seek`] trait.
1103 /// [`Seek`]: trait.Seek.html
1104 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1105 #[stable(feature = "rust1", since = "1.0.0")]
1107 /// Set the offset to the provided number of bytes.
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1111 /// Set the offset to the size of this object plus the specified number of
1114 /// It is possible to seek beyond the end of an object, but it's an error to
1115 /// seek before byte 0.
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1119 /// Set the offset to the current position plus the specified number of
1122 /// It is possible to seek beyond the end of an object, but it's an error to
1123 /// seek before byte 0.
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1128 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1132 let (done, used) = {
1133 let available = match r.fill_buf() {
1135 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1136 Err(e) => return Err(e)
1138 match memchr::memchr(delim, available) {
1140 buf.extend_from_slice(&available[..i + 1]);
1144 buf.extend_from_slice(available);
1145 (false, available.len())
1151 if done || used == 0 {
1157 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1158 /// to perform extra ways of reading.
1160 /// For example, reading line-by-line is inefficient without using a buffer, so
1161 /// if you want to read by line, you'll need `BufRead`, which includes a
1162 /// [`read_line`] method as well as a [`lines`] iterator.
1166 /// A locked standard input implements `BufRead`:
1170 /// use std::io::prelude::*;
1172 /// let stdin = io::stdin();
1173 /// for line in stdin.lock().lines() {
1174 /// println!("{}", line.unwrap());
1178 /// If you have something that implements [`Read`], you can use the [`BufReader`
1179 /// type][`BufReader`] to turn it into a `BufRead`.
1181 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1182 /// [`BufReader`] to the rescue!
1184 /// [`BufReader`]: struct.BufReader.html
1185 /// [`File`]: ../fs/struct.File.html
1186 /// [`read_line`]: #method.read_line
1187 /// [`lines`]: #method.lines
1188 /// [`Read`]: trait.Read.html
1191 /// use std::io::{self, BufReader};
1192 /// use std::io::prelude::*;
1193 /// use std::fs::File;
1195 /// # fn foo() -> io::Result<()> {
1196 /// let f = File::open("foo.txt")?;
1197 /// let f = BufReader::new(f);
1199 /// for line in f.lines() {
1200 /// println!("{}", line.unwrap());
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 pub trait BufRead: Read {
1209 /// Fills the internal buffer of this object, returning the buffer contents.
1211 /// This function is a lower-level call. It needs to be paired with the
1212 /// [`consume`] method to function properly. When calling this
1213 /// method, none of the contents will be "read" in the sense that later
1214 /// calling `read` may return the same contents. As such, [`consume`] must
1215 /// be called with the number of bytes that are consumed from this buffer to
1216 /// ensure that the bytes are never returned twice.
1218 /// [`consume`]: #tymethod.consume
1220 /// An empty buffer returned indicates that the stream has reached EOF.
1224 /// This function will return an I/O error if the underlying reader was
1225 /// read, but returned an error.
1229 /// A locked standard input implements `BufRead`:
1233 /// use std::io::prelude::*;
1235 /// let stdin = io::stdin();
1236 /// let mut stdin = stdin.lock();
1238 /// // we can't have two `&mut` references to `stdin`, so use a block
1239 /// // to end the borrow early.
1241 /// let buffer = stdin.fill_buf().unwrap();
1243 /// // work with buffer
1244 /// println!("{:?}", buffer);
1249 /// // ensure the bytes we worked with aren't returned again later
1250 /// stdin.consume(length);
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 fn fill_buf(&mut self) -> Result<&[u8]>;
1255 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1256 /// so they should no longer be returned in calls to `read`.
1258 /// This function is a lower-level call. It needs to be paired with the
1259 /// [`fill_buf`] method to function properly. This function does
1260 /// not perform any I/O, it simply informs this object that some amount of
1261 /// its buffer, returned from [`fill_buf`], has been consumed and should
1262 /// no longer be returned. As such, this function may do odd things if
1263 /// [`fill_buf`] isn't called before calling it.
1265 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1270 /// Since `consume()` is meant to be used with [`fill_buf`],
1271 /// that method's example includes an example of `consume()`.
1273 /// [`fill_buf`]: #tymethod.fill_buf
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 fn consume(&mut self, amt: usize);
1277 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1279 /// This function will read bytes from the underlying stream until the
1280 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1281 /// the delimiter (if found) will be appended to `buf`.
1283 /// If successful, this function will return the total number of bytes read.
1287 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1288 /// will otherwise return any errors returned by [`fill_buf`].
1290 /// If an I/O error is encountered then all bytes read so far will be
1291 /// present in `buf` and its length will have been adjusted appropriately.
1295 /// A locked standard input implements `BufRead`. In this example, we'll
1296 /// read from standard input until we see an `a` byte.
1298 /// [`fill_buf`]: #tymethod.fill_buf
1299 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1303 /// use std::io::prelude::*;
1305 /// fn foo() -> io::Result<()> {
1306 /// let stdin = io::stdin();
1307 /// let mut stdin = stdin.lock();
1308 /// let mut buffer = Vec::new();
1310 /// stdin.read_until(b'a', &mut buffer)?;
1312 /// println!("{:?}", buffer);
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1318 read_until(self, byte, buf)
1321 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1322 /// them to the provided buffer.
1324 /// This function will read bytes from the underlying stream until the
1325 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1326 /// up to, and including, the delimiter (if found) will be appended to
1329 /// If successful, this function will return the total number of bytes read.
1333 /// This function has the same error semantics as [`read_until`] and will
1334 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1335 /// error is encountered then `buf` may contain some bytes already read in
1336 /// the event that all data read so far was valid UTF-8.
1340 /// A locked standard input implements `BufRead`. In this example, we'll
1341 /// read all of the lines from standard input. If we were to do this in
1342 /// an actual project, the [`lines`] method would be easier, of
1345 /// [`lines`]: #method.lines
1346 /// [`read_until`]: #method.read_until
1350 /// use std::io::prelude::*;
1352 /// let stdin = io::stdin();
1353 /// let mut stdin = stdin.lock();
1354 /// let mut buffer = String::new();
1356 /// while stdin.read_line(&mut buffer).unwrap() > 0 {
1357 /// // work with buffer
1358 /// println!("{:?}", buffer);
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1365 // Note that we are not calling the `.read_until` method here, but
1366 // rather our hardcoded implementation. For more details as to why, see
1367 // the comments in `read_to_end`.
1368 append_to_string(buf, |b| read_until(self, b'\n', b))
1371 /// Returns an iterator over the contents of this reader split on the byte
1374 /// The iterator returned from this function will return instances of
1375 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1376 /// the delimiter byte at the end.
1378 /// This function will yield errors whenever [`read_until`] would have
1379 /// also yielded an error.
1383 /// A locked standard input implements `BufRead`. In this example, we'll
1384 /// read some input from standard input, splitting on commas.
1386 /// [`io::Result`]: type.Result.html
1387 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1388 /// [`read_until`]: #method.read_until
1392 /// use std::io::prelude::*;
1394 /// let stdin = io::stdin();
1396 /// for content in stdin.lock().split(b',') {
1397 /// println!("{:?}", content.unwrap());
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1402 Split { buf: self, delim: byte }
1405 /// Returns an iterator over the lines of this reader.
1407 /// The iterator returned from this function will yield instances of
1408 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1409 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1411 /// [`io::Result`]: type.Result.html
1412 /// [`String`]: ../string/struct.String.html
1416 /// A locked standard input implements `BufRead`:
1420 /// use std::io::prelude::*;
1422 /// let stdin = io::stdin();
1424 /// for line in stdin.lock().lines() {
1425 /// println!("{}", line.unwrap());
1431 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1433 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 fn lines(self) -> Lines<Self> where Self: Sized {
1440 /// Adaptor to chain together two readers.
1442 /// This struct is generally created by calling [`chain`] on a reader.
1443 /// Please see the documentation of [`chain`] for more details.
1445 /// [`chain`]: trait.Read.html#method.chain
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 pub struct Chain<T, U> {
1453 #[stable(feature = "std_debug", since = "1.16.0")]
1454 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1455 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1456 f.debug_struct("Chain")
1457 .field("t", &self.first)
1458 .field("u", &self.second)
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 impl<T: Read, U: Read> Read for Chain<T, U> {
1465 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1466 if !self.done_first {
1467 match self.first.read(buf)? {
1468 0 if buf.len() != 0 => { self.done_first = true; }
1472 self.second.read(buf)
1476 #[stable(feature = "chain_bufread", since = "1.9.0")]
1477 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1478 fn fill_buf(&mut self) -> Result<&[u8]> {
1479 if !self.done_first {
1480 match self.first.fill_buf()? {
1481 buf if buf.len() == 0 => { self.done_first = true; }
1482 buf => return Ok(buf),
1485 self.second.fill_buf()
1488 fn consume(&mut self, amt: usize) {
1489 if !self.done_first {
1490 self.first.consume(amt)
1492 self.second.consume(amt)
1497 /// Reader adaptor which limits the bytes read from an underlying reader.
1499 /// This struct is generally created by calling [`take`] on a reader.
1500 /// Please see the documentation of [`take`] for more details.
1502 /// [`take`]: trait.Read.html#method.take
1503 #[stable(feature = "rust1", since = "1.0.0")]
1505 pub struct Take<T> {
1511 /// Returns the number of bytes that can be read before this instance will
1516 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1517 /// this method if the underlying [`Read`] instance reaches EOF.
1519 /// [`Read`]: ../../std/io/trait.Read.html
1525 /// use std::io::prelude::*;
1526 /// use std::fs::File;
1528 /// # fn foo() -> io::Result<()> {
1529 /// let f = File::open("foo.txt")?;
1531 /// // read at most five bytes
1532 /// let handle = f.take(5);
1534 /// println!("limit: {}", handle.limit());
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 pub fn limit(&self) -> u64 { self.limit }
1541 /// Consumes the `Take`, returning the wrapped reader.
1547 /// use std::io::prelude::*;
1548 /// use std::fs::File;
1550 /// # fn foo() -> io::Result<()> {
1551 /// let mut file = File::open("foo.txt")?;
1553 /// let mut buffer = [0; 5];
1554 /// let mut handle = file.take(5);
1555 /// handle.read(&mut buffer)?;
1557 /// let file = handle.into_inner();
1561 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1562 pub fn into_inner(self) -> T {
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 impl<T: Read> Read for Take<T> {
1569 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1570 // Don't call into inner reader at all at EOF because it may still block
1571 if self.limit == 0 {
1575 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1576 let n = self.inner.read(&mut buf[..max])?;
1577 self.limit -= n as u64;
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl<T: BufRead> BufRead for Take<T> {
1584 fn fill_buf(&mut self) -> Result<&[u8]> {
1585 // Don't call into inner reader at all at EOF because it may still block
1586 if self.limit == 0 {
1590 let buf = self.inner.fill_buf()?;
1591 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1595 fn consume(&mut self, amt: usize) {
1596 // Don't let callers reset the limit by passing an overlarge value
1597 let amt = cmp::min(amt as u64, self.limit) as usize;
1598 self.limit -= amt as u64;
1599 self.inner.consume(amt);
1603 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1606 return match reader.read(&mut buf) {
1608 Ok(..) => Some(Ok(buf[0])),
1609 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1610 Err(e) => Some(Err(e)),
1615 /// An iterator over `u8` values of a reader.
1617 /// This struct is generally created by calling [`bytes`] on a reader.
1618 /// Please see the documentation of [`bytes`] for more details.
1620 /// [`bytes`]: trait.Read.html#method.bytes
1621 #[stable(feature = "rust1", since = "1.0.0")]
1623 pub struct Bytes<R> {
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<R: Read> Iterator for Bytes<R> {
1629 type Item = Result<u8>;
1631 fn next(&mut self) -> Option<Result<u8>> {
1632 read_one_byte(&mut self.inner)
1636 /// An iterator over the `char`s of a reader.
1638 /// This struct is generally created by calling [`chars`][chars] on a reader.
1639 /// Please see the documentation of `chars()` for more details.
1641 /// [chars]: trait.Read.html#method.chars
1642 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1645 pub struct Chars<R> {
1649 /// An enumeration of possible errors that can be generated from the `Chars`
1652 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1654 pub enum CharsError {
1655 /// Variant representing that the underlying stream was read successfully
1656 /// but it did not contain valid utf8 data.
1659 /// Variant representing that an I/O error occurred.
1663 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1665 impl<R: Read> Iterator for Chars<R> {
1666 type Item = result::Result<char, CharsError>;
1668 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1669 let first_byte = match read_one_byte(&mut self.inner) {
1670 None => return None,
1672 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1674 let width = core_str::utf8_char_width(first_byte);
1675 if width == 1 { return Some(Ok(first_byte as char)) }
1676 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1677 let mut buf = [first_byte, 0, 0, 0];
1680 while start < width {
1681 match self.inner.read(&mut buf[start..width]) {
1682 Ok(0) => return Some(Err(CharsError::NotUtf8)),
1683 Ok(n) => start += n,
1684 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1685 Err(e) => return Some(Err(CharsError::Other(e))),
1689 Some(match str::from_utf8(&buf[..width]).ok() {
1690 Some(s) => Ok(s.chars().next().unwrap()),
1691 None => Err(CharsError::NotUtf8),
1696 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1698 impl std_error::Error for CharsError {
1699 fn description(&self) -> &str {
1701 CharsError::NotUtf8 => "invalid utf8 encoding",
1702 CharsError::Other(ref e) => std_error::Error::description(e),
1705 fn cause(&self) -> Option<&std_error::Error> {
1707 CharsError::NotUtf8 => None,
1708 CharsError::Other(ref e) => e.cause(),
1713 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1715 impl fmt::Display for CharsError {
1716 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1718 CharsError::NotUtf8 => {
1719 "byte stream did not contain valid utf8".fmt(f)
1721 CharsError::Other(ref e) => e.fmt(f),
1726 /// An iterator over the contents of an instance of `BufRead` split on a
1727 /// particular byte.
1729 /// This struct is generally created by calling [`split`][split] on a
1730 /// `BufRead`. Please see the documentation of `split()` for more details.
1732 /// [split]: trait.BufRead.html#method.split
1733 #[stable(feature = "rust1", since = "1.0.0")]
1735 pub struct Split<B> {
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 impl<B: BufRead> Iterator for Split<B> {
1742 type Item = Result<Vec<u8>>;
1744 fn next(&mut self) -> Option<Result<Vec<u8>>> {
1745 let mut buf = Vec::new();
1746 match self.buf.read_until(self.delim, &mut buf) {
1749 if buf[buf.len() - 1] == self.delim {
1754 Err(e) => Some(Err(e))
1759 /// An iterator over the lines of an instance of `BufRead`.
1761 /// This struct is generally created by calling [`lines`][lines] on a
1762 /// `BufRead`. Please see the documentation of `lines()` for more details.
1764 /// [lines]: trait.BufRead.html#method.lines
1765 #[stable(feature = "rust1", since = "1.0.0")]
1767 pub struct Lines<B> {
1771 #[stable(feature = "rust1", since = "1.0.0")]
1772 impl<B: BufRead> Iterator for Lines<B> {
1773 type Item = Result<String>;
1775 fn next(&mut self) -> Option<Result<String>> {
1776 let mut buf = String::new();
1777 match self.buf.read_line(&mut buf) {
1780 if buf.ends_with("\n") {
1782 if buf.ends_with("\r") {
1788 Err(e) => Some(Err(e))
1802 #[cfg_attr(target_os = "emscripten", ignore)]
1804 let mut buf = Cursor::new(&b"12"[..]);
1805 let mut v = Vec::new();
1806 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
1807 assert_eq!(v, b"12");
1809 let mut buf = Cursor::new(&b"1233"[..]);
1810 let mut v = Vec::new();
1811 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
1812 assert_eq!(v, b"123");
1814 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
1815 assert_eq!(v, b"3");
1817 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
1823 let buf = Cursor::new(&b"12"[..]);
1824 let mut s = buf.split(b'3');
1825 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1826 assert!(s.next().is_none());
1828 let buf = Cursor::new(&b"1233"[..]);
1829 let mut s = buf.split(b'3');
1830 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1831 assert_eq!(s.next().unwrap().unwrap(), vec![]);
1832 assert!(s.next().is_none());
1837 let mut buf = Cursor::new(&b"12"[..]);
1838 let mut v = String::new();
1839 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
1840 assert_eq!(v, "12");
1842 let mut buf = Cursor::new(&b"12\n\n"[..]);
1843 let mut v = String::new();
1844 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
1845 assert_eq!(v, "12\n");
1847 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
1848 assert_eq!(v, "\n");
1850 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
1856 let buf = Cursor::new(&b"12\r"[..]);
1857 let mut s = buf.lines();
1858 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
1859 assert!(s.next().is_none());
1861 let buf = Cursor::new(&b"12\r\n\n"[..]);
1862 let mut s = buf.lines();
1863 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
1864 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
1865 assert!(s.next().is_none());
1870 let mut c = Cursor::new(&b""[..]);
1871 let mut v = Vec::new();
1872 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
1875 let mut c = Cursor::new(&b"1"[..]);
1876 let mut v = Vec::new();
1877 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
1878 assert_eq!(v, b"1");
1880 let cap = 1024 * 1024;
1881 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
1882 let mut v = Vec::new();
1883 let (a, b) = data.split_at(data.len() / 2);
1884 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
1885 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
1886 assert_eq!(v, data);
1890 fn read_to_string() {
1891 let mut c = Cursor::new(&b""[..]);
1892 let mut v = String::new();
1893 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
1896 let mut c = Cursor::new(&b"1"[..]);
1897 let mut v = String::new();
1898 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
1901 let mut c = Cursor::new(&b"\xff"[..]);
1902 let mut v = String::new();
1903 assert!(c.read_to_string(&mut v).is_err());
1908 let mut buf = [0; 4];
1910 let mut c = Cursor::new(&b""[..]);
1911 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1912 io::ErrorKind::UnexpectedEof);
1914 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
1915 c.read_exact(&mut buf).unwrap();
1916 assert_eq!(&buf, b"1234");
1917 c.read_exact(&mut buf).unwrap();
1918 assert_eq!(&buf, b"5678");
1919 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1920 io::ErrorKind::UnexpectedEof);
1924 fn read_exact_slice() {
1925 let mut buf = [0; 4];
1927 let mut c = &b""[..];
1928 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1929 io::ErrorKind::UnexpectedEof);
1931 let mut c = &b"123"[..];
1932 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1933 io::ErrorKind::UnexpectedEof);
1934 // make sure the optimized (early returning) method is being used
1935 assert_eq!(&buf, &[0; 4]);
1937 let mut c = &b"1234"[..];
1938 c.read_exact(&mut buf).unwrap();
1939 assert_eq!(&buf, b"1234");
1941 let mut c = &b"56789"[..];
1942 c.read_exact(&mut buf).unwrap();
1943 assert_eq!(&buf, b"5678");
1944 assert_eq!(c, b"9");
1952 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1953 Err(io::Error::new(io::ErrorKind::Other, ""))
1956 impl BufRead for R {
1957 fn fill_buf(&mut self) -> io::Result<&[u8]> {
1958 Err(io::Error::new(io::ErrorKind::Other, ""))
1960 fn consume(&mut self, _amt: usize) { }
1963 let mut buf = [0; 1];
1964 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
1965 assert_eq!(b"", R.take(0).fill_buf().unwrap());
1968 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
1969 let mut cat = Vec::new();
1972 let buf1 = br1.fill_buf().unwrap();
1973 let buf2 = br2.fill_buf().unwrap();
1974 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
1975 assert_eq!(buf1[..minlen], buf2[..minlen]);
1976 cat.extend_from_slice(&buf1[..minlen]);
1982 br1.consume(consume);
1983 br2.consume(consume);
1985 assert_eq!(br1.fill_buf().unwrap().len(), 0);
1986 assert_eq!(br2.fill_buf().unwrap().len(), 0);
1987 assert_eq!(&cat[..], &exp[..])
1991 fn chain_bufread() {
1992 let testdata = b"ABCDEFGHIJKL";
1993 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
1994 .chain(&testdata[6..9])
1995 .chain(&testdata[9..]);
1996 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
1997 .chain(&testdata[8..]);
1998 cmp_bufread(chain1, chain2, &testdata[..]);
2002 fn chain_zero_length_read_is_not_eof() {
2005 let mut s = String::new();
2006 let mut chain = (&a[..]).chain(&b[..]);
2007 chain.read(&mut []).unwrap();
2008 chain.read_to_string(&mut s).unwrap();
2009 assert_eq!("AB", s);
2013 #[cfg_attr(target_os = "emscripten", ignore)]
2014 fn bench_read_to_end(b: &mut test::Bencher) {
2016 let mut lr = repeat(1).take(10000000);
2017 let mut vec = Vec::with_capacity(1024);
2018 super::read_to_end(&mut lr, &mut vec)