winget_types/installer/
protocol.rs1use core::{fmt, str::FromStr};
2
3use compact_str::CompactString;
4use thiserror::Error;
5
6#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8#[cfg_attr(feature = "serde", serde(try_from = "CompactString"))]
9#[repr(transparent)]
10pub struct Protocol(CompactString);
11
12#[derive(Debug, Error, Eq, PartialEq)]
13pub enum ProtocolError {
14 #[error("Protocol must not be empty")]
15 Empty,
16 #[error(
17 "Protocol must not have more than {} characters but has {_0}",
18 Protocol::MAX_CHAR_LENGTH
19 )]
20 TooLong(usize),
21}
22
23impl Protocol {
24 pub const MAX_CHAR_LENGTH: usize = 2048;
25
26 pub fn new<T: AsRef<str> + Into<CompactString>>(protocol: T) -> Result<Self, ProtocolError> {
47 let channel_str = protocol.as_ref();
48
49 if channel_str.is_empty() {
50 return Err(ProtocolError::Empty);
51 }
52
53 let char_count = channel_str.chars().count();
54 if char_count > Self::MAX_CHAR_LENGTH {
55 return Err(ProtocolError::TooLong(char_count));
56 }
57
58 Ok(Self(protocol.into()))
59 }
60
61 #[must_use]
68 #[inline]
69 pub unsafe fn new_unchecked<T: Into<CompactString>>(protocol: T) -> Self {
70 Self(protocol.into())
71 }
72
73 #[must_use]
75 #[inline]
76 pub fn as_str(&self) -> &str {
77 self.0.as_str()
78 }
79}
80
81impl AsRef<str> for Protocol {
82 #[inline]
83 fn as_ref(&self) -> &str {
84 self.as_str()
85 }
86}
87
88impl fmt::Display for Protocol {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 self.0.fmt(f)
91 }
92}
93
94impl FromStr for Protocol {
95 type Err = ProtocolError;
96
97 #[inline]
98 fn from_str(s: &str) -> Result<Self, Self::Err> {
99 Self::new(s)
100 }
101}
102
103impl TryFrom<CompactString> for Protocol {
104 type Error = ProtocolError;
105
106 #[inline]
107 fn try_from(value: CompactString) -> Result<Self, Self::Error> {
108 Self::new(value)
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 #[cfg(feature = "serde")]
115 #[test]
116 fn serialize_protocol() {
117 use indoc::indoc;
118
119 use super::Protocol;
120
121 assert_eq!(
122 serde_yaml::to_string(&Protocol::new("ftp").unwrap()).unwrap(),
123 indoc! {"
124 ftp
125 "}
126 );
127 }
128
129 #[cfg(feature = "serde")]
130 #[test]
131 fn deserialize_protocol() {
132 use indoc::indoc;
133
134 use super::Protocol;
135
136 assert_eq!(
137 serde_yaml::from_str::<Protocol>(&indoc! {"
138 ftp
139 "})
140 .unwrap(),
141 Protocol::new("ftp").unwrap(),
142 );
143 }
144}