Skip to main content

agp_config/grpc/
compression.rs

1// Copyright AGNTCY Contributors (https://github.com/agntcy)
2// SPDX-License-Identifier: Apache-2.0
3
4use std::fmt;
5use std::str::FromStr;
6
7use serde::Deserialize;
8
9/// CompressionType represents the supported compression types for gRPC messages.
10/// The supported types are: Gzip, Zlib, Deflate, Snappy, Zstd, Lz4, None, and Empty.
11/// The default type is None.
12#[derive(Debug, Deserialize, PartialEq, Clone, Default)]
13pub enum CompressionType {
14    Gzip,
15    Zlib,
16    Deflate,
17    Snappy,
18    Zstd,
19    Lz4,
20    #[default]
21    None,
22    Empty,
23}
24
25impl CompressionType {
26    /// Determines if the compression type is considered "compressed"
27    pub fn is_compressed(&self) -> bool {
28        *self != CompressionType::None && *self != CompressionType::Empty
29    }
30}
31
32/// Implement the FromStr trait to handle string conversion and parsing
33impl FromStr for CompressionType {
34    type Err = CompressionError;
35
36    fn from_str(s: &str) -> Result<Self, Self::Err> {
37        match s {
38            "gzip" => Ok(CompressionType::Gzip),
39            "zlib" => Ok(CompressionType::Zlib),
40            "deflate" => Ok(CompressionType::Deflate),
41            "snappy" => Ok(CompressionType::Snappy),
42            "zstd" => Ok(CompressionType::Zstd),
43            "lz4" => Ok(CompressionType::Lz4),
44            "none" => Ok(CompressionType::None),
45            "" => Ok(CompressionType::Empty),
46            _ => Err(CompressionError::UnsupportedType(s.to_string())),
47        }
48    }
49}
50
51/// Custom error type for handling unsupported compression types
52#[derive(Debug)]
53pub enum CompressionError {
54    UnsupportedType(String),
55}
56
57/// Implement the Display trait for better error messages.
58impl fmt::Display for CompressionError {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        match self {
61            CompressionError::UnsupportedType(t) => {
62                write!(f, "unsupported compression type {:?}", t)
63            }
64        }
65    }
66}