mod.rs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  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. ///
  1031. /// [`SeekFrom::Start`]: enum.SeekFrom.html#variant.Start
  1032. fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
  1033. }
  1034. /// Enumeration of possible methods to seek within an I/O object.
  1035. ///
  1036. /// It is used by the [`Seek`] trait.
  1037. ///
  1038. /// [`Seek`]: trait.Seek.html
  1039. #[derive(Copy, PartialEq, Eq, Clone, Debug)]
  1040. pub enum SeekFrom {
  1041. /// Set the offset to the provided number of bytes.
  1042. Start(u64),
  1043. /// Set the offset to the size of this object 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. End(i64),
  1049. /// Set the offset to the current position plus the specified number of
  1050. /// bytes.
  1051. ///
  1052. /// It is possible to seek beyond the end of an object, but it's an error to
  1053. /// seek before byte 0.
  1054. Current(i64),
  1055. }
  1056. #[cfg(feature="collections")]
  1057. fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
  1058. -> Result<usize> {
  1059. let mut read = 0;
  1060. loop {
  1061. let (done, used) = {
  1062. let available = match r.fill_buf() {
  1063. Ok(n) => n,
  1064. Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
  1065. Err(e) => return Err(e)
  1066. };
  1067. match memchr::memchr(delim, available) {
  1068. Some(i) => {
  1069. buf.extend_from_slice(&available[..i + 1]);
  1070. (true, i + 1)
  1071. }
  1072. None => {
  1073. buf.extend_from_slice(available);
  1074. (false, available.len())
  1075. }
  1076. }
  1077. };
  1078. r.consume(used);
  1079. read += used;
  1080. if done || used == 0 {
  1081. return Ok(read);
  1082. }
  1083. }
  1084. }
  1085. /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
  1086. /// to perform extra ways of reading.
  1087. ///
  1088. /// For example, reading line-by-line is inefficient without using a buffer, so
  1089. /// if you want to read by line, you'll need `BufRead`, which includes a
  1090. /// [`read_line()`][readline] method as well as a [`lines()`][lines] iterator.
  1091. ///
  1092. /// [readline]: #method.read_line
  1093. /// [lines]: #method.lines
  1094. ///
  1095. /// # Examples
  1096. ///
  1097. /// A locked standard input implements `BufRead`:
  1098. ///
  1099. /// ```
  1100. /// use std::io;
  1101. /// use std::io::prelude::*;
  1102. ///
  1103. /// let stdin = io::stdin();
  1104. /// for line in stdin.lock().lines() {
  1105. /// println!("{}", line.unwrap());
  1106. /// }
  1107. /// ```
  1108. ///
  1109. /// If you have something that implements `Read`, you can use the [`BufReader`
  1110. /// type][bufreader] to turn it into a `BufRead`.
  1111. ///
  1112. /// For example, [`File`][file] implements `Read`, but not `BufRead`.
  1113. /// `BufReader` to the rescue!
  1114. ///
  1115. /// [bufreader]: struct.BufReader.html
  1116. /// [file]: ../fs/struct.File.html
  1117. ///
  1118. /// ```
  1119. /// use std::io::{self, BufReader};
  1120. /// use std::io::prelude::*;
  1121. /// use std::fs::File;
  1122. ///
  1123. /// # fn foo() -> io::Result<()> {
  1124. /// let f = try!(File::open("foo.txt"));
  1125. /// let f = BufReader::new(f);
  1126. ///
  1127. /// for line in f.lines() {
  1128. /// println!("{}", line.unwrap());
  1129. /// }
  1130. ///
  1131. /// # Ok(())
  1132. /// # }
  1133. /// ```
  1134. ///
  1135. #[cfg(feature="collections")]
  1136. pub trait BufRead: Read {
  1137. /// Fills the internal buffer of this object, returning the buffer contents.
  1138. ///
  1139. /// This function is a lower-level call. It needs to be paired with the
  1140. /// [`consume`][consume] method to function properly. When calling this
  1141. /// method, none of the contents will be "read" in the sense that later
  1142. /// calling `read` may return the same contents. As such, `consume` must be
  1143. /// called with the number of bytes that are consumed from this buffer to
  1144. /// ensure that the bytes are never returned twice.
  1145. ///
  1146. /// [consume]: #tymethod.consume
  1147. ///
  1148. /// An empty buffer returned indicates that the stream has reached EOF.
  1149. ///
  1150. /// # Errors
  1151. ///
  1152. /// This function will return an I/O error if the underlying reader was
  1153. /// read, but returned an error.
  1154. ///
  1155. /// # Examples
  1156. ///
  1157. /// A locked standard input implements `BufRead`:
  1158. ///
  1159. /// ```
  1160. /// use std::io;
  1161. /// use std::io::prelude::*;
  1162. ///
  1163. /// let stdin = io::stdin();
  1164. /// let mut stdin = stdin.lock();
  1165. ///
  1166. /// // we can't have two `&mut` references to `stdin`, so use a block
  1167. /// // to end the borrow early.
  1168. /// let length = {
  1169. /// let buffer = stdin.fill_buf().unwrap();
  1170. ///
  1171. /// // work with buffer
  1172. /// println!("{:?}", buffer);
  1173. ///
  1174. /// buffer.len()
  1175. /// };
  1176. ///
  1177. /// // ensure the bytes we worked with aren't returned again later
  1178. /// stdin.consume(length);
  1179. /// ```
  1180. fn fill_buf(&mut self) -> Result<&[u8]>;
  1181. /// Tells this buffer that `amt` bytes have been consumed from the buffer,
  1182. /// so they should no longer be returned in calls to `read`.
  1183. ///
  1184. /// This function is a lower-level call. It needs to be paired with the
  1185. /// [`fill_buf`][fillbuf] method to function properly. This function does
  1186. /// not perform any I/O, it simply informs this object that some amount of
  1187. /// its buffer, returned from `fill_buf`, has been consumed and should no
  1188. /// longer be returned. As such, this function may do odd things if
  1189. /// `fill_buf` isn't called before calling it.
  1190. ///
  1191. /// [fillbuf]: #tymethod.fill_buf
  1192. ///
  1193. /// The `amt` must be `<=` the number of bytes in the buffer returned by
  1194. /// `fill_buf`.
  1195. ///
  1196. /// # Examples
  1197. ///
  1198. /// Since `consume()` is meant to be used with [`fill_buf()`][fillbuf],
  1199. /// that method's example includes an example of `consume()`.
  1200. fn consume(&mut self, amt: usize);
  1201. /// Read all bytes into `buf` until the delimiter `byte` is reached.
  1202. ///
  1203. /// This function will read bytes from the underlying stream until the
  1204. /// delimiter or EOF is found. Once found, all bytes up to, and including,
  1205. /// the delimiter (if found) will be appended to `buf`.
  1206. ///
  1207. /// If this reader is currently at EOF then this function will not modify
  1208. /// `buf` and will return `Ok(n)` where `n` is the number of bytes which
  1209. /// were read.
  1210. ///
  1211. /// # Errors
  1212. ///
  1213. /// This function will ignore all instances of `ErrorKind::Interrupted` and
  1214. /// will otherwise return any errors returned by `fill_buf`.
  1215. ///
  1216. /// If an I/O error is encountered then all bytes read so far will be
  1217. /// present in `buf` and its length will have been adjusted appropriately.
  1218. ///
  1219. /// # Examples
  1220. ///
  1221. /// A locked standard input implements `BufRead`. In this example, we'll
  1222. /// read from standard input until we see an `a` byte.
  1223. ///
  1224. /// ```
  1225. /// use std::io;
  1226. /// use std::io::prelude::*;
  1227. ///
  1228. /// fn foo() -> io::Result<()> {
  1229. /// let stdin = io::stdin();
  1230. /// let mut stdin = stdin.lock();
  1231. /// let mut buffer = Vec::new();
  1232. ///
  1233. /// try!(stdin.read_until(b'a', &mut buffer));
  1234. ///
  1235. /// println!("{:?}", buffer);
  1236. /// # Ok(())
  1237. /// # }
  1238. /// ```
  1239. fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
  1240. read_until(self, byte, buf)
  1241. }
  1242. /// Read all bytes until a newline (the 0xA byte) is reached, and append
  1243. /// them to the provided buffer.
  1244. ///
  1245. /// This function will read bytes from the underlying stream until the
  1246. /// newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
  1247. /// up to, and including, the delimiter (if found) will be appended to
  1248. /// `buf`.
  1249. ///
  1250. /// If this reader is currently at EOF then this function will not modify
  1251. /// `buf` and will return `Ok(n)` where `n` is the number of bytes which
  1252. /// were read.
  1253. ///
  1254. /// # Errors
  1255. ///
  1256. /// This function has the same error semantics as `read_until` and will also
  1257. /// return an error if the read bytes are not valid UTF-8. If an I/O error
  1258. /// is encountered then `buf` may contain some bytes already read in the
  1259. /// event that all data read so far was valid UTF-8.
  1260. ///
  1261. /// # Examples
  1262. ///
  1263. /// A locked standard input implements `BufRead`. In this example, we'll
  1264. /// read all of the lines from standard input. If we were to do this in
  1265. /// an actual project, the [`lines()`][lines] method would be easier, of
  1266. /// course.
  1267. ///
  1268. /// [lines]: #method.lines
  1269. ///
  1270. /// ```
  1271. /// use std::io;
  1272. /// use std::io::prelude::*;
  1273. ///
  1274. /// let stdin = io::stdin();
  1275. /// let mut stdin = stdin.lock();
  1276. /// let mut buffer = String::new();
  1277. ///
  1278. /// while stdin.read_line(&mut buffer).unwrap() > 0 {
  1279. /// // work with buffer
  1280. /// println!("{:?}", buffer);
  1281. ///
  1282. /// buffer.clear();
  1283. /// }
  1284. /// ```
  1285. fn read_line(&mut self, buf: &mut String) -> Result<usize> {
  1286. // Note that we are not calling the `.read_until` method here, but
  1287. // rather our hardcoded implementation. For more details as to why, see
  1288. // the comments in `read_to_end`.
  1289. append_to_string(buf, |b| read_until(self, b'\n', b))
  1290. }
  1291. /// Returns an iterator over the contents of this reader split on the byte
  1292. /// `byte`.
  1293. ///
  1294. /// The iterator returned from this function will return instances of
  1295. /// `io::Result<Vec<u8>>`. Each vector returned will *not* have the
  1296. /// delimiter byte at the end.
  1297. ///
  1298. /// This function will yield errors whenever `read_until` would have also
  1299. /// yielded an error.
  1300. ///
  1301. /// # Examples
  1302. ///
  1303. /// A locked standard input implements `BufRead`. In this example, we'll
  1304. /// read some input from standard input, splitting on commas.
  1305. ///
  1306. /// ```
  1307. /// use std::io;
  1308. /// use std::io::prelude::*;
  1309. ///
  1310. /// let stdin = io::stdin();
  1311. ///
  1312. /// for content in stdin.lock().split(b',') {
  1313. /// println!("{:?}", content.unwrap());
  1314. /// }
  1315. /// ```
  1316. fn split(self, byte: u8) -> Split<Self> where Self: Sized {
  1317. Split { buf: self, delim: byte }
  1318. }
  1319. /// Returns an iterator over the lines of this reader.
  1320. ///
  1321. /// The iterator returned from this function will yield instances of
  1322. /// `io::Result<String>`. Each string returned will *not* have a newline
  1323. /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
  1324. ///
  1325. /// # Examples
  1326. ///
  1327. /// A locked standard input implements `BufRead`:
  1328. ///
  1329. /// ```
  1330. /// use std::io;
  1331. /// use std::io::prelude::*;
  1332. ///
  1333. /// let stdin = io::stdin();
  1334. ///
  1335. /// for line in stdin.lock().lines() {
  1336. /// println!("{}", line.unwrap());
  1337. /// }
  1338. /// ```
  1339. fn lines(self) -> Lines<Self> where Self: Sized {
  1340. Lines { buf: self }
  1341. }
  1342. }
  1343. /// Adaptor to chain together two readers.
  1344. ///
  1345. /// This struct is generally created by calling [`chain()`][chain] on a reader.
  1346. /// Please see the documentation of `chain()` for more details.
  1347. ///
  1348. /// [chain]: trait.Read.html#method.chain
  1349. pub struct Chain<T, U> {
  1350. first: T,
  1351. second: U,
  1352. done_first: bool,
  1353. }
  1354. impl<T: Read, U: Read> Read for Chain<T, U> {
  1355. fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
  1356. if !self.done_first {
  1357. match self.first.read(buf)? {
  1358. 0 => { self.done_first = true; }
  1359. n => return Ok(n),
  1360. }
  1361. }
  1362. self.second.read(buf)
  1363. }
  1364. }
  1365. #[cfg(feature="collections")]
  1366. impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
  1367. fn fill_buf(&mut self) -> Result<&[u8]> {
  1368. if !self.done_first {
  1369. match self.first.fill_buf()? {
  1370. buf if buf.len() == 0 => { self.done_first = true; }
  1371. buf => return Ok(buf),
  1372. }
  1373. }
  1374. self.second.fill_buf()
  1375. }
  1376. fn consume(&mut self, amt: usize) {
  1377. if !self.done_first {
  1378. self.first.consume(amt)
  1379. } else {
  1380. self.second.consume(amt)
  1381. }
  1382. }
  1383. }
  1384. /// Reader adaptor which limits the bytes read from an underlying reader.
  1385. ///
  1386. /// This struct is generally created by calling [`take()`][take] on a reader.
  1387. /// Please see the documentation of `take()` for more details.
  1388. ///
  1389. /// [take]: trait.Read.html#method.take
  1390. pub struct Take<T> {
  1391. inner: T,
  1392. limit: u64,
  1393. }
  1394. impl<T> Take<T> {
  1395. /// Returns the number of bytes that can be read before this instance will
  1396. /// return EOF.
  1397. ///
  1398. /// # Note
  1399. ///
  1400. /// This instance may reach EOF after reading fewer bytes than indicated by
  1401. /// this method if the underlying `Read` instance reaches EOF.
  1402. ///
  1403. /// # Examples
  1404. ///
  1405. /// ```
  1406. /// use std::io;
  1407. /// use std::io::prelude::*;
  1408. /// use std::fs::File;
  1409. ///
  1410. /// # fn foo() -> io::Result<()> {
  1411. /// let f = try!(File::open("foo.txt"));
  1412. ///
  1413. /// // read at most five bytes
  1414. /// let handle = f.take(5);
  1415. ///
  1416. /// println!("limit: {}", handle.limit());
  1417. /// # Ok(())
  1418. /// # }
  1419. /// ```
  1420. pub fn limit(&self) -> u64 { self.limit }
  1421. /// Consumes the `Take`, returning the wrapped reader.
  1422. ///
  1423. /// # Examples
  1424. ///
  1425. /// ```
  1426. /// #![feature(io_take_into_inner)]
  1427. ///
  1428. /// use std::io;
  1429. /// use std::io::prelude::*;
  1430. /// use std::fs::File;
  1431. ///
  1432. /// # fn foo() -> io::Result<()> {
  1433. /// let mut file = try!(File::open("foo.txt"));
  1434. ///
  1435. /// let mut buffer = [0; 5];
  1436. /// let mut handle = file.take(5);
  1437. /// try!(handle.read(&mut buffer));
  1438. ///
  1439. /// let file = handle.into_inner();
  1440. /// # Ok(())
  1441. /// # }
  1442. /// ```
  1443. pub fn into_inner(self) -> T {
  1444. self.inner
  1445. }
  1446. }
  1447. impl<T: Read> Read for Take<T> {
  1448. fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
  1449. // Don't call into inner reader at all at EOF because it may still block
  1450. if self.limit == 0 {
  1451. return Ok(0);
  1452. }
  1453. let max = cmp::min(buf.len() as u64, self.limit) as usize;
  1454. let n = self.inner.read(&mut buf[..max])?;
  1455. self.limit -= n as u64;
  1456. Ok(n)
  1457. }
  1458. }
  1459. #[cfg(feature="collections")]
  1460. impl<T: BufRead> BufRead for Take<T> {
  1461. fn fill_buf(&mut self) -> Result<&[u8]> {
  1462. // Don't call into inner reader at all at EOF because it may still block
  1463. if self.limit == 0 {
  1464. return Ok(&[]);
  1465. }
  1466. let buf = self.inner.fill_buf()?;
  1467. let cap = cmp::min(buf.len() as u64, self.limit) as usize;
  1468. Ok(&buf[..cap])
  1469. }
  1470. fn consume(&mut self, amt: usize) {
  1471. // Don't let callers reset the limit by passing an overlarge value
  1472. let amt = cmp::min(amt as u64, self.limit) as usize;
  1473. self.limit -= amt as u64;
  1474. self.inner.consume(amt);
  1475. }
  1476. }
  1477. fn read_one_byte(reader: &mut Read) -> Option<Result<u8>> {
  1478. let mut buf = [0];
  1479. loop {
  1480. return match reader.read(&mut buf) {
  1481. Ok(0) => None,
  1482. Ok(..) => Some(Ok(buf[0])),
  1483. Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
  1484. Err(e) => Some(Err(e)),
  1485. };
  1486. }
  1487. }
  1488. /// An iterator over `u8` values of a reader.
  1489. ///
  1490. /// This struct is generally created by calling [`bytes()`][bytes] on a reader.
  1491. /// Please see the documentation of `bytes()` for more details.
  1492. ///
  1493. /// [bytes]: trait.Read.html#method.bytes
  1494. pub struct Bytes<R> {
  1495. inner: R,
  1496. }
  1497. impl<R: Read> Iterator for Bytes<R> {
  1498. type Item = Result<u8>;
  1499. fn next(&mut self) -> Option<Result<u8>> {
  1500. read_one_byte(&mut self.inner)
  1501. }
  1502. }
  1503. /// An iterator over the `char`s of a reader.
  1504. ///
  1505. /// This struct is generally created by calling [`chars()`][chars] on a reader.
  1506. /// Please see the documentation of `chars()` for more details.
  1507. ///
  1508. /// [chars]: trait.Read.html#method.chars
  1509. pub struct Chars<R> {
  1510. inner: R,
  1511. }
  1512. /// An enumeration of possible errors that can be generated from the `Chars`
  1513. /// adapter.
  1514. #[derive(Debug)]
  1515. pub enum CharsError {
  1516. /// Variant representing that the underlying stream was read successfully
  1517. /// but it did not contain valid utf8 data.
  1518. NotUtf8,
  1519. /// Variant representing that an I/O error occurred.
  1520. Other(Error),
  1521. }
  1522. impl<R: Read> Iterator for Chars<R> {
  1523. type Item = result::Result<char, CharsError>;
  1524. fn next(&mut self) -> Option<result::Result<char, CharsError>> {
  1525. let first_byte = match read_one_byte(&mut self.inner) {
  1526. None => return None,
  1527. Some(Ok(b)) => b,
  1528. Some(Err(e)) => return Some(Err(CharsError::Other(e))),
  1529. };
  1530. let width = core_str::utf8_char_width(first_byte);
  1531. if width == 1 { return Some(Ok(first_byte as char)) }
  1532. if width == 0 { return Some(Err(CharsError::NotUtf8)) }
  1533. let mut buf = [first_byte, 0, 0, 0];
  1534. {
  1535. let mut start = 1;
  1536. while start < width {
  1537. match self.inner.read(&mut buf[start..width]) {
  1538. Ok(0) => return Some(Err(CharsError::NotUtf8)),
  1539. Ok(n) => start += n,
  1540. Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
  1541. Err(e) => return Some(Err(CharsError::Other(e))),
  1542. }
  1543. }
  1544. }
  1545. Some(match str::from_utf8(&buf[..width]).ok() {
  1546. Some(s) => Ok(s.chars().next().unwrap()),
  1547. None => Err(CharsError::NotUtf8),
  1548. })
  1549. }
  1550. }
  1551. impl fmt::Display for CharsError {
  1552. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  1553. match *self {
  1554. CharsError::NotUtf8 => {
  1555. "byte stream did not contain valid utf8".fmt(f)
  1556. }
  1557. CharsError::Other(ref e) => e.fmt(f),
  1558. }
  1559. }
  1560. }
  1561. /// An iterator over the contents of an instance of `BufRead` split on a
  1562. /// particular byte.
  1563. ///
  1564. /// This struct is generally created by calling [`split()`][split] on a
  1565. /// `BufRead`. Please see the documentation of `split()` for more details.
  1566. ///
  1567. /// [split]: trait.BufRead.html#method.split
  1568. #[cfg(feature="collections")]
  1569. pub struct Split<B> {
  1570. buf: B,
  1571. delim: u8,
  1572. }
  1573. #[cfg(feature="collections")]
  1574. impl<B: BufRead> Iterator for Split<B> {
  1575. type Item = Result<Vec<u8>>;
  1576. fn next(&mut self) -> Option<Result<Vec<u8>>> {
  1577. let mut buf = Vec::new();
  1578. match self.buf.read_until(self.delim, &mut buf) {
  1579. Ok(0) => None,
  1580. Ok(_n) => {
  1581. if buf[buf.len() - 1] == self.delim {
  1582. buf.pop();
  1583. }
  1584. Some(Ok(buf))
  1585. }
  1586. Err(e) => Some(Err(e))
  1587. }
  1588. }
  1589. }
  1590. /// An iterator over the lines of an instance of `BufRead`.
  1591. ///
  1592. /// This struct is generally created by calling [`lines()`][lines] on a
  1593. /// `BufRead`. Please see the documentation of `lines()` for more details.
  1594. ///
  1595. /// [lines]: trait.BufRead.html#method.lines
  1596. #[cfg(feature="collections")]
  1597. pub struct Lines<B> {
  1598. buf: B,
  1599. }
  1600. #[cfg(feature="collections")]
  1601. impl<B: BufRead> Iterator for Lines<B> {
  1602. type Item = Result<String>;
  1603. fn next(&mut self) -> Option<Result<String>> {
  1604. let mut buf = String::new();
  1605. match self.buf.read_line(&mut buf) {
  1606. Ok(0) => None,
  1607. Ok(_n) => {
  1608. if buf.ends_with("\n") {
  1609. buf.pop();
  1610. if buf.ends_with("\r") {
  1611. buf.pop();
  1612. }
  1613. }
  1614. Some(Ok(buf))
  1615. }
  1616. Err(e) => Some(Err(e))
  1617. }
  1618. }
  1619. }
  1620. #[cfg(test)]
  1621. mod tests {
  1622. use io::prelude::*;
  1623. use io;
  1624. use super::Cursor;
  1625. use test;
  1626. use super::repeat;
  1627. #[test]
  1628. fn read_until() {
  1629. let mut buf = Cursor::new(&b"12"[..]);
  1630. let mut v = Vec::new();
  1631. assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 2);
  1632. assert_eq!(v, b"12");
  1633. let mut buf = Cursor::new(&b"1233"[..]);
  1634. let mut v = Vec::new();
  1635. assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 3);
  1636. assert_eq!(v, b"123");
  1637. v.truncate(0);
  1638. assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 1);
  1639. assert_eq!(v, b"3");
  1640. v.truncate(0);
  1641. assert_eq!(buf.read_until(b'3', &mut v).unwrap(), 0);
  1642. assert_eq!(v, []);
  1643. }
  1644. #[test]
  1645. fn split() {
  1646. let buf = Cursor::new(&b"12"[..]);
  1647. let mut s = buf.split(b'3');
  1648. assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
  1649. assert!(s.next().is_none());
  1650. let buf = Cursor::new(&b"1233"[..]);
  1651. let mut s = buf.split(b'3');
  1652. assert_eq!(s.next().unwrap().unwrap(), vec![b'1', b'2']);
  1653. assert_eq!(s.next().unwrap().unwrap(), vec![]);
  1654. assert!(s.next().is_none());
  1655. }
  1656. #[test]
  1657. fn read_line() {
  1658. let mut buf = Cursor::new(&b"12"[..]);
  1659. let mut v = String::new();
  1660. assert_eq!(buf.read_line(&mut v).unwrap(), 2);
  1661. assert_eq!(v, "12");
  1662. let mut buf = Cursor::new(&b"12\n\n"[..]);
  1663. let mut v = String::new();
  1664. assert_eq!(buf.read_line(&mut v).unwrap(), 3);
  1665. assert_eq!(v, "12\n");
  1666. v.truncate(0);
  1667. assert_eq!(buf.read_line(&mut v).unwrap(), 1);
  1668. assert_eq!(v, "\n");
  1669. v.truncate(0);
  1670. assert_eq!(buf.read_line(&mut v).unwrap(), 0);
  1671. assert_eq!(v, "");
  1672. }
  1673. #[test]
  1674. fn lines() {
  1675. let buf = Cursor::new(&b"12\r"[..]);
  1676. let mut s = buf.lines();
  1677. assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string());
  1678. assert!(s.next().is_none());
  1679. let buf = Cursor::new(&b"12\r\n\n"[..]);
  1680. let mut s = buf.lines();
  1681. assert_eq!(s.next().unwrap().unwrap(), "12".to_string());
  1682. assert_eq!(s.next().unwrap().unwrap(), "".to_string());
  1683. assert!(s.next().is_none());
  1684. }
  1685. #[test]
  1686. fn read_to_end() {
  1687. let mut c = Cursor::new(&b""[..]);
  1688. let mut v = Vec::new();
  1689. assert_eq!(c.read_to_end(&mut v).unwrap(), 0);
  1690. assert_eq!(v, []);
  1691. let mut c = Cursor::new(&b"1"[..]);
  1692. let mut v = Vec::new();
  1693. assert_eq!(c.read_to_end(&mut v).unwrap(), 1);
  1694. assert_eq!(v, b"1");
  1695. let cap = 1024 * 1024;
  1696. let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>();
  1697. let mut v = Vec::new();
  1698. let (a, b) = data.split_at(data.len() / 2);
  1699. assert_eq!(Cursor::new(a).read_to_end(&mut v).unwrap(), a.len());
  1700. assert_eq!(Cursor::new(b).read_to_end(&mut v).unwrap(), b.len());
  1701. assert_eq!(v, data);
  1702. }
  1703. #[test]
  1704. fn read_to_string() {
  1705. let mut c = Cursor::new(&b""[..]);
  1706. let mut v = String::new();
  1707. assert_eq!(c.read_to_string(&mut v).unwrap(), 0);
  1708. assert_eq!(v, "");
  1709. let mut c = Cursor::new(&b"1"[..]);
  1710. let mut v = String::new();
  1711. assert_eq!(c.read_to_string(&mut v).unwrap(), 1);
  1712. assert_eq!(v, "1");
  1713. let mut c = Cursor::new(&b"\xff"[..]);
  1714. let mut v = String::new();
  1715. assert!(c.read_to_string(&mut v).is_err());
  1716. }
  1717. #[test]
  1718. fn read_exact() {
  1719. let mut buf = [0; 4];
  1720. let mut c = Cursor::new(&b""[..]);
  1721. assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
  1722. io::ErrorKind::UnexpectedEof);
  1723. let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
  1724. c.read_exact(&mut buf).unwrap();
  1725. assert_eq!(&buf, b"1234");
  1726. c.read_exact(&mut buf).unwrap();
  1727. assert_eq!(&buf, b"5678");
  1728. assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
  1729. io::ErrorKind::UnexpectedEof);
  1730. }
  1731. #[test]
  1732. fn read_exact_slice() {
  1733. let mut buf = [0; 4];
  1734. let mut c = &b""[..];
  1735. assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
  1736. io::ErrorKind::UnexpectedEof);
  1737. let mut c = &b"123"[..];
  1738. assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
  1739. io::ErrorKind::UnexpectedEof);
  1740. // make sure the optimized (early returning) method is being used
  1741. assert_eq!(&buf, &[0; 4]);
  1742. let mut c = &b"1234"[..];
  1743. c.read_exact(&mut buf).unwrap();
  1744. assert_eq!(&buf, b"1234");
  1745. let mut c = &b"56789"[..];
  1746. c.read_exact(&mut buf).unwrap();
  1747. assert_eq!(&buf, b"5678");
  1748. assert_eq!(c, b"9");
  1749. }
  1750. #[test]
  1751. fn take_eof() {
  1752. struct R;
  1753. impl Read for R {
  1754. fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
  1755. Err(io::Error::new(io::ErrorKind::Other, ""))
  1756. }
  1757. }
  1758. impl BufRead for R {
  1759. fn fill_buf(&mut self) -> io::Result<&[u8]> {
  1760. Err(io::Error::new(io::ErrorKind::Other, ""))
  1761. }
  1762. fn consume(&mut self, _amt: usize) { }
  1763. }
  1764. let mut buf = [0; 1];
  1765. assert_eq!(0, R.take(0).read(&mut buf).unwrap());
  1766. assert_eq!(b"", R.take(0).fill_buf().unwrap());
  1767. }
  1768. fn cmp_bufread<Br1: BufRead, Br2: BufRead>(mut br1: Br1, mut br2: Br2, exp: &[u8]) {
  1769. let mut cat = Vec::new();
  1770. loop {
  1771. let consume = {
  1772. let buf1 = br1.fill_buf().unwrap();
  1773. let buf2 = br2.fill_buf().unwrap();
  1774. let minlen = if buf1.len() < buf2.len() { buf1.len() } else { buf2.len() };
  1775. assert_eq!(buf1[..minlen], buf2[..minlen]);
  1776. cat.extend_from_slice(&buf1[..minlen]);
  1777. minlen
  1778. };
  1779. if consume == 0 {
  1780. break;
  1781. }
  1782. br1.consume(consume);
  1783. br2.consume(consume);
  1784. }
  1785. assert_eq!(br1.fill_buf().unwrap().len(), 0);
  1786. assert_eq!(br2.fill_buf().unwrap().len(), 0);
  1787. assert_eq!(&cat[..], &exp[..])
  1788. }
  1789. #[test]
  1790. fn chain_bufread() {
  1791. let testdata = b"ABCDEFGHIJKL";
  1792. let chain1 = (&testdata[..3]).chain(&testdata[3..6])
  1793. .chain(&testdata[6..9])
  1794. .chain(&testdata[9..]);
  1795. let chain2 = (&testdata[..4]).chain(&testdata[4..8])
  1796. .chain(&testdata[8..]);
  1797. cmp_bufread(chain1, chain2, &testdata[..]);
  1798. }
  1799. #[bench]
  1800. fn bench_read_to_end(b: &mut test::Bencher) {
  1801. b.iter(|| {
  1802. let mut lr = repeat(1).take(10000000);
  1803. let mut vec = Vec::with_capacity(1024);
  1804. super::read_to_end(&mut lr, &mut vec)
  1805. });
  1806. }
  1807. }