sdp_rs/lines/key/
mod.rs

1//! Types related to the key line (`k=`). Key line is deprecated according to
2//! [RFC8866](https://www.rfc-editor.org/rfc/rfc8866.html).
3
4mod key_method;
5
6/// The key line (`k=`) tokenizer. This is low level stuff and you shouldn't interact directly
7/// with it, unless you know what you are doing.
8pub use crate::tokenizers::key_optvalue::Tokenizer;
9pub use key_method::KeyMethod;
10
11/// The key line (`k=`) of SDP. It can appear in the main session description or in a media
12/// description. Key line is deprecated according to
13/// [RFC8866](https://www.rfc-editor.org/rfc/rfc8866.html) but might appear when working with
14/// legacy stuff.
15#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Clone)]
16pub struct Key {
17    pub method: KeyMethod,
18    pub encryption_key: String,
19}
20
21impl<'a> From<Tokenizer<'a, 'k'>> for Key {
22    fn from(tokenizer: Tokenizer<'a, 'k'>) -> Self {
23        Self {
24            method: tokenizer.key.into(),
25            encryption_key: tokenizer.value.map(Into::into).unwrap_or_default(),
26        }
27    }
28}
29
30impl std::fmt::Display for Key {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        match self.method {
33            KeyMethod::Prompt => write!(f, "k={}", self.method),
34            _ => write!(f, "k={}:{}", self.method, self.encryption_key),
35        }
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn from_tokenizer1() {
45        let tokenizer: Tokenizer<'k'> = ("key", Some("something")).into();
46
47        assert_eq!(
48            Key::from(tokenizer),
49            Key {
50                method: KeyMethod::Other("key".into()),
51                encryption_key: "something".into()
52            }
53        );
54    }
55
56    #[test]
57    fn from_tokenizer2() {
58        let tokenizer: Tokenizer<'k'> = ("clear", Some("something")).into();
59
60        assert_eq!(
61            Key::from(tokenizer),
62            Key {
63                method: KeyMethod::Clear,
64                encryption_key: "something".into()
65            }
66        );
67    }
68
69    #[test]
70    fn from_tokenizer3() {
71        let tokenizer: Tokenizer<'k'> = ("prompt", None).into();
72
73        assert_eq!(
74            Key::from(tokenizer),
75            Key {
76                method: KeyMethod::Prompt,
77                encryption_key: "".into()
78            }
79        );
80    }
81
82    #[test]
83    fn display1() {
84        let key = Key {
85            method: KeyMethod::Clear,
86            encryption_key: "password".into(),
87        };
88
89        assert_eq!(key.to_string(), "k=clear:password");
90    }
91
92    #[test]
93    fn display2() {
94        let key = Key {
95            method: KeyMethod::Prompt,
96            encryption_key: "".into(),
97        };
98
99        assert_eq!(key.to_string(), "k=prompt");
100    }
101}