Skip to content

Commit 278731d

Browse files
committed
Fix reading empty files
1 parent 2d0155c commit 278731d

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

src/body.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -467,9 +467,12 @@ impl BufRead for Body {
467467
/// This is used for various binary formats such as images and videos.
468468
#[cfg(feature = "async_std")]
469469
async fn peek_mime(file: &mut async_std::fs::File) -> io::Result<Option<Mime>> {
470+
// Reading the first 8 bytes should be enough to sniff the mime type.
470471
let mut buf = [0_u8; 8];
471-
file.read_exact(&mut buf).await?;
472+
file.read(&mut buf).await?;
472473
let mime = Mime::sniff(&buf).ok();
474+
475+
// Reset the file cursor back to the start.
473476
file.seek(io::SeekFrom::Start(0)).await?;
474477
Ok(mime)
475478
}

tests/mime.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use async_std::io;
2+
use async_std::fs;
23
use http_types::{mime, Body, Response};
34

45
#[async_std::test]
@@ -11,11 +12,16 @@ async fn guess_plain_text_mime() -> io::Result<()> {
1112
}
1213

1314
#[async_std::test]
14-
async fn guess_binary_mime() -> io::Result<()> {
15+
async fn guess_binary_mime() -> http_types::Result<()> {
1516
let body = Body::from_file("tests/fixtures/nori.png").await?;
1617
let mut res = Response::new(200);
1718
res.set_body(body);
1819
assert_eq!(res.content_type(), Some(mime::PNG));
20+
21+
// Assert the file is correctly reset after we've peeked the bytes
22+
let left = fs::read("tests/fixtures/nori.png").await?;
23+
let right = res.body_bytes().await?;
24+
assert_eq!(left, right);
1925
Ok(())
2026
}
2127

0 commit comments

Comments
 (0)