pub(crate) trait ResponseCompression {
fn content_encoding<'a>(&'a self) -> Option<&'a str>;
fn content_type<'a>(&'a self) -> Option<&'a str>;
#[cfg(feature = "br")]
fn can_brotli_compress(&self) -> bool {
if self.content_encoding().is_some() {
return false;
}
if let Some(header_val) = self.content_type() {
let ctype = header_val.trim().to_ascii_lowercase();
ctype.starts_with("text/")
|| ctype.starts_with("application/json")
|| ctype.starts_with("application/xhtml")
|| ctype.starts_with("application/xml")
|| ctype.starts_with("application/wasm")
|| ctype.starts_with("image/svg")
} else {
false
}
}
#[cfg(not(feature = "br"))]
fn can_brotli_compress(&self) -> bool {
false
}
}
#[cfg(feature = "br")]
pub(crate) fn compress_response_body<'a>(body: &[u8]) -> String {
let cfg = brotli::enc::BrotliEncoderParams {
quality: 4,
..Default::default()
};
let mut body_reader = std::io::Cursor::new(body);
let mut compressed_base64 = base64::write::EncoderStringWriter::new(base64::STANDARD);
let _sz = brotli::BrotliCompress(&mut body_reader, &mut compressed_base64, &cfg);
compressed_base64.into_inner()
}
#[cfg(not(feature = "br"))]
pub(crate) fn compress_response_body<'a>(body: &[u8]) -> String {
base64::encode(body)
}