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