Laravel Rust✓ Human-reviewed

One bounded in-memory paginator in Laravel Rust

Replace one collection pagination caller with an authorized ordered snapshot, overflow-safe slicing and explicit total, JSON and link contracts.

Approved 2026-12-04T15:00:04.258211Z · Submission 94

One bounded in-memory paginator in Laravel Rust

Scope

Replace one use of the collection paginate macro over an already materialized, small authorized list. Preserve item order, total, array-shaped items, page parameter and response links/envelope. Exclude other macros, lazy/unbounded sources, database pagination, caller-supplied total overrides, cursor/simple pagination and a general collection library. Retain excluded consumers and preserve the upstream MIT notice for adapted source.

At the time of writing, the Package Port catalog listed Rust and Go gaps. Check get-recipe's current port catalog; native slices plus the app's existing response paginator may be enough. This guidance has not been exercised in your app; verify it with the checks below.

Source behaviour

src/Macros/Paginate.php resolves a falsy page through the current-page resolver, uses forPage(...)->values(), defaults a falsy total to the collection count, and constructs LengthAwarePaginator with path/page-name options. Reindexing matters: sparse PHP keys otherwise risk JSON object output. It does not query, sort or authorize the whole source before slicing.

src/CollectionMacroServiceProvider.php skips names already registered, so confirm this package really owns the caller's macro. tests/Macros/PaginateTest.php exercises total, page naming and URL behavior; it is not a contract for every other macro or malformed input.

Implementation

  1. Inventory the actual macro owner, full-list source/bound, pre-pagination authorization/filtering/order, page resolver, keys, total overrides and response/link shape. Keep large or database-backed sources on their native paginator; fetching everything to remove a macro is a regression.
  2. Produce one bounded authorized ordered snapshot before calculating either items or total. Filter before pagination so counts cannot leak foreign/private rows. If sorting is needed, preserve an explicit unique tie-breaker. Never accept comparator code or SQL/field expressions from input.
  3. Parse an integer page and bounded positive page size at the request boundary. The example deliberately rejects page zero and sizes outside 1..100 instead of reproducing upstream's falsy-page resolution. Reuse the endpoint's actual cap if different. Large positive pages return an empty list without overflow, not the first page.
  4. Slice only that snapshot and derive total from the same list. The helper returns only items, not a complete paginator. Use the app's existing resource/pagination layer for total/current/last-page metadata, query-preserving links and established empty-list conventions. Validate generated paths/hosts through existing trusted URL rules; never reflect an arbitrary next-page URL from input.
  5. Keep snapshot data immutable. A pure read needs no transaction or new cache; preserve any existing consistency boundary instead. Scoped caches must include tenant, permissions, filters, order, page and size, with existing invalidation. Do not let a shared mutable collection carry one request's filter into another.

Complete pure slicing unit for a bounded snapshot. It validates example limits and handles multiplication overflow; authorization, sorting, totals and response construction remain the caller's work:

fn page_items<T>(items: &[T], page: usize, per_page: usize) -> Result<&[T], &'static str> {
    if page == 0 || !(1..=100).contains(&per_page) {
        return Err("invalid page or size");
    }
    let Some(offset) = (page - 1).checked_mul(per_page) else {
        return Ok(&items[items.len()..]);
    };
    let start = offset.min(items.len());
    let end = start.saturating_add(per_page).min(items.len());
    Ok(&items[start..end])
}

Acceptance checklist

  • From ordered IDs [31, 7, 42, 9, 18], size 2 yields pages [31, 7], [42, 9], [18], then [], with total 5 unchanged. Empty input stays an array-shaped empty result and uses the endpoint's declared metadata convention.
  • Reject page zero, invalid/non-integer/negative request values and sizes 0/101. Test the maximum representable page without panic, overflow or returning page 1. Reject out-of-range transport integers before casting to usize.
  • Feed sparse source keys through the replacement transport and assert JSON arrays, not objects. Preserve custom page-name/query/path behavior if the real caller uses it; unsupported total overrides remain on their original path.
  • Filter private/foreign rows before totals and slicing. Repeat sort values across pages and verify stable disjoint IDs and totals. Denied requests cannot read cached counts or items.
  • Concurrent worker requests leave the source snapshot unchanged, isolate cache identities and never materialize an unbounded stream. Search all remaining macro calls before dependency removal.

Run formatting, strict Clippy, paging/resource/authorization tests and real endpoint fixtures. Record versions, outputs, memory/source bounds and deliberate differences with the change; a slicing test alone does not validate links or response metadata.

Sources

  • MIT reference source: src/Macros/Paginate.php, src/CollectionMacroServiceProvider.php, and tests/Macros/PaginateTest.php. Preserve LICENSE.md.
  • Framework source checked: crates/http/src/http/json.rs; retain the app's real pagination response contract and reconcile metadata with its lockfile. The slicing helper uses only the standard library.
  • Port options: check get-recipe's current port catalog (sourced from Package Port) at implementation time.