From 9a6f6fe2411bdaa1a96e5c8c8a584f405ada1d2a Mon Sep 17 00:00:00 2001 From: ducaale Date: Fri, 15 Apr 2022 19:44:28 +0100 Subject: [PATCH] improve errors from decompressing response body --- src/utils.rs | 44 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/src/utils.rs b/src/utils.rs index e9655dd9..d476be2e 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -63,15 +63,45 @@ pub fn get_compression_type(headers: &HeaderMap) -> Option { compression_type } -pub fn decompress<'a>( - reader: &'a mut impl Read, +enum Decoder +where + R: Read, +{ + PlainText(R), + Gzip(GzDecoder), + Deflate(ZlibDecoder), + Brotli(BrotliDecoder), +} + +impl Read for Decoder +where + R: Read, +{ + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match self { + Decoder::PlainText(decoder) => decoder.read(buf), + Decoder::Gzip(decoder) => decoder.read(buf).map_err(|e| { + io::Error::new(e.kind(), format!("error decoding response body: {}", e)) + }), + Decoder::Deflate(decoder) => decoder.read(buf).map_err(|e| { + io::Error::new(e.kind(), format!("error decoding response body: {}", e)) + }), + Decoder::Brotli(decoder) => decoder.read(buf).map_err(|e| { + io::Error::new(e.kind(), format!("error decoding response body: {}", e)) + }), + } + } +} + +pub fn decompress( + reader: &mut impl Read, compression_type: Option, -) -> Box { +) -> impl Read + '_ { match compression_type { - Some(CompressionType::Gzip) => Box::new(GzDecoder::new(reader)), - Some(CompressionType::Deflate) => Box::new(ZlibDecoder::new(reader)), - Some(CompressionType::Brotli) => Box::new(BrotliDecoder::new(reader, 4096)), - None => Box::new(reader), + Some(CompressionType::Gzip) => Decoder::Gzip(GzDecoder::new(reader)), + Some(CompressionType::Deflate) => Decoder::Deflate(ZlibDecoder::new(reader)), + Some(CompressionType::Brotli) => Decoder::Brotli(BrotliDecoder::new(reader, 4096)), + None => Decoder::PlainText(reader), } }