Skip to main content

use_api_media_type/
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!(MediaType);
109text_newtype!(MediaSubtype);
110text_newtype!(MediaTypeSuffix);
111text_newtype!(Charset);
112text_newtype!(StructuredSyntaxSuffix);
113
114/// Common API media type labels.
115#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
116pub enum CommonApiMediaType {
117    /// A stable label variant.
118    Json,
119    /// A stable label variant.
120    ProblemJson,
121    /// A stable label variant.
122    MergePatchJson,
123    /// A stable label variant.
124    Ndjson,
125    /// A stable label variant.
126    Xml,
127    /// A stable label variant.
128    TextPlain,
129    /// A stable label variant.
130    OctetStream,
131}
132
133impl CommonApiMediaType {
134    /// Returns the stable label.
135    #[must_use]
136    pub const fn as_str(self) -> &'static str {
137        match self {
138            Self::Json => "json",
139            Self::ProblemJson => "problem-json",
140            Self::MergePatchJson => "merge-patch-json",
141            Self::Ndjson => "ndjson",
142            Self::Xml => "xml",
143            Self::TextPlain => "text-plain",
144            Self::OctetStream => "octet-stream",
145        }
146    }
147}
148
149impl Default for CommonApiMediaType {
150    fn default() -> Self {
151        Self::Json
152    }
153}
154
155impl fmt::Display for CommonApiMediaType {
156    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
157        formatter.write_str(self.as_str())
158    }
159}
160
161impl FromStr for CommonApiMediaType {
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            "json" => Ok(Self::Json),
172            "problem-json" => Ok(Self::ProblemJson),
173            "merge-patch-json" => Ok(Self::MergePatchJson),
174            "ndjson" => Ok(Self::Ndjson),
175            "xml" => Ok(Self::Xml),
176            "text-plain" => Ok(Self::TextPlain),
177            "octet-stream" => Ok(Self::OctetStream),
178            _ => Err(ApiPrimitiveError::Unknown),
179        }
180    }
181}
182
183/// Lightweight metadata tying this crate's primary text and label together.
184#[derive(Clone, Debug, Eq, PartialEq)]
185pub struct PrimitiveMetadata {
186    name: MediaType,
187    kind: CommonApiMediaType,
188}
189
190impl PrimitiveMetadata {
191    /// Creates primitive metadata.
192    #[must_use]
193    pub const fn new(name: MediaType, kind: CommonApiMediaType) -> Self {
194        Self { name, kind }
195    }
196
197    /// Returns the primary text value.
198    #[must_use]
199    pub const fn name(&self) -> &MediaType {
200        &self.name
201    }
202
203    /// Returns the primary label.
204    #[must_use]
205    pub const fn kind(&self) -> CommonApiMediaType {
206        self.kind
207    }
208}
209
210impl CommonApiMediaType {
211    /// Returns the conventional media type string.
212    #[must_use]
213    pub const fn media_type(self) -> &'static str {
214        match self {
215            Self::Json => "application/json",
216            Self::ProblemJson => "application/problem+json",
217            Self::MergePatchJson => "application/merge-patch+json",
218            Self::Ndjson => "application/x-ndjson",
219            Self::Xml => "application/xml",
220            Self::TextPlain => "text/plain",
221            Self::OctetStream => "application/octet-stream",
222        }
223    }
224}
225
226impl MediaType {
227    /// Returns the structured syntax suffix when one is present.
228    #[must_use]
229    pub fn suffix(&self) -> Option<&str> {
230        self.as_str()
231            .split(';')
232            .next()?
233            .rsplit_once('+')
234            .map(|(_, suffix)| suffix)
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
244        let value = MediaType::new("application/json")?;
245
246        assert_eq!(value.as_str(), "application/json");
247        assert_eq!(value.to_string(), "application/json");
248        assert_eq!("application/json".parse::<MediaType>()?, value);
249        Ok(())
250    }
251
252    #[test]
253    fn rejects_empty_text() {
254        assert_eq!(MediaType::new(""), Err(ApiPrimitiveError::Empty));
255    }
256
257    #[test]
258    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
259        let kind = "json".parse::<CommonApiMediaType>()?;
260
261        assert_eq!(kind, CommonApiMediaType::Json);
262        assert_eq!(kind.to_string(), "json");
263        Ok(())
264    }
265
266    #[test]
267    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
268        let metadata = PrimitiveMetadata::new(
269            MediaType::new("application/json")?,
270            CommonApiMediaType::default(),
271        );
272
273        assert_eq!(metadata.name().as_str(), "application/json");
274        assert_eq!(metadata.kind(), CommonApiMediaType::default());
275        Ok(())
276    }
277}