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
use async_graphql::{FieldResult, OutputType, SimpleObject};
use std::convert::TryFrom;

#[derive(SimpleObject)]
pub struct ConnectionFields<C: OutputType + Send + Sync> {
    pub total_count: C,
}

pub struct ValidatedPaginationArguments<I> {
    pub first: Option<usize>,
    pub last: Option<usize>,
    pub before: Option<I>,
    pub after: Option<I>,
}

pub struct PageMeta {
    pub has_next_page: bool,
    pub has_previous_page: bool,
    pub total_count: u64,
}

fn compute_range_boundaries(
    total_elements: InclusivePaginationInterval<u64>,
    pagination_arguments: ValidatedPaginationArguments<u64>,
) -> InclusivePaginationInterval<u64>
where
{
    use std::cmp::{max, min};

    let InclusivePaginationInterval {
        upper_bound,
        lower_bound,
    } = total_elements;

    // Compute the required range of blocks in two variables: [from, to]
    // Both ends are inclusive
    let mut from: u64 = match pagination_arguments.after {
        Some(cursor) => max(cursor + 1, lower_bound),
        // If `after` is not set, start from the beginning
        None => lower_bound,
    };

    let mut to: u64 = match pagination_arguments.before {
        Some(cursor) => min(cursor - 1, upper_bound),
        // If `before` is not set, start from the beginning
        None => upper_bound,
    };

    // Move `to` enough values to make the result have `first` blocks
    if let Some(first) = pagination_arguments.first {
        to = min(
            from.checked_add(u64::try_from(first).unwrap())
                .and_then(|n| n.checked_sub(1))
                .unwrap_or(to),
            to,
        );
    }

    // Move `from` enough values to make the result have `last` blocks
    if let Some(last) = pagination_arguments.last {
        from = max(
            to.checked_sub(u64::try_from(last).unwrap())
                .and_then(|n| n.checked_add(1))
                .unwrap_or(from),
            from,
        );
    }

    InclusivePaginationInterval {
        lower_bound: from,
        upper_bound: to,
    }
}

pub fn compute_interval<I>(
    bounds: PaginationInterval<I>,
    pagination_arguments: ValidatedPaginationArguments<I>,
) -> FieldResult<(PaginationInterval<I>, PageMeta)>
where
    I: TryFrom<u64> + Clone,
    u64: From<I>,
{
    let pagination_arguments = pagination_arguments.cursors_into::<u64>();
    let bounds = bounds.bounds_into::<u64>();

    let (page_interval, has_next_page, has_previous_page, total_count) = match bounds {
        PaginationInterval::Empty => (PaginationInterval::Empty, false, false, 0u64),
        PaginationInterval::Inclusive(total_elements) => {
            let InclusivePaginationInterval {
                upper_bound,
                lower_bound,
            } = total_elements;

            let page = compute_range_boundaries(total_elements, pagination_arguments);

            let has_next_page = page.upper_bound < upper_bound;
            let has_previous_page = page.lower_bound > lower_bound;

            let total_count = upper_bound
                .checked_add(1)
                .unwrap()
                .checked_sub(lower_bound)
                .expect("upper_bound should be >= than lower_bound");
            (
                PaginationInterval::Inclusive(page),
                has_next_page,
                has_previous_page,
                total_count,
            )
        }
    };

    Ok(page_interval
        .bounds_try_into::<I>()
        .map(|interval| {
            (
                interval,
                PageMeta {
                    has_next_page,
                    has_previous_page,
                    total_count,
                },
            )
        })
        .map_err(|_| "computed page interval is outside pagination boundaries")
        .unwrap())
}

impl<I> ValidatedPaginationArguments<I> {
    fn cursors_into<T>(self) -> ValidatedPaginationArguments<T>
    where
        T: From<I>,
    {
        ValidatedPaginationArguments {
            after: self.after.map(T::from),
            before: self.before.map(T::from),
            first: self.first,
            last: self.last,
        }
    }
}

pub enum PaginationInterval<I> {
    Empty,
    Inclusive(InclusivePaginationInterval<I>),
}

pub struct InclusivePaginationInterval<I> {
    pub lower_bound: I,
    pub upper_bound: I,
}

impl<I> PaginationInterval<I> {
    fn bounds_into<T>(self) -> PaginationInterval<T>
    where
        T: From<I>,
    {
        match self {
            Self::Empty => PaginationInterval::<T>::Empty,
            Self::Inclusive(interval) => {
                PaginationInterval::<T>::Inclusive(InclusivePaginationInterval::<T> {
                    lower_bound: T::from(interval.lower_bound),
                    upper_bound: T::from(interval.upper_bound),
                })
            }
        }
    }

    fn bounds_try_into<T>(self) -> Result<PaginationInterval<T>, <T as TryFrom<I>>::Error>
    where
        T: TryFrom<I>,
    {
        match self {
            Self::Empty => Ok(PaginationInterval::<T>::Empty),
            Self::Inclusive(interval) => Ok(PaginationInterval::<T>::Inclusive(
                InclusivePaginationInterval::<T> {
                    lower_bound: T::try_from(interval.lower_bound)?,
                    upper_bound: T::try_from(interval.upper_bound)?,
                },
            )),
        }
    }
}