Skip to main content

fasm_storage/
keyspace.rs

1//! Byte-keyspace helpers: prefix successors, prefix ranges, bound conversion.
2//!
3//! Everything here is pure arithmetic on the lexicographic byte ordering that
4//! [`KvStore`](crate::KvStore) mandates. Backend implementors need it to map
5//! bounds; key-schema authors need it to turn a prefix into a scan range.
6
7use core::ops::Bound;
8
9/// Whether a range is empty solely from its bounds.
10///
11/// Every [`KvStore`](crate::KvStore) backend must normalize these ranges to an
12/// empty result before calling an engine whose native range API rejects them.
13/// A range is empty when both bounds are keyed and the start sorts after the
14/// end, or when equal keyed bounds exclude that one possible key.
15///
16/// ```
17/// use std::ops::Bound;
18///
19/// use fasm_storage::is_empty_range;
20///
21/// assert!(is_empty_range(
22///     &Bound::Included(b"z"),
23///     &Bound::Excluded(b"a"),
24/// ));
25/// assert!(is_empty_range(
26///     &Bound::Excluded(b"k"),
27///     &Bound::Included(b"k"),
28/// ));
29/// assert!(!is_empty_range(
30///     &Bound::Included(b"k"),
31///     &Bound::Included(b"k"),
32/// ));
33/// ```
34pub fn is_empty_range(start: &Bound<&[u8]>, end: &Bound<&[u8]>) -> bool {
35    match (start, end) {
36        (
37            Bound::Included(start_key) | Bound::Excluded(start_key),
38            Bound::Included(end_key) | Bound::Excluded(end_key),
39        ) => {
40            start_key > end_key
41                || (start_key == end_key
42                    && (matches!(start, Bound::Excluded(_)) || matches!(end, Bound::Excluded(_))))
43        }
44        _ => false,
45    }
46}
47
48/// Returns the shortest byte string that sorts strictly after every key
49/// beginning with `prefix`, or `None` when no such string exists.
50///
51/// This is the "successor" of a prefix: incrementing the last byte below `0xFF`
52/// and truncating everything after it. `Excluded(next_prefix(p))` is therefore
53/// the exact upper bound of the `p` namespace.
54///
55/// # The all-`0xFF` case
56///
57/// A prefix consisting entirely of `0xFF` bytes has **no** successor — every
58/// byte is already at its maximum, so there is nothing to carry into. `None`
59/// means *unbounded*: the namespace runs to the end of the keyspace, and the
60/// caller must use [`Bound::Unbounded`] rather than inventing a sentinel. An
61/// implementation that "solves" this by appending `0xFF` bytes is wrong: it
62/// would exclude keys such as `[0xFF, 0xFF, 0xFF]` from the `[0xFF, 0xFF]`
63/// namespace.
64///
65/// The empty prefix is the degenerate case of the same rule: it matches the
66/// entire keyspace, so it has no successor either.
67///
68/// ```
69/// use fasm_storage::next_prefix;
70///
71/// assert_eq!(next_prefix(&[0x10, 0x20]), Some(vec![0x10, 0x21]));
72/// // The carry truncates: everything after the incremented byte is dropped.
73/// assert_eq!(next_prefix(&[0x10, 0xFF]), Some(vec![0x11]));
74/// // No successor exists.
75/// assert_eq!(next_prefix(&[0xFF, 0xFF]), None);
76/// assert_eq!(next_prefix(&[]), None);
77/// ```
78pub fn next_prefix(prefix: &[u8]) -> Option<Vec<u8>> {
79    let mut next = prefix.to_vec();
80    for i in (0..next.len()).rev() {
81        if next[i] != 0xFF {
82            next[i] += 1;
83            next.truncate(i + 1);
84            return Some(next);
85        }
86    }
87    None
88}
89
90/// Returns the bound pair that matches exactly the keys carrying `prefix`.
91///
92/// The upper bound is `Excluded(next_prefix(prefix))`, falling back to
93/// [`Bound::Unbounded`] when the prefix has no successor (see
94/// [`next_prefix`]).
95///
96/// ```
97/// use std::ops::Bound;
98///
99/// use fasm_storage::prefix_range;
100///
101/// let (start, end) = prefix_range(&[0x10, 0x20]);
102/// assert_eq!(start, Bound::Included(vec![0x10, 0x20]));
103/// assert_eq!(end, Bound::Excluded(vec![0x10, 0x21]));
104///
105/// let (_, end) = prefix_range(&[0xFF, 0xFF]);
106/// assert_eq!(end, Bound::Unbounded);
107/// ```
108pub fn prefix_range(prefix: &[u8]) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
109    let start = Bound::Included(prefix.to_vec());
110    let end = match next_prefix(prefix) {
111        Some(next) => Bound::Excluded(next),
112        None => Bound::Unbounded,
113    };
114    (start, end)
115}
116
117/// Copy a borrowed bound into an owned one.
118///
119/// Backends that hand bounds to an owning collection (a `BTreeMap` range, a
120/// query builder) need this because [`KvStore::range`](crate::KvStore::range)
121/// borrows its bounds for the call only.
122pub fn bound_to_owned(bound: Bound<&[u8]>) -> Bound<Vec<u8>> {
123    match bound {
124        Bound::Included(bytes) => Bound::Included(bytes.to_vec()),
125        Bound::Excluded(bytes) => Bound::Excluded(bytes.to_vec()),
126        Bound::Unbounded => Bound::Unbounded,
127    }
128}
129
130/// Borrow an owned bound as a slice bound.
131///
132/// The inverse of [`bound_to_owned`], for handing a computed bound back down to
133/// an inner [`KvStore`](crate::KvStore).
134pub fn bound_as_slice(bound: &Bound<Vec<u8>>) -> Bound<&[u8]> {
135    match bound {
136        Bound::Included(bytes) => Bound::Included(bytes.as_slice()),
137        Bound::Excluded(bytes) => Bound::Excluded(bytes.as_slice()),
138        Bound::Unbounded => Bound::Unbounded,
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
145    use super::{bound_as_slice, bound_to_owned};
146    use super::{is_empty_range, next_prefix, prefix_range};
147    use core::ops::Bound;
148
149    // `proptest` reaches `wait-timeout`, which does not support browser wasm.
150    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
151    use proptest::prelude::*;
152
153    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
154    use crate::tests::{arb_key, bounds_contain};
155
156    #[test]
157    fn next_prefix_increments_last_non_ff_byte() {
158        assert_eq!(next_prefix(&[0x00]), Some(vec![0x01]));
159        assert_eq!(next_prefix(&[0x10, 0x20]), Some(vec![0x10, 0x21]));
160        assert_eq!(next_prefix(&[0xFE]), Some(vec![0xFF]));
161    }
162
163    #[test]
164    fn next_prefix_carries_and_truncates() {
165        assert_eq!(next_prefix(&[0x10, 0xFF]), Some(vec![0x11]));
166        assert_eq!(next_prefix(&[0x10, 0xFF, 0xFF]), Some(vec![0x11]));
167        assert_eq!(next_prefix(&[0x00, 0xFF, 0xFF]), Some(vec![0x01]));
168    }
169
170    #[test]
171    fn next_prefix_has_no_successor_for_all_ff_or_empty() {
172        assert_eq!(next_prefix(&[0xFF]), None);
173        assert_eq!(next_prefix(&[0xFF, 0xFF, 0xFF]), None);
174        assert_eq!(next_prefix(&[]), None);
175    }
176
177    #[test]
178    fn prefix_range_bounds_the_namespace() {
179        let (start, end) = prefix_range(&[0x10, 0x20]);
180        assert_eq!(start, Bound::Included(vec![0x10, 0x20]));
181        assert_eq!(end, Bound::Excluded(vec![0x10, 0x21]));
182    }
183
184    #[test]
185    fn prefix_range_is_unbounded_above_for_all_ff() {
186        let (start, end) = prefix_range(&[0xFF, 0xFF]);
187        assert_eq!(start, Bound::Included(vec![0xFF, 0xFF]));
188        assert_eq!(end, Bound::Unbounded);
189
190        // The `Unbounded` answer is the correct one: longer all-0xFF keys are
191        // inside the namespace and must not be excluded.
192        let inside: &[u8] = &[0xFF, 0xFF, 0xFF];
193        assert!(inside.starts_with(&[0xFF, 0xFF]));
194    }
195
196    #[test]
197    fn empty_range_covers_inverted_and_equal_exclusive_bounds() {
198        assert!(is_empty_range(
199            &Bound::Included(b"z"),
200            &Bound::Excluded(b"a")
201        ));
202        assert!(is_empty_range(
203            &Bound::Excluded(b"z"),
204            &Bound::Included(b"a")
205        ));
206        assert!(is_empty_range(
207            &Bound::Excluded(b"k"),
208            &Bound::Excluded(b"k")
209        ));
210        assert!(is_empty_range(
211            &Bound::Included(b"k"),
212            &Bound::Excluded(b"k")
213        ));
214        assert!(is_empty_range(
215            &Bound::Excluded(b"k"),
216            &Bound::Included(b"k")
217        ));
218
219        assert!(!is_empty_range(
220            &Bound::Included(b"k"),
221            &Bound::Included(b"k")
222        ));
223        assert!(!is_empty_range(&Bound::Unbounded, &Bound::Excluded(b"k")));
224        assert!(!is_empty_range(&Bound::Included(b"k"), &Bound::Unbounded));
225    }
226
227    /// Arbitrary owned bound over [`arb_key`] bytes.
228    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
229    fn arb_bound() -> impl Strategy<Value = Bound<Vec<u8>>> {
230        prop_oneof![
231            Just(Bound::Unbounded),
232            arb_key().prop_map(Bound::Included),
233            arb_key().prop_map(Bound::Excluded),
234        ]
235    }
236
237    /// A key drawn from the *neighbourhood* of `prefix`.
238    ///
239    /// An independently drawn key essentially never lands on the boundary a
240    /// prefix range is defined by, so a bound that is off by one key would go
241    /// unnoticed. The keys that matter are the prefix's own extensions, the
242    /// first key past it (some byte carried, everything after it dropped — the
243    /// shape a successor has), and its truncations. Those are generated
244    /// deliberately, with unrelated keys mixed in.
245    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
246    fn arb_key_near(prefix: Vec<u8>) -> impl Strategy<Value = Vec<u8>> {
247        let extension = (Just(prefix.clone()), arb_key()).prop_map(|(mut key, tail)| {
248            key.extend_from_slice(&tail);
249            key
250        });
251        let successor = (
252            Just(prefix.clone()),
253            arb_key(),
254            any::<prop::sample::Index>(),
255        )
256            .prop_map(|(prefix, tail, index)| {
257                if prefix.is_empty() {
258                    return tail;
259                }
260                let at = index.index(prefix.len());
261                let mut key = prefix[..=at].to_vec();
262                key[at] = key[at].wrapping_add(1);
263                key.extend_from_slice(&tail);
264                key
265            });
266        let truncation =
267            (Just(prefix), any::<prop::sample::Index>()).prop_map(|(prefix, index)| {
268                if prefix.is_empty() {
269                    return prefix;
270                }
271                prefix[..index.index(prefix.len())].to_vec()
272            });
273
274        prop_oneof![
275            3 => extension,
276            3 => successor,
277            2 => truncation,
278            2 => arb_key(),
279        ]
280    }
281
282    /// A prefix together with a key from its neighbourhood.
283    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
284    fn arb_prefix_and_key() -> impl Strategy<Value = (Vec<u8>, Vec<u8>)> {
285        arb_key().prop_flat_map(|prefix| (Just(prefix.clone()), arb_key_near(prefix)))
286    }
287
288    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
289    proptest! {
290        /// The defining property of [`prefix_range`]: its bounds select exactly
291        /// the keys carrying the prefix, no more and no less. Every key schema
292        /// in the SDK turns a prefix into a scan this way, so an off-by-one here
293        /// would either hide rows or leak a neighbouring namespace's.
294        #[test]
295        fn prop_prefix_range_selects_exactly_the_prefixed_keys(
296            (prefix, key) in arb_prefix_and_key(),
297        ) {
298            prop_assert_eq!(
299                key.starts_with(&prefix),
300                bounds_contain(&prefix_range(&prefix), &key),
301            );
302        }
303
304        /// The same law stated where it bites: an arbitrary *extension* of the
305        /// prefix is always inside the range. Drawing the key independently
306        /// above rarely produces one.
307        #[test]
308        fn prop_prefix_range_contains_every_extension(prefix in arb_key(), tail in arb_key()) {
309            let mut key = prefix.clone();
310            key.extend_from_slice(&tail);
311            prop_assert!(bounds_contain(&prefix_range(&prefix), &key));
312        }
313
314        /// `next_prefix` is a *strict* upper bound: every key beginning with the
315        /// prefix sorts before it. An implementation that appended `0xFF` bytes
316        /// instead of carrying would fail this for long all-`0xFF` extensions.
317        #[test]
318        fn prop_next_prefix_strictly_exceeds_every_extension(
319            prefix in arb_key(),
320            tail in arb_key(),
321        ) {
322            let Some(next) = next_prefix(&prefix) else {
323                return Ok(());
324            };
325            let mut key = prefix.clone();
326            key.extend_from_slice(&tail);
327            prop_assert!(
328                key.as_slice() < next.as_slice(),
329                "{:02x?} must sort before {:02x?}",
330                key,
331                next
332            );
333        }
334
335        /// There is no successor exactly when every byte is already at its
336        /// maximum — which the empty prefix satisfies vacuously.
337        #[test]
338        fn prop_next_prefix_is_none_exactly_for_all_ff(prefix in arb_key()) {
339            prop_assert_eq!(
340                next_prefix(&prefix).is_none(),
341                prefix.iter().all(|byte| *byte == 0xFF),
342            );
343        }
344
345        #[test]
346        fn prop_bound_conversions_round_trip(bound in arb_bound()) {
347            prop_assert_eq!(bound_to_owned(bound_as_slice(&bound)), bound);
348        }
349    }
350}