identity_verification/verification_method/
method_type.rs1use core::fmt::Display;
5use core::fmt::Formatter;
6use core::str::FromStr;
7use std::borrow::Cow;
8
9use crate::error::Error;
10use crate::error::Result;
11
12const ED25519_VERIFICATION_KEY_2018_STR: &str = "Ed25519VerificationKey2018";
13const X25519_KEY_AGREEMENT_KEY_2019_STR: &str = "X25519KeyAgreementKey2019";
14const JSON_WEB_KEY_METHOD_TYPE: &str = "JsonWebKey";
15const JSON_WEB_KEY_2020_STR: &str = "JsonWebKey2020";
16
17#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
19pub struct MethodType(Cow<'static, str>);
20
21impl MethodType {
22 pub const ED25519_VERIFICATION_KEY_2018: Self = Self(Cow::Borrowed(ED25519_VERIFICATION_KEY_2018_STR));
24 pub const X25519_KEY_AGREEMENT_KEY_2019: Self = Self(Cow::Borrowed(X25519_KEY_AGREEMENT_KEY_2019_STR));
26 #[deprecated(since = "1.3.0", note = "use JSON_WEB_KEY_2020 instead")]
29 pub const JSON_WEB_KEY: Self = Self(Cow::Borrowed(JSON_WEB_KEY_METHOD_TYPE));
30 pub const JSON_WEB_KEY_2020: Self = Self(Cow::Borrowed(JSON_WEB_KEY_2020_STR));
33 pub fn custom(type_: impl AsRef<str>) -> Self {
35 Self(Cow::Owned(type_.as_ref().to_owned()))
36 }
37}
38
39impl MethodType {
40 pub fn as_str(&self) -> &str {
42 &self.0
43 }
44}
45
46impl AsRef<str> for MethodType {
47 fn as_ref(&self) -> &str {
48 self.0.as_ref()
49 }
50}
51
52impl Display for MethodType {
53 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
54 f.write_str(self.as_str())
55 }
56}
57
58impl FromStr for MethodType {
59 type Err = Error;
60
61 fn from_str(string: &str) -> Result<Self, Self::Err> {
62 match string {
63 ED25519_VERIFICATION_KEY_2018_STR => Ok(Self::ED25519_VERIFICATION_KEY_2018),
64 X25519_KEY_AGREEMENT_KEY_2019_STR => Ok(Self::X25519_KEY_AGREEMENT_KEY_2019),
65 JSON_WEB_KEY_METHOD_TYPE => Ok(
66 #[allow(deprecated)]
67 Self::JSON_WEB_KEY,
68 ),
69 JSON_WEB_KEY_2020_STR => Ok(Self::JSON_WEB_KEY_2020),
70 _ => Ok(Self(Cow::Owned(string.to_owned()))),
71 }
72 }
73}
74
75#[cfg(test)]
76mod tests {
77 use serde_json::Value;
78
79 use super::*;
80
81 #[test]
82 fn test_method_type_serde() {
83 for method_type in [
84 MethodType::ED25519_VERIFICATION_KEY_2018,
85 MethodType::X25519_KEY_AGREEMENT_KEY_2019,
86 MethodType::JSON_WEB_KEY_2020,
87 ] {
88 let ser: Value = serde_json::to_value(method_type.clone()).unwrap();
89 assert_eq!(ser.as_str().unwrap(), method_type.as_str());
90 let de: MethodType = serde_json::from_value(ser.clone()).unwrap();
91 assert_eq!(de, method_type);
92
93 assert_eq!(MethodType::from_str(method_type.as_str()).unwrap(), method_type);
94 assert_eq!(MethodType::from_str(ser.as_str().unwrap()).unwrap(), method_type);
95 }
96 }
97}