Refactor into_string body reading

This commit is contained in:
Martin Algesten
2021-03-25 17:37:11 +01:00
parent 7c6ed53df3
commit 3cfa9e6b35

View File

@@ -334,36 +334,29 @@ impl Response {
/// I.e. `Content-Length: text/plain; charset=iso-8859-1` would be decoded in latin-1. /// I.e. `Content-Length: text/plain; charset=iso-8859-1` would be decoded in latin-1.
/// ///
pub fn into_string(self) -> io::Result<String> { pub fn into_string(self) -> io::Result<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<u8> = 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")] #[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<u8> = 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); let (text, _, _) = encoding.decode(&buf);
Ok(text.into_owned()) Ok(text.into_owned())
} }
#[cfg(not(feature = "charset"))] #[cfg(not(feature = "charset"))]
{ {
let mut buf: Vec<u8> = 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()) Ok(String::from_utf8_lossy(&buf).to_string())
} }
} }