kellnr_settings/
protocol.rs1use serde::{Deserialize, Deserializer, Serialize};
2
3use crate::deserialize_with::DeserializeWith;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
6pub enum Protocol {
7 #[default]
8 Http,
9 Https,
10}
11
12impl std::fmt::Display for Protocol {
13 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14 match self {
15 Protocol::Http => write!(f, "http"),
16 Protocol::Https => write!(f, "https"),
17 }
18 }
19}
20
21impl<'de> Deserialize<'de> for Protocol {
22 fn deserialize<D>(de: D) -> Result<Self, D::Error>
23 where
24 D: Deserializer<'de>,
25 {
26 Protocol::deserialize_with(de)
27 }
28}
29
30impl DeserializeWith for Protocol {
31 fn deserialize_with<'de, D>(de: D) -> Result<Self, D::Error>
32 where
33 D: Deserializer<'de>,
34 {
35 let s = String::deserialize(de)?.to_lowercase();
36
37 match s.as_ref() {
38 "http" => Ok(Protocol::Http),
39 "https" => Ok(Protocol::Https),
40 _ => Err(serde::de::Error::custom(
41 "error trying to deserialize protocol config",
42 )),
43 }
44 }
45}
46
47impl Serialize for Protocol {
48 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
49 where
50 S: serde::Serializer,
51 {
52 match self {
53 Protocol::Http => serializer.serialize_str("http"),
54 Protocol::Https => serializer.serialize_str("https"),
55 }
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use serde::Deserialize;
62
63 use super::*;
64
65 #[test]
66 fn test_protocol_display() {
67 assert_eq!(Protocol::Http.to_string(), "http");
68 assert_eq!(Protocol::Https.to_string(), "https");
69 }
70
71 #[derive(Debug, Deserialize)]
72 struct Settings {
73 #[serde(deserialize_with = "Protocol::deserialize_with")]
74 protocol: Protocol,
75 }
76
77 #[test]
78 fn test_deserialize_protocol_https() {
79 let toml = r#"
80 protocol = "https"
81 "#;
82
83 let settings: Settings = toml::from_str(toml).unwrap();
84 assert_eq!(settings.protocol, Protocol::Https);
85 }
86
87 #[test]
88 fn test_deserialize_protocol_http() {
89 let toml = r#"
90 protocol = "http"
91 "#;
92
93 let settings: Settings = toml::from_str(toml).unwrap();
94 assert_eq!(settings.protocol, Protocol::Http);
95 }
96
97 #[test]
98 fn test_deserialize_protocol_uppercase() {
99 let toml = r#"
100 protocol = "HTTPS"
101 "#;
102
103 let settings: Settings = toml::from_str(toml).unwrap();
104 assert_eq!(settings.protocol, Protocol::Https);
105 }
106
107 #[test]
108 fn test_deserialize_protocol_error() {
109 let toml = r#"
110 protocol = "ftp"
111 "#;
112
113 let settings: Result<Settings, toml::de::Error> = toml::from_str(toml);
114 assert!(settings.is_err());
115 }
116
117 #[test]
118 fn test_serialize_protocol_http() {
119 let protocol = Protocol::Http;
120 let json = serde_json::to_string(&protocol).unwrap();
121 assert_eq!(json, r#""http""#);
122 }
123
124 #[test]
125 fn test_serialize_protocol_https() {
126 let protocol = Protocol::Https;
127 let json = serde_json::to_string(&protocol).unwrap();
128 assert_eq!(json, r#""https""#);
129 }
130}