http_types/transfer/
encoding.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use crate::headers::HeaderValue;
use std::fmt::{self, Display};

/// Available compression algorithms.
///
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding#Directives)
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Encoding {
    /// Send a series of chunks.
    Chunked,
    /// The Gzip encoding.
    Gzip,
    /// The Deflate encoding.
    Deflate,
    /// The Brotli encoding.
    Brotli,
    /// The Zstd encoding.
    Zstd,
    /// No encoding.
    Identity,
}

impl Encoding {
    /// Parses a given string into its corresponding encoding.
    pub(crate) fn from_str(s: &str) -> Option<Encoding> {
        let s = s.trim();

        // We're dealing with an empty string.
        if s.is_empty() {
            return None;
        }

        match s {
            "chunked" => Some(Encoding::Chunked),
            "gzip" => Some(Encoding::Gzip),
            "deflate" => Some(Encoding::Deflate),
            "br" => Some(Encoding::Brotli),
            "zstd" => Some(Encoding::Zstd),
            "identity" => Some(Encoding::Identity),
            _ => None,
        }
    }
}

impl Display for Encoding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Encoding::Gzip => write!(f, "gzip"),
            Encoding::Deflate => write!(f, "deflate"),
            Encoding::Brotli => write!(f, "br"),
            Encoding::Zstd => write!(f, "zstd"),
            Encoding::Identity => write!(f, "identity"),
            Encoding::Chunked => write!(f, "chunked"),
        }
    }
}

impl From<Encoding> for HeaderValue {
    fn from(directive: Encoding) -> Self {
        let s = directive.to_string();
        unsafe { HeaderValue::from_bytes_unchecked(s.into_bytes()) }
    }
}