deboa_extras/io/
gzip.rs

1use std::io::{Read, Write};
2
3use bytes::{Buf, Bytes};
4use deboa::{
5    errors::{DeboaError, IoError},
6    fs::io::{Compressor, Decompressor},
7    request::DeboaRequest,
8    response::DeboaResponse,
9    Result,
10};
11use flate2::{read::GzDecoder, write::GzEncoder};
12
13#[derive(PartialEq)]
14pub struct GzipCompressor;
15
16#[deboa::async_trait]
17impl Compressor for GzipCompressor {
18    fn name(&self) -> String {
19        "gzip".to_string()
20    }
21
22    async fn compress_body(&self, request: &DeboaRequest) -> Result<Bytes> {
23        let mut writer = GzEncoder::new(Vec::new(), flate2::Compression::default());
24        let result = writer.write_all(request.raw_body().as_ref());
25
26        if let Err(e) = result {
27            return Err(DeboaError::Io(IoError::Compress {
28                message: e.to_string(),
29            }));
30        }
31
32        let result = writer.finish();
33
34        if let Err(e) = result {
35            return Err(DeboaError::Io(IoError::Compress {
36                message: e.to_string(),
37            }));
38        }
39
40        Ok(Bytes::from(result.unwrap()))
41    }
42}
43
44#[derive(PartialEq)]
45pub struct GzipDecompressor;
46
47#[deboa::async_trait]
48impl Decompressor for GzipDecompressor {
49    fn name(&self) -> String {
50        "gzip".to_string()
51    }
52
53    async fn decompress_body(&self, response: &mut DeboaResponse) -> Result<()> {
54        let body = response.raw_body().await;
55        let mut reader = GzDecoder::new(body.reader());
56        let mut buffer = Vec::new();
57        let result = reader.read_to_end(&mut buffer);
58
59        if let Err(e) = result {
60            return Err(DeboaError::Io(IoError::Decompress {
61                message: e.to_string(),
62            }));
63        }
64
65        response.set_raw_body(Bytes::from(buffer));
66        Ok(())
67    }
68}