Paginates a list of items based on limit and offset.
(
args: PaginatedItemsArgs<'_, T>,
)
| 39 | |
| 40 | /// Paginates a list of items based on limit and offset. |
| 41 | pub fn paginated_items<T>( |
| 42 | args: PaginatedItemsArgs<'_, T>, |
| 43 | ) -> Result<PaginatedData<T>, PaginationError> |
| 44 | where |
| 45 | T: Clone, |
| 46 | { |
| 47 | let offset = args.offset.unwrap_or(0) as usize; |
| 48 | |
| 49 | if let (Some(max_limit), Some(limit)) = (args.max_limit, args.limit) { |
| 50 | if limit > max_limit { |
| 51 | Err(PaginationError::MaxLimitExceeded { max: max_limit })?; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | let default_limit = args.default_limit.unwrap_or(match args.max_limit { |
| 56 | Some(max_limit) => max_limit, |
| 57 | None => DEFAULT_PAGINATION_LIMIT, |
| 58 | }); |
| 59 | let limit = args.limit.unwrap_or(default_limit) as usize; |
| 60 | |
| 61 | let total = args.items.len(); |
| 62 | |
| 63 | let next_offset = match (offset + limit) < total { |
| 64 | true => Some((offset + limit) as u64), |
| 65 | false => None, |
| 66 | }; |
| 67 | |
| 68 | let items = args |
| 69 | .items |
| 70 | .get(offset..std::cmp::min(offset + limit, total)) |
| 71 | .unwrap_or(&[]) |
| 72 | .to_vec(); |
| 73 | |
| 74 | Ok(PaginatedData { |
| 75 | items, |
| 76 | next_offset, |
| 77 | total: total as u64, |
| 78 | }) |
| 79 | } |
| 80 | |
| 81 | #[cfg(test)] |
| 82 | mod tests { |