cometbft_rpc/
paging.rs

1//! Pagination-related data structures for the CometBFT RPC.
2
3use core::{convert::TryInto, str::FromStr};
4
5use serde::{Deserialize, Serialize};
6
7use crate::Error;
8
9/// Pagination control for those RPC client methods supporting pagination.
10#[derive(Debug, Clone, Copy, Eq, PartialEq)]
11pub enum Paging {
12    /// No explicit options set - use whatever the endpoint's defaults are.
13    Default,
14    /// Try to automatically fetch all pages' data.
15    All,
16    /// Fetch a specific page's data.
17    Specific {
18        /// The number of the page to fetch.
19        page_number: PageNumber,
20        /// The number of items to fetch per page.
21        per_page: PerPage,
22    },
23}
24
25/// A page number in paginated RPC responses.
26#[derive(Debug, Clone, Copy, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
27pub struct PageNumber(usize);
28
29impl FromStr for PageNumber {
30    type Err = Error;
31
32    fn from_str(s: &str) -> Result<Self, Self::Err> {
33        let raw = i64::from_str(s).map_err(Error::parse_int)?;
34        let raw_usize: usize = raw.try_into().map_err(Error::out_of_range)?;
35        Ok(raw_usize.into())
36    }
37}
38
39impl core::fmt::Display for PageNumber {
40    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
41        write!(f, "{}", self.0)
42    }
43}
44
45impl From<usize> for PageNumber {
46    fn from(value: usize) -> Self {
47        Self(value)
48    }
49}
50
51/// The number of items to return per page, for paginated RPC responses.
52#[derive(Debug, Clone, Copy, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
53pub struct PerPage(u8);
54
55impl FromStr for PerPage {
56    type Err = Error;
57
58    fn from_str(s: &str) -> Result<Self, Self::Err> {
59        let raw = i64::from_str(s).map_err(Error::parse_int)?;
60        let raw_u8: u8 = raw.try_into().map_err(Error::out_of_range)?;
61        Ok(raw_u8.into())
62    }
63}
64
65impl core::fmt::Display for PerPage {
66    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
67        write!(f, "{}", self.0)
68    }
69}
70
71impl From<u8> for PerPage {
72    fn from(value: u8) -> Self {
73        Self(value)
74    }
75}