Skip to main content

use_api_schema/
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!(SchemaName);
109text_newtype!(SchemaFieldName);
110
111/// Schema field kind labels.
112#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
113pub enum FieldKind {
114    /// A stable label variant.
115    String,
116    /// A stable label variant.
117    Number,
118    /// A stable label variant.
119    Integer,
120    /// A stable label variant.
121    Boolean,
122    /// A stable label variant.
123    Array,
124    /// A stable label variant.
125    Object,
126    /// A stable label variant.
127    Null,
128    /// A stable label variant.
129    Custom,
130}
131
132impl FieldKind {
133    /// Returns the stable label.
134    #[must_use]
135    pub const fn as_str(self) -> &'static str {
136        match self {
137            Self::String => "string",
138            Self::Number => "number",
139            Self::Integer => "integer",
140            Self::Boolean => "boolean",
141            Self::Array => "array",
142            Self::Object => "object",
143            Self::Null => "null",
144            Self::Custom => "custom",
145        }
146    }
147}
148
149impl Default for FieldKind {
150    fn default() -> Self {
151        Self::String
152    }
153}
154
155impl fmt::Display for FieldKind {
156    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
157        formatter.write_str(self.as_str())
158    }
159}
160
161impl FromStr for FieldKind {
162    type Err = ApiPrimitiveError;
163
164    fn from_str(value: &str) -> Result<Self, Self::Err> {
165        let trimmed = value.trim();
166        if trimmed.is_empty() {
167            return Err(ApiPrimitiveError::Empty);
168        }
169        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
170        match normalized.as_str() {
171            "string" => Ok(Self::String),
172            "number" => Ok(Self::Number),
173            "integer" => Ok(Self::Integer),
174            "boolean" => Ok(Self::Boolean),
175            "array" => Ok(Self::Array),
176            "object" => Ok(Self::Object),
177            "null" => Ok(Self::Null),
178            "custom" => Ok(Self::Custom),
179            _ => Err(ApiPrimitiveError::Unknown),
180        }
181    }
182}
183/// Schema field requirement labels.
184#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
185pub enum FieldRequirement {
186    /// A stable label variant.
187    Required,
188    /// A stable label variant.
189    Optional,
190}
191
192impl FieldRequirement {
193    /// Returns the stable label.
194    #[must_use]
195    pub const fn as_str(self) -> &'static str {
196        match self {
197            Self::Required => "required",
198            Self::Optional => "optional",
199        }
200    }
201}
202
203impl Default for FieldRequirement {
204    fn default() -> Self {
205        Self::Required
206    }
207}
208
209impl fmt::Display for FieldRequirement {
210    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
211        formatter.write_str(self.as_str())
212    }
213}
214
215impl FromStr for FieldRequirement {
216    type Err = ApiPrimitiveError;
217
218    fn from_str(value: &str) -> Result<Self, Self::Err> {
219        let trimmed = value.trim();
220        if trimmed.is_empty() {
221            return Err(ApiPrimitiveError::Empty);
222        }
223        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
224        match normalized.as_str() {
225            "required" => Ok(Self::Required),
226            "optional" => Ok(Self::Optional),
227            _ => Err(ApiPrimitiveError::Unknown),
228        }
229    }
230}
231/// Schema nullability labels.
232#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
233pub enum Nullability {
234    /// A stable label variant.
235    Nullable,
236    /// A stable label variant.
237    NonNullable,
238}
239
240impl Nullability {
241    /// Returns the stable label.
242    #[must_use]
243    pub const fn as_str(self) -> &'static str {
244        match self {
245            Self::Nullable => "nullable",
246            Self::NonNullable => "non-nullable",
247        }
248    }
249}
250
251impl Default for Nullability {
252    fn default() -> Self {
253        Self::Nullable
254    }
255}
256
257impl fmt::Display for Nullability {
258    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
259        formatter.write_str(self.as_str())
260    }
261}
262
263impl FromStr for Nullability {
264    type Err = ApiPrimitiveError;
265
266    fn from_str(value: &str) -> Result<Self, Self::Err> {
267        let trimmed = value.trim();
268        if trimmed.is_empty() {
269            return Err(ApiPrimitiveError::Empty);
270        }
271        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
272        match normalized.as_str() {
273            "nullable" => Ok(Self::Nullable),
274            "non-nullable" => Ok(Self::NonNullable),
275            _ => Err(ApiPrimitiveError::Unknown),
276        }
277    }
278}
279/// Broad schema shape labels.
280#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
281pub enum SchemaShape {
282    /// A stable label variant.
283    Scalar,
284    /// A stable label variant.
285    Array,
286    /// A stable label variant.
287    Object,
288}
289
290impl SchemaShape {
291    /// Returns the stable label.
292    #[must_use]
293    pub const fn as_str(self) -> &'static str {
294        match self {
295            Self::Scalar => "scalar",
296            Self::Array => "array",
297            Self::Object => "object",
298        }
299    }
300}
301
302impl Default for SchemaShape {
303    fn default() -> Self {
304        Self::Scalar
305    }
306}
307
308impl fmt::Display for SchemaShape {
309    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
310        formatter.write_str(self.as_str())
311    }
312}
313
314impl FromStr for SchemaShape {
315    type Err = ApiPrimitiveError;
316
317    fn from_str(value: &str) -> Result<Self, Self::Err> {
318        let trimmed = value.trim();
319        if trimmed.is_empty() {
320            return Err(ApiPrimitiveError::Empty);
321        }
322        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
323        match normalized.as_str() {
324            "scalar" => Ok(Self::Scalar),
325            "array" => Ok(Self::Array),
326            "object" => Ok(Self::Object),
327            _ => Err(ApiPrimitiveError::Unknown),
328        }
329    }
330}
331
332/// Lightweight metadata tying this crate's primary text and label together.
333#[derive(Clone, Debug, Eq, PartialEq)]
334pub struct PrimitiveMetadata {
335    name: SchemaName,
336    kind: FieldKind,
337}
338
339impl PrimitiveMetadata {
340    /// Creates primitive metadata.
341    #[must_use]
342    pub const fn new(name: SchemaName, kind: FieldKind) -> Self {
343        Self { name, kind }
344    }
345
346    /// Returns the primary text value.
347    #[must_use]
348    pub const fn name(&self) -> &SchemaName {
349        &self.name
350    }
351
352    /// Returns the primary label.
353    #[must_use]
354    pub const fn kind(&self) -> FieldKind {
355        self.kind
356    }
357}
358
359/// API schema field metadata.
360#[derive(Clone, Debug, Eq, PartialEq)]
361pub struct SchemaField {
362    name: SchemaFieldName,
363    kind: FieldKind,
364    requirement: FieldRequirement,
365    nullability: Nullability,
366}
367
368impl SchemaField {
369    /// Creates schema field metadata.
370    #[must_use]
371    pub const fn new(name: SchemaFieldName, kind: FieldKind) -> Self {
372        Self {
373            name,
374            kind,
375            requirement: FieldRequirement::Optional,
376            nullability: Nullability::NonNullable,
377        }
378    }
379
380    /// Marks the field as required.
381    #[must_use]
382    pub const fn required(mut self) -> Self {
383        self.requirement = FieldRequirement::Required;
384        self
385    }
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    #[test]
393    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
394        let value = SchemaName::new("User")?;
395
396        assert_eq!(value.as_str(), "User");
397        assert_eq!(value.to_string(), "User");
398        assert_eq!("User".parse::<SchemaName>()?, value);
399        Ok(())
400    }
401
402    #[test]
403    fn rejects_empty_text() {
404        assert_eq!(SchemaName::new(""), Err(ApiPrimitiveError::Empty));
405    }
406
407    #[test]
408    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
409        let kind = "string".parse::<FieldKind>()?;
410
411        assert_eq!(kind, FieldKind::String);
412        assert_eq!(kind.to_string(), "string");
413        Ok(())
414    }
415
416    #[test]
417    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
418        let metadata = PrimitiveMetadata::new(SchemaName::new("User")?, FieldKind::default());
419
420        assert_eq!(metadata.name().as_str(), "User");
421        assert_eq!(metadata.kind(), FieldKind::default());
422        Ok(())
423    }
424}