Skip to main content

base_web_multipart/
content_transfer_encoding.rs

1// Released under the MIT License.
2// Copyright, 2026, by Samuel Williams.
3
4use base_message::{FieldType, FieldValueError, ascii_text, combination::Singleton};
5
6/// A part's `Content-Transfer-Encoding` field, limited to the identity encodings of RFC 2045 section 6, under which content is passed as it was written.
7///
8/// This crate does not decode content, so `base64` and `quoted-printable`, and any other encoding, are invalid values: content in them would otherwise be read as if it were not encoded. RFC 7578 section 4.7 deprecates the field for form data.
9///
10/// ```
11/// use base_web_multipart::ContentTransferEncoding;
12/// use base_message::FieldType;
13///
14/// assert_eq!(ContentTransferEncoding::parse(b"Binary"), Ok(ContentTransferEncoding::Binary));
15/// assert!(ContentTransferEncoding::parse(b"base64").is_err());
16/// ```
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub enum ContentTransferEncoding {
19    /// `7bit`: lines of ASCII.
20    SevenBit,
21    /// `8bit`: lines that may have bytes above ASCII.
22    EightBit,
23    /// `binary`: any bytes.
24    Binary,
25}
26
27impl ContentTransferEncoding {
28    /// The encoding's name, as it is written.
29    pub fn as_str(self) -> &'static str {
30        match self {
31            Self::SevenBit => "7bit",
32            Self::EightBit => "8bit",
33            Self::Binary => "binary",
34        }
35    }
36}
37
38impl std::fmt::Display for ContentTransferEncoding {
39    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        formatter.write_str(self.as_str())
41    }
42}
43
44impl FieldType<'_> for ContentTransferEncoding {
45    type Combination = Singleton;
46
47    fn parse(value: &[u8]) -> Result<Self, FieldValueError> {
48        let text = ascii_text(value)?;
49        [Self::SevenBit, Self::EightBit, Self::Binary]
50            .into_iter()
51            .find(|encoding| encoding.as_str().eq_ignore_ascii_case(text))
52            .ok_or(FieldValueError::new(
53                "unsupported content transfer encoding",
54            ))
55    }
56}