#pagination #traits #serde #collection

paginator-rs

Pagination trait for Rust collections

3 releases

new 0.1.2 May 7, 2025
0.1.1 May 7, 2025
0.1.0 May 7, 2025

#801 in Data structures

MIT license

10KB

paginator-rs

A modular Rust library providing a reusable trait for paginating any serializable collection. Built using Cargo workspace structure for flexibility and clarity.

๐Ÿงฑ Workspace Structure

root/
โ”œโ”€โ”€ paginator/            # Main trait and implementation logic
โ”‚   โ”œโ”€โ”€ src/lib.rs
โ”‚   โ””โ”€โ”€ Cargo.toml
โ”œโ”€โ”€ paginator-utils/      # Shared types and helper functions (e.g. response format)
โ”‚   โ”œโ”€โ”€ src/lib.rs
โ”‚   โ””โ”€โ”€ Cargo.toml
โ”œโ”€โ”€ paginator-examples/   # Usage examples and test cases
โ”‚   โ”œโ”€โ”€ src/lib.rs
โ”‚   โ”œโ”€โ”€ src/examples/
โ”‚   โ””โ”€โ”€ Cargo.toml
โ”œโ”€โ”€ Cargo.toml            # Root workspace config
โ””โ”€โ”€ README.md

โœจ Features

  • PaginatorTrait<T> for consistent pagination logic
  • PaginatorResponse<T> as a standardized response structure
  • JSON serialization support using serde
  • Clean separation of logic, utilities, and examples

๐Ÿ“ฆ Installation

To use in your project, add this to your Cargo.toml:

[dependencies]
paginator-rs = "0.1.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

This project will be published to crates.io soon ๐Ÿš€

๐Ÿš€ Usage Example

use paginator_rs::{PaginatorResponse, PaginatorResponseMeta, PaginatorTrait};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UsersData {
    pub id: u32,
    pub name: String,
    pub email: String,
}

impl UsersData {
    pub fn new(id: u32, name: String, email: String) -> Self {
        UsersData { id, name, email }
    }
}

impl PaginatorTrait<UsersData> for Vec<UsersData> {
    fn paginate(&self) -> PaginatorResponse<UsersData> {
        let mut data = self.clone();
        data.sort_by(|a, b| a.id.cmp(&b.id));
        PaginatorResponse {
            data,
            meta: PaginatorResponseMeta {
                page: 1,
                per_page: self.len() as u32,
                total: self.len() as u32,
            },
        }
    }
}


fn main() {
    let users = vec![
        UsersData::new(1, "John Doe".to_string(), "john@doe.com".to_string()),
        UsersData::new(2, "Jane Doe".to_string(), "jane@doe.com".to_string()),
        UsersData::new(3, "Bob Doe".to_string(), "bob@doe.com".to_string()),
    ];
    println!("{:#?}", users.paginate());
    println!("{}", users.paginate_json());
}

๐Ÿงช Sample Output

{
  "data": [
    { "id": 1, "name": "Alpha" },
    { "id": 2, "name": "Beta" }
  ],
  "meta": {
    "page": 1,
    "per_page": 2,
    "total": 2
  }
}

๐Ÿ“„ License

MIT ยฉ 2025 Maulana Sodiqin

Dependencies

~0.6โ€“1.5MB
~31K SLoC