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