mod.rs 59 KB

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