Skip to main content

kevy_embedded/
ops_p2.rs

1//! Hash field reads, sorted-set range queries, list slice access, and
2//! the atomic single-call string helpers `getset` / `getdel`.
3//!
4//! Every method is a thin facade over the corresponding
5//! `kevy_store::Store` method, with `commit_write` AOF logging on the
6//! write paths.
7
8use crate::KevyResult;
9
10use kevy_store::ScoreBound;
11
12use crate::store::ensure_writable;
13use crate::store::{Store, commit_write, store_err};
14
15impl Store {
16    // ---- hash mass-getters --------------------------------------------
17
18    /// `HGETALL key` — every `(field, value)` pair in `key`'s hash, in
19    /// arbitrary order. Empty when `key` is absent. Errors on wrong type.
20    pub fn hgetall(&self, key: &[u8]) -> KevyResult<Vec<(Vec<u8>, Vec<u8>)>> {
21        let flat = self.wshard(key).store.hgetall(key).map_err(store_err)?;
22        // kevy-store returns [f0, v0, f1, v1, ...] — pair them up.
23        let mut out = Vec::with_capacity(flat.len() / 2);
24        let mut it = flat.into_iter();
25        while let (Some(f), Some(v)) = (it.next(), it.next()) {
26            out.push((f, v));
27        }
28        Ok(out)
29    }
30
31    /// `HEXISTS key field` — `true` when `field` is present.
32    pub fn hexists(&self, key: &[u8], field: &[u8]) -> KevyResult<bool> {
33        self.wshard(key).store.hexists(key, field).map_err(store_err)
34    }
35
36    /// `HLEN key` — number of fields; 0 when absent.
37    pub fn hlen(&self, key: &[u8]) -> KevyResult<usize> {
38        self.wshard(key).store.hlen(key).map_err(store_err)
39    }
40
41    /// `HKEYS key` — every field name in `key`'s hash.
42    pub fn hkeys(&self, key: &[u8]) -> KevyResult<Vec<Vec<u8>>> {
43        self.wshard(key).store.hkeys(key).map_err(store_err)
44    }
45
46    /// `HRANDFIELD key count [WITHVALUES]` — random fields, distinct for a
47    /// positive count and with repeats allowed for a negative one.
48    pub fn hrandfield(
49        &self,
50        key: &[u8],
51        count: i64,
52        with_values: bool,
53    ) -> KevyResult<kevy_store::FieldValuePairs> {
54        self.wshard(key).store.hrandfield(key, count, with_values).map_err(store_err)
55    }
56
57    /// `HVALS key` — every value in `key`'s hash.
58    pub fn hvals(&self, key: &[u8]) -> KevyResult<Vec<Vec<u8>>> {
59        self.wshard(key).store.hvals(key).map_err(store_err)
60    }
61
62    /// `HMGET key field [field ...]` — read multiple fields in one
63    /// call. `None` per requested field that is absent.
64    pub fn hmget(&self, key: &[u8], fields: &[&[u8]]) -> KevyResult<Vec<Option<Vec<u8>>>> {
65        self.wshard(key).store.hmget(key, fields).map_err(store_err)
66    }
67
68    /// `HINCRBY key field delta` — atomic integer increment of a hash
69    /// field. Returns the post-increment value.
70    pub fn hincrby(&self, key: &[u8], field: &[u8], delta: i64) -> KevyResult<i64> {
71        ensure_writable(self)?;
72        let mut g = self.wshard(key);
73        let new_val = g.store.hincrby(key, field, delta).map_err(store_err)?;
74        let delta_str = format!("{delta}");
75        commit_write(&mut g, &[b"HINCRBY", key, field, delta_str.as_bytes()])?;
76        Ok(new_val)
77    }
78
79    // ---- zset mass-readers + atomic incr -----------------------------
80
81    /// `ZRANGE key start stop WITHSCORES` — members in ascending score
82    /// order between rank `start..=stop` (Redis-style inclusive
83    /// indexing; negatives count from the tail). Returns `(member,
84    /// score)` pairs.
85    pub fn zrange(&self, key: &[u8], start: i64, stop: i64) -> KevyResult<Vec<(Vec<u8>, f64)>> {
86        self.wshard(key).store.zrange(key, start, stop).map_err(store_err)
87    }
88
89    /// `ZREVRANGE key start stop WITHSCORES` — `zrange` with the order
90    /// reversed (highest score first). The `start..=stop` indexing is
91    /// against the reversed list, matching Redis semantics.
92    pub fn zrevrange(&self, key: &[u8], start: i64, stop: i64) -> KevyResult<Vec<(Vec<u8>, f64)>> {
93        self.wshard(key).store.zrevrange(key, start, stop).map_err(store_err)
94    }
95
96    /// `ZRANGEBYSCORE` — score-range read. `min` / `max` are
97    /// inclusive; pass `f64::NEG_INFINITY` / `f64::INFINITY` for open
98    /// bounds. Returns `(member, score)` pairs in ascending score
99    /// order. Exclusive bounds are `ZRANGEBYSCORE (` syntax in Redis;
100    /// expose via the dedicated [`Self::zrange_by_score_excl`].
101    pub fn zrange_by_score(
102        &self,
103        key: &[u8],
104        min: f64,
105        max: f64,
106    ) -> KevyResult<Vec<(Vec<u8>, f64)>> {
107        self.wshard(key)
108            .store
109            .zrange_by_score(
110                key,
111                ScoreBound { value: min, exclusive: false },
112                ScoreBound { value: max, exclusive: false },
113            )
114            .map_err(store_err)
115    }
116
117    /// Same as [`Self::zrange_by_score`] but with explicit
118    /// inclusive/exclusive control on each bound (`(min` / `(max` in
119    /// Redis syntax).
120    pub fn zrange_by_score_excl(
121        &self,
122        key: &[u8],
123        min: ScoreBound,
124        max: ScoreBound,
125    ) -> KevyResult<Vec<(Vec<u8>, f64)>> {
126        self.wshard(key).store.zrange_by_score(key, min, max).map_err(store_err)
127    }
128
129    /// `ZRANGEBYSCORE key min max LIMIT offset count` — score-range
130    /// read with pagination (closes the embedded LIMIT gap —
131    /// the server parser always had it).
132    pub fn zrange_by_score_limit(
133        &self,
134        key: &[u8],
135        min: f64,
136        max: f64,
137        offset: usize,
138        count: usize,
139    ) -> KevyResult<Vec<(Vec<u8>, f64)>> {
140        let all = self.zrange_by_score(key, min, max)?;
141        Ok(all.into_iter().skip(offset).take(count).collect())
142    }
143
144    /// `ZREVRANGEBYSCORE key max min LIMIT offset count` — descending
145    /// score-range read with pagination.
146    pub fn zrevrange_by_score_limit(
147        &self,
148        key: &[u8],
149        max: f64,
150        min: f64,
151        offset: usize,
152        count: usize,
153    ) -> KevyResult<Vec<(Vec<u8>, f64)>> {
154        let mut all = self.zrange_by_score(key, min, max)?;
155        all.reverse();
156        Ok(all.into_iter().skip(offset).take(count).collect())
157    }
158
159    /// `zpopmin_below` — pop up to `count` lowest members with
160    /// score strictly `< below` (delayed-job "pop what's due").
161    /// AOF logs the effect (`ZREM` of the popped members).
162    pub fn zpopmin_below(
163        &self,
164        key: &[u8],
165        below: f64,
166        count: usize,
167    ) -> KevyResult<Vec<(Vec<u8>, f64)>> {
168        ensure_writable(self)?;
169        let mut g = self.wshard(key);
170        let items = g.store.zpopmin_below(key, below, count).map_err(store_err)?;
171        if !items.is_empty() {
172            let mut argv: Vec<&[u8]> = Vec::with_capacity(2 + items.len());
173            argv.push(b"ZREM");
174            argv.push(key);
175            argv.extend(items.iter().map(|(m, _)| m.as_slice()));
176            commit_write(&mut g, &argv)?;
177        }
178        Ok(items)
179    }
180
181    /// `ZINCRBY key delta member` — atomic float increment of a member's
182    /// score. Returns the post-increment score.
183    pub fn zincrby(&self, key: &[u8], delta: f64, member: &[u8]) -> KevyResult<f64> {
184        ensure_writable(self)?;
185        let mut g = self.wshard(key);
186        let new_score = g.store.zincrby(key, delta, member).map_err(store_err)?;
187        let delta_str = format!("{delta}");
188        commit_write(&mut g, &[b"ZINCRBY", key, delta_str.as_bytes(), member])?;
189        Ok(new_score)
190    }
191
192    // ---- list slice + index ops --------------------------------------
193
194    /// `LRANGE key start stop` — list slice. Negative indices count
195    /// from the tail. Empty when absent.
196    pub fn lrange(&self, key: &[u8], start: i64, stop: i64) -> KevyResult<Vec<Vec<u8>>> {
197        self.wshard(key).store.lrange(key, start, stop).map_err(store_err)
198    }
199
200    /// `LINDEX key idx` — element at index `idx`; `None` out of range.
201    pub fn lindex(&self, key: &[u8], idx: i64) -> KevyResult<Option<Vec<u8>>> {
202        self.wshard(key).store.lindex(key, idx).map_err(store_err)
203    }
204
205    /// `LREM key count value` — remove up to `|count|` occurrences of
206    /// `value`. `count > 0` from head, `count < 0` from tail,
207    /// `count == 0` all. Returns the count actually removed.
208    pub fn lrem(&self, key: &[u8], count: i64, value: &[u8]) -> KevyResult<usize> {
209        ensure_writable(self)?;
210        let mut g = self.wshard(key);
211        let removed = g.store.lrem(key, count, value).map_err(store_err)?;
212        if removed > 0 {
213            let count_str = format!("{count}");
214            commit_write(&mut g, &[b"LREM", key, count_str.as_bytes(), value])?;
215        }
216        Ok(removed)
217    }
218
219    // ---- string single-call atomic patterns --------------------------
220
221    /// `GETSET key new` — set `key` to `new`, return the previous
222    /// value (or `None` when `key` was absent).
223    pub fn getset(&self, key: &[u8], new: &[u8]) -> KevyResult<Option<Vec<u8>>> {
224        ensure_writable(self)?;
225        let mut g = self.wshard(key);
226        let prev = g.store.getset(key, new.to_vec()).map_err(store_err)?;
227        commit_write(&mut g, &[b"SET", key, new])?;
228        Ok(prev)
229    }
230
231    /// `GETDEL key` — delete `key`, return the previous value
232    /// (`None` when `key` was absent).
233    pub fn getdel(&self, key: &[u8]) -> KevyResult<Option<Vec<u8>>> {
234        ensure_writable(self)?;
235        let mut g = self.wshard(key);
236        let prev = g.store.getdel(key).map_err(store_err)?;
237        if prev.is_some() {
238            commit_write(&mut g, &[b"DEL", key])?;
239        }
240        Ok(prev)
241    }
242}