Skip to content

Commit 952eee2

Browse files
borsgitbot
authored and
gitbot
committed
Auto merge of rust-lang#85815 - YuhanLiin:buf-read-data-left, r=m-ou-se
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.
2 parents 76c8513 + 7942882 commit 952eee2

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

std/src/io/mod.rs

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

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

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)