Skip to main content

use_api_response/
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!(ResponseMetadata);
109text_newtype!(ResponseTiming);
110text_newtype!(ResponseLink);
111
112/// Response status category labels.
113#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
114pub enum ResponseStatusCategory {
115    /// A stable label variant.
116    Informational,
117    /// A stable label variant.
118    Success,
119    /// A stable label variant.
120    Redirection,
121    /// A stable label variant.
122    ClientError,
123    /// A stable label variant.
124    ServerError,
125    /// A stable label variant.
126    Unknown,
127}
128
129impl ResponseStatusCategory {
130    /// Returns the stable label.
131    #[must_use]
132    pub const fn as_str(self) -> &'static str {
133        match self {
134            Self::Informational => "informational",
135            Self::Success => "success",
136            Self::Redirection => "redirection",
137            Self::ClientError => "client-error",
138            Self::ServerError => "server-error",
139            Self::Unknown => "unknown",
140        }
141    }
142}
143
144impl Default for ResponseStatusCategory {
145    fn default() -> Self {
146        Self::Informational
147    }
148}
149
150impl fmt::Display for ResponseStatusCategory {
151    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
152        formatter.write_str(self.as_str())
153    }
154}
155
156impl FromStr for ResponseStatusCategory {
157    type Err = ApiPrimitiveError;
158
159    fn from_str(value: &str) -> Result<Self, Self::Err> {
160        let trimmed = value.trim();
161        if trimmed.is_empty() {
162            return Err(ApiPrimitiveError::Empty);
163        }
164        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
165        match normalized.as_str() {
166            "informational" => Ok(Self::Informational),
167            "success" => Ok(Self::Success),
168            "redirection" => Ok(Self::Redirection),
169            "client-error" => Ok(Self::ClientError),
170            "server-error" => Ok(Self::ServerError),
171            "unknown" => Ok(Self::Unknown),
172            _ => Err(ApiPrimitiveError::Unknown),
173        }
174    }
175}
176
177/// Lightweight metadata tying this crate's primary text and label together.
178#[derive(Clone, Debug, Eq, PartialEq)]
179pub struct PrimitiveMetadata {
180    name: ResponseMetadata,
181    kind: ResponseStatusCategory,
182}
183
184impl PrimitiveMetadata {
185    /// Creates primitive metadata.
186    #[must_use]
187    pub const fn new(name: ResponseMetadata, kind: ResponseStatusCategory) -> Self {
188        Self { name, kind }
189    }
190
191    /// Returns the primary text value.
192    #[must_use]
193    pub const fn name(&self) -> &ResponseMetadata {
194        &self.name
195    }
196
197    /// Returns the primary label.
198    #[must_use]
199    pub const fn kind(&self) -> ResponseStatusCategory {
200        self.kind
201    }
202}
203
204/// Protocol-neutral response envelope.
205#[derive(Clone, Debug, Eq, PartialEq)]
206pub struct ApiResponse<T> {
207    category: ResponseStatusCategory,
208    body: T,
209}
210
211impl<T> ApiResponse<T> {
212    /// Creates a response envelope.
213    #[must_use]
214    pub const fn new(category: ResponseStatusCategory, body: T) -> Self {
215        Self { category, body }
216    }
217
218    /// Returns the status category.
219    #[must_use]
220    pub const fn category(&self) -> ResponseStatusCategory {
221        self.category
222    }
223}
224
225/// Lightweight response page metadata.
226#[derive(Clone, Debug, Eq, PartialEq)]
227pub struct ResponsePageInfo {
228    has_more: bool,
229}
230
231impl ResponsePageInfo {
232    /// Creates response page metadata.
233    #[must_use]
234    pub const fn new(has_more: bool) -> Self {
235        Self { has_more }
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242
243    #[test]
244    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
245        let value = ResponseMetadata::new("response-link")?;
246
247        assert_eq!(value.as_str(), "response-link");
248        assert_eq!(value.to_string(), "response-link");
249        assert_eq!("response-link".parse::<ResponseMetadata>()?, value);
250        Ok(())
251    }
252
253    #[test]
254    fn rejects_empty_text() {
255        assert_eq!(ResponseMetadata::new(""), Err(ApiPrimitiveError::Empty));
256    }
257
258    #[test]
259    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
260        let kind = "informational".parse::<ResponseStatusCategory>()?;
261
262        assert_eq!(kind, ResponseStatusCategory::Informational);
263        assert_eq!(kind.to_string(), "informational");
264        Ok(())
265    }
266
267    #[test]
268    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
269        let metadata = PrimitiveMetadata::new(
270            ResponseMetadata::new("response-link")?,
271            ResponseStatusCategory::default(),
272        );
273
274        assert_eq!(metadata.name().as_str(), "response-link");
275        assert_eq!(metadata.kind(), ResponseStatusCategory::default());
276        Ok(())
277    }
278}