From 3cfa9e6b355cac69fdf0d2a2eda5044a5811406a Mon Sep 17 00:00:00 2001 From: Martin Algesten Date: Thu, 25 Mar 2021 17:37:11 +0100 Subject: [PATCH] Refactor into_string body reading --- src/response.rs | 39 ++++++++++++++++----------------------- 1 file changed, 16 insertions(+), 23 deletions(-) diff --git a/src/response.rs b/src/response.rs index 922cba1..25f3adf 100644 --- a/src/response.rs +++ b/src/response.rs @@ -334,36 +334,29 @@ impl Response { /// I.e. `Content-Length: text/plain; charset=iso-8859-1` would be decoded in latin-1. /// pub fn into_string(self) -> io::Result { + #[cfg(feature = "charset")] + let encoding = Encoding::for_label(self.charset().as_bytes()) + .or_else(|| Encoding::for_label(DEFAULT_CHARACTER_SET.as_bytes())) + .unwrap(); + + let mut buf: Vec = vec![]; + self.into_reader() + .take((INTO_STRING_LIMIT + 1) as u64) + .read_to_end(&mut buf)?; + if buf.len() > INTO_STRING_LIMIT { + return Err(io::Error::new( + io::ErrorKind::Other, + "response too big for into_string", + )); + } + #[cfg(feature = "charset")] { - let encoding = Encoding::for_label(self.charset().as_bytes()) - .or_else(|| Encoding::for_label(DEFAULT_CHARACTER_SET.as_bytes())) - .unwrap(); - let mut buf: Vec = vec![]; - self.into_reader() - .take((INTO_STRING_LIMIT + 1) as u64) - .read_to_end(&mut buf)?; - if buf.len() > INTO_STRING_LIMIT { - return Err(io::Error::new( - io::ErrorKind::Other, - "response too big for into_string", - )); - } let (text, _, _) = encoding.decode(&buf); Ok(text.into_owned()) } #[cfg(not(feature = "charset"))] { - let mut buf: Vec = vec![]; - self.into_reader() - .take((INTO_STRING_LIMIT + 1) as u64) - .read_to_end(&mut buf)?; - if buf.len() > INTO_STRING_LIMIT { - return Err(io::Error::new( - io::ErrorKind::Other, - "response too big for into_string", - )); - } Ok(String::from_utf8_lossy(&buf).to_string()) } }