razorpay_api/util/
pagination.rs1use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
34pub struct ListOptions {
35 #[serde(skip_serializing_if = "Option::is_none")]
37 pub from: Option<i64>,
38
39 #[serde(skip_serializing_if = "Option::is_none")]
41 pub to: Option<i64>,
42
43 #[serde(skip_serializing_if = "Option::is_none")]
45 pub count: Option<u32>,
46
47 #[serde(skip_serializing_if = "Option::is_none")]
49 pub skip: Option<u32>,
50}
51
52impl ListOptions {
53 pub fn new() -> Self {
55 Self::default()
56 }
57
58 pub fn from(mut self, from: i64) -> Self {
60 self.from = Some(from);
61 self
62 }
63
64 pub fn to(mut self, to: i64) -> Self {
66 self.to = Some(to);
67 self
68 }
69
70 pub fn count(mut self, count: u32) -> Self {
72 self.count = Some(count);
73 self
74 }
75
76 pub fn skip(mut self, skip: u32) -> Self {
78 self.skip = Some(skip);
79 self
80 }
81}
82
83#[derive(Debug, Clone, PartialEq, Deserialize)]
99pub struct Collection<T> {
100 #[serde(default)]
102 pub entity: String,
103
104 #[serde(default)]
106 pub count: u32,
107
108 #[serde(default = "Vec::new")]
110 pub items: Vec<T>,
111}
112
113impl<T> Collection<T> {
114 pub fn len(&self) -> usize {
116 self.items.len()
117 }
118
119 pub fn is_empty(&self) -> bool {
121 self.items.is_empty()
122 }
123
124 pub fn iter(&self) -> std::slice::Iter<'_, T> {
126 self.items.iter()
127 }
128}
129
130impl<T> IntoIterator for Collection<T> {
131 type Item = T;
132 type IntoIter = std::vec::IntoIter<T>;
133
134 fn into_iter(self) -> Self::IntoIter {
135 self.items.into_iter()
136 }
137}
138
139impl<'a, T> IntoIterator for &'a Collection<T> {
140 type Item = &'a T;
141 type IntoIter = std::slice::Iter<'a, T>;
142
143 fn into_iter(self) -> Self::IntoIter {
144 self.items.iter()
145 }
146}
147
148impl<T> Default for Collection<T> {
149 fn default() -> Self {
150 Self {
151 entity: "collection".to_string(),
152 count: 0,
153 items: Vec::new(),
154 }
155 }
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 #[test]
163 fn none_fields_are_omitted_entirely() {
164 let qs = serde_urlencoded::to_string(ListOptions::default()).unwrap();
166 assert_eq!(qs, "");
167 }
168
169 #[test]
170 fn set_fields_serialize() {
171 let qs = serde_urlencoded::to_string(ListOptions::new().count(10).skip(20)).unwrap();
172 assert_eq!(qs, "count=10&skip=20");
173 }
174
175 #[test]
176 fn collection_deserializes_and_iterates() {
177 let json = r#"{"entity":"collection","count":2,"items":[1,2]}"#;
178 let c: Collection<i64> = serde_json::from_str(json).unwrap();
179 assert_eq!(c.count, 2);
180 assert_eq!(c.len(), 2);
181 assert!(!c.is_empty());
182 assert_eq!(c.iter().sum::<i64>(), 3);
183 assert_eq!(c.into_iter().collect::<Vec<_>>(), vec![1, 2]);
184 }
185
186 #[test]
187 fn missing_items_defaults_to_empty_rather_than_failing() {
188 let c: Collection<i64> = serde_json::from_str(r#"{"entity":"collection","count":0}"#).unwrap();
189 assert!(c.is_empty());
190 }
191}