Skip to main content

use_endpoint/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7/// Error returned when API primitive text or labels are invalid.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10    /// The supplied value was empty after trimming.
11    Empty,
12    /// The supplied value used syntax this crate rejects.
13    Invalid,
14    /// The supplied label was not recognized.
15    Unknown,
16}
17
18impl fmt::Display for ApiPrimitiveError {
19    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            Self::Empty => formatter.write_str("API primitive value cannot be empty"),
22            Self::Invalid => formatter.write_str("invalid API primitive value"),
23            Self::Unknown => formatter.write_str("unknown API primitive label"),
24        }
25    }
26}
27
28impl Error for ApiPrimitiveError {}
29
30fn validate_api_text(value: &str) -> Result<&str, ApiPrimitiveError> {
31    let trimmed = value.trim();
32    if trimmed.is_empty() {
33        return Err(ApiPrimitiveError::Empty);
34    }
35    if trimmed.chars().any(char::is_control) {
36        return Err(ApiPrimitiveError::Invalid);
37    }
38    Ok(trimmed)
39}
40
41macro_rules! text_newtype {
42    ($name:ident) => {
43        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44        pub struct $name(String);
45
46        impl $name {
47            /// Creates validated text metadata.
48            ///
49            /// # Errors
50            ///
51            /// Returns [ApiPrimitiveError] when the value is empty or contains control characters.
52            pub fn new(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
53                validate_api_text(value.as_ref()).map(|value| Self(value.to_owned()))
54            }
55
56            /// Parses validated text metadata.
57            ///
58            /// # Errors
59            ///
60            /// Returns [ApiPrimitiveError] when validation fails.
61            pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62                Self::new(value)
63            }
64
65            /// Returns the stored text.
66            #[must_use]
67            pub fn as_str(&self) -> &str {
68                &self.0
69            }
70
71            /// Consumes the value and returns the stored text.
72            #[must_use]
73            pub fn into_string(self) -> String {
74                self.0
75            }
76        }
77
78        impl AsRef<str> for $name {
79            fn as_ref(&self) -> &str {
80                self.as_str()
81            }
82        }
83
84        impl fmt::Display for $name {
85            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86                formatter.write_str(self.as_str())
87            }
88        }
89
90        impl FromStr for $name {
91            type Err = ApiPrimitiveError;
92
93            fn from_str(value: &str) -> Result<Self, Self::Err> {
94                Self::new(value)
95            }
96        }
97
98        impl TryFrom<&str> for $name {
99            type Error = ApiPrimitiveError;
100
101            fn try_from(value: &str) -> Result<Self, Self::Error> {
102                Self::new(value)
103            }
104        }
105    };
106}
107
108text_newtype!(EndpointName);
109text_newtype!(EndpointPath);
110text_newtype!(EndpointId);
111text_newtype!(EndpointGroup);
112
113/// Endpoint status labels.
114#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115pub enum EndpointStatus {
116    /// A stable label variant.
117    Active,
118    /// A stable label variant.
119    Deprecated,
120    /// A stable label variant.
121    Experimental,
122    /// A stable label variant.
123    Disabled,
124}
125
126impl EndpointStatus {
127    /// Returns the stable label.
128    #[must_use]
129    pub const fn as_str(self) -> &'static str {
130        match self {
131            Self::Active => "active",
132            Self::Deprecated => "deprecated",
133            Self::Experimental => "experimental",
134            Self::Disabled => "disabled",
135        }
136    }
137}
138
139impl Default for EndpointStatus {
140    fn default() -> Self {
141        Self::Active
142    }
143}
144
145impl fmt::Display for EndpointStatus {
146    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
147        formatter.write_str(self.as_str())
148    }
149}
150
151impl FromStr for EndpointStatus {
152    type Err = ApiPrimitiveError;
153
154    fn from_str(value: &str) -> Result<Self, Self::Err> {
155        let trimmed = value.trim();
156        if trimmed.is_empty() {
157            return Err(ApiPrimitiveError::Empty);
158        }
159        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
160        match normalized.as_str() {
161            "active" => Ok(Self::Active),
162            "deprecated" => Ok(Self::Deprecated),
163            "experimental" => Ok(Self::Experimental),
164            "disabled" => Ok(Self::Disabled),
165            _ => Err(ApiPrimitiveError::Unknown),
166        }
167    }
168}
169
170/// Lightweight metadata tying this crate's primary text and label together.
171#[derive(Clone, Debug, Eq, PartialEq)]
172pub struct PrimitiveMetadata {
173    name: EndpointName,
174    kind: EndpointStatus,
175}
176
177impl PrimitiveMetadata {
178    /// Creates primitive metadata.
179    #[must_use]
180    pub const fn new(name: EndpointName, kind: EndpointStatus) -> Self {
181        Self { name, kind }
182    }
183
184    /// Returns the primary text value.
185    #[must_use]
186    pub const fn name(&self) -> &EndpointName {
187        &self.name
188    }
189
190    /// Returns the primary label.
191    #[must_use]
192    pub const fn kind(&self) -> EndpointStatus {
193        self.kind
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
203        let value = EndpointName::new("/v1/users")?;
204
205        assert_eq!(value.as_str(), "/v1/users");
206        assert_eq!(value.to_string(), "/v1/users");
207        assert_eq!("/v1/users".parse::<EndpointName>()?, value);
208        Ok(())
209    }
210
211    #[test]
212    fn rejects_empty_text() {
213        assert_eq!(EndpointName::new(""), Err(ApiPrimitiveError::Empty));
214    }
215
216    #[test]
217    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
218        let kind = "active".parse::<EndpointStatus>()?;
219
220        assert_eq!(kind, EndpointStatus::Active);
221        assert_eq!(kind.to_string(), "active");
222        Ok(())
223    }
224
225    #[test]
226    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
227        let metadata =
228            PrimitiveMetadata::new(EndpointName::new("/v1/users")?, EndpointStatus::default());
229
230        assert_eq!(metadata.name().as_str(), "/v1/users");
231        assert_eq!(metadata.kind(), EndpointStatus::default());
232        Ok(())
233    }
234}