PageRenderTime 52ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/src/libstd/io/mod.rs

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