use bytes::Bytes;
use futures::StreamExt as _;
use http::{HeaderMap, HeaderValue};
use web_faith_encoding::{
AcceptEncoding, Coding, DEFAULT_ACCEPT_ENCODING, compress_buffer, decision, decode_stream,
layer_content_encoding, strip_decoded_headers,
};
#[tokio::main]
async fn main() {
let accept = AcceptEncoding::parse(DEFAULT_ACCEPT_ENCODING);
let mut headers = HeaderMap::new();
headers.insert("content-encoding", HeaderValue::from_static("gzip"));
headers.insert("content-length", HeaderValue::from_static("42"));
let coding = decision(&headers, &accept).expect("gzip is in the default Accept-Encoding");
println!("negotiated: {coding:?}");
strip_decoded_headers(&mut headers);
println!("headers after decoding: {:?}", headers.keys().count());
let original = b"the quick brown fox jumps over the lazy dog".repeat(8);
let compressed = compress_buffer(&original, coding)
.await
.expect("gzip compresses");
println!(
"{} bytes in, {} bytes out",
original.len(),
compressed.len()
);
let stream = futures::stream::once(async move { Ok(Bytes::from(compressed)) });
let mut decoded = decode_stream(Box::pin(stream), coding);
let mut round_tripped = Vec::new();
while let Some(chunk) = decoded.next().await {
round_tripped.extend_from_slice(&chunk.expect("the body decodes"));
}
println!("round-tripped intact: {}", round_tripped == original);
println!(
"Content-Encoding: {}",
layer_content_encoding(Some("br"), Coding::Gzip)
);
}