From 4c21e640d40da60082105850a59b6f295eda04e4 Mon Sep 17 00:00:00 2001 From: qwerty2501 <939468+qwerty2501@users.noreply.github.com> Date: Fri, 15 Jul 2022 00:36:22 +0900 Subject: [PATCH] optimize into_bytes buffer and into_json capacity by body len --- src/body.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/body.rs b/src/body.rs index ac1acfc7..61e25422 100644 --- a/src/body.rs +++ b/src/body.rs @@ -176,7 +176,8 @@ impl Body { /// # Ok(()) }) } /// ``` pub async fn into_bytes(mut self) -> crate::Result> { - let mut buf = Vec::with_capacity(1024); + let len = usize::try_from(self.len().unwrap_or(0)).status(StatusCode::PayloadTooLarge)?; + let mut buf = Vec::with_capacity(len); self.read_to_end(&mut buf) .await .status(StatusCode::UnprocessableEntity)?; @@ -280,9 +281,8 @@ impl Body { /// # Ok(()) }) } /// ``` #[cfg(feature = "serde")] - pub async fn into_json(mut self) -> crate::Result { - let mut buf = Vec::with_capacity(1024); - self.read_to_end(&mut buf).await?; + pub async fn into_json(self) -> crate::Result { + let buf = self.into_bytes().await?; serde_json::from_slice(&buf).status(StatusCode::UnprocessableEntity) }