use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct ListOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub from: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub to: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub count: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub skip: Option<u32>,
}
impl ListOptions {
pub fn new() -> Self {
Self::default()
}
pub fn from(mut self, from: i64) -> Self {
self.from = Some(from);
self
}
pub fn to(mut self, to: i64) -> Self {
self.to = Some(to);
self
}
pub fn count(mut self, count: u32) -> Self {
self.count = Some(count);
self
}
pub fn skip(mut self, skip: u32) -> Self {
self.skip = Some(skip);
self
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Collection<T> {
#[serde(default)]
pub entity: String,
#[serde(default)]
pub count: u32,
#[serde(default = "Vec::new")]
pub items: Vec<T>,
}
impl<T> Collection<T> {
pub fn len(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn iter(&self) -> std::slice::Iter<'_, T> {
self.items.iter()
}
}
impl<T> IntoIterator for Collection<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.items.into_iter()
}
}
impl<'a, T> IntoIterator for &'a Collection<T> {
type Item = &'a T;
type IntoIter = std::slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.items.iter()
}
}
impl<T> Default for Collection<T> {
fn default() -> Self {
Self {
entity: "collection".to_string(),
count: 0,
items: Vec::new(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn none_fields_are_omitted_entirely() {
let qs = serde_urlencoded::to_string(ListOptions::default()).unwrap();
assert_eq!(qs, "");
}
#[test]
fn set_fields_serialize() {
let qs = serde_urlencoded::to_string(ListOptions::new().count(10).skip(20)).unwrap();
assert_eq!(qs, "count=10&skip=20");
}
#[test]
fn collection_deserializes_and_iterates() {
let json = r#"{"entity":"collection","count":2,"items":[1,2]}"#;
let c: Collection<i64> = serde_json::from_str(json).unwrap();
assert_eq!(c.count, 2);
assert_eq!(c.len(), 2);
assert!(!c.is_empty());
assert_eq!(c.iter().sum::<i64>(), 3);
assert_eq!(c.into_iter().collect::<Vec<_>>(), vec![1, 2]);
}
#[test]
fn missing_items_defaults_to_empty_rather_than_failing() {
let c: Collection<i64> = serde_json::from_str(r#"{"entity":"collection","count":0}"#).unwrap();
assert!(c.is_empty());
}
}