mod.rs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  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. fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
  1429. let mut buf = [0];
  1430. loop {
  1431. return match reader.read(&mut buf) {
  1432. Ok(0) => None,
  1433. Ok(..) => Some(Ok(buf[0])),
  1434. Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
  1435. Err(e) => Some(Err(e)),
  1436. };
  1437. }
  1438. }
  1439. /// An iterator over `u8` values of a reader.
  1440. ///
  1441. /// This struct is generally created by calling [`bytes()`][bytes] on a reader.
  1442. /// Please see the documentation of `bytes()` for more details.
  1443. ///
  1444. /// [bytes]: trait.Read.html#method.bytes
  1445. pub struct Bytes<R> {
  1446. inner: R,
  1447. }
  1448. impl<R: Read> Iterator for Bytes<R> {
  1449. type Item = Result<u8>;
  1450. fn next(&mut self) -> Option<Result<u8>> {
  1451. read_one_byte(&mut self.inner)
  1452. }
  1453. }
  1454. /// An iterator over the `char`s of a reader.
  1455. ///
  1456. /// This struct is generally created by calling [`chars()`][chars] on a reader.
  1457. /// Please see the documentation of `chars()` for more details.
  1458. ///
  1459. /// [chars]: trait.Read.html#method.chars
  1460. pub struct Chars<R> {
  1461. inner: R,
  1462. }
  1463. /// An enumeration of possible errors that can be generated from the `Chars`
  1464. /// adapter.
  1465. #[derive(Debug)]
  1466. pub enum CharsError {
  1467. /// Variant representing that the underlying stream was read successfully
  1468. /// but it did not contain valid utf8 data.
  1469. NotUtf8,
  1470. /// Variant representing that an I/O error occurred.
  1471. Other(Error),
  1472. }
  1473. impl<R: Read> Iterator for Chars<R> {
  1474. type Item = result::Result<char, CharsError>;
  1475. fn next(&mut self) -> Option<result::Result<char, CharsError>> {
  1476. let first_byte = match read_one_byte(&mut self.inner) {
  1477. None => return None,
  1478. Some(Ok(b)) => b,
  1479. Some(Err(e)) => return Some(Err(CharsError::Other(e))),
  1480. };
  1481. let width = core_str::utf8_char_width(first_byte);
  1482. if width == 1 { return Some(Ok(first_byte as char)) }
  1483. if width == 0 { return Some(Err(CharsError::NotUtf8)) }
  1484. let mut buf = [first_byte, 0, 0, 0];
  1485. {
  1486. let mut start = 1;
  1487. while start < width {
  1488. match self.inner.read(&mut buf[start..width]) {
  1489. Ok(0) => return Some(Err(CharsError::NotUtf8)),
  1490. Ok(n) => start += n,
  1491. Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
  1492. Err(e) => return Some(Err(CharsError::Other(e))),
  1493. }
  1494. }
  1495. }
  1496. Some(match str::from_utf8(&buf[..width]).ok() {
  1497. Some(s) => Ok(s.chars().next().unwrap()),
  1498. None => Err(CharsError::NotUtf8),
  1499. })
  1500. }
  1501. }
  1502. impl fmt::Display for CharsError {
  1503. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  1504. match *self {
  1505. CharsError::NotUtf8 => {
  1506. "byte stream did not contain valid utf8".fmt(f)
  1507. }
  1508. CharsError::Other(ref e) => e.fmt(f),
  1509. }
  1510. }
  1511. }
  1512. /// An iterator over the contents of an instance of `BufRead` split on a
  1513. /// particular byte.
  1514. ///
  1515. /// This struct is generally created by calling [`split()`][split] on a
  1516. /// `BufRead`. Please see the documentation of `split()` for more details.
  1517. ///
  1518. /// [split]: trait.BufRead.html#method.split
  1519. #[cfg(feature="collections")]
  1520. pub struct Split<B> {
  1521. buf: B,
  1522. delim: u8,
  1523. }
  1524. #[cfg(feature="collections")]
  1525. impl<B: BufRead> Iterator for Split<B> {
  1526. type Item = Result<Vec<u8>>;
  1527. fn next(&mut self) -> Option<Result<Vec<u8>>> {
  1528. let mut buf = Vec::new();
  1529. match self.buf.read_until(self.delim, &mut buf) {
  1530. Ok(0) => None,
  1531. Ok(_n) => {
  1532. if buf[buf.len() - 1] == self.delim {
  1533. buf.pop();
  1534. }
  1535. Some(Ok(buf))
  1536. }
  1537. Err(e) => Some(Err(e))
  1538. }
  1539. }
  1540. }
  1541. /// An iterator over the lines of an instance of `BufRead`.
  1542. ///
  1543. /// This struct is generally created by calling [`lines()`][lines] on a
  1544. /// `BufRead`. Please see the documentation of `lines()` for more details.
  1545. ///
  1546. /// [lines]: trait.BufRead.html#method.lines
  1547. #[cfg(feature="collections")]
  1548. pub struct Lines<B> {
  1549. buf: B,
  1550. }
  1551. #[cfg(feature="collections")]
  1552. impl<B: BufRead> Iterator for Lines<B> {
  1553. type Item = Result<String>;
  1554. fn next(&mut self) -> Option<Result<String>> {
  1555. let mut buf = String::new();
  1556. match self.buf.read_line(&mut buf) {
  1557. Ok(0) => None,
  1558. Ok(_n) => {
  1559. if buf.ends_with("\n") {
  1560. buf.pop();
  1561. if buf.ends_with("\r") {
  1562. buf.pop();
  1563. }
  1564. }
  1565. Some(Ok(buf))
  1566. }
  1567. Err(e) => Some(Err(e))
  1568. }
  1569. }
  1570. }
  1571. #[cfg(test)]
  1572. mod tests {
  1573. use prelude::v1::*;
  1574. use io::prelude::*;
  1575. use io;
  1576. use super::Cursor;
  1577. use test;
  1578. use super::repeat;
  1579. #[test]
  1580. fn read_until() {
  1581. let mut buf = Cursor::new(&b"12"[..]);
  1582. let mut v = Vec::new();
  1583. assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
  1584. assert_eq!(v, b"12");
  1585. let mut buf = Cursor::new(&b"1233"[..]);
  1586. let mut v = Vec::new();
  1587. assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
  1588. assert_eq!(v, b"123");
  1589. v.truncate(0);
  1590. assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
  1591. assert_eq!(v, b"3");
  1592. v.truncate(0);
  1593. assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
  1594. assert_eq!(v, []);
  1595. }
  1596. #[test]
  1597. fn split() {
  1598. let buf = Cursor::new(&b"12"[..]);
  1599. let mut s = buf.split(b'3');
  1600. assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
  1601. assert!(s.next().is_none());
  1602. let buf = Cursor::new(&b"1233"[..]);
  1603. let mut s = buf.split(b'3');
  1604. assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
  1605. assert_eq!(s.next().unwrap().unwrap(), vec![]);
  1606. assert!(s.next().is_none());
  1607. }
  1608. #[test]
  1609. fn read_line() {
  1610. let mut buf = Cursor::new(&b"12"[..]);
  1611. let mut v = String::new();
  1612. assert_eq!(buf.read_line(&mut v).unwrap(), 2);
  1613. assert_eq!(v, "12");
  1614. let mut buf = Cursor::new(&b"12\n\n"[..]);
  1615. let mut v = String::new();
  1616. assert_eq!(buf.read_line(&mut v).unwrap(), 3);
  1617. assert_eq!(v, "12\n");
  1618. v.truncate(0);
  1619. assert_eq!(buf.read_line(&mut v).unwrap(), 1);
  1620. assert_eq!(v, "\n");
  1621. v.truncate(0);
  1622. assert_eq!(buf.read_line(&mut v).unwrap(), 0);
  1623. assert_eq!(v, "");
  1624. }
  1625. #[test]
  1626. fn lines() {
  1627. let buf = Cursor::new(&b"12\r"[..]);
  1628. let mut s = buf.lines();
  1629. assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
  1630. assert!(s.next().is_none());
  1631. let buf = Cursor::new(&b"12\r\n\n"[..]);
  1632. let mut s = buf.lines();
  1633. assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
  1634. assert_eq!(s.next().unwrap().unwrap(), "".to_string());
  1635. assert!(s.next().is_none());
  1636. }
  1637. #[test]
  1638. fn read_to_end() {
  1639. let mut c = Cursor::new(&b""[..]);
  1640. let mut v = Vec::new();
  1641. assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
  1642. assert_eq!(v, []);
  1643. let mut c = Cursor::new(&b"1"[..]);
  1644. let mut v = Vec::new();
  1645. assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
  1646. assert_eq!(v, b"1");
  1647. let cap = 1024 * 1024;
  1648. let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
  1649. let mut v = Vec::new();
  1650. let (a, b) = data.split_at(data.len() / 2);
  1651. assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
  1652. assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
  1653. assert_eq!(v, data);
  1654. }
  1655. #[test]
  1656. fn read_to_string() {
  1657. let mut c = Cursor::new(&b""[..]);
  1658. let mut v = String::new();
  1659. assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
  1660. assert_eq!(v, "");
  1661. let mut c = Cursor::new(&b"1"[..]);
  1662. let mut v = String::new();
  1663. assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
  1664. assert_eq!(v, "1");
  1665. let mut c = Cursor::new(&b"\xff"[..]);
  1666. let mut v = String::new();
  1667. assert!(c.read_to_string(&mut v).is_err());
  1668. }
  1669. #[test]
  1670. fn read_exact() {
  1671. let mut buf = [0; 4];
  1672. let mut c = Cursor::new(&b""[..]);
  1673. assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
  1674. io::ErrorKind::UnexpectedEof);
  1675. let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
  1676. c.read_exact(&mut buf).unwrap();
  1677. assert_eq!(&buf, b"1234");
  1678. c.read_exact(&mut buf).unwrap();
  1679. assert_eq!(&buf, b"5678");
  1680. assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
  1681. io::ErrorKind::UnexpectedEof);
  1682. }
  1683. #[test]
  1684. fn read_exact_slice() {
  1685. let mut buf = [0; 4];
  1686. let mut c = &b""[..];
  1687. assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
  1688. io::ErrorKind::UnexpectedEof);
  1689. let mut c = &b"123"[..];
  1690. assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
  1691. io::ErrorKind::UnexpectedEof);
  1692. // make sure the optimized (early returning) method is being used
  1693. assert_eq!(&buf, &[0; 4]);
  1694. let mut c = &b"1234"[..];
  1695. c.read_exact(&mut buf).unwrap();
  1696. assert_eq!(&buf, b"1234");
  1697. let mut c = &b"56789"[..];
  1698. c.read_exact(&mut buf).unwrap();
  1699. assert_eq!(&buf, b"5678");
  1700. assert_eq!(c, b"9");
  1701. }
  1702. #[test]
  1703. fn take_eof() {
  1704. struct R;
  1705. impl Read for R {
  1706. fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
  1707. Err(io::Error::new(io::ErrorKind::Other, ""))
  1708. }
  1709. }
  1710. impl BufRead for R {
  1711. fn fill_buf(&mut self) -> io::Result<&[u8]> {
  1712. Err(io::Error::new(io::ErrorKind::Other, ""))
  1713. }
  1714. fn consume(&mut self, _amt: usize) { }
  1715. }
  1716. let mut buf = [0; 1];
  1717. assert_eq!(0, R.take(0).read(&mut buf).unwrap());
  1718. assert_eq!(b"", R.take(0).fill_buf().unwrap());
  1719. }
  1720. fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
  1721. let mut cat = Vec::new();
  1722. loop {
  1723. let consume = {
  1724. let buf1 = br1.fill_buf().unwrap();
  1725. let buf2 = br2.fill_buf().unwrap();
  1726. let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
  1727. assert_eq!(buf1[..minlen], buf2[..minlen]);
  1728. cat.extend_from_slice(&buf1[..minlen]);
  1729. minlen
  1730. };
  1731. if consume == 0 {
  1732. break;
  1733. }
  1734. br1.consume(consume);
  1735. br2.consume(consume);
  1736. }
  1737. assert_eq!(br1.fill_buf().unwrap().len(), 0);
  1738. assert_eq!(br2.fill_buf().unwrap().len(), 0);
  1739. assert_eq!(&cat[..], &exp[..])
  1740. }
  1741. #[test]
  1742. fn chain_bufread() {
  1743. let testdata = b"ABCDEFGHIJKL";
  1744. let chain1 = (&testdata[..3]).chain(&testdata[3..6])
  1745. .chain(&testdata[6..9])
  1746. .chain(&testdata[9..]);
  1747. let chain2 = (&testdata[..4]).chain(&testdata[4..8])
  1748. .chain(&testdata[8..]);
  1749. cmp_bufread(chain1, chain2, &testdata[..]);
  1750. }
  1751. #[bench]
  1752. fn bench_read_to_end(b: &mut test::Bencher) {
  1753. b.iter(|| {
  1754. let mut lr = repeat(1).take(10000000);
  1755. let mut vec = Vec::with_capacity(1024);
  1756. super::read_to_end(&mut lr, &mut vec)
  1757. });
  1758. }
  1759. }