1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use std::{fmt, num::ParseIntError};

use anyhow::bail;
use serde::{
    de::{self, MapAccess, Visitor},
    Deserialize, Deserializer,
};
#[cfg(feature = "ts_rs")]
use ts_rs::TS;

/// Represents the URL query parameters `page` and `limit`, used for paginating database queries.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct Pagination {
    // the deserialize implementation contains a default value for page
    #[cfg_attr(feature = "ts_rs", ts(type = "number | undefined"))]
    page: u32,
    // the deserialize implementation contains a default value for limit
    #[cfg_attr(feature = "ts_rs", ts(type = "number | undefined"))]
    limit: u32,
}

impl Pagination {
    /// Errors on non-positive page or limit values.
    pub fn new(page: u32, limit: u32) -> anyhow::Result<Self> {
        if page == 0 {
            bail!("Page must be a positive value.");
        }
        if limit == 0 {
            bail!("Limit must be a positive value.");
        }
        if limit > 10_000 {
            bail!("Limit can be at most 10000.")
        }
        Ok(Pagination { page, limit })
    }

    /// Guaranteed to be positive.
    pub fn page(&self) -> i64 {
        self.page.into()
    }

    /// Guaranteed to be positive.
    pub fn limit(&self) -> i64 {
        self.limit.into()
    }

    /// Guaranteed to be nonnegative.
    pub fn offset(&self) -> i64 {
        (self.limit * (self.page - 1)).into()
    }

    /// Guaranteed to be positive.
    pub fn total_pages(&self, total_count: u32) -> u32 {
        let remainder = total_count % self.limit;
        if remainder == 0 {
            total_count / self.limit
        } else {
            total_count / self.limit + 1
        }
    }

    /// Helper to paginate an existing Vec efficiently.
    pub fn paginate<T>(&self, v: &mut Vec<T>) {
        let limit = self.limit as usize;
        let start = limit * (self.page as usize - 1);
        v.truncate(start + limit);
        v.drain(..start);
    }

    pub fn next_page(&mut self) {
        self.page += 1;
    }
}

impl Default for Pagination {
    fn default() -> Self {
        Self {
            page: 1,
            limit: 100,
        }
    }
}

impl<'de> Deserialize<'de> for Pagination {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct PaginationVisitor;

        impl<'de> Visitor<'de> for PaginationVisitor {
            type Value = Pagination;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("query parameters `page` and `limit`")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut page = None;
                let mut limit = None;
                while let Some(key) = map.next_key().map_err(|e| {
                    de::Error::custom(format!("Failed to deserialize map key: {}", e))
                })? {
                    match key {
                        "page" => {
                            if page.is_some() {
                                return Err(de::Error::duplicate_field("page"));
                            }
                            let value: StrOrInt = map.next_value().map_err(|e| {
                                de::Error::custom(format!(
                                    "Failed to deserialize page value: {}",
                                    e
                                ))
                            })?;
                            let value = value.into_int().map_err(|e| {
                                de::Error::custom(format!(
                                    "Failed to deserialize page value: {}",
                                    e
                                ))
                            })?;
                            if value < 1 {
                                return Err(de::Error::custom(
                                    "query parameter `page` must be a positive integer",
                                ));
                            }
                            page = Some(value);
                        }
                        "limit" => {
                            if limit.is_some() {
                                return Err(de::Error::duplicate_field("limit"));
                            }
                            let value: StrOrInt = map.next_value().map_err(|e| {
                                de::Error::custom(format!(
                                    "Failed to deserialize limit value: {}",
                                    e
                                ))
                            })?;
                            let value = value.into_int().map_err(|e| {
                                de::Error::custom(format!(
                                    "Failed to deserialize limit value: {}",
                                    e
                                ))
                            })?;
                            if !(1..=10000).contains(&value) {
                                return Err(de::Error::custom(
                                    "query parameter `limit` must be an integer between 1 and 10000",
                                ));
                            }
                            limit = Some(value);
                        }
                        field => {
                            return Err(de::Error::custom(&format!(
                                "unexpected parameter `{}`",
                                field
                            )))
                        }
                    }
                }
                Ok(Pagination {
                    page: page.unwrap_or(Pagination::default().page),
                    limit: limit.unwrap_or(Pagination::default().limit),
                })
            }
        }

        deserializer.deserialize_struct("Pagination", &["page", "limit"], PaginationVisitor)
    }
}

// for some reason, it seems like when there are only numeric query parameters, actix gives them to serde as numbers,
// but if there's a string mixed in, they are all given as strings. this helper is used to handle both cases
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum StrOrInt<'a> {
    Str(&'a str),
    Int(u32),
}

impl StrOrInt<'_> {
    fn into_int(self) -> Result<u32, ParseIntError> {
        match self {
            Self::Str(s) => s.parse(),
            Self::Int(i) => Ok(i),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn paginates() {
        let mut v = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let pagination = Pagination::new(2, 3).unwrap();
        pagination.paginate(&mut v);
        assert_eq!(v, &[4, 5, 6]);
    }

    #[test]
    fn paginates_non_existent_page() {
        let mut v = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let pagination = Pagination::new(3, 4).unwrap();
        pagination.paginate(&mut v);
        assert_eq!(v, &[] as &[i32]);
    }

    #[test]
    fn paginates_incomplete_page() {
        let mut v = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let pagination = Pagination::new(2, 5).unwrap();
        pagination.paginate(&mut v);
        assert_eq!(v, &[6, 7, 8]);
    }
}