Skip to content

Commit ce1d561

Browse files
committed
Auto merge of #85815 - YuhanLiin:buf-read-data-left, r=m-ou-se
Add has_data_left() to BufRead This is a continuation of #40747 and also addresses #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.
2 parents 88ba8ad + 99939c4 commit ce1d561

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

library/std/src/io/mod.rs

+31
Original file line numberDiff line numberDiff line change
@@ -2005,6 +2005,37 @@ pub trait BufRead: Read {
20052005
#[stable(feature = "rust1", since = "1.0.0")]
20062006
fn consume(&mut self, amt: usize);
20072007

2008+
/// Check if the underlying `Read` has any data left to be read.
2009+
///
2010+
/// This function may fill the buffer to check for data,
2011+
/// so this functions returns `Result<bool>`, not `bool`.
2012+
///
2013+
/// Default implementation calls `fill_buf` and checks that
2014+
/// returned slice is empty (which means that there is no data left,
2015+
/// since EOF is reached).
2016+
///
2017+
/// Examples
2018+
///
2019+
/// ```
2020+
/// #![feature(buf_read_has_data_left)]
2021+
/// use std::io;
2022+
/// use std::io::prelude::*;
2023+
///
2024+
/// let stdin = io::stdin();
2025+
/// let mut stdin = stdin.lock();
2026+
///
2027+
/// while stdin.has_data_left().unwrap() {
2028+
/// let mut line = String::new();
2029+
/// stdin.read_line(&mut line).unwrap();
2030+
/// // work with line
2031+
/// println!("{:?}", line);
2032+
/// }
2033+
/// ```
2034+
#[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
2035+
fn has_data_left(&mut self) -> Result<bool> {
2036+
self.fill_buf().map(|b| !b.is_empty())
2037+
}
2038+
20082039
/// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
20092040
///
20102041
/// This function will read bytes from the underlying stream until the

library/std/src/io/tests.rs

+10
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)