Skip to main content

use_pagination/
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!(PageMarker);
109text_newtype!(NextMarker);
110text_newtype!(PreviousMarker);
111
112/// Pagination direction labels.
113#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
114pub enum PaginationDirection {
115    /// A stable label variant.
116    Next,
117    /// A stable label variant.
118    Previous,
119    /// A stable label variant.
120    Current,
121}
122
123impl PaginationDirection {
124    /// Returns the stable label.
125    #[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/// Lightweight metadata tying this crate's primary text and label together.
166#[derive(Clone, Debug, Eq, PartialEq)]
167pub struct PrimitiveMetadata {
168    name: PageMarker,
169    kind: PaginationDirection,
170}
171
172impl PrimitiveMetadata {
173    /// Creates primitive metadata.
174    #[must_use]
175    pub const fn new(name: PageMarker, kind: PaginationDirection) -> Self {
176        Self { name, kind }
177    }
178
179    /// Returns the primary text value.
180    #[must_use]
181    pub const fn name(&self) -> &PageMarker {
182        &self.name
183    }
184
185    /// Returns the primary label.
186    #[must_use]
187    pub const fn kind(&self) -> PaginationDirection {
188        self.kind
189    }
190}
191
192/// A one-based page number.
193#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
194pub struct PageNumber(u64);
195
196impl PageNumber {
197    /// Creates a one-based page number.
198    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    /// Returns the numeric page number.
207    #[must_use]
208    pub const fn value(self) -> u64 {
209        self.0
210    }
211}
212
213/// A bounded page size.
214#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
215pub struct PageSize(u64);
216
217impl PageSize {
218    /// Creates a non-zero page size.
219    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    /// Returns the numeric page size.
228    #[must_use]
229    pub const fn value(self) -> u64 {
230        self.0
231    }
232}
233
234/// Pagination metadata.
235#[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    /// Creates pagination metadata.
245    #[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    /// Adds a total count.
256    #[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    /// Sets whether a next page is available.
263    #[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    /// Returns true when another page is available.
270    #[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}