From 9ccb9f51d48d7fc1b56932f06f865e4ccfd4b39e Mon Sep 17 00:00:00 2001 From: SabrinaJewson Date: Mon, 18 Nov 2024 14:03:47 +0000 Subject: [PATCH] Set `size_hint` for identity compession bodies --- tower-http/src/compression/body.rs | 8 ++++++++ tower-http/src/compression/mod.rs | 13 +++++++++++++ 2 files changed, 21 insertions(+) diff --git a/tower-http/src/compression/body.rs b/tower-http/src/compression/body.rs index 0174b458..989685c1 100644 --- a/tower-http/src/compression/body.rs +++ b/tower-http/src/compression/body.rs @@ -269,6 +269,14 @@ where }, } } + + fn size_hint(&self) -> http_body::SizeHint { + if let BodyInner::Identity { inner } = &self.inner { + inner.size_hint() + } else { + http_body::SizeHint::new() + } + } } #[cfg(feature = "compression-gzip")] diff --git a/tower-http/src/compression/mod.rs b/tower-http/src/compression/mod.rs index 5107fac3..5772b9ba 100644 --- a/tower-http/src/compression/mod.rs +++ b/tower-http/src/compression/mod.rs @@ -99,6 +99,7 @@ mod tests { ACCEPT_ENCODING, ACCEPT_RANGES, CONTENT_ENCODING, CONTENT_RANGE, CONTENT_TYPE, RANGE, }; use http::{HeaderMap, HeaderName, HeaderValue, Request, Response}; + use http_body::Body as _; use http_body_util::BodyExt; use std::convert::Infallible; use std::io::Read; @@ -495,4 +496,16 @@ mod tests { assert_eq!(headers[CONTENT_ENCODING], "gzip"); assert_eq!(decompressed, "Hello, World!"); } + + #[tokio::test] + async fn size_hint_identity() { + let msg = "Hello, world!"; + let svc = service_fn(|_| async { Ok::<_, std::io::Error>(Response::new(Body::from(msg))) }); + let mut svc = Compression::new(svc); + + let req = Request::new(Body::empty()); + let res = svc.ready().await.unwrap().call(req).await.unwrap(); + let body = res.into_body(); + assert_eq!(body.size_hint().exact().unwrap(), msg.len() as u64); + } }