Skip to main content

use_api_operation/
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!(OperationId);
109text_newtype!(OperationName);
110text_newtype!(OperationSummary);
111
112/// API operation kind labels.
113#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
114pub enum OperationKind {
115    /// A stable label variant.
116    Query,
117    /// A stable label variant.
118    Command,
119    /// A stable label variant.
120    Mutation,
121    /// A stable label variant.
122    Subscription,
123    /// A stable label variant.
124    Action,
125}
126
127impl OperationKind {
128    /// Returns the stable label.
129    #[must_use]
130    pub const fn as_str(self) -> &'static str {
131        match self {
132            Self::Query => "query",
133            Self::Command => "command",
134            Self::Mutation => "mutation",
135            Self::Subscription => "subscription",
136            Self::Action => "action",
137        }
138    }
139}
140
141impl Default for OperationKind {
142    fn default() -> Self {
143        Self::Query
144    }
145}
146
147impl fmt::Display for OperationKind {
148    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149        formatter.write_str(self.as_str())
150    }
151}
152
153impl FromStr for OperationKind {
154    type Err = ApiPrimitiveError;
155
156    fn from_str(value: &str) -> Result<Self, Self::Err> {
157        let trimmed = value.trim();
158        if trimmed.is_empty() {
159            return Err(ApiPrimitiveError::Empty);
160        }
161        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
162        match normalized.as_str() {
163            "query" => Ok(Self::Query),
164            "command" => Ok(Self::Command),
165            "mutation" => Ok(Self::Mutation),
166            "subscription" => Ok(Self::Subscription),
167            "action" => Ok(Self::Action),
168            _ => Err(ApiPrimitiveError::Unknown),
169        }
170    }
171}
172/// API operation status labels.
173#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
174pub enum OperationStatus {
175    /// A stable label variant.
176    Active,
177    /// A stable label variant.
178    Deprecated,
179    /// A stable label variant.
180    Experimental,
181    /// A stable label variant.
182    Disabled,
183}
184
185impl OperationStatus {
186    /// Returns the stable label.
187    #[must_use]
188    pub const fn as_str(self) -> &'static str {
189        match self {
190            Self::Active => "active",
191            Self::Deprecated => "deprecated",
192            Self::Experimental => "experimental",
193            Self::Disabled => "disabled",
194        }
195    }
196}
197
198impl Default for OperationStatus {
199    fn default() -> Self {
200        Self::Active
201    }
202}
203
204impl fmt::Display for OperationStatus {
205    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
206        formatter.write_str(self.as_str())
207    }
208}
209
210impl FromStr for OperationStatus {
211    type Err = ApiPrimitiveError;
212
213    fn from_str(value: &str) -> Result<Self, Self::Err> {
214        let trimmed = value.trim();
215        if trimmed.is_empty() {
216            return Err(ApiPrimitiveError::Empty);
217        }
218        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
219        match normalized.as_str() {
220            "active" => Ok(Self::Active),
221            "deprecated" => Ok(Self::Deprecated),
222            "experimental" => Ok(Self::Experimental),
223            "disabled" => Ok(Self::Disabled),
224            _ => Err(ApiPrimitiveError::Unknown),
225        }
226    }
227}
228/// API operation lifecycle labels.
229#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
230pub enum OperationLifecycle {
231    /// A stable label variant.
232    Design,
233    /// A stable label variant.
234    Preview,
235    /// A stable label variant.
236    Stable,
237    /// A stable label variant.
238    Deprecated,
239    /// A stable label variant.
240    Retired,
241}
242
243impl OperationLifecycle {
244    /// Returns the stable label.
245    #[must_use]
246    pub const fn as_str(self) -> &'static str {
247        match self {
248            Self::Design => "design",
249            Self::Preview => "preview",
250            Self::Stable => "stable",
251            Self::Deprecated => "deprecated",
252            Self::Retired => "retired",
253        }
254    }
255}
256
257impl Default for OperationLifecycle {
258    fn default() -> Self {
259        Self::Design
260    }
261}
262
263impl fmt::Display for OperationLifecycle {
264    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
265        formatter.write_str(self.as_str())
266    }
267}
268
269impl FromStr for OperationLifecycle {
270    type Err = ApiPrimitiveError;
271
272    fn from_str(value: &str) -> Result<Self, Self::Err> {
273        let trimmed = value.trim();
274        if trimmed.is_empty() {
275            return Err(ApiPrimitiveError::Empty);
276        }
277        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
278        match normalized.as_str() {
279            "design" => Ok(Self::Design),
280            "preview" => Ok(Self::Preview),
281            "stable" => Ok(Self::Stable),
282            "deprecated" => Ok(Self::Deprecated),
283            "retired" => Ok(Self::Retired),
284            _ => Err(ApiPrimitiveError::Unknown),
285        }
286    }
287}
288
289/// Lightweight metadata tying this crate's primary text and label together.
290#[derive(Clone, Debug, Eq, PartialEq)]
291pub struct PrimitiveMetadata {
292    name: OperationId,
293    kind: OperationKind,
294}
295
296impl PrimitiveMetadata {
297    /// Creates primitive metadata.
298    #[must_use]
299    pub const fn new(name: OperationId, kind: OperationKind) -> Self {
300        Self { name, kind }
301    }
302
303    /// Returns the primary text value.
304    #[must_use]
305    pub const fn name(&self) -> &OperationId {
306        &self.name
307    }
308
309    /// Returns the primary label.
310    #[must_use]
311    pub const fn kind(&self) -> OperationKind {
312        self.kind
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319
320    #[test]
321    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
322        let value = OperationId::new("listUsers")?;
323
324        assert_eq!(value.as_str(), "listUsers");
325        assert_eq!(value.to_string(), "listUsers");
326        assert_eq!("listUsers".parse::<OperationId>()?, value);
327        Ok(())
328    }
329
330    #[test]
331    fn rejects_empty_text() {
332        assert_eq!(OperationId::new(""), Err(ApiPrimitiveError::Empty));
333    }
334
335    #[test]
336    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
337        let kind = "query".parse::<OperationKind>()?;
338
339        assert_eq!(kind, OperationKind::Query);
340        assert_eq!(kind.to_string(), "query");
341        Ok(())
342    }
343
344    #[test]
345    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
346        let metadata =
347            PrimitiveMetadata::new(OperationId::new("listUsers")?, OperationKind::default());
348
349        assert_eq!(metadata.name().as_str(), "listUsers");
350        assert_eq!(metadata.kind(), OperationKind::default());
351        Ok(())
352    }
353}