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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use std::{
    convert::Infallible,
    fmt::{self, Display, Formatter},
    str::FromStr,
};

/// Encryption key field.
///
/// # Note
/// This field is considered obsolete by RFC 8866.
#[derive(Clone)]
pub struct EncryptionKey {
    method: String,
    key: Option<String>,
}

impl EncryptionKey {
    /// Create a new method-only encryption key field.
    #[inline]
    pub fn new<M>(method: M) -> Self
    where
        M: ToString,
    {
        Self {
            method: method.to_string(),
            key: None,
        }
    }

    /// Create a new encryption key field.
    #[inline]
    pub fn new_with_key<M, K>(method: M, key: K) -> Self
    where
        M: ToString,
        K: ToString,
    {
        Self {
            method: method.to_string(),
            key: Some(key.to_string()),
        }
    }

    /// Get the method for obtaining the encryption key.
    #[inline]
    pub fn method(&self) -> &str {
        &self.method
    }

    /// Get the encryption key (if any).
    #[inline]
    pub fn key(&self) -> Option<&str> {
        self.key.as_deref()
    }
}

impl Display for EncryptionKey {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str(&self.method)?;

        if let Some(k) = self.key.as_ref() {
            write!(f, ":{}", k)?;
        }

        Ok(())
    }
}

impl FromStr for EncryptionKey {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (method, key) = if let Some(colon) = s.find(':') {
            let (m, r) = s.split_at(colon);

            let k = &r[1..];

            (m.to_string(), Some(k.to_string()))
        } else {
            (s.to_string(), None)
        };

        let res = Self { method, key };

        Ok(res)
    }
}