Skip to main content

kevy_embedded/
ops_scan.rs

1//! Cursor-based and iterator-based scanning: `scan` / `hscan` /
2//! `zscan` plus the `keys_iter` / `hash_iter` / `zset_iter` adapters.
3//!
4//! Two API shapes:
5//!
6//! - **Cursor-based** (Redis-shaped): `scan(cursor, pattern, count) ->
7//!   (next_cursor, batch)`. A `cursor` of `0` starts a fresh walk; a
8//!   returned `next_cursor` of `0` means the walk completed.
9//! - **Iterator-based** (Rust-shaped): `keys_iter(pattern) -> impl
10//!   Iterator<Item = Vec<u8>>`, etc.
11//!
12//! Each call snapshots the matching set in one shot and slices into
13//! it by cursor. The snapshot is stable across a single walk even
14//! while other writers mutate concurrently, and the memory cost is
15//! bounded by the matching subset.
16
17use crate::KevyResult;
18
19use crate::store::{Store, store_err};
20
21/// One `HSCAN`/`ZSCAN`-style page: `(next_cursor, items)` where each
22/// item is a `(member, value-or-score)` pair.
23type PairPage = (u64, Vec<(Vec<u8>, Vec<u8>)>);
24
25/// One `ZSCAN` page: `(next_cursor, (member, score) pairs)`.
26type ScorePage = (u64, Vec<(Vec<u8>, f64)>);
27
28impl Store {
29    // ---- keyspace scan ----------------------------------------------
30
31    /// `SCAN cursor [MATCH pattern] [COUNT n]` — return up to `count`
32    /// keys, plus the next cursor. `cursor = 0` starts the walk;
33    /// `next_cursor = 0` means the walk completed.
34    ///
35    /// `count` is the page size; pass `usize::MAX` to drain in one
36    /// call.
37    pub fn scan(&self, cursor: u64, pattern: Option<&[u8]>, count: usize) -> (u64, Vec<Vec<u8>>) {
38        let all = self.collect_keys(pattern, None);
39        page_into(all, cursor, count)
40    }
41
42    /// Iterator wrapper around [`Self::scan`] — emits every matching
43    /// key as a `Vec<u8>`. Drains the keyspace in one snapshot at
44    /// construction time; matches Rust idioms.
45    pub fn keys_iter(&self, pattern: Option<&[u8]>) -> std::vec::IntoIter<Vec<u8>> {
46        self.collect_keys(pattern, None).into_iter()
47    }
48
49    // ---- hash scan --------------------------------------------------
50
51    /// `HSCAN key cursor [COUNT n]` — return up to `count` `(field,
52    /// value)` pairs from the hash at `key`, plus the next cursor.
53    /// `cursor = 0` starts; `next_cursor = 0` means complete.
54    pub fn hscan(&self, key: &[u8], cursor: u64, count: usize) -> KevyResult<PairPage> {
55        let pairs = self.hgetall(key)?;
56        Ok(page_into(pairs, cursor, count))
57    }
58
59    /// Iterator wrapper around [`Self::hscan`].
60    pub fn hash_iter(&self, key: &[u8]) -> KevyResult<std::vec::IntoIter<(Vec<u8>, Vec<u8>)>> {
61        Ok(self.hgetall(key)?.into_iter())
62    }
63
64    // ---- zset scan --------------------------------------------------
65
66    /// `ZSCAN key cursor [COUNT n]` — return up to `count` `(member,
67    /// score)` pairs from the sorted set at `key`, in ascending score
68    /// order, plus the next cursor.
69    pub fn zscan(&self, key: &[u8], cursor: u64, count: usize) -> KevyResult<ScorePage> {
70        let pairs = self.wshard(key).store.zrange(key, 0, -1).map_err(store_err)?;
71        Ok(page_into(pairs, cursor, count))
72    }
73
74    /// Iterator wrapper around [`Self::zscan`].
75    pub fn zset_iter(&self, key: &[u8]) -> KevyResult<std::vec::IntoIter<(Vec<u8>, f64)>> {
76        let pairs = self.wshard(key).store.zrange(key, 0, -1).map_err(store_err)?;
77        Ok(pairs.into_iter())
78    }
79}
80
81/// Slice `data[cursor..cursor+count]` and report the next cursor
82/// (`0` when the walk completed).
83fn page_into<T>(data: Vec<T>, cursor: u64, count: usize) -> (u64, Vec<T>) {
84    let total = data.len();
85    let start = (cursor as usize).min(total);
86    let end = start.saturating_add(count).min(total);
87    let batch = data.into_iter().skip(start).take(end - start).collect();
88    let next_cursor = if end >= total { 0 } else { end as u64 };
89    (next_cursor, batch)
90}