ns_axum_web/
encoding.rs

1use axum::http::header;
2use libflate::gzip::{Decoder, Encoder};
3use std::{io, string::ToString};
4
5// recommended minimum size for compression.
6pub const MIN_ENCODING_SIZE: u16 = 128;
7
8#[derive(Debug, PartialEq, Eq, Clone, Copy)]
9pub enum Encoding {
10    Zstd,
11    Gzip,
12    Identity,
13}
14
15impl ToString for Encoding {
16    fn to_string(&self) -> String {
17        match self {
18            Self::Zstd => "zstd".to_string(),
19            Self::Gzip => "gzip".to_string(),
20            Self::Identity => "identity".to_string(),
21        }
22    }
23}
24
25impl Encoding {
26    pub fn identity(&self) -> bool {
27        matches!(self, Self::Identity)
28    }
29
30    pub fn from_header_value(val: Option<&header::HeaderValue>) -> Self {
31        if let Some(val) = val {
32            if let Ok(val) = val.to_str() {
33                if val.contains("zstd") {
34                    return Self::Zstd;
35                } else if val.contains("gzip") {
36                    return Self::Gzip;
37                }
38            }
39        }
40        Self::Identity
41    }
42
43    pub fn header_value(&self) -> header::HeaderValue {
44        match self {
45            Self::Zstd => header::HeaderValue::from_static("zstd"),
46            Self::Gzip => header::HeaderValue::from_static("gzip"),
47            Self::Identity => header::HeaderValue::from_static("identity"),
48        }
49    }
50
51    pub fn encode_all<R: io::Read>(&self, r: R) -> Result<Vec<u8>, io::Error> {
52        match self {
53            Self::Zstd => {
54                let buf = zstd::stream::encode_all(r, 9)?;
55                Ok(buf)
56            }
57            Self::Gzip => {
58                let mut encoder = Encoder::new(Vec::new())?;
59                let mut r = r;
60                let _ = io::copy(&mut r, &mut encoder);
61                encoder.finish().into_result()
62            }
63            Self::Identity => Err(io::Error::new(
64                io::ErrorKind::Unsupported,
65                "identity encoding not supported",
66            )),
67        }
68    }
69
70    pub fn decode_all<R: io::Read>(&self, r: R) -> Result<Vec<u8>, io::Error> {
71        use io::Read;
72        match self {
73            Self::Zstd => {
74                let buf = zstd::stream::decode_all(r)?;
75                Ok(buf)
76            }
77            Self::Gzip => {
78                let mut decoder = Decoder::new(r)?;
79                let mut buf = Vec::new();
80                decoder.read_to_end(&mut buf)?;
81                Ok(buf)
82            }
83            Self::Identity => Err(io::Error::new(
84                io::ErrorKind::Unsupported,
85                "identity decoding not supported",
86            )),
87        }
88    }
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94
95    #[test]
96    fn gzip_encode_decode() {
97        let enc = Encoding::from_header_value(Some(&Encoding::Gzip.header_value()));
98        assert_eq!(enc, Encoding::Gzip);
99
100        let data = r#"[{"id":"------","texts":[]},{"id":"Esp9G6","texts":["Stream:"]},{"id": "------","texts":[]},{"id":"ykuRdu","texts":["Internet Engineering Task Force (IETF)"]}]"#;
101
102        let encoded = enc.encode_all(data.as_bytes()).unwrap();
103        println!("{}, {}", data.len(), encoded.len());
104        assert!(encoded.len() < data.len());
105
106        let decoded = enc.decode_all(encoded.as_slice()).unwrap();
107        assert_eq!(data.as_bytes(), decoded.as_slice());
108    }
109
110    #[test]
111    fn zstd_encode_decode() {
112        let enc = Encoding::from_header_value(Some(&Encoding::Zstd.header_value()));
113        assert_eq!(enc, Encoding::Zstd);
114
115        let data = r#"[{"id":"------","texts":[]},{"id":"Esp9G6","texts":["Stream:"]},{"id": "------","texts":[]},{"id":"ykuRdu","texts":["Internet Engineering Task Force (IETF)"]}]"#;
116
117        let encoded = enc.encode_all(data.as_bytes()).unwrap();
118        println!("{}, {}", data.len(), encoded.len());
119        assert!(encoded.len() < data.len());
120
121        let decoded = enc.decode_all(encoded.as_slice()).unwrap();
122        assert_eq!(data.as_bytes(), decoded.as_slice());
123    }
124}