http_types/transfer/
encoding.rs

1use crate::headers::HeaderValue;
2use std::fmt::{self, Display};
3
4/// Available compression algorithms.
5///
6/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding#Directives)
7#[non_exhaustive]
8#[derive(Debug, Clone, Copy, Eq, PartialEq)]
9pub enum Encoding {
10    /// Send a series of chunks.
11    Chunked,
12    /// The Gzip encoding.
13    Gzip,
14    /// The Deflate encoding.
15    Deflate,
16    /// The Brotli encoding.
17    Brotli,
18    /// The Zstd encoding.
19    Zstd,
20    /// No encoding.
21    Identity,
22}
23
24impl Encoding {
25    /// Parses a given string into its corresponding encoding.
26    pub(crate) fn from_str(s: &str) -> Option<Encoding> {
27        let s = s.trim();
28
29        // We're dealing with an empty string.
30        if s.is_empty() {
31            return None;
32        }
33
34        match s {
35            "chunked" => Some(Encoding::Chunked),
36            "gzip" => Some(Encoding::Gzip),
37            "deflate" => Some(Encoding::Deflate),
38            "br" => Some(Encoding::Brotli),
39            "zstd" => Some(Encoding::Zstd),
40            "identity" => Some(Encoding::Identity),
41            _ => None,
42        }
43    }
44}
45
46impl Display for Encoding {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self {
49            Encoding::Gzip => write!(f, "gzip"),
50            Encoding::Deflate => write!(f, "deflate"),
51            Encoding::Brotli => write!(f, "br"),
52            Encoding::Zstd => write!(f, "zstd"),
53            Encoding::Identity => write!(f, "identity"),
54            Encoding::Chunked => write!(f, "chunked"),
55        }
56    }
57}
58
59impl From<Encoding> for HeaderValue {
60    fn from(directive: Encoding) -> Self {
61        let s = directive.to_string();
62        unsafe { HeaderValue::from_bytes_unchecked(s.into_bytes()) }
63    }
64}