http_stat/
decompress.rs

1// Copyright 2025 Tree xie.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// This file implements HTTP request functionality with support for HTTP/1.1, HTTP/2, and HTTP/3
16// It includes features like DNS resolution, TLS handshake, and request/response handling
17
18use super::error::{Error, Result};
19use brotli_decompressor::Decompressor;
20use bytes::Bytes;
21use flate2::read::GzDecoder;
22use zstd::Decoder;
23
24// Decompress gzip data
25fn decompress_gzip(data: &[u8]) -> Result<Bytes> {
26    let mut decoder = GzDecoder::new(data);
27    let mut decompressed = Vec::new();
28    std::io::Read::read_to_end(&mut decoder, &mut decompressed).map_err(|e| Error::Common {
29        category: "gzip".to_string(),
30        message: format!("Failed to decompress gzip data: {e}"),
31    })?;
32    Ok(Bytes::from(decompressed))
33}
34
35fn decompress_brotli(data: &[u8]) -> Result<Bytes> {
36    let mut decompressor = Decompressor::new(data, 4096);
37    let mut decompressed = Vec::new();
38    std::io::Read::read_to_end(&mut decompressor, &mut decompressed).map_err(|e| {
39        Error::Common {
40            category: "brotli".to_string(),
41            message: format!("Failed to decompress brotli data: {e}"),
42        }
43    })?;
44    Ok(Bytes::from(decompressed))
45}
46
47fn decompress_zstd(data: &[u8]) -> Result<Bytes> {
48    let mut decompressor = Decoder::new(data).map_err(|e| Error::Common {
49        category: "zstd".to_string(),
50        message: format!("Failed to create zstd decoder: {e}"),
51    })?;
52    let mut decompressed = Vec::new();
53    std::io::Read::read_to_end(&mut decompressor, &mut decompressed).map_err(|e| {
54        Error::Common {
55            category: "zstd".to_string(),
56            message: format!("Failed to decompress zstd data: {e}"),
57        }
58    })?;
59    Ok(Bytes::from(decompressed))
60}
61
62pub fn decompress(encoding: &str, data: &Bytes) -> Result<Bytes> {
63    match encoding {
64        "gzip" => decompress_gzip(data),
65        "br" => decompress_brotli(data),
66        "zstd" => decompress_zstd(data),
67        _ => Ok(data.clone()),
68    }
69}