Skip to content

Commit e76929f

Browse files
committed
Add has_data_left() to BufRead
1 parent ff5522f commit e76929f

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

library/std/src/io/mod.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1953,6 +1953,37 @@ pub trait BufRead: Read {
19531953
#[stable(feature = "rust1", since = "1.0.0")]
19541954
fn consume(&mut self, amt: usize);
19551955

1956+
/// Check if the underlying `Read` has any data left to be read.
1957+
///
1958+
/// This function may fill the buffer to check for data,
1959+
/// so this functions returns `Result<bool>`, not `bool`.
1960+
///
1961+
/// Default implementation calls `fill_buf` and checks that
1962+
/// returned slice is empty (which means that there is no data left,
1963+
/// since EOF is reached).
1964+
///
1965+
/// Examples
1966+
///
1967+
/// ```
1968+
/// #![feature(buf_read_has_data_left)]
1969+
/// use std::io;
1970+
/// use std::io::prelude::*;
1971+
///
1972+
/// let stdin = io::stdin();
1973+
/// let mut stdin = stdin.lock();
1974+
///
1975+
/// while stdin.has_data_left().unwrap() {
1976+
/// let mut line = String::new();
1977+
/// stdin.read_line(&mut line).unwrap();
1978+
/// // work with line
1979+
/// println!("{:?}", line);
1980+
/// }
1981+
/// ```
1982+
#[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "40745")]
1983+
fn has_data_left(&mut self) -> Result<bool> {
1984+
self.fill_buf().map(|b| !b.is_empty())
1985+
}
1986+
19561987
/// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
19571988
///
19581989
/// This function will read bytes from the underlying stream until the

library/std/src/io/tests.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,16 @@ fn lines() {
7171
assert!(s.next().is_none());
7272
}
7373

74+
#[test]
75+
fn buf_read_has_data_left() {
76+
let mut buf = Cursor::new(&b"abcd"[..]);
77+
assert!(buf.has_data_left().unwrap());
78+
buf.read_exact(&mut [0; 2]).unwrap();
79+
assert!(buf.has_data_left().unwrap());
80+
buf.read_exact(&mut [0; 2]).unwrap();
81+
assert!(!buf.has_data_left().unwrap());
82+
}
83+
7484
#[test]
7585
fn read_to_end() {
7686
let mut c = Cursor::new(&b""[..]);

0 commit comments

Comments
 (0)