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