1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10 Empty,
12 Invalid,
14 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 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 pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62 Self::new(value)
63 }
64
65 #[must_use]
67 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70
71 #[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!(PageMarker);
109text_newtype!(NextMarker);
110text_newtype!(PreviousMarker);
111
112#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
114pub enum PaginationDirection {
115 Next,
117 Previous,
119 Current,
121}
122
123impl PaginationDirection {
124 #[must_use]
126 pub const fn as_str(self) -> &'static str {
127 match self {
128 Self::Next => "next",
129 Self::Previous => "previous",
130 Self::Current => "current",
131 }
132 }
133}
134
135impl Default for PaginationDirection {
136 fn default() -> Self {
137 Self::Next
138 }
139}
140
141impl fmt::Display for PaginationDirection {
142 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
143 formatter.write_str(self.as_str())
144 }
145}
146
147impl FromStr for PaginationDirection {
148 type Err = ApiPrimitiveError;
149
150 fn from_str(value: &str) -> Result<Self, Self::Err> {
151 let trimmed = value.trim();
152 if trimmed.is_empty() {
153 return Err(ApiPrimitiveError::Empty);
154 }
155 let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
156 match normalized.as_str() {
157 "next" => Ok(Self::Next),
158 "previous" => Ok(Self::Previous),
159 "current" => Ok(Self::Current),
160 _ => Err(ApiPrimitiveError::Unknown),
161 }
162 }
163}
164
165#[derive(Clone, Debug, Eq, PartialEq)]
167pub struct PrimitiveMetadata {
168 name: PageMarker,
169 kind: PaginationDirection,
170}
171
172impl PrimitiveMetadata {
173 #[must_use]
175 pub const fn new(name: PageMarker, kind: PaginationDirection) -> Self {
176 Self { name, kind }
177 }
178
179 #[must_use]
181 pub const fn name(&self) -> &PageMarker {
182 &self.name
183 }
184
185 #[must_use]
187 pub const fn kind(&self) -> PaginationDirection {
188 self.kind
189 }
190}
191
192#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
194pub struct PageNumber(u64);
195
196impl PageNumber {
197 pub const fn new(value: u64) -> Result<Self, ApiPrimitiveError> {
199 if value == 0 {
200 Err(ApiPrimitiveError::Invalid)
201 } else {
202 Ok(Self(value))
203 }
204 }
205
206 #[must_use]
208 pub const fn value(self) -> u64 {
209 self.0
210 }
211}
212
213#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
215pub struct PageSize(u64);
216
217impl PageSize {
218 pub const fn new(value: u64) -> Result<Self, ApiPrimitiveError> {
220 if value == 0 {
221 Err(ApiPrimitiveError::Invalid)
222 } else {
223 Ok(Self(value))
224 }
225 }
226
227 #[must_use]
229 pub const fn value(self) -> u64 {
230 self.0
231 }
232}
233
234#[derive(Clone, Debug, Eq, PartialEq)]
236pub struct PageInfo {
237 page: PageNumber,
238 size: PageSize,
239 total_count: Option<u64>,
240 has_more: bool,
241}
242
243impl PageInfo {
244 #[must_use]
246 pub const fn new(page: PageNumber, size: PageSize) -> Self {
247 Self {
248 page,
249 size,
250 total_count: None,
251 has_more: false,
252 }
253 }
254
255 #[must_use]
257 pub const fn with_total_count(mut self, total_count: u64) -> Self {
258 self.total_count = Some(total_count);
259 self
260 }
261
262 #[must_use]
264 pub const fn with_has_more(mut self, has_more: bool) -> Self {
265 self.has_more = has_more;
266 self
267 }
268
269 #[must_use]
271 pub const fn has_more(&self) -> bool {
272 self.has_more
273 }
274}
275
276#[cfg(test)]
277mod tests {
278 use super::*;
279
280 #[test]
281 fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
282 let value = PageMarker::new("page-1")?;
283
284 assert_eq!(value.as_str(), "page-1");
285 assert_eq!(value.to_string(), "page-1");
286 assert_eq!("page-1".parse::<PageMarker>()?, value);
287 Ok(())
288 }
289
290 #[test]
291 fn rejects_empty_text() {
292 assert_eq!(PageMarker::new(""), Err(ApiPrimitiveError::Empty));
293 }
294
295 #[test]
296 fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
297 let kind = "next".parse::<PaginationDirection>()?;
298
299 assert_eq!(kind, PaginationDirection::Next);
300 assert_eq!(kind.to_string(), "next");
301 Ok(())
302 }
303
304 #[test]
305 fn creates_metadata() -> Result<(), ApiPrimitiveError> {
306 let metadata =
307 PrimitiveMetadata::new(PageMarker::new("page-1")?, PaginationDirection::default());
308
309 assert_eq!(metadata.name().as_str(), "page-1");
310 assert_eq!(metadata.kind(), PaginationDirection::default());
311 Ok(())
312 }
313}