Skip to main content

use_api_param/
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!(PathParamName);
109text_newtype!(QueryParamName);
110text_newtype!(HeaderParamName);
111text_newtype!(BodyParamName);
112
113/// API parameter location labels.
114#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115pub enum ParamLocation {
116    /// A stable label variant.
117    Path,
118    /// A stable label variant.
119    Query,
120    /// A stable label variant.
121    Header,
122    /// A stable label variant.
123    Body,
124}
125
126impl ParamLocation {
127    /// Returns the stable label.
128    #[must_use]
129    pub const fn as_str(self) -> &'static str {
130        match self {
131            Self::Path => "path",
132            Self::Query => "query",
133            Self::Header => "header",
134            Self::Body => "body",
135        }
136    }
137}
138
139impl Default for ParamLocation {
140    fn default() -> Self {
141        Self::Path
142    }
143}
144
145impl fmt::Display for ParamLocation {
146    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
147        formatter.write_str(self.as_str())
148    }
149}
150
151impl FromStr for ParamLocation {
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            "path" => Ok(Self::Path),
162            "query" => Ok(Self::Query),
163            "header" => Ok(Self::Header),
164            "body" => Ok(Self::Body),
165            _ => Err(ApiPrimitiveError::Unknown),
166        }
167    }
168}
169/// API parameter requirement labels.
170#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
171pub enum ParamRequirement {
172    /// A stable label variant.
173    Required,
174    /// A stable label variant.
175    Optional,
176}
177
178impl ParamRequirement {
179    /// Returns the stable label.
180    #[must_use]
181    pub const fn as_str(self) -> &'static str {
182        match self {
183            Self::Required => "required",
184            Self::Optional => "optional",
185        }
186    }
187}
188
189impl Default for ParamRequirement {
190    fn default() -> Self {
191        Self::Required
192    }
193}
194
195impl fmt::Display for ParamRequirement {
196    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
197        formatter.write_str(self.as_str())
198    }
199}
200
201impl FromStr for ParamRequirement {
202    type Err = ApiPrimitiveError;
203
204    fn from_str(value: &str) -> Result<Self, Self::Err> {
205        let trimmed = value.trim();
206        if trimmed.is_empty() {
207            return Err(ApiPrimitiveError::Empty);
208        }
209        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
210        match normalized.as_str() {
211            "required" => Ok(Self::Required),
212            "optional" => Ok(Self::Optional),
213            _ => Err(ApiPrimitiveError::Unknown),
214        }
215    }
216}
217/// API parameter style labels.
218#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
219pub enum ParamStyle {
220    /// A stable label variant.
221    Simple,
222    /// A stable label variant.
223    Form,
224    /// A stable label variant.
225    Matrix,
226    /// A stable label variant.
227    Label,
228    /// A stable label variant.
229    DeepObject,
230}
231
232impl ParamStyle {
233    /// Returns the stable label.
234    #[must_use]
235    pub const fn as_str(self) -> &'static str {
236        match self {
237            Self::Simple => "simple",
238            Self::Form => "form",
239            Self::Matrix => "matrix",
240            Self::Label => "label",
241            Self::DeepObject => "deep-object",
242        }
243    }
244}
245
246impl Default for ParamStyle {
247    fn default() -> Self {
248        Self::Simple
249    }
250}
251
252impl fmt::Display for ParamStyle {
253    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
254        formatter.write_str(self.as_str())
255    }
256}
257
258impl FromStr for ParamStyle {
259    type Err = ApiPrimitiveError;
260
261    fn from_str(value: &str) -> Result<Self, Self::Err> {
262        let trimmed = value.trim();
263        if trimmed.is_empty() {
264            return Err(ApiPrimitiveError::Empty);
265        }
266        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
267        match normalized.as_str() {
268            "simple" => Ok(Self::Simple),
269            "form" => Ok(Self::Form),
270            "matrix" => Ok(Self::Matrix),
271            "label" => Ok(Self::Label),
272            "deep-object" => Ok(Self::DeepObject),
273            _ => Err(ApiPrimitiveError::Unknown),
274        }
275    }
276}
277
278/// Lightweight metadata tying this crate's primary text and label together.
279#[derive(Clone, Debug, Eq, PartialEq)]
280pub struct PrimitiveMetadata {
281    name: PathParamName,
282    kind: ParamLocation,
283}
284
285impl PrimitiveMetadata {
286    /// Creates primitive metadata.
287    #[must_use]
288    pub const fn new(name: PathParamName, kind: ParamLocation) -> Self {
289        Self { name, kind }
290    }
291
292    /// Returns the primary text value.
293    #[must_use]
294    pub const fn name(&self) -> &PathParamName {
295        &self.name
296    }
297
298    /// Returns the primary label.
299    #[must_use]
300    pub const fn kind(&self) -> ParamLocation {
301        self.kind
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308
309    #[test]
310    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
311        let value = PathParamName::new("user_id")?;
312
313        assert_eq!(value.as_str(), "user_id");
314        assert_eq!(value.to_string(), "user_id");
315        assert_eq!("user_id".parse::<PathParamName>()?, value);
316        Ok(())
317    }
318
319    #[test]
320    fn rejects_empty_text() {
321        assert_eq!(PathParamName::new(""), Err(ApiPrimitiveError::Empty));
322    }
323
324    #[test]
325    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
326        let kind = "path".parse::<ParamLocation>()?;
327
328        assert_eq!(kind, ParamLocation::Path);
329        assert_eq!(kind.to_string(), "path");
330        Ok(())
331    }
332
333    #[test]
334    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
335        let metadata =
336            PrimitiveMetadata::new(PathParamName::new("user_id")?, ParamLocation::default());
337
338        assert_eq!(metadata.name().as_str(), "user_id");
339        assert_eq!(metadata.kind(), ParamLocation::default());
340        Ok(())
341    }
342}