Skip to content
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

fix(body): return exactly 0 SizeHint for empty body #2122

Merged
merged 1 commit into from
Jan 29, 2020
Merged
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
33 changes: 25 additions & 8 deletions src/body/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,19 +331,15 @@ impl HttpBody for Body {

fn size_hint(&self) -> SizeHint {
match self.kind {
Kind::Once(Some(ref val)) => {
let mut hint = SizeHint::default();
hint.set_exact(val.len() as u64);
hint
}
Kind::Once(None) => SizeHint::default(),
Kind::Once(Some(ref val)) => SizeHint::with_exact(val.len() as u64),
Kind::Once(None) => SizeHint::with_exact(0),
#[cfg(feature = "stream")]
Kind::Wrapped(..) => SizeHint::default(),
Kind::Chan { content_length, .. } | Kind::H2 { content_length, .. } => {
let mut hint = SizeHint::default();

if let Some(content_length) = content_length.into_opt() {
hint.set_exact(content_length as u64);
hint.set_exact(content_length);
}

hint
Expand Down Expand Up @@ -547,7 +543,7 @@ mod tests {
use std::mem;
use std::task::Poll;

use super::{Body, DecodedLength, HttpBody, Sender};
use super::{Body, DecodedLength, HttpBody, Sender, SizeHint};

#[test]
fn test_size_of() {
Expand Down Expand Up @@ -578,6 +574,27 @@ mod tests {
);
}

#[test]
fn size_hint() {
fn eq(body: Body, b: SizeHint, note: &str) {
let a = body.size_hint();
assert_eq!(a.lower(), b.lower(), "lower for {:?}", note);
assert_eq!(a.upper(), b.upper(), "upper for {:?}", note);
}

eq(Body::from("Hello"), SizeHint::with_exact(5), "from str");

eq(Body::empty(), SizeHint::with_exact(0), "empty");

eq(Body::channel().1, SizeHint::new(), "channel");

eq(
Body::new_channel(DecodedLength::new(4), /*wanter =*/ false).1,
SizeHint::with_exact(4),
"channel with length",
);
}

#[tokio::test]
async fn channel_abort() {
let (tx, mut rx) = Body::channel();
Expand Down