mod.rs 58 KB

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