PageRenderTime 54ms CodeModel.GetById 19ms 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

Large files files are truncated, but you can click here to view the full file

  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…

Large files files are truncated, but you can click here to view the full file