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());
147 //! Note that you cannot use the `?` operator in functions that do not return a `Result` (e.g. `main()`).
148 //! Instead, you can `match` on the return value to catch any possible errors:
151 //! let mut input = String::new();
152 //! match io::stdin().read_line(&mut input) {
153 //! Err(why) => panic!("Failed to read input: {}", why.description()),
154 //! Ok(_) => println!("You typed: {}", input.trim()),
158 //! And a very common source of output is standard output:
162 //! use std::io::prelude::*;
164 //! # fn foo() -> io::Result<()> {
165 //! io::stdout().write(&[42])?;
170 //! Of course, using [`io::stdout`] directly is less common than something like
173 //! ## Iterator types
175 //! A large number of the structures provided by `std::io` are for various
176 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
181 //! use std::io::prelude::*;
182 //! use std::io::BufReader;
183 //! use std::fs::File;
185 //! # fn foo() -> io::Result<()> {
186 //! let f = File::open("foo.txt")?;
187 //! let reader = BufReader::new(f);
189 //! for line in reader.lines() {
190 //! println!("{}", line?);
199 //! There are a number of [functions][functions-list] that offer access to various
200 //! features. For example, we can use three of these functions to copy everything
201 //! from standard input to standard output:
206 //! # fn foo() -> io::Result<()> {
207 //! io::copy(&mut io::stdin(), &mut io::stdout())?;
212 //! [functions-list]: #functions-1
216 //! Last, but certainly not least, is [`io::Result`]. This type is used
217 //! as the return type of many `std::io` functions that can cause an error, and
218 //! can be returned from your own functions as well. Many of the examples in this
219 //! module use the [`?` operator]:
224 //! fn read_input() -> io::Result<()> {
225 //! let mut input = String::new();
227 //! io::stdin().read_line(&mut input)?;
229 //! println!("You typed: {}", input.trim());
235 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
236 //! common type for functions which don't have a 'real' return value, but do want to
237 //! return errors if they happen. In this case, the only purpose of this function is
238 //! to read the line and print it, so we use `()`.
240 //! ## Platform-specific behavior
242 //! Many I/O functions throughout the standard library are documented to indicate
243 //! what various library or syscalls they are delegated to. This is done to help
244 //! applications both understand what's happening under the hood as well as investigate
245 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
246 //! contract. The implementation of many of these functions are subject to change over
247 //! time and may call fewer or more syscalls/library functions.
249 //! [`Read`]: trait.Read.html
250 //! [`Write`]: trait.Write.html
251 //! [`Seek`]: trait.Seek.html
252 //! [`BufRead`]: trait.BufRead.html
253 //! [`File`]: ../fs/struct.File.html
254 //! [`TcpStream`]: ../net/struct.TcpStream.html
255 //! [`Vec<T>`]: ../vec/struct.Vec.html
256 //! [`BufReader`]: struct.BufReader.html
257 //! [`BufWriter`]: struct.BufWriter.html
258 //! [`write`]: trait.Write.html#tymethod.write
259 //! [`io::stdout`]: fn.stdout.html
260 //! [`println!`]: ../macro.println.html
261 //! [`Lines`]: struct.Lines.html
262 //! [`io::Result`]: type.Result.html
263 //! [`?` operator]: ../../book/syntax-index.html
264 //! [`read`]: trait.Read.html#tymethod.read
266 #![stable(feature = "rust1", since = "1.0.0")]
269 use core::str as core_str;
270 use error as std_error;
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub use self::buffered::{BufReader, BufWriter, LineWriter};
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub use self::buffered::IntoInnerError;
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub use self::cursor::Cursor;
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub use self::error::{Result, Error, ErrorKind};
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
290 #[unstable(feature = "libstd_io_internals", issue = "0")]
291 #[doc(no_inline, hidden)]
292 pub use self::stdio::{set_panic, set_print};
303 const DEFAULT_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE;
305 // A few methods below (read_to_string, read_line) will append data into a
306 // `String` buffer, but we need to be pretty careful when doing this. The
307 // implementation will just call `.as_mut_vec()` and then delegate to a
308 // byte-oriented reading method, but we must ensure that when returning we never
309 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
311 // To this end, we use an RAII guard (to protect against panics) which updates
312 // the length of the string when it is dropped. This guard initially truncates
313 // the string to the prior length and only after we've validated that the
314 // new contents are valid UTF-8 do we allow it to set a longer length.
316 // The unsafety in this function is twofold:
318 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
320 // 2. We're passing a raw buffer to the function `f`, and it is expected that
321 // the function only *appends* bytes to the buffer. We'll get undefined
322 // behavior if existing bytes are overwritten to have non-UTF-8 data.
323 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
324 where F: FnOnce(&mut Vec<u8>) -> Result<usize>
326 struct Guard<'a> { s: &'a mut Vec<u8>, len: usize }
327 impl<'a> Drop for Guard<'a> {
329 unsafe { self.s.set_len(self.len); }
334 let mut g = Guard { len: buf.len(), s: buf.as_mut_vec() };
336 if str::from_utf8(&g.s[g.len..]).is_err() {
338 Err(Error::new(ErrorKind::InvalidData,
339 "stream did not contain valid UTF-8"))
348 // This uses an adaptive system to extend the vector when it fills. We want to
349 // avoid paying to allocate and zero a huge chunk of memory if the reader only
350 // has 4 bytes while still making large reads if the reader does have a ton
351 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
352 // time is 4,500 times (!) slower than this if the reader has a very small
353 // amount of data to return.
354 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
355 let start_len = buf.len();
356 let mut len = start_len;
357 let mut new_write_size = 16;
360 if len == buf.len() {
361 if new_write_size < DEFAULT_BUF_SIZE {
364 buf.resize(len + new_write_size, 0);
367 match r.read(&mut buf[len..]) {
369 ret = Ok(len - start_len);
373 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
385 /// The `Read` trait allows for reading bytes from a source.
387 /// Implementors of the `Read` trait are sometimes called 'readers'.
389 /// Readers are defined by one required method, `read()`. Each call to `read`
390 /// will attempt to pull bytes from this source into a provided buffer. A
391 /// number of other methods are implemented in terms of `read()`, giving
392 /// implementors a number of ways to read bytes while only needing to implement
395 /// Readers are intended to be composable with one another. Many implementors
396 /// throughout `std::io` take and provide types which implement the `Read`
399 /// Please note that each call to `read` may involve a system call, and
400 /// therefore, using something that implements [`BufRead`][bufread], such as
401 /// [`BufReader`][bufreader], will be more efficient.
403 /// [bufread]: trait.BufRead.html
404 /// [bufreader]: struct.BufReader.html
408 /// [`File`][file]s implement `Read`:
410 /// [file]: ../fs/struct.File.html
414 /// use std::io::prelude::*;
415 /// use std::fs::File;
417 /// # fn foo() -> io::Result<()> {
418 /// let mut f = File::open("foo.txt")?;
419 /// let mut buffer = [0; 10];
421 /// // read up to 10 bytes
422 /// f.read(&mut buffer)?;
424 /// let mut buffer = vec![0; 10];
425 /// // read the whole file
426 /// f.read_to_end(&mut buffer)?;
428 /// // read into a String, so that you don't need to do the conversion.
429 /// let mut buffer = String::new();
430 /// f.read_to_string(&mut buffer)?;
432 /// // and more! See the other methods for more details.
436 #[stable(feature = "rust1", since = "1.0.0")]
438 /// Pull some bytes from this source into the specified buffer, returning
439 /// how many bytes were read.
441 /// This function does not provide any guarantees about whether it blocks
442 /// waiting for data, but if an object needs to block for a read but cannot
443 /// it will typically signal this via an `Err` return value.
445 /// If the return value of this method is `Ok(n)`, then it must be
446 /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
447 /// that the buffer `buf` has been filled in with `n` bytes of data from this
448 /// source. If `n` is `0`, then it can indicate one of two scenarios:
450 /// 1. This reader has reached its "end of file" and will likely no longer
451 /// be able to produce bytes. Note that this does not mean that the
452 /// reader will *always* no longer be able to produce bytes.
453 /// 2. The buffer specified was 0 bytes in length.
455 /// No guarantees are provided about the contents of `buf` when this
456 /// function is called, implementations cannot rely on any property of the
457 /// contents of `buf` being true. It is recommended that implementations
458 /// only write data to `buf` instead of reading its contents.
462 /// If this function encounters any form of I/O or other error, an error
463 /// variant will be returned. If an error is returned then it must be
464 /// guaranteed that no bytes were read.
468 /// [`File`][file]s implement `Read`:
470 /// [file]: ../fs/struct.File.html
474 /// use std::io::prelude::*;
475 /// use std::fs::File;
477 /// # fn foo() -> io::Result<()> {
478 /// let mut f = File::open("foo.txt")?;
479 /// let mut buffer = [0; 10];
482 /// f.read(&mut buffer[..])?;
486 #[stable(feature = "rust1", since = "1.0.0")]
487 fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
489 /// Read all bytes until EOF in this source, placing them into `buf`.
491 /// All bytes read from this source will be appended to the specified buffer
492 /// `buf`. This function will continuously call `read` to append more data to
493 /// `buf` until `read` returns either `Ok(0)` or an error of
494 /// non-`ErrorKind::Interrupted` kind.
496 /// If successful, this function will return the total number of bytes read.
500 /// If this function encounters an error of the kind
501 /// `ErrorKind::Interrupted` then the error is ignored and the operation
504 /// If any other read error is encountered then this function immediately
505 /// returns. Any bytes which have already been read will be appended to
510 /// [`File`][file]s implement `Read`:
512 /// [file]: ../fs/struct.File.html
516 /// use std::io::prelude::*;
517 /// use std::fs::File;
519 /// # fn foo() -> io::Result<()> {
520 /// let mut f = File::open("foo.txt")?;
521 /// let mut buffer = Vec::new();
523 /// // read the whole file
524 /// f.read_to_end(&mut buffer)?;
528 #[stable(feature = "rust1", since = "1.0.0")]
529 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
530 read_to_end(self, buf)
533 /// Read all bytes until EOF in this source, placing them into `buf`.
535 /// If successful, this function returns the number of bytes which were read
536 /// and appended to `buf`.
540 /// If the data in this stream is *not* valid UTF-8 then an error is
541 /// returned and `buf` is unchanged.
543 /// See [`read_to_end`][readtoend] for other error semantics.
545 /// [readtoend]: #method.read_to_end
549 /// [`File`][file]s implement `Read`:
551 /// [file]: ../fs/struct.File.html
555 /// use std::io::prelude::*;
556 /// use std::fs::File;
558 /// # fn foo() -> io::Result<()> {
559 /// let mut f = File::open("foo.txt")?;
560 /// let mut buffer = String::new();
562 /// f.read_to_string(&mut buffer)?;
566 #[stable(feature = "rust1", since = "1.0.0")]
567 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
568 // Note that we do *not* call `.read_to_end()` here. We are passing
569 // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
570 // method to fill it up. An arbitrary implementation could overwrite the
571 // entire contents of the vector, not just append to it (which is what
572 // we are expecting).
574 // To prevent extraneously checking the UTF-8-ness of the entire buffer
575 // we pass it to our hardcoded `read_to_end` implementation which we
576 // know is guaranteed to only read data into the end of the buffer.
577 append_to_string(buf, |b| read_to_end(self, b))
580 /// Read the exact number of bytes required to fill `buf`.
582 /// This function reads as many bytes as necessary to completely fill the
583 /// specified buffer `buf`.
585 /// No guarantees are provided about the contents of `buf` when this
586 /// function is called, implementations cannot rely on any property of the
587 /// contents of `buf` being true. It is recommended that implementations
588 /// only write data to `buf` instead of reading its contents.
592 /// If this function encounters an error of the kind
593 /// `ErrorKind::Interrupted` then the error is ignored and the operation
596 /// If this function encounters an "end of file" before completely filling
597 /// the buffer, it returns an error of the kind `ErrorKind::UnexpectedEof`.
598 /// The contents of `buf` are unspecified in this case.
600 /// If any other read error is encountered then this function immediately
601 /// returns. The contents of `buf` are unspecified in this case.
603 /// If this function returns an error, it is unspecified how many bytes it
604 /// has read, but it will never read more than would be necessary to
605 /// completely fill the buffer.
609 /// [`File`][file]s implement `Read`:
611 /// [file]: ../fs/struct.File.html
615 /// use std::io::prelude::*;
616 /// use std::fs::File;
618 /// # fn foo() -> io::Result<()> {
619 /// let mut f = File::open("foo.txt")?;
620 /// let mut buffer = [0; 10];
622 /// // read exactly 10 bytes
623 /// f.read_exact(&mut buffer)?;
627 #[stable(feature = "read_exact", since = "1.6.0")]
628 fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
629 while !buf.is_empty() {
630 match self.read(buf) {
632 Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
633 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
634 Err(e) => return Err(e),
638 Err(Error::new(ErrorKind::UnexpectedEof,
639 "failed to fill whole buffer"))
645 /// Creates a "by reference" adaptor for this instance of `Read`.
647 /// The returned adaptor also implements `Read` and will simply borrow this
652 /// [`File`][file]s implement `Read`:
654 /// [file]: ../fs/struct.File.html
658 /// use std::io::Read;
659 /// use std::fs::File;
661 /// # fn foo() -> io::Result<()> {
662 /// let mut f = File::open("foo.txt")?;
663 /// let mut buffer = Vec::new();
664 /// let mut other_buffer = Vec::new();
667 /// let reference = f.by_ref();
669 /// // read at most 5 bytes
670 /// reference.take(5).read_to_end(&mut buffer)?;
672 /// } // drop our &mut reference so we can use f again
674 /// // original file still usable, read the rest
675 /// f.read_to_end(&mut other_buffer)?;
679 #[stable(feature = "rust1", since = "1.0.0")]
680 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
682 /// Transforms this `Read` instance to an `Iterator` over its bytes.
684 /// The returned type implements `Iterator` where the `Item` is `Result<u8,
685 /// R::Err>`. The yielded item is `Ok` if a byte was successfully read and
686 /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from
691 /// [`File`][file]s implement `Read`:
693 /// [file]: ../fs/struct.File.html
697 /// use std::io::prelude::*;
698 /// use std::fs::File;
700 /// # fn foo() -> io::Result<()> {
701 /// let mut f = File::open("foo.txt")?;
703 /// for byte in f.bytes() {
704 /// println!("{}", byte.unwrap());
709 #[stable(feature = "rust1", since = "1.0.0")]
710 fn bytes(self) -> Bytes<Self> where Self: Sized {
711 Bytes { inner: self }
714 /// Transforms this `Read` instance to an `Iterator` over `char`s.
716 /// This adaptor will attempt to interpret this reader as a UTF-8 encoded
717 /// sequence of characters. The returned iterator will return `None` once
718 /// EOF is reached for this reader. Otherwise each element yielded will be a
719 /// `Result<char, E>` where `E` may contain information about what I/O error
720 /// occurred or where decoding failed.
722 /// Currently this adaptor will discard intermediate data read, and should
723 /// be avoided if this is not desired.
727 /// [`File`][file]s implement `Read`:
729 /// [file]: ../fs/struct.File.html
734 /// use std::io::prelude::*;
735 /// use std::fs::File;
737 /// # fn foo() -> io::Result<()> {
738 /// let mut f = File::open("foo.txt")?;
740 /// for c in f.chars() {
741 /// println!("{}", c.unwrap());
746 #[unstable(feature = "io", reason = "the semantics of a partial read/write \
747 of where errors happen is currently \
748 unclear and may change",
750 fn chars(self) -> Chars<Self> where Self: Sized {
751 Chars { inner: self }
754 /// Creates an adaptor which will chain this stream with another.
756 /// The returned `Read` instance will first read all bytes from this object
757 /// until EOF is encountered. Afterwards the output is equivalent to the
758 /// output of `next`.
762 /// [`File`][file]s implement `Read`:
764 /// [file]: ../fs/struct.File.html
768 /// use std::io::prelude::*;
769 /// use std::fs::File;
771 /// # fn foo() -> io::Result<()> {
772 /// let mut f1 = File::open("foo.txt")?;
773 /// let mut f2 = File::open("bar.txt")?;
775 /// let mut handle = f1.chain(f2);
776 /// let mut buffer = String::new();
778 /// // read the value into a String. We could use any Read method here,
779 /// // this is just one example.
780 /// handle.read_to_string(&mut buffer)?;
784 #[stable(feature = "rust1", since = "1.0.0")]
785 fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
786 Chain { first: self, second: next, done_first: false }
789 /// Creates an adaptor which will read at most `limit` bytes from it.
791 /// This function returns a new instance of `Read` which will read at most
792 /// `limit` bytes, after which it will always return EOF (`Ok(0)`). Any
793 /// read errors will not count towards the number of bytes read and future
794 /// calls to `read` may succeed.
798 /// [`File`][file]s implement `Read`:
800 /// [file]: ../fs/struct.File.html
804 /// use std::io::prelude::*;
805 /// use std::fs::File;
807 /// # fn foo() -> io::Result<()> {
808 /// let mut f = File::open("foo.txt")?;
809 /// let mut buffer = [0; 5];
811 /// // read at most five bytes
812 /// let mut handle = f.take(5);
814 /// handle.read(&mut buffer)?;
818 #[stable(feature = "rust1", since = "1.0.0")]
819 fn take(self, limit: u64) -> Take<Self> where Self: Sized {
820 Take { inner: self, limit: limit }
824 /// A trait for objects which are byte-oriented sinks.
826 /// Implementors of the `Write` trait are sometimes called 'writers'.
828 /// Writers are defined by two required methods, [`write`] and [`flush`]:
830 /// * The [`write`] method will attempt to write some data into the object,
831 /// returning how many bytes were successfully written.
833 /// * The [`flush`] method is useful for adaptors and explicit buffers
834 /// themselves for ensuring that all buffered data has been pushed out to the
837 /// Writers are intended to be composable with one another. Many implementors
838 /// throughout [`std::io`] take and provide types which implement the `Write`
841 /// [`write`]: #tymethod.write
842 /// [`flush`]: #tymethod.flush
843 /// [`std::io`]: index.html
848 /// use std::io::prelude::*;
849 /// use std::fs::File;
851 /// # fn foo() -> std::io::Result<()> {
852 /// let mut buffer = File::create("foo.txt")?;
854 /// buffer.write(b"some bytes")?;
858 #[stable(feature = "rust1", since = "1.0.0")]
860 /// Write a buffer into this object, returning how many bytes were written.
862 /// This function will attempt to write the entire contents of `buf`, but
863 /// the entire write may not succeed, or the write may also generate an
864 /// error. A call to `write` represents *at most one* attempt to write to
865 /// any wrapped object.
867 /// Calls to `write` are not guaranteed to block waiting for data to be
868 /// written, and a write which would otherwise block can be indicated through
869 /// an `Err` variant.
871 /// If the return value is `Ok(n)` then it must be guaranteed that
872 /// `0 <= n <= buf.len()`. A return value of `0` typically means that the
873 /// underlying object is no longer able to accept bytes and will likely not
874 /// be able to in the future as well, or that the buffer provided is empty.
878 /// Each call to `write` may generate an I/O error indicating that the
879 /// operation could not be completed. If an error is returned then no bytes
880 /// in the buffer were written to this writer.
882 /// It is **not** considered an error if the entire buffer could not be
883 /// written to this writer.
888 /// use std::io::prelude::*;
889 /// use std::fs::File;
891 /// # fn foo() -> std::io::Result<()> {
892 /// let mut buffer = File::create("foo.txt")?;
894 /// buffer.write(b"some bytes")?;
898 #[stable(feature = "rust1", since = "1.0.0")]
899 fn write(&mut self, buf: &[u8]) -> Result<usize>;
901 /// Flush this output stream, ensuring that all intermediately buffered
902 /// contents reach their destination.
906 /// It is considered an error if not all bytes could be written due to
907 /// I/O errors or EOF being reached.
912 /// use std::io::prelude::*;
913 /// use std::io::BufWriter;
914 /// use std::fs::File;
916 /// # fn foo() -> std::io::Result<()> {
917 /// let mut buffer = BufWriter::new(File::create("foo.txt")?);
919 /// buffer.write(b"some bytes")?;
924 #[stable(feature = "rust1", since = "1.0.0")]
925 fn flush(&mut self) -> Result<()>;
927 /// Attempts to write an entire buffer into this write.
929 /// This method will continuously call `write` while there is more data to
930 /// write. This method will not return until the entire buffer has been
931 /// successfully written or an error occurs. The first error generated from
932 /// this method will be returned.
936 /// This function will return the first error that `write` returns.
941 /// use std::io::prelude::*;
942 /// use std::fs::File;
944 /// # fn foo() -> std::io::Result<()> {
945 /// let mut buffer = File::create("foo.txt")?;
947 /// buffer.write_all(b"some bytes")?;
951 #[stable(feature = "rust1", since = "1.0.0")]
952 fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
953 while !buf.is_empty() {
954 match self.write(buf) {
955 Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
956 "failed to write whole buffer")),
957 Ok(n) => buf = &buf[n..],
958 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
959 Err(e) => return Err(e),
965 /// Writes a formatted string into this writer, returning any error
968 /// This method is primarily used to interface with the
969 /// [`format_args!`][formatargs] macro, but it is rare that this should
970 /// explicitly be called. The [`write!`][write] macro should be favored to
971 /// invoke this method instead.
973 /// [formatargs]: ../macro.format_args.html
974 /// [write]: ../macro.write.html
976 /// This function internally uses the [`write_all`][writeall] method on
977 /// this trait and hence will continuously write data so long as no errors
978 /// are received. This also means that partial writes are not indicated in
981 /// [writeall]: #method.write_all
985 /// This function will return any I/O error reported while formatting.
990 /// use std::io::prelude::*;
991 /// use std::fs::File;
993 /// # fn foo() -> std::io::Result<()> {
994 /// let mut buffer = File::create("foo.txt")?;
997 /// write!(buffer, "{:.*}", 2, 1.234567)?;
998 /// // turns into this:
999 /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()> {
1005 // Create a shim which translates a Write to a fmt::Write and saves
1006 // off I/O errors. instead of discarding them
1007 struct Adaptor<'a, T: ?Sized + 'a> {
1012 impl<'a, T: Write + ?Sized> fmt::Write for Adaptor<'a, T> {
1013 fn write_str(&mut self, s: &str) -> fmt::Result {
1014 match self.inner.write_all(s.as_bytes()) {
1017 self.error = Err(e);
1024 let mut output = Adaptor { inner: self, error: Ok(()) };
1025 match fmt::write(&mut output, fmt) {
1028 // check if the error came from the underlying `Write` or not
1029 if output.error.is_err() {
1032 Err(Error::new(ErrorKind::Other, "formatter error"))
1038 /// Creates a "by reference" adaptor for this instance of `Write`.
1040 /// The returned adaptor also implements `Write` and will simply borrow this
1046 /// use std::io::Write;
1047 /// use std::fs::File;
1049 /// # fn foo() -> std::io::Result<()> {
1050 /// let mut buffer = File::create("foo.txt")?;
1052 /// let reference = buffer.by_ref();
1054 /// // we can use reference just like our original buffer
1055 /// reference.write_all(b"some bytes")?;
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1063 /// The `Seek` trait provides a cursor which can be moved within a stream of
1066 /// The stream typically has a fixed size, allowing seeking relative to either
1067 /// end or the current offset.
1071 /// [`File`][file]s implement `Seek`:
1073 /// [file]: ../fs/struct.File.html
1077 /// use std::io::prelude::*;
1078 /// use std::fs::File;
1079 /// use std::io::SeekFrom;
1081 /// # fn foo() -> io::Result<()> {
1082 /// let mut f = File::open("foo.txt")?;
1084 /// // move the cursor 42 bytes from the start of the file
1085 /// f.seek(SeekFrom::Start(42))?;
1089 #[stable(feature = "rust1", since = "1.0.0")]
1091 /// Seek to an offset, in bytes, in a stream.
1093 /// A seek beyond the end of a stream is allowed, but implementation
1096 /// If the seek operation completed successfully,
1097 /// this method returns the new position from the start of the stream.
1098 /// That position can be used later with [`SeekFrom::Start`].
1102 /// Seeking to a negative offset is considered an error.
1104 /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1109 /// Enumeration of possible methods to seek within an I/O object.
1111 /// It is used by the [`Seek`] trait.
1113 /// [`Seek`]: trait.Seek.html
1114 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1115 #[stable(feature = "rust1", since = "1.0.0")]
1117 /// Set the offset to the provided number of bytes.
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1121 /// Set the offset to the size of this object plus the specified number of
1124 /// It is possible to seek beyond the end of an object, but it's an error to
1125 /// seek before byte 0.
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1129 /// Set the offset to the current position plus the specified number of
1132 /// It is possible to seek beyond the end of an object, but it's an error to
1133 /// seek before byte 0.
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1138 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
1142 let (done, used) = {
1143 let available = match r.fill_buf() {
1145 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1146 Err(e) => return Err(e)
1148 match memchr::memchr(delim, available) {
1150 buf.extend_from_slice(&available[..i + 1]);
1154 buf.extend_from_slice(available);
1155 (false, available.len())
1161 if done || used == 0 {
1167 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1168 /// to perform extra ways of reading.
1170 /// For example, reading line-by-line is inefficient without using a buffer, so
1171 /// if you want to read by line, you'll need `BufRead`, which includes a
1172 /// [`read_line`] method as well as a [`lines`] iterator.
1176 /// A locked standard input implements `BufRead`:
1180 /// use std::io::prelude::*;
1182 /// let stdin = io::stdin();
1183 /// for line in stdin.lock().lines() {
1184 /// println!("{}", line.unwrap());
1188 /// If you have something that implements [`Read`], you can use the [`BufReader`
1189 /// type][`BufReader`] to turn it into a `BufRead`.
1191 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1192 /// [`BufReader`] to the rescue!
1194 /// [`BufReader`]: struct.BufReader.html
1195 /// [`File`]: ../fs/struct.File.html
1196 /// [`read_line`]: #method.read_line
1197 /// [`lines`]: #method.lines
1198 /// [`Read`]: trait.Read.html
1201 /// use std::io::{self, BufReader};
1202 /// use std::io::prelude::*;
1203 /// use std::fs::File;
1205 /// # fn foo() -> io::Result<()> {
1206 /// let f = File::open("foo.txt")?;
1207 /// let f = BufReader::new(f);
1209 /// for line in f.lines() {
1210 /// println!("{}", line.unwrap());
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub trait BufRead: Read {
1219 /// Fills the internal buffer of this object, returning the buffer contents.
1221 /// This function is a lower-level call. It needs to be paired with the
1222 /// [`consume`] method to function properly. When calling this
1223 /// method, none of the contents will be "read" in the sense that later
1224 /// calling `read` may return the same contents. As such, [`consume`] must
1225 /// be called with the number of bytes that are consumed from this buffer to
1226 /// ensure that the bytes are never returned twice.
1228 /// [`consume`]: #tymethod.consume
1230 /// An empty buffer returned indicates that the stream has reached EOF.
1234 /// This function will return an I/O error if the underlying reader was
1235 /// read, but returned an error.
1239 /// A locked standard input implements `BufRead`:
1243 /// use std::io::prelude::*;
1245 /// let stdin = io::stdin();
1246 /// let mut stdin = stdin.lock();
1248 /// // we can't have two `&mut` references to `stdin`, so use a block
1249 /// // to end the borrow early.
1251 /// let buffer = stdin.fill_buf().unwrap();
1253 /// // work with buffer
1254 /// println!("{:?}", buffer);
1259 /// // ensure the bytes we worked with aren't returned again later
1260 /// stdin.consume(length);
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 fn fill_buf(&mut self) -> Result<&[u8]>;
1265 /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1266 /// so they should no longer be returned in calls to `read`.
1268 /// This function is a lower-level call. It needs to be paired with the
1269 /// [`fill_buf`] method to function properly. This function does
1270 /// not perform any I/O, it simply informs this object that some amount of
1271 /// its buffer, returned from [`fill_buf`], has been consumed and should
1272 /// no longer be returned. As such, this function may do odd things if
1273 /// [`fill_buf`] isn't called before calling it.
1275 /// The `amt` must be `<=` the number of bytes in the buffer returned by
1280 /// Since `consume()` is meant to be used with [`fill_buf`],
1281 /// that method's example includes an example of `consume()`.
1283 /// [`fill_buf`]: #tymethod.fill_buf
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 fn consume(&mut self, amt: usize);
1287 /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1289 /// This function will read bytes from the underlying stream until the
1290 /// delimiter or EOF is found. Once found, all bytes up to, and including,
1291 /// the delimiter (if found) will be appended to `buf`.
1293 /// If successful, this function will return the total number of bytes read.
1297 /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1298 /// will otherwise return any errors returned by [`fill_buf`].
1300 /// If an I/O error is encountered then all bytes read so far will be
1301 /// present in `buf` and its length will have been adjusted appropriately.
1305 /// A locked standard input implements `BufRead`. In this example, we'll
1306 /// read from standard input until we see an `a` byte.
1308 /// [`fill_buf`]: #tymethod.fill_buf
1309 /// [`ErrorKind::Interrupted`]: enum.ErrorKind.html#variant.Interrupted
1313 /// use std::io::prelude::*;
1315 /// fn foo() -> io::Result<()> {
1316 /// let stdin = io::stdin();
1317 /// let mut stdin = stdin.lock();
1318 /// let mut buffer = Vec::new();
1320 /// stdin.read_until(b'a', &mut buffer)?;
1322 /// println!("{:?}", buffer);
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1328 read_until(self, byte, buf)
1331 /// Read all bytes until a newline (the 0xA byte) is reached, and append
1332 /// them to the provided buffer.
1334 /// This function will read bytes from the underlying stream until the
1335 /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
1336 /// up to, and including, the delimiter (if found) will be appended to
1339 /// If successful, this function will return the total number of bytes read.
1343 /// This function has the same error semantics as [`read_until`] and will
1344 /// also return an error if the read bytes are not valid UTF-8. If an I/O
1345 /// error is encountered then `buf` may contain some bytes already read in
1346 /// the event that all data read so far was valid UTF-8.
1350 /// A locked standard input implements `BufRead`. In this example, we'll
1351 /// read all of the lines from standard input. If we were to do this in
1352 /// an actual project, the [`lines`] method would be easier, of
1355 /// [`lines`]: #method.lines
1356 /// [`read_until`]: #method.read_until
1360 /// use std::io::prelude::*;
1362 /// let stdin = io::stdin();
1363 /// let mut stdin = stdin.lock();
1364 /// let mut buffer = String::new();
1366 /// while stdin.read_line(&mut buffer).unwrap() > 0 {
1367 /// // work with buffer
1368 /// println!("{:?}", buffer);
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1375 // Note that we are not calling the `.read_until` method here, but
1376 // rather our hardcoded implementation. For more details as to why, see
1377 // the comments in `read_to_end`.
1378 append_to_string(buf, |b| read_until(self, b'\n', b))
1381 /// Returns an iterator over the contents of this reader split on the byte
1384 /// The iterator returned from this function will return instances of
1385 /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1386 /// the delimiter byte at the end.
1388 /// This function will yield errors whenever [`read_until`] would have
1389 /// also yielded an error.
1393 /// A locked standard input implements `BufRead`. In this example, we'll
1394 /// read some input from standard input, splitting on commas.
1396 /// [`io::Result`]: type.Result.html
1397 /// [`Vec<u8>`]: ../vec/struct.Vec.html
1398 /// [`read_until`]: #method.read_until
1402 /// use std::io::prelude::*;
1404 /// let stdin = io::stdin();
1406 /// for content in stdin.lock().split(b',') {
1407 /// println!("{:?}", content.unwrap());
1410 #[stable(feature = "rust1", since = "1.0.0")]
1411 fn split(self, byte: u8) -> Split<Self> where Self: Sized {
1412 Split { buf: self, delim: byte }
1415 /// Returns an iterator over the lines of this reader.
1417 /// The iterator returned from this function will yield instances of
1418 /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
1419 /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
1421 /// [`io::Result`]: type.Result.html
1422 /// [`String`]: ../string/struct.String.html
1426 /// A locked standard input implements `BufRead`:
1430 /// use std::io::prelude::*;
1432 /// let stdin = io::stdin();
1434 /// for line in stdin.lock().lines() {
1435 /// println!("{}", line.unwrap());
1441 /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
1443 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 fn lines(self) -> Lines<Self> where Self: Sized {
1450 /// Adaptor to chain together two readers.
1452 /// This struct is generally created by calling [`chain`] on a reader.
1453 /// Please see the documentation of [`chain`] for more details.
1455 /// [`chain`]: trait.Read.html#method.chain
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 pub struct Chain<T, U> {
1463 #[stable(feature = "std_debug", since = "1.16.0")]
1464 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
1465 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1466 f.debug_struct("Chain")
1467 .field("t", &self.first)
1468 .field("u", &self.second)
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<T: Read, U: Read> Read for Chain<T, U> {
1475 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1476 if !self.done_first {
1477 match self.first.read(buf)? {
1478 0 if buf.len() != 0 => { self.done_first = true; }
1482 self.second.read(buf)
1486 #[stable(feature = "chain_bufread", since = "1.9.0")]
1487 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
1488 fn fill_buf(&mut self) -> Result<&[u8]> {
1489 if !self.done_first {
1490 match self.first.fill_buf()? {
1491 buf if buf.len() == 0 => { self.done_first = true; }
1492 buf => return Ok(buf),
1495 self.second.fill_buf()
1498 fn consume(&mut self, amt: usize) {
1499 if !self.done_first {
1500 self.first.consume(amt)
1502 self.second.consume(amt)
1507 /// Reader adaptor which limits the bytes read from an underlying reader.
1509 /// This struct is generally created by calling [`take`] on a reader.
1510 /// Please see the documentation of [`take`] for more details.
1512 /// [`take`]: trait.Read.html#method.take
1513 #[stable(feature = "rust1", since = "1.0.0")]
1515 pub struct Take<T> {
1521 /// Returns the number of bytes that can be read before this instance will
1526 /// This instance may reach `EOF` after reading fewer bytes than indicated by
1527 /// this method if the underlying [`Read`] instance reaches EOF.
1529 /// [`Read`]: ../../std/io/trait.Read.html
1535 /// use std::io::prelude::*;
1536 /// use std::fs::File;
1538 /// # fn foo() -> io::Result<()> {
1539 /// let f = File::open("foo.txt")?;
1541 /// // read at most five bytes
1542 /// let handle = f.take(5);
1544 /// println!("limit: {}", handle.limit());
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 pub fn limit(&self) -> u64 { self.limit }
1551 /// Consumes the `Take`, returning the wrapped reader.
1557 /// use std::io::prelude::*;
1558 /// use std::fs::File;
1560 /// # fn foo() -> io::Result<()> {
1561 /// let mut file = File::open("foo.txt")?;
1563 /// let mut buffer = [0; 5];
1564 /// let mut handle = file.take(5);
1565 /// handle.read(&mut buffer)?;
1567 /// let file = handle.into_inner();
1571 #[stable(feature = "io_take_into_inner", since = "1.15.0")]
1572 pub fn into_inner(self) -> T {
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl<T: Read> Read for Take<T> {
1579 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1580 // Don't call into inner reader at all at EOF because it may still block
1581 if self.limit == 0 {
1585 let max = cmp::min(buf.len() as u64, self.limit) as usize;
1586 let n = self.inner.read(&mut buf[..max])?;
1587 self.limit -= n as u64;
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl<T: BufRead> BufRead for Take<T> {
1594 fn fill_buf(&mut self) -> Result<&[u8]> {
1595 // Don't call into inner reader at all at EOF because it may still block
1596 if self.limit == 0 {
1600 let buf = self.inner.fill_buf()?;
1601 let cap = cmp::min(buf.len() as u64, self.limit) as usize;
1605 fn consume(&mut self, amt: usize) {
1606 // Don't let callers reset the limit by passing an overlarge value
1607 let amt = cmp::min(amt as u64, self.limit) as usize;
1608 self.limit -= amt as u64;
1609 self.inner.consume(amt);
1613 fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
1616 return match reader.read(&mut buf) {
1618 Ok(..) => Some(Ok(buf[0])),
1619 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1620 Err(e) => Some(Err(e)),
1625 /// An iterator over `u8` values of a reader.
1627 /// This struct is generally created by calling [`bytes`] on a reader.
1628 /// Please see the documentation of [`bytes`] for more details.
1630 /// [`bytes`]: trait.Read.html#method.bytes
1631 #[stable(feature = "rust1", since = "1.0.0")]
1633 pub struct Bytes<R> {
1637 #[stable(feature = "rust1", since = "1.0.0")]
1638 impl<R: Read> Iterator for Bytes<R> {
1639 type Item = Result<u8>;
1641 fn next(&mut self) -> Option<Result<u8>> {
1642 read_one_byte(&mut self.inner)
1646 /// An iterator over the `char`s of a reader.
1648 /// This struct is generally created by calling [`chars`][chars] on a reader.
1649 /// Please see the documentation of `chars()` for more details.
1651 /// [chars]: trait.Read.html#method.chars
1652 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1655 pub struct Chars<R> {
1659 /// An enumeration of possible errors that can be generated from the `Chars`
1662 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1664 pub enum CharsError {
1665 /// Variant representing that the underlying stream was read successfully
1666 /// but it did not contain valid utf8 data.
1669 /// Variant representing that an I/O error occurred.
1673 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1675 impl<R: Read> Iterator for Chars<R> {
1676 type Item = result::Result<char, CharsError>;
1678 fn next(&mut self) -> Option<result::Result<char, CharsError>> {
1679 let first_byte = match read_one_byte(&mut self.inner) {
1680 None => return None,
1682 Some(Err(e)) => return Some(Err(CharsError::Other(e))),
1684 let width = core_str::utf8_char_width(first_byte);
1685 if width == 1 { return Some(Ok(first_byte as char)) }
1686 if width == 0 { return Some(Err(CharsError::NotUtf8)) }
1687 let mut buf = [first_byte, 0, 0, 0];
1690 while start < width {
1691 match self.inner.read(&mut buf[start..width]) {
1692 Ok(0) => return Some(Err(CharsError::NotUtf8)),
1693 Ok(n) => start += n,
1694 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1695 Err(e) => return Some(Err(CharsError::Other(e))),
1699 Some(match str::from_utf8(&buf[..width]).ok() {
1700 Some(s) => Ok(s.chars().next().unwrap()),
1701 None => Err(CharsError::NotUtf8),
1706 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1708 impl std_error::Error for CharsError {
1709 fn description(&self) -> &str {
1711 CharsError::NotUtf8 => "invalid utf8 encoding",
1712 CharsError::Other(ref e) => std_error::Error::description(e),
1715 fn cause(&self) -> Option<&std_error::Error> {
1717 CharsError::NotUtf8 => None,
1718 CharsError::Other(ref e) => e.cause(),
1723 #[unstable(feature = "io", reason = "awaiting stability of Read::chars",
1725 impl fmt::Display for CharsError {
1726 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1728 CharsError::NotUtf8 => {
1729 "byte stream did not contain valid utf8".fmt(f)
1731 CharsError::Other(ref e) => e.fmt(f),
1736 /// An iterator over the contents of an instance of `BufRead` split on a
1737 /// particular byte.
1739 /// This struct is generally created by calling [`split`][split] on a
1740 /// `BufRead`. Please see the documentation of `split()` for more details.
1742 /// [split]: trait.BufRead.html#method.split
1743 #[stable(feature = "rust1", since = "1.0.0")]
1745 pub struct Split<B> {
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 impl<B: BufRead> Iterator for Split<B> {
1752 type Item = Result<Vec<u8>>;
1754 fn next(&mut self) -> Option<Result<Vec<u8>>> {
1755 let mut buf = Vec::new();
1756 match self.buf.read_until(self.delim, &mut buf) {
1759 if buf[buf.len() - 1] == self.delim {
1764 Err(e) => Some(Err(e))
1769 /// An iterator over the lines of an instance of `BufRead`.
1771 /// This struct is generally created by calling [`lines`][lines] on a
1772 /// `BufRead`. Please see the documentation of `lines()` for more details.
1774 /// [lines]: trait.BufRead.html#method.lines
1775 #[stable(feature = "rust1", since = "1.0.0")]
1777 pub struct Lines<B> {
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 impl<B: BufRead> Iterator for Lines<B> {
1783 type Item = Result<String>;
1785 fn next(&mut self) -> Option<Result<String>> {
1786 let mut buf = String::new();
1787 match self.buf.read_line(&mut buf) {
1790 if buf.ends_with("\n") {
1792 if buf.ends_with("\r") {
1798 Err(e) => Some(Err(e))
1812 #[cfg_attr(target_os = "emscripten", ignore)]
1814 let mut buf = Cursor::new(&b"12"[..]);
1815 let mut v = Vec::new();
1816 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
1817 assert_eq!(v, b"12");
1819 let mut buf = Cursor::new(&b"1233"[..]);
1820 let mut v = Vec::new();
1821 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
1822 assert_eq!(v, b"123");
1824 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
1825 assert_eq!(v, b"3");
1827 assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
1833 let buf = Cursor::new(&b"12"[..]);
1834 let mut s = buf.split(b'3');
1835 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1836 assert!(s.next().is_none());
1838 let buf = Cursor::new(&b"1233"[..]);
1839 let mut s = buf.split(b'3');
1840 assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
1841 assert_eq!(s.next().unwrap().unwrap(), vec![]);
1842 assert!(s.next().is_none());
1847 let mut buf = Cursor::new(&b"12"[..]);
1848 let mut v = String::new();
1849 assert_eq!(buf.read_line(&mut v).unwrap(), 2);
1850 assert_eq!(v, "12");
1852 let mut buf = Cursor::new(&b"12\n\n"[..]);
1853 let mut v = String::new();
1854 assert_eq!(buf.read_line(&mut v).unwrap(), 3);
1855 assert_eq!(v, "12\n");
1857 assert_eq!(buf.read_line(&mut v).unwrap(), 1);
1858 assert_eq!(v, "\n");
1860 assert_eq!(buf.read_line(&mut v).unwrap(), 0);
1866 let buf = Cursor::new(&b"12\r"[..]);
1867 let mut s = buf.lines();
1868 assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
1869 assert!(s.next().is_none());
1871 let buf = Cursor::new(&b"12\r\n\n"[..]);
1872 let mut s = buf.lines();
1873 assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
1874 assert_eq!(s.next().unwrap().unwrap(), "".to_string());
1875 assert!(s.next().is_none());
1880 let mut c = Cursor::new(&b""[..]);
1881 let mut v = Vec::new();
1882 assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
1885 let mut c = Cursor::new(&b"1"[..]);
1886 let mut v = Vec::new();
1887 assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
1888 assert_eq!(v, b"1");
1890 let cap = 1024 * 1024;
1891 let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
1892 let mut v = Vec::new();
1893 let (a, b) = data.split_at(data.len() / 2);
1894 assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
1895 assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
1896 assert_eq!(v, data);
1900 fn read_to_string() {
1901 let mut c = Cursor::new(&b""[..]);
1902 let mut v = String::new();
1903 assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
1906 let mut c = Cursor::new(&b"1"[..]);
1907 let mut v = String::new();
1908 assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
1911 let mut c = Cursor::new(&b"\xff"[..]);
1912 let mut v = String::new();
1913 assert!(c.read_to_string(&mut v).is_err());
1918 let mut buf = [0; 4];
1920 let mut c = Cursor::new(&b""[..]);
1921 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1922 io::ErrorKind::UnexpectedEof);
1924 let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
1925 c.read_exact(&mut buf).unwrap();
1926 assert_eq!(&buf, b"1234");
1927 c.read_exact(&mut buf).unwrap();
1928 assert_eq!(&buf, b"5678");
1929 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1930 io::ErrorKind::UnexpectedEof);
1934 fn read_exact_slice() {
1935 let mut buf = [0; 4];
1937 let mut c = &b""[..];
1938 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1939 io::ErrorKind::UnexpectedEof);
1941 let mut c = &b"123"[..];
1942 assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
1943 io::ErrorKind::UnexpectedEof);
1944 // make sure the optimized (early returning) method is being used
1945 assert_eq!(&buf, &[0; 4]);
1947 let mut c = &b"1234"[..];
1948 c.read_exact(&mut buf).unwrap();
1949 assert_eq!(&buf, b"1234");
1951 let mut c = &b"56789"[..];
1952 c.read_exact(&mut buf).unwrap();
1953 assert_eq!(&buf, b"5678");
1954 assert_eq!(c, b"9");
1962 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1963 Err(io::Error::new(io::ErrorKind::Other, ""))
1966 impl BufRead for R {
1967 fn fill_buf(&mut self) -> io::Result<&[u8]> {
1968 Err(io::Error::new(io::ErrorKind::Other, ""))
1970 fn consume(&mut self, _amt: usize) { }
1973 let mut buf = [0; 1];
1974 assert_eq!(0, R.take(0).read(&mut buf).unwrap());
1975 assert_eq!(b"", R.take(0).fill_buf().unwrap());
1978 fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
1979 let mut cat = Vec::new();
1982 let buf1 = br1.fill_buf().unwrap();
1983 let buf2 = br2.fill_buf().unwrap();
1984 let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
1985 assert_eq!(buf1[..minlen], buf2[..minlen]);
1986 cat.extend_from_slice(&buf1[..minlen]);
1992 br1.consume(consume);
1993 br2.consume(consume);
1995 assert_eq!(br1.fill_buf().unwrap().len(), 0);
1996 assert_eq!(br2.fill_buf().unwrap().len(), 0);
1997 assert_eq!(&cat[..], &exp[..])
2001 fn chain_bufread() {
2002 let testdata = b"ABCDEFGHIJKL";
2003 let chain1 = (&testdata[..3]).chain(&testdata[3..6])
2004 .chain(&testdata[6..9])
2005 .chain(&testdata[9..]);
2006 let chain2 = (&testdata[..4]).chain(&testdata[4..8])
2007 .chain(&testdata[8..]);
2008 cmp_bufread(chain1, chain2, &testdata[..]);
2012 fn chain_zero_length_read_is_not_eof() {
2015 let mut s = String::new();
2016 let mut chain = (&a[..]).chain(&b[..]);
2017 chain.read(&mut []).unwrap();
2018 chain.read_to_string(&mut s).unwrap();
2019 assert_eq!("AB", s);
2023 #[cfg_attr(target_os = "emscripten", ignore)]
2024 fn bench_read_to_end(b: &mut test::Bencher) {
2026 let mut lr = repeat(1).take(10000000);
2027 let mut vec = Vec::with_capacity(1024);
2028 super::read_to_end(&mut lr, &mut vec)