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
use std::{
borrow::Cow,
fmt::{Display, Formatter, Result as FmtResult},
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(from = "Cow<'_, str>", into = "String")]
pub enum Algorithm {
OlmV1Curve25519AesSha2,
MegolmV1AesSha2,
Custom(String),
#[doc(hidden)]
__Nonexhaustive,
}
impl Display for Algorithm {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
let algorithm_str = match *self {
Algorithm::OlmV1Curve25519AesSha2 => "m.olm.v1.curve25519-aes-sha2",
Algorithm::MegolmV1AesSha2 => "m.megolm.v1.aes-sha2",
Algorithm::Custom(ref algorithm) => algorithm,
Algorithm::__Nonexhaustive => {
panic!("__Nonexhaustive enum variant is not intended for use.")
}
};
write!(f, "{}", algorithm_str)
}
}
impl From<Cow<'_, str>> for Algorithm {
fn from(s: Cow<'_, str>) -> Algorithm {
match &s as &str {
"m.olm.v1.curve25519-aes-sha2" => Algorithm::OlmV1Curve25519AesSha2,
"m.megolm.v1.aes-sha2" => Algorithm::MegolmV1AesSha2,
_ => Algorithm::Custom(s.into_owned()),
}
}
}
impl From<&str> for Algorithm {
fn from(s: &str) -> Algorithm {
Algorithm::from(Cow::Borrowed(s))
}
}
impl From<Algorithm> for String {
fn from(algorithm: Algorithm) -> String {
algorithm.to_string()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::util::serde_json_eq;
#[test]
fn serialize_and_deserialize_from_display_form() {
serde_json_eq(Algorithm::MegolmV1AesSha2, json!("m.megolm.v1.aes-sha2"));
serde_json_eq(
Algorithm::OlmV1Curve25519AesSha2,
json!("m.olm.v1.curve25519-aes-sha2"),
);
serde_json_eq(
Algorithm::Custom("io.ruma.test".to_string()),
json!("io.ruma.test"),
);
}
}