Skip to content

Commit

Permalink
Auto merge of rust-lang#85815 - YuhanLiin:buf-read-data-left, r=m-ou-se
Browse files Browse the repository at this point in the history
Add has_data_left() to BufRead

This is a continuation of rust-lang#40747 and also addresses rust-lang#40745. The problem with the previous PR was that it had "eof" in its method name. This PR uses a more descriptive method name, but I'm open to changing it.
  • Loading branch information
bors committed Jun 18, 2021
2 parents 88ba8ad + 99939c4 commit ce1d561
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
31 changes: 31 additions & 0 deletions library/std/src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2005,6 +2005,37 @@ pub trait BufRead: Read {
#[stable(feature = "rust1", since = "1.0.0")]
fn consume(&mut self, amt: usize);

/// Check if the underlying `Read` has any data left to be read.
///
/// This function may fill the buffer to check for data,
/// so this functions returns `Result<bool>`, not `bool`.
///
/// Default implementation calls `fill_buf` and checks that
/// returned slice is empty (which means that there is no data left,
/// since EOF is reached).
///
/// Examples
///
/// ```
/// #![feature(buf_read_has_data_left)]
/// use std::io;
/// use std::io::prelude::*;
///
/// let stdin = io::stdin();
/// let mut stdin = stdin.lock();
///
/// while stdin.has_data_left().unwrap() {
/// let mut line = String::new();
/// stdin.read_line(&mut line).unwrap();
/// // work with line
/// println!("{:?}", line);
/// }
/// ```
#[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
fn has_data_left(&mut self) -> Result<bool> {
self.fill_buf().map(|b| !b.is_empty())
}

/// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
///
/// This function will read bytes from the underlying stream until the
Expand Down
10 changes: 10 additions & 0 deletions library/std/src/io/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ fn lines() {
assert!(s.next().is_none());
}

#[test]
fn buf_read_has_data_left() {
let mut buf = Cursor::new(&b"abcd"[..]);
assert!(buf.has_data_left().unwrap());
buf.read_exact(&mut [0; 2]).unwrap();
assert!(buf.has_data_left().unwrap());
buf.read_exact(&mut [0; 2]).unwrap();
assert!(!buf.has_data_left().unwrap());
}

#[test]
fn read_to_end() {
let mut c = Cursor::new(&b""[..]);
Expand Down

0 comments on commit ce1d561

Please sign in to comment.