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 //! Note that you cannot use the `?` operator in functions that do not return
149 //! a `Result<T, E>` (e.g. `main`). Instead, you can call `.unwrap()` or `match`
150 //! on the return value to catch any possible errors:
155 //! let mut input = String::new();
157 //! io::stdin().read_line(&mut input).unwrap();
160 //! And a very common source of output is standard output:
164 //! use std::io::prelude::*;
166 //! # fn foo() -> io::Result<()> {
167 //! io::stdout().write(&[42])?;
172 //! Of course, using [`io::stdout`] directly is less common than something like
175 //! ## Iterator types
177 //! A large number of the structures provided by `std::io` are for various
178 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
183 //! use std::io::prelude::*;
184 //! use std::io::BufReader;
185 //! use std::fs::File;
187 //! # fn foo() -> io::Result<()> {
188 //! let f = File::open("foo.txt")?;
189 //! let reader = BufReader::new(f);
191 //! for line in reader.lines() {
192 //! println!("{}", line?);
201 //! There are a number of [functions][functions-list] that offer access to various
202 //! features. For example, we can use three of these functions to copy everything
203 //! from standard input to standard output:
208 //! # fn foo() -> io::Result<()> {
209 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
214 //! [functions-list]: #functions-1
218 //! Last, but certainly not least, is [`io::Result`]. This type is used
219 //! as the return type of many `std::io` functions that can cause an error, and
220 //! can be returned from your own functions as well. Many of the examples in this
221 //! module use the [`?` operator]:
226 //! fn read_input() -> io::Result<()> {
227 //! let mut input = String::new();
229 //! io::stdin().read_line(&mut input)?;
231 //! println!("You typed: {}", input.trim());
237 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
238 //! common type for functions which don't have a 'real' return value, but do want to
239 //! return errors if they happen. In this case, the only purpose of this function is
240 //! to read the line and print it, so we use `()`.
242 //! ## Platform-specific behavior
244 //! Many I/O functions throughout the standard library are documented to indicate
245 //! what various library or syscalls they are delegated to. This is done to help
246 //! applications both understand what's happening under the hood as well as investigate
247 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
248 //! contract. The implementation of many of these functions are subject to change over
249 //! time and may call fewer or more syscalls/library functions.
251 //! [`Read`]: trait.Read.html
252 //! [`Write`]: trait.Write.html
253 //! [`Seek`]: trait.Seek.html
254 //! [`BufRead`]: trait.BufRead.html
255 //! [`File`]: ../fs/struct.File.html
256 //! [`TcpStream`]: ../net/struct.TcpStream.html
257 //! [`Vec<T>`]: ../vec/struct.Vec.html
258 //! [`BufReader`]: struct.BufReader.html
259 //! [`BufWriter`]: struct.BufWriter.html
260 //! [`write`]: trait.Write.html#tymethod.write
261 //! [`io::stdout`]: fn.stdout.html
262 //! [`println!`]: ../macro.println.html
263 //! [`Lines`]: struct.Lines.html
264 //! [`io::Result`]: type.Result.html
265 //! [`?` operator]: ../../book/syntax-index.html
266 //! [`read`]: trait.Read.html#tymethod.read
268 #![stable(feature = "rust1", since = "1.0.0")]
271 use core::str as core_str;
272 use error as std_error;
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::buffered::{BufReader, BufWriter, LineWriter};
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub use self::buffered::IntoInnerError;
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub use self::cursor::Cursor;
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub use self::error::{Result, Error, ErrorKind};
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
292 #[unstable(feature = "libstd_io_internals", issue = "0")]
293 #[doc(no_inline, hidden)]
294 pub use self::stdio::{set_panic, set_print};
305 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
307 // A few methods below (read_to_string, read_line) will append data into a
308 // `String` buffer, but we need to be pretty careful when doing this. The
309 // implementation will just call `.as_mut_vec()` and then delegate to a
310 // byte-oriented reading method, but we must ensure that when returning we never
311 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
313 // To this end, we use an RAII guard (to protect against panics) which updates
314 // the length of the string when it is dropped. This guard initially truncates
315 // the string to the prior length and only after we've validated that the
316 // new contents are valid UTF-8 do we allow it to set a longer length.
318 // The unsafety in this function is twofold:
320 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
322 // 2. We're passing a raw buffer to the function `f`, and it is expected that
323 // the function only *appends* bytes to the buffer. We'll get undefined
324 // behavior if existing bytes are overwritten to have non-UTF-8 data.
325 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
326 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
328 struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
329 impl<'a> Drop for Guard<'a> {
331 unsafe { self.s.set_len(self.len); }
336 let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
338 if str::from_utf8(&g.s[g.len..]).is_err() {
340 Err(Error::new(ErrorKind::InvalidData,
341 "stream did not contain valid UTF-8"))
350 // This uses an adaptive system to extend the vector when it fills. We want to
351 // avoid paying to allocate and zero a huge chunk of memory if the reader only
352 // has 4 bytes while still making large reads if the reader does have a ton
353 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
354 // time is 4,500 times (!) slower than this if the reader has a very small
355 // amount of data to return.
356 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
357 let start_len = buf.len();
358 let mut len = start_len;
359 let mut new_write_size = 16;
362 if len == buf.len() {
363 if new_write_size < DEFAULT_BUF_SIZE {
366 buf.resize(len + new_write_size, 0);
369 match r.read(&mut buf[len..]) {
371 ret = Ok(len - start_len);
375 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
387 /// The `Read` trait allows for reading bytes from a source.
389 /// Implementors of the `Read` trait are sometimes called 'readers'.
391 /// Readers are defined by one required method, `read()`. Each call to `read`
392 /// will attempt to pull bytes from this source into a provided buffer. A
393 /// number of other methods are implemented in terms of `read()`, giving
394 /// implementors a number of ways to read bytes while only needing to implement
397 /// Readers are intended to be composable with one another. Many implementors
398 /// throughout `std::io` take and provide types which implement the `Read`
401 /// Please note that each call to `read` may involve a system call, and
402 /// therefore, using something that implements [`BufRead`][bufread], such as
403 /// [`BufReader`][bufreader], will be more efficient.
405 /// [bufread]: trait.BufRead.html
406 /// [bufreader]: struct.BufReader.html
410 /// [`File`][file]s implement `Read`:
412 /// [file]: ../fs/struct.File.html
416 /// use std::io::prelude::*;
417 /// use std::fs::File;
419 /// # fn foo() -> io::Result<()> {
420 /// let mut f = File::open("foo.txt")?;
421 /// let mut buffer = [0; 10];
423 /// // read up to 10 bytes
424 /// f.read(&mut buffer)?;
426 /// let mut buffer = vec![0; 10];
427 /// // read the whole file
428 /// f.read_to_end(&mut buffer)?;
430 /// // read into a String, so that you don't need to do the conversion.
431 /// let mut buffer = String::new();
432 /// f.read_to_string(&mut buffer)?;
434 /// // and more! See the other methods for more details.
438 #[stable(feature = "rust1", since = "1.0.0")]
440 /// Pull some bytes from this source into the specified buffer, returning
441 /// how many bytes were read.
443 /// This function does not provide any guarantees about whether it blocks
444 /// waiting for data, but if an object needs to block for a read but cannot
445 /// it will typically signal this via an `Err` return value.
447 /// If the return value of this method is `Ok(n)`, then it must be
448 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
449 /// that the buffer `buf` has been filled in with `n` bytes of data from this
450 /// source. If `n` is `0`, then it can indicate one of two scenarios:
452 /// 1. This reader has reached its "end of file" and will likely no longer
453 /// be able to produce bytes. Note that this does not mean that the
454 /// reader will *always* no longer be able to produce bytes.
455 /// 2. The buffer specified was 0 bytes in length.
457 /// No guarantees are provided about the contents of `buf` when this
458 /// function is called, implementations cannot rely on any property of the
459 /// contents of `buf` being true. It is recommended that implementations
460 /// only write data to `buf` instead of reading its contents.
464 /// If this function encounters any form of I/O or other error, an error
465 /// variant will be returned. If an error is returned then it must be
466 /// guaranteed that no bytes were read.
470 /// [`File`][file]s implement `Read`:
472 /// [file]: ../fs/struct.File.html
476 /// use std::io::prelude::*;
477 /// use std::fs::File;
479 /// # fn foo() -> io::Result<()> {
480 /// let mut f = File::open("foo.txt")?;
481 /// let mut buffer = [0; 10];
484 /// f.read(&mut buffer[..])?;
488 #[stable(feature = "rust1", since = "1.0.0")]
489 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
491 /// Read all bytes until EOF in this source, placing them into `buf`.
493 /// All bytes read from this source will be appended to the specified buffer
494 /// `buf`. This function will continuously call `read` to append more data to
495 /// `buf` until `read` returns either `Ok(0)` or an error of
496 /// non-`ErrorKind::Interrupted` kind.
498 /// If successful, this function will return the total number of bytes read.
502 /// If this function encounters an error of the kind
503 /// `ErrorKind::Interrupted` then the error is ignored and the operation
506 /// If any other read error is encountered then this function immediately
507 /// returns. Any bytes which have already been read will be appended to
512 /// [`File`][file]s implement `Read`:
514 /// [file]: ../fs/struct.File.html
518 /// use std::io::prelude::*;
519 /// use std::fs::File;
521 /// # fn foo() -> io::Result<()> {
522 /// let mut f = File::open("foo.txt")?;
523 /// let mut buffer = Vec::new();
525 /// // read the whole file
526 /// f.read_to_end(&mut buffer)?;
530 #[stable(feature = "rust1", since = "1.0.0")]
531 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
532 read_to_end(self, buf)
535 /// Read all bytes until EOF in this source, placing them into `buf`.
537 /// If successful, this function returns the number of bytes which were read
538 /// and appended to `buf`.
542 /// If the data in this stream is *not* valid UTF-8 then an error is
543 /// returned and `buf` is unchanged.
545 /// See [`read_to_end`][readtoend] for other error semantics.
547 /// [readtoend]: #method.read_to_end
551 /// [`File`][file]s implement `Read`:
553 /// [file]: ../fs/struct.File.html
557 /// use std::io::prelude::*;
558 /// use std::fs::File;
560 /// # fn foo() -> io::Result<()> {
561 /// let mut f = File::open("foo.txt")?;
562 /// let mut buffer = String::new();
564 /// f.read_to_string(&mut buffer)?;
568 #[stable(feature = "rust1", since = "1.0.0")]
569 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
570 // Note that we do *not* call `.read_to_end()` here. We are passing
571 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
572 // method to fill it up. An arbitrary implementation could overwrite the
573 // entire contents of the vector, not just append to it (which is what
574 // we are expecting).
576 // To prevent extraneously checking the UTF-8-ness of the entire buffer
577 // we pass it to our hardcoded `read_to_end` implementation which we
578 // know is guaranteed to only read data into the end of the buffer.
579 append_to_string(buf, |b| read_to_end(self, b))
582 /// Read the exact number of bytes required to fill `buf`.
584 /// This function reads as many bytes as necessary to completely fill the
585 /// specified buffer `buf`.
587 /// No guarantees are provided about the contents of `buf` when this
588 /// function is called, implementations cannot rely on any property of the
589 /// contents of `buf` being true. It is recommended that implementations
590 /// only write data to `buf` instead of reading its contents.
594 /// If this function encounters an error of the kind
595 /// `ErrorKind::Interrupted` then the error is ignored and the operation
598 /// If this function encounters an "end of file" before completely filling
599 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
600 /// The contents of `buf` are unspecified in this case.
602 /// If any other read error is encountered then this function immediately
603 /// returns. The contents of `buf` are unspecified in this case.
605 /// If this function returns an error, it is unspecified how many bytes it
606 /// has read, but it will never read more than would be necessary to
607 /// completely fill the buffer.
611 /// [`File`][file]s implement `Read`:
613 /// [file]: ../fs/struct.File.html
617 /// use std::io::prelude::*;
618 /// use std::fs::File;
620 /// # fn foo() -> io::Result<()> {
621 /// let mut f = File::open("foo.txt")?;
622 /// let mut buffer = [0; 10];
624 /// // read exactly 10 bytes
625 /// f.read_exact(&mut buffer)?;
629 #[stable(feature = "read_exact", since = "1.6.0")]
630 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
631 while !buf.is_empty() {
632 match self.read(buf) {
634 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
635 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
636 Err(e) => return Err(e),
640 Err(Error::new(ErrorKind::UnexpectedEof,
641 "failed to fill whole buffer"))
647 /// Creates a "by reference" adaptor for this instance of `Read`.
649 /// The returned adaptor also implements `Read` and will simply borrow this
654 /// [`File`][file]s implement `Read`:
656 /// [file]: ../fs/struct.File.html
660 /// use std::io::Read;
661 /// use std::fs::File;
663 /// # fn foo() -> io::Result<()> {
664 /// let mut f = File::open("foo.txt")?;
665 /// let mut buffer = Vec::new();
666 /// let mut other_buffer = Vec::new();
669 /// let reference = f.by_ref();
671 /// // read at most 5 bytes
672 /// reference.take(5).read_to_end(&mut buffer)?;
674 /// } // drop our &mut reference so we can use f again
676 /// // original file still usable, read the rest
677 /// f.read_to_end(&mut other_buffer)?;
681 #[stable(feature = "rust1", since = "1.0.0")]
682 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
684 /// Transforms this `Read` instance to an `Iterator` over its bytes.
686 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
687 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
688 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
693 /// [`File`][file]s implement `Read`:
695 /// [file]: ../fs/struct.File.html
699 /// use std::io::prelude::*;
700 /// use std::fs::File;
702 /// # fn foo() -> io::Result<()> {
703 /// let mut f = File::open("foo.txt")?;
705 /// for byte in f.bytes() {
706 /// println!("{}", byte.unwrap());
711 #[stable(feature = "rust1", since = "1.0.0")]
712 fn bytes(self) -> Bytes<Self> where Self: Sized {
713 Bytes { inner: self }
716 /// Transforms this `Read` instance to an `Iterator` over `char`s.
718 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
719 /// sequence of characters. The returned iterator will return `None` once
720 /// EOF is reached for this reader. Otherwise each element yielded will be a
721 /// `Result<char, E>` where `E` may contain information about what I/O error
722 /// occurred or where decoding failed.
724 /// Currently this adaptor will discard intermediate data read, and should
725 /// be avoided if this is not desired.
729 /// [`File`][file]s implement `Read`:
731 /// [file]: ../fs/struct.File.html
736 /// use std::io::prelude::*;
737 /// use std::fs::File;
739 /// # fn foo() -> io::Result<()> {
740 /// let mut f = File::open("foo.txt")?;
742 /// for c in f.chars() {
743 /// println!("{}", c.unwrap());
748 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
749 of where errors happen is currently \
750 unclear and may change",
752 fn chars(self) -> Chars<Self> where Self: Sized {
753 Chars { inner: self }
756 /// Creates an adaptor which will chain this stream with another.
758 /// The returned `Read` instance will first read all bytes from this object
759 /// until EOF is encountered. Afterwards the output is equivalent to the
760 /// output of `next`.
764 /// [`File`][file]s implement `Read`:
766 /// [file]: ../fs/struct.File.html
770 /// use std::io::prelude::*;
771 /// use std::fs::File;
773 /// # fn foo() -> io::Result<()> {
774 /// let mut f1 = File::open("foo.txt")?;
775 /// let mut f2 = File::open("bar.txt")?;
777 /// let mut handle = f1.chain(f2);
778 /// let mut buffer = String::new();
780 /// // read the value into a String. We could use any Read method here,
781 /// // this is just one example.
782 /// handle.read_to_string(&mut buffer)?;
786 #[stable(feature = "rust1", since = "1.0.0")]
787 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
788 Chain { first: self, second: next, done_first: false }
791 /// Creates an adaptor which will read at most `limit` bytes from it.
793 /// This function returns a new instance of `Read` which will read at most
794 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
795 /// read errors will not count towards the number of bytes read and future
796 /// calls to `read` may succeed.
800 /// [`File`][file]s implement `Read`:
802 /// [file]: ../fs/struct.File.html
806 /// use std::io::prelude::*;
807 /// use std::fs::File;
809 /// # fn foo() -> io::Result<()> {
810 /// let mut f = File::open("foo.txt")?;
811 /// let mut buffer = [0; 5];
813 /// // read at most five bytes
814 /// let mut handle = f.take(5);
816 /// handle.read(&mut buffer)?;
820 #[stable(feature = "rust1", since = "1.0.0")]
821 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
822 Take { inner: self, limit: limit }
826 /// A trait for objects which are byte-oriented sinks.
828 /// Implementors of the `Write` trait are sometimes called 'writers'.
830 /// Writers are defined by two required methods, [`write`] and [`flush`]:
832 /// * The [`write`] method will attempt to write some data into the object,
833 /// returning how many bytes were successfully written.
835 /// * The [`flush`] method is useful for adaptors and explicit buffers
836 /// themselves for ensuring that all buffered data has been pushed out to the
839 /// Writers are intended to be composable with one another. Many implementors
840 /// throughout [`std::io`] take and provide types which implement the `Write`
843 /// [`write`]: #tymethod.write
844 /// [`flush`]: #tymethod.flush
845 /// [`std::io`]: index.html
850 /// use std::io::prelude::*;
851 /// use std::fs::File;
853 /// # fn foo() -> std::io::Result<()> {
854 /// let mut buffer = File::create("foo.txt")?;
856 /// buffer.write(b"some bytes")?;
860 #[stable(feature = "rust1", since = "1.0.0")]
862 /// Write a buffer into this object, returning how many bytes were written.
864 /// This function will attempt to write the entire contents of `buf`, but
865 /// the entire write may not succeed, or the write may also generate an
866 /// error. A call to `write` represents *at most one* attempt to write to
867 /// any wrapped object.
869 /// Calls to `write` are not guaranteed to block waiting for data to be
870 /// written, and a write which would otherwise block can be indicated through
871 /// an `Err` variant.
873 /// If the return value is `Ok(n)` then it must be guaranteed that
874 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
875 /// underlying object is no longer able to accept bytes and will likely not
876 /// be able to in the future as well, or that the buffer provided is empty.
880 /// Each call to `write` may generate an I/O error indicating that the
881 /// operation could not be completed. If an error is returned then no bytes
882 /// in the buffer were written to this writer.
884 /// It is **not** considered an error if the entire buffer could not be
885 /// written to this writer.
890 /// use std::io::prelude::*;
891 /// use std::fs::File;
893 /// # fn foo() -> std::io::Result<()> {
894 /// let mut buffer = File::create("foo.txt")?;
896 /// buffer.write(b"some bytes")?;
900 #[stable(feature = "rust1", since = "1.0.0")]
901 fn write(&mut self, buf: &[u8]) -> Result<usize>;
903 /// Flush this output stream, ensuring that all intermediately buffered
904 /// contents reach their destination.
908 /// It is considered an error if not all bytes could be written due to
909 /// I/O errors or EOF being reached.
914 /// use std::io::prelude::*;
915 /// use std::io::BufWriter;
916 /// use std::fs::File;
918 /// # fn foo() -> std::io::Result<()> {
919 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
921 /// buffer.write(b"some bytes")?;
926 #[stable(feature = "rust1", since = "1.0.0")]
927 fn flush(&mut self) -> Result<()>;
929 /// Attempts to write an entire buffer into this write.
931 /// This method will continuously call `write` while there is more data to
932 /// write. This method will not return until the entire buffer has been
933 /// successfully written or an error occurs. The first error generated from
934 /// this method will be returned.
938 /// This function will return the first error that `write` returns.
943 /// use std::io::prelude::*;
944 /// use std::fs::File;
946 /// # fn foo() -> std::io::Result<()> {
947 /// let mut buffer = File::create("foo.txt")?;
949 /// buffer.write_all(b"some bytes")?;
953 #[stable(feature = "rust1", since = "1.0.0")]
954 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
955 while !buf.is_empty() {
956 match self.write(buf) {
957 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
958 "failed to write whole buffer")),
959 Ok(n) => buf = &buf[n..],
960 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
961 Err(e) => return Err(e),
967 /// Writes a formatted string into this writer, returning any error
970 /// This method is primarily used to interface with the
971 /// [`format_args!`][formatargs] macro, but it is rare that this should
972 /// explicitly be called. The [`write!`][write] macro should be favored to
973 /// invoke this method instead.
975 /// [formatargs]: ../macro.format_args.html
976 /// [write]: ../macro.write.html
978 /// This function internally uses the [`write_all`][writeall] method on
979 /// this trait and hence will continuously write data so long as no errors
980 /// are received. This also means that partial writes are not indicated in
983 /// [writeall]: #method.write_all
987 /// This function will return any I/O error reported while formatting.
992 /// use std::io::prelude::*;
993 /// use std::fs::File;
995 /// # fn foo() -> std::io::Result<()> {
996 /// let mut buffer = File::create("foo.txt")?;
999 /// write!(buffer, "{:.*}", 2, 1.234567)?;
1000 /// // turns into this:
1001 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1007 // Create a shim which translates a Write to a fmt::Write and saves
1008 // off I/O errors. instead of discarding them
1009 struct Adaptor<'a, T: ?Sized + 'a> {
1014 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1015 fn write_str(&mut self, s: &str) -> fmt::Result {
1016 match self.inner.write_all(s.as_bytes()) {
1019 self.error = Err(e);
1026 let mut output = Adaptor { inner: self, error: Ok(()) };
1027 match fmt::write(&mut output, fmt) {
1030 // check if the error came from the underlying `Write` or not
1031 if output.error.is_err() {
1034 Err(Error::new(ErrorKind::Other, "formatter error"))
1040 /// Creates a "by reference" adaptor for this instance of `Write`.
1042 /// The returned adaptor also implements `Write` and will simply borrow this
1048 /// use std::io::Write;
1049 /// use std::fs::File;
1051 /// # fn foo() -> std::io::Result<()> {
1052 /// let mut buffer = File::create("foo.txt")?;
1054 /// let reference = buffer.by_ref();
1056 /// // we can use reference just like our original buffer
1057 /// reference.write_all(b"some bytes")?;
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1065 /// The `Seek` trait provides a cursor which can be moved within a stream of
1068 /// The stream typically has a fixed size, allowing seeking relative to either
1069 /// end or the current offset.
1073 /// [`File`][file]s implement `Seek`:
1075 /// [file]: ../fs/struct.File.html
1079 /// use std::io::prelude::*;
1080 /// use std::fs::File;
1081 /// use std::io::SeekFrom;
1083 /// # fn foo() -> io::Result<()> {
1084 /// let mut f = File::open("foo.txt")?;
1086 /// // move the cursor 42 bytes from the start of the file
1087 /// f.seek(SeekFrom::Start(42))?;
1091 #[stable(feature = "rust1", since = "1.0.0")]
1093 /// Seek to an offset, in bytes, in a stream.
1095 /// A seek beyond the end of a stream is allowed, but implementation
1098 /// If the seek operation completed successfully,
1099 /// this method returns the new position from the start of the stream.
1100 /// That position can be used later with [`SeekFrom::Start`].
1104 /// Seeking to a negative offset is considered an error.
1106 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1111 /// Enumeration of possible methods to seek within an I/O object.
1113 /// It is used by the [`Seek`] trait.
1115 /// [`Seek`]: trait.Seek.html
1116 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1117 #[stable(feature = "rust1", since = "1.0.0")]
1119 /// Set the offset to the provided number of bytes.
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1123 /// Set the offset to the size of this object plus the specified number of
1126 /// It is possible to seek beyond the end of an object, but it's an error to
1127 /// seek before byte 0.
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1131 /// Set the offset to the current position plus the specified number of
1134 /// It is possible to seek beyond the end of an object, but it's an error to
1135 /// seek before byte 0.
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1140 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1144 let (done, used) = {
1145 let available = match r.fill_buf() {
1147 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1148 Err(e) => return Err(e)
1150 match memchr::memchr(delim, available) {
1152 buf.extend_from_slice(&available[..i + 1]);
1156 buf.extend_from_slice(available);
1157 (false, available.len())
1163 if done || used == 0 {
1169 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1170 /// to perform extra ways of reading.
1172 /// For example, reading line-by-line is inefficient without using a buffer, so
1173 /// if you want to read by line, you'll need `BufRead`, which includes a
1174 /// [`read_line`] method as well as a [`lines`] iterator.
1178 /// A locked standard input implements `BufRead`:
1182 /// use std::io::prelude::*;
1184 /// let stdin = io::stdin();
1185 /// for line in stdin.lock().lines() {
1186 /// println!("{}", line.unwrap());
1190 /// If you have something that implements [`Read`], you can use the [`BufReader`
1191 /// type][`BufReader`] to turn it into a `BufRead`.
1193 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1194 /// [`BufReader`] to the rescue!
1196 /// [`BufReader`]: struct.BufReader.html
1197 /// [`File`]: ../fs/struct.File.html
1198 /// [`read_line`]: #method.read_line
1199 /// [`lines`]: #method.lines
1200 /// [`Read`]: trait.Read.html
1203 /// use std::io::{self, BufReader};
1204 /// use std::io::prelude::*;
1205 /// use std::fs::File;
1207 /// # fn foo() -> io::Result<()> {
1208 /// let f = File::open("foo.txt")?;
1209 /// let f = BufReader::new(f);
1211 /// for line in f.lines() {
1212 /// println!("{}", line.unwrap());
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 pub trait BufRead: Read {
1221 /// Fills the internal buffer of this object, returning the buffer contents.
1223 /// This function is a lower-level call. It needs to be paired with the
1224 /// [`consume`] method to function properly. When calling this
1225 /// method, none of the contents will be "read" in the sense that later
1226 /// calling `read` may return the same contents. As such, [`consume`] must
1227 /// be called with the number of bytes that are consumed from this buffer to
1228 /// ensure that the bytes are never returned twice.
1230 /// [`consume`]: #tymethod.consume
1232 /// An empty buffer returned indicates that the stream has reached EOF.
1236 /// This function will return an I/O error if the underlying reader was
1237 /// read, but returned an error.
1241 /// A locked standard input implements `BufRead`:
1245 /// use std::io::prelude::*;
1247 /// let stdin = io::stdin();
1248 /// let mut stdin = stdin.lock();
1250 /// // we can't have two `&mut` references to `stdin`, so use a block
1251 /// // to end the borrow early.
1253 /// let buffer = stdin.fill_buf().unwrap();
1255 /// // work with buffer
1256 /// println!("{:?}", buffer);
1261 /// // ensure the bytes we worked with aren't returned again later
1262 /// stdin.consume(length);
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 fn fill_buf(&mut self) -> Result<&[u8]>;
1267 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1268 /// so they should no longer be returned in calls to `read`.
1270 /// This function is a lower-level call. It needs to be paired with the
1271 /// [`fill_buf`] method to function properly. This function does
1272 /// not perform any I/O, it simply informs this object that some amount of
1273 /// its buffer, returned from [`fill_buf`], has been consumed and should
1274 /// no longer be returned. As such, this function may do odd things if
1275 /// [`fill_buf`] isn't called before calling it.
1277 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1282 /// Since `consume()` is meant to be used with [`fill_buf`],
1283 /// that method's example includes an example of `consume()`.
1285 /// [`fill_buf`]: #tymethod.fill_buf
1286 #[stable(feature = "rust1", since = "1.0.0")]
1287 fn consume(&mut self, amt: usize);
1289 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1291 /// This function will read bytes from the underlying stream until the
1292 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1293 /// the delimiter (if found) will be appended to `buf`.
1295 /// If successful, this function will return the total number of bytes read.
1299 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1300 /// will otherwise return any errors returned by [`fill_buf`].
1302 /// If an I/O error is encountered then all bytes read so far will be
1303 /// present in `buf` and its length will have been adjusted appropriately.
1307 /// A locked standard input implements `BufRead`. In this example, we'll
1308 /// read from standard input until we see an `a` byte.
1310 /// [`fill_buf`]: #tymethod.fill_buf
1311 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1315 /// use std::io::prelude::*;
1317 /// fn foo() -> io::Result<()> {
1318 /// let stdin = io::stdin();
1319 /// let mut stdin = stdin.lock();
1320 /// let mut buffer = Vec::new();
1322 /// stdin.read_until(b'a', &mut buffer)?;
1324 /// println!("{:?}", buffer);
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1330 read_until(self, byte, buf)
1333 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1334 /// them to the provided buffer.
1336 /// This function will read bytes from the underlying stream until the
1337 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1338 /// up to, and including, the delimiter (if found) will be appended to
1341 /// If successful, this function will return the total number of bytes read.
1345 /// This function has the same error semantics as [`read_until`] and will
1346 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1347 /// error is encountered then `buf` may contain some bytes already read in
1348 /// the event that all data read so far was valid UTF-8.
1352 /// A locked standard input implements `BufRead`. In this example, we'll
1353 /// read all of the lines from standard input. If we were to do this in
1354 /// an actual project, the [`lines`] method would be easier, of
1357 /// [`lines`]: #method.lines
1358 /// [`read_until`]: #method.read_until
1362 /// use std::io::prelude::*;
1364 /// let stdin = io::stdin();
1365 /// let mut stdin = stdin.lock();
1366 /// let mut buffer = String::new();
1368 /// while stdin.read_line(&mut buffer).unwrap() > 0 {
1369 /// // work with buffer
1370 /// println!("{:?}", buffer);
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1377 // Note that we are not calling the `.read_until` method here, but
1378 // rather our hardcoded implementation. For more details as to why, see
1379 // the comments in `read_to_end`.
1380 append_to_string(buf, |b| read_until(self, b'\n', b))
1383 /// Returns an iterator over the contents of this reader split on the byte
1386 /// The iterator returned from this function will return instances of
1387 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1388 /// the delimiter byte at the end.
1390 /// This function will yield errors whenever [`read_until`] would have
1391 /// also yielded an error.
1395 /// A locked standard input implements `BufRead`. In this example, we'll
1396 /// read some input from standard input, splitting on commas.
1398 /// [`io::Result`]: type.Result.html
1399 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1400 /// [`read_until`]: #method.read_until
1404 /// use std::io::prelude::*;
1406 /// let stdin = io::stdin();
1408 /// for content in stdin.lock().split(b',') {
1409 /// println!("{:?}", content.unwrap());
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1414 Split { buf: self, delim: byte }
1417 /// Returns an iterator over the lines of this reader.
1419 /// The iterator returned from this function will yield instances of
1420 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1421 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1423 /// [`io::Result`]: type.Result.html
1424 /// [`String`]: ../string/struct.String.html
1428 /// A locked standard input implements `BufRead`:
1432 /// use std::io::prelude::*;
1434 /// let stdin = io::stdin();
1436 /// for line in stdin.lock().lines() {
1437 /// println!("{}", line.unwrap());
1443 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1445 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 fn lines(self) -> Lines<Self> where Self: Sized {
1452 /// Adaptor to chain together two readers.
1454 /// This struct is generally created by calling [`chain`] on a reader.
1455 /// Please see the documentation of [`chain`] for more details.
1457 /// [`chain`]: trait.Read.html#method.chain
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 pub struct Chain<T, U> {
1465 #[stable(feature = "std_debug", since = "1.16.0")]
1466 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1467 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1468 f.debug_struct("Chain")
1469 .field("t", &self.first)
1470 .field("u", &self.second)
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 impl<T: Read, U: Read> Read for Chain<T, U> {
1477 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1478 if !self.done_first {
1479 match self.first.read(buf)? {
1480 0 if buf.len() != 0 => { self.done_first = true; }
1484 self.second.read(buf)
1488 #[stable(feature = "chain_bufread", since = "1.9.0")]
1489 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1490 fn fill_buf(&mut self) -> Result<&[u8]> {
1491 if !self.done_first {
1492 match self.first.fill_buf()? {
1493 buf if buf.len() == 0 => { self.done_first = true; }
1494 buf => return Ok(buf),
1497 self.second.fill_buf()
1500 fn consume(&mut self, amt: usize) {
1501 if !self.done_first {
1502 self.first.consume(amt)
1504 self.second.consume(amt)
1509 /// Reader adaptor which limits the bytes read from an underlying reader.
1511 /// This struct is generally created by calling [`take`] on a reader.
1512 /// Please see the documentation of [`take`] for more details.
1514 /// [`take`]: trait.Read.html#method.take
1515 #[stable(feature = "rust1", since = "1.0.0")]
1517 pub struct Take<T> {
1523 /// Returns the number of bytes that can be read before this instance will
1528 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1529 /// this method if the underlying [`Read`] instance reaches EOF.
1531 /// [`Read`]: ../../std/io/trait.Read.html
1537 /// use std::io::prelude::*;
1538 /// use std::fs::File;
1540 /// # fn foo() -> io::Result<()> {
1541 /// let f = File::open("foo.txt")?;
1543 /// // read at most five bytes
1544 /// let handle = f.take(5);
1546 /// println!("limit: {}", handle.limit());
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 pub fn limit(&self) -> u64 { self.limit }
1553 /// Consumes the `Take`, returning the wrapped reader.
1559 /// use std::io::prelude::*;
1560 /// use std::fs::File;
1562 /// # fn foo() -> io::Result<()> {
1563 /// let mut file = File::open("foo.txt")?;
1565 /// let mut buffer = [0; 5];
1566 /// let mut handle = file.take(5);
1567 /// handle.read(&mut buffer)?;
1569 /// let file = handle.into_inner();
1573 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1574 pub fn into_inner(self) -> T {
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl<T: Read> Read for Take<T> {
1581 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1582 // Don't call into inner reader at all at EOF because it may still block
1583 if self.limit == 0 {
1587 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1588 let n = self.inner.read(&mut buf[..max])?;
1589 self.limit -= n as u64;
1594 #[stable(feature = "rust1", since = "1.0.0")]
1595 impl<T: BufRead> BufRead for Take<T> {
1596 fn fill_buf(&mut self) -> Result<&[u8]> {
1597 // Don't call into inner reader at all at EOF because it may still block
1598 if self.limit == 0 {
1602 let buf = self.inner.fill_buf()?;
1603 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1607 fn consume(&mut self, amt: usize) {
1608 // Don't let callers reset the limit by passing an overlarge value
1609 let amt = cmp::min(amt as u64, self.limit) as usize;
1610 self.limit -= amt as u64;
1611 self.inner.consume(amt);
1615 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1618 return match reader.read(&mut buf) {
1620 Ok(..) => Some(Ok(buf[0])),
1621 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1622 Err(e) => Some(Err(e)),
1627 /// An iterator over `u8` values of a reader.
1629 /// This struct is generally created by calling [`bytes`] on a reader.
1630 /// Please see the documentation of [`bytes`] for more details.
1632 /// [`bytes`]: trait.Read.html#method.bytes
1633 #[stable(feature = "rust1", since = "1.0.0")]
1635 pub struct Bytes<R> {
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 impl<R: Read> Iterator for Bytes<R> {
1641 type Item = Result<u8>;
1643 fn next(&mut self) -> Option<Result<u8>> {
1644 read_one_byte(&mut self.inner)
1648 /// An iterator over the `char`s of a reader.
1650 /// This struct is generally created by calling [`chars`][chars] on a reader.
1651 /// Please see the documentation of `chars()` for more details.
1653 /// [chars]: trait.Read.html#method.chars
1654 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1657 pub struct Chars<R> {
1661 /// An enumeration of possible errors that can be generated from the `Chars`
1664 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1666 pub enum CharsError {
1667 /// Variant representing that the underlying stream was read successfully
1668 /// but it did not contain valid utf8 data.
1671 /// Variant representing that an I/O error occurred.
1675 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1677 impl<R: Read> Iterator for Chars<R> {
1678 type Item = result::Result<char, CharsError>;
1680 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1681 let first_byte = match read_one_byte(&mut self.inner) {
1682 None => return None,
1684 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1686 let width = core_str::utf8_char_width(first_byte);
1687 if width == 1 { return Some(Ok(first_byte as char)) }
1688 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1689 let mut buf = [first_byte, 0, 0, 0];
1692 while start < width {
1693 match self.inner.read(&mut buf[start..width]) {
1694 Ok(0) => return Some(Err(CharsError::NotUtf8)),
1695 Ok(n) => start += n,
1696 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1697 Err(e) => return Some(Err(CharsError::Other(e))),
1701 Some(match str::from_utf8(&buf[..width]).ok() {
1702 Some(s) => Ok(s.chars().next().unwrap()),
1703 None => Err(CharsError::NotUtf8),
1708 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1710 impl std_error::Error for CharsError {
1711 fn description(&self) -> &str {
1713 CharsError::NotUtf8 => "invalid utf8 encoding",
1714 CharsError::Other(ref e) => std_error::Error::description(e),
1717 fn cause(&self) -> Option<&std_error::Error> {
1719 CharsError::NotUtf8 => None,
1720 CharsError::Other(ref e) => e.cause(),
1725 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1727 impl fmt::Display for CharsError {
1728 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1730 CharsError::NotUtf8 => {
1731 "byte stream did not contain valid utf8".fmt(f)
1733 CharsError::Other(ref e) => e.fmt(f),
1738 /// An iterator over the contents of an instance of `BufRead` split on a
1739 /// particular byte.
1741 /// This struct is generally created by calling [`split`][split] on a
1742 /// `BufRead`. Please see the documentation of `split()` for more details.
1744 /// [split]: trait.BufRead.html#method.split
1745 #[stable(feature = "rust1", since = "1.0.0")]
1747 pub struct Split<B> {
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 impl<B: BufRead> Iterator for Split<B> {
1754 type Item = Result<Vec<u8>>;
1756 fn next(&mut self) -> Option<Result<Vec<u8>>> {
1757 let mut buf = Vec::new();
1758 match self.buf.read_until(self.delim, &mut buf) {
1761 if buf[buf.len() - 1] == self.delim {
1766 Err(e) => Some(Err(e))
1771 /// An iterator over the lines of an instance of `BufRead`.
1773 /// This struct is generally created by calling [`lines`][lines] on a
1774 /// `BufRead`. Please see the documentation of `lines()` for more details.
1776 /// [lines]: trait.BufRead.html#method.lines
1777 #[stable(feature = "rust1", since = "1.0.0")]
1779 pub struct Lines<B> {
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 impl<B: BufRead> Iterator for Lines<B> {
1785 type Item = Result<String>;
1787 fn next(&mut self) -> Option<Result<String>> {
1788 let mut buf = String::new();
1789 match self.buf.read_line(&mut buf) {
1792 if buf.ends_with("\n") {
1794 if buf.ends_with("\r") {
1800 Err(e) => Some(Err(e))
1814 #[cfg_attr(target_os = "emscripten", ignore)]
1816 let mut buf = Cursor::new(&b"12"[..]);
1817 let mut v = Vec::new();
1818 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
1819 assert_eq!(v, b"12");
1821 let mut buf = Cursor::new(&b"1233"[..]);
1822 let mut v = Vec::new();
1823 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
1824 assert_eq!(v, b"123");
1826 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
1827 assert_eq!(v, b"3");
1829 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
1835 let buf = Cursor::new(&b"12"[..]);
1836 let mut s = buf.split(b'3');
1837 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1838 assert!(s.next().is_none());
1840 let buf = Cursor::new(&b"1233"[..]);
1841 let mut s = buf.split(b'3');
1842 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1843 assert_eq!(s.next().unwrap().unwrap(), vec![]);
1844 assert!(s.next().is_none());
1849 let mut buf = Cursor::new(&b"12"[..]);
1850 let mut v = String::new();
1851 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
1852 assert_eq!(v, "12");
1854 let mut buf = Cursor::new(&b"12\n\n"[..]);
1855 let mut v = String::new();
1856 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
1857 assert_eq!(v, "12\n");
1859 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
1860 assert_eq!(v, "\n");
1862 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
1868 let buf = Cursor::new(&b"12\r"[..]);
1869 let mut s = buf.lines();
1870 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
1871 assert!(s.next().is_none());
1873 let buf = Cursor::new(&b"12\r\n\n"[..]);
1874 let mut s = buf.lines();
1875 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
1876 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
1877 assert!(s.next().is_none());
1882 let mut c = Cursor::new(&b""[..]);
1883 let mut v = Vec::new();
1884 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
1887 let mut c = Cursor::new(&b"1"[..]);
1888 let mut v = Vec::new();
1889 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
1890 assert_eq!(v, b"1");
1892 let cap = 1024 * 1024;
1893 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
1894 let mut v = Vec::new();
1895 let (a, b) = data.split_at(data.len() / 2);
1896 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
1897 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
1898 assert_eq!(v, data);
1902 fn read_to_string() {
1903 let mut c = Cursor::new(&b""[..]);
1904 let mut v = String::new();
1905 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
1908 let mut c = Cursor::new(&b"1"[..]);
1909 let mut v = String::new();
1910 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
1913 let mut c = Cursor::new(&b"\xff"[..]);
1914 let mut v = String::new();
1915 assert!(c.read_to_string(&mut v).is_err());
1920 let mut buf = [0; 4];
1922 let mut c = Cursor::new(&b""[..]);
1923 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1924 io::ErrorKind::UnexpectedEof);
1926 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
1927 c.read_exact(&mut buf).unwrap();
1928 assert_eq!(&buf, b"1234");
1929 c.read_exact(&mut buf).unwrap();
1930 assert_eq!(&buf, b"5678");
1931 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1932 io::ErrorKind::UnexpectedEof);
1936 fn read_exact_slice() {
1937 let mut buf = [0; 4];
1939 let mut c = &b""[..];
1940 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1941 io::ErrorKind::UnexpectedEof);
1943 let mut c = &b"123"[..];
1944 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1945 io::ErrorKind::UnexpectedEof);
1946 // make sure the optimized (early returning) method is being used
1947 assert_eq!(&buf, &[0; 4]);
1949 let mut c = &b"1234"[..];
1950 c.read_exact(&mut buf).unwrap();
1951 assert_eq!(&buf, b"1234");
1953 let mut c = &b"56789"[..];
1954 c.read_exact(&mut buf).unwrap();
1955 assert_eq!(&buf, b"5678");
1956 assert_eq!(c, b"9");
1964 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1965 Err(io::Error::new(io::ErrorKind::Other, ""))
1968 impl BufRead for R {
1969 fn fill_buf(&mut self) -> io::Result<&[u8]> {
1970 Err(io::Error::new(io::ErrorKind::Other, ""))
1972 fn consume(&mut self, _amt: usize) { }
1975 let mut buf = [0; 1];
1976 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
1977 assert_eq!(b"", R.take(0).fill_buf().unwrap());
1980 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
1981 let mut cat = Vec::new();
1984 let buf1 = br1.fill_buf().unwrap();
1985 let buf2 = br2.fill_buf().unwrap();
1986 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
1987 assert_eq!(buf1[..minlen], buf2[..minlen]);
1988 cat.extend_from_slice(&buf1[..minlen]);
1994 br1.consume(consume);
1995 br2.consume(consume);
1997 assert_eq!(br1.fill_buf().unwrap().len(), 0);
1998 assert_eq!(br2.fill_buf().unwrap().len(), 0);
1999 assert_eq!(&cat[..], &exp[..])
2003 fn chain_bufread() {
2004 let testdata = b"ABCDEFGHIJKL";
2005 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2006 .chain(&testdata[6..9])
2007 .chain(&testdata[9..]);
2008 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2009 .chain(&testdata[8..]);
2010 cmp_bufread(chain1, chain2, &testdata[..]);
2014 fn chain_zero_length_read_is_not_eof() {
2017 let mut s = String::new();
2018 let mut chain = (&a[..]).chain(&b[..]);
2019 chain.read(&mut []).unwrap();
2020 chain.read_to_string(&mut s).unwrap();
2021 assert_eq!("AB", s);
2025 #[cfg_attr(target_os = "emscripten", ignore)]
2026 fn bench_read_to_end(b: &mut test::Bencher) {
2028 let mut lr = repeat(1).take(10000000);
2029 let mut vec = Vec::with_capacity(1024);
2030 super::read_to_end(&mut lr, &mut vec)