1use std::{
2 convert::Infallible,
3 fmt::{self, Display, Formatter},
4 str::FromStr,
5};
6
7#[derive(Clone)]
12pub struct EncryptionKey {
13 method: String,
14 key: Option<String>,
15}
16
17impl EncryptionKey {
18 #[inline]
20 pub fn new<M>(method: M) -> Self
21 where
22 M: ToString,
23 {
24 Self {
25 method: method.to_string(),
26 key: None,
27 }
28 }
29
30 #[inline]
32 pub fn new_with_key<M, K>(method: M, key: K) -> Self
33 where
34 M: ToString,
35 K: ToString,
36 {
37 Self {
38 method: method.to_string(),
39 key: Some(key.to_string()),
40 }
41 }
42
43 #[inline]
45 pub fn method(&self) -> &str {
46 &self.method
47 }
48
49 #[inline]
51 pub fn key(&self) -> Option<&str> {
52 self.key.as_deref()
53 }
54}
55
56impl Display for EncryptionKey {
57 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
58 f.write_str(&self.method)?;
59
60 if let Some(k) = self.key.as_ref() {
61 write!(f, ":{k}")?;
62 }
63
64 Ok(())
65 }
66}
67
68impl FromStr for EncryptionKey {
69 type Err = Infallible;
70
71 fn from_str(s: &str) -> Result<Self, Self::Err> {
72 let (method, key) = if let Some(colon) = s.find(':') {
73 let (m, r) = s.split_at(colon);
74
75 let k = &r[1..];
76
77 (m.to_string(), Some(k.to_string()))
78 } else {
79 (s.to_string(), None)
80 };
81
82 let res = Self { method, key };
83
84 Ok(res)
85 }
86}