Skip to content

fs: empty reads on File should not start a background read #7139

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion tokio/src/fs/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,7 @@ impl AsyncRead for File {
dst: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
ready!(crate::trace::trace_leaf(cx));

let me = self.get_mut();
let inner = me.inner.get_mut();

Expand All @@ -595,7 +596,7 @@ impl AsyncRead for File {
State::Idle(ref mut buf_cell) => {
let mut buf = buf_cell.take().unwrap();

if !buf.is_empty() {
if !buf.is_empty() || dst.remaining() == 0 {
buf.copy_to(dst);
*buf_cell = Some(buf);
return Poll::Ready(Ok(()));
Expand Down
19 changes: 19 additions & 0 deletions tokio/tests/fs_file.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![warn(rust_2018_idioms)]
#![cfg(all(feature = "full", not(target_os = "wasi")))] // WASI does not support all fs operations

use futures::future::FutureExt;
use std::io::prelude::*;
use std::io::IoSlice;
use tempfile::NamedTempFile;
Expand Down Expand Up @@ -176,6 +177,24 @@ async fn read_file_from_std() {
assert_eq!(&buf[..n], HELLO);
}

#[tokio::test]
async fn empty_read() {
let mut tempfile = tempfile();
tempfile.write_all(HELLO).unwrap();

let mut file = File::open(tempfile.path()).await.unwrap();

// Perform an empty read and get a length of zero.
assert!(matches!(file.read(&mut []).now_or_never(), Some(Ok(0))));

// Check that we don't get EOF on the next read.
let mut buf = [0; 1024];
let n = file.read(&mut buf).await.unwrap();

assert_eq!(n, HELLO.len());
assert_eq!(&buf[..n], HELLO);
}

fn tempfile() -> NamedTempFile {
NamedTempFile::new().unwrap()
}
Expand Down
Loading