Skip to main content

fasm_storage/flatdir/
tuple.rs

1//! The tuple byte encoding the flat directory layout uses for its row
2//! keys.
3//!
4//! This is a port of the subset of the FoundationDB tuple packing format
5//! that the directory layout produces and consumes: integer elements,
6//! byte-string elements, string (UTF-8) elements, and depth-0 tuples of
7//! them. It replicates the encoding of the `foundationdb-tuple` crate at
8//! the version the fdb backend is built against, so that keys produced
9//! here are byte-identical to the keys the FoundationDB directory layer
10//! would write for the same paths.
11//!
12//! What is ported, and why it is sufficient:
13//!
14//! - `i64` — the allocated prefixes, the HCA window starts and candidate
15//!   values, and the fixed `0` first element of child-row keys.
16//! - bytes (`&[u8]`) — node subspaces are addressed by the raw allocated
17//!   prefix bytes, and the `version` / `layer` / `hca` row tags are byte
18//!   strings in the layer's own code.
19//! - string (`&str`) — directory segment names in child-row keys.
20//! - depth-0 tuples — the only multi-element key the layout builds is
21//!   `(0i64, name)` for child rows.
22//!
23//! What is not ported: `None`, `bool`, `f64`, versionstamps, and nested
24//! (depth > 0) elements. The layout never produces or consumes them; a
25//! row whose encoding needs one of them cannot be a valid row of this
26//! layout, and the strict decoders here reject it.
27//!
28//! Element codes (matching the `foundationdb-tuple` crate):
29//!
30//! | Code | Meaning |
31//! |------|---------|
32//! | `0x00` | terminator of a byte/string payload (after escaping) |
33//! | `0x01` | BYTES element |
34//! | `0x02` | STRING element |
35//! | `0x0b` | start of the integer band (`NEGINTSTART`); `i64` values pack into `0x14±len` with `len` ≤ 8, so `i64` codes stay within `0x0c..=0x1c` |
36//! | `0x14` | INT zero; `0x14+len` / `0x14-len` carry positive / negative integers |
37//! | `0x1d` | end of the integer band (`POSINTEND`; not produced by `i64` packing) |
38//! | `0xff` | escape: inside a byte/string payload, `0x00` is written as `0x00 0xff` |
39//!
40//! Byte/string payloads carry no length prefix: they end at the first
41//! unescaped `0x00`. An element is therefore self-delimiting, which is
42//! what makes the row keys decodable one element at a time.
43
44/// Code for a BYTES element.
45pub const CODE_BYTES: u8 = 0x01;
46/// Code for a STRING element.
47pub const CODE_STRING: u8 = 0x02;
48/// Code for the integer `0`; `0x14 ± len` carries other integers.
49pub const CODE_INT_ZERO: u8 = 0x14;
50/// Escape byte: inside a payload, `0x00 0xff` stands for one `0x00`.
51pub const ESCAPE: u8 = 0xff;
52
53/// Pack an `i64` as a top-level tuple element.
54///
55/// `0` packs to the single byte `0x14`. `n > 0` packs to `0x14 + len`
56/// followed by the `len` most significant big-endian bytes of `n`.
57/// `n < 0` packs to `0x14 - len` followed by the `len` most significant
58/// big-endian bytes of `n - 1`. `len` is the smallest count in 1..=8
59/// that holds the value's magnitude representation.
60///
61/// Every `i64` packs to 1..=9 bytes and the first byte alone determines
62/// the length (two integers of different lengths have different first
63/// bytes), so no packed `i64` is a byte-prefix of another.
64pub fn pack_i64(value: i64) -> Vec<u8> {
65    let mut out = Vec::with_capacity(9);
66    if value == 0 {
67        out.push(CODE_INT_ZERO);
68        return out;
69    }
70    // Ported from `foundationdb-tuple`'s `impl_ix!(i64, u64)`: `n` is the
71    // minimal byte count holding the value's magnitude.
72    let magnitude = value.wrapping_abs() as u64;
73    let n = 8 - (magnitude.leading_zeros() as usize) / 8;
74    if value > 0 {
75        out.push(CODE_INT_ZERO + n as u8);
76        out.extend_from_slice(&(value as u64).to_be_bytes()[8 - n..]);
77    } else {
78        // FDB encodes a negative n as the magnitude of n - 1: the payload
79        // is the low `n` bytes of (value - 1) in two's complement.
80        out.push(CODE_INT_ZERO - n as u8);
81        out.extend_from_slice(&value.wrapping_sub(1).to_be_bytes()[8 - n..]);
82    }
83    out
84}
85
86/// Pack a byte string as a top-level BYTES element.
87///
88/// `0x01`, the payload with every `0x00` written as `0x00 0xff`, and a
89/// terminating `0x00`. No length prefix.
90pub fn pack_bytes(payload: &[u8]) -> Vec<u8> {
91    let mut out =
92        Vec::with_capacity(2 + payload.len() + payload.iter().filter(|&&b| b == 0).count());
93    out.push(CODE_BYTES);
94    for &b in payload {
95        out.push(b);
96        if b == 0 {
97            out.push(ESCAPE);
98        }
99    }
100    out.push(0x00);
101    out
102}
103
104/// Pack a string as a top-level STRING element (UTF-8 bytes with the
105/// same escaping as [`pack_bytes`]).
106pub fn pack_string(payload: &str) -> Vec<u8> {
107    let mut out = pack_bytes(payload.as_bytes());
108    out[0] = CODE_STRING;
109    out
110}
111
112/// Decode a top-level integer element that fills `bytes` exactly.
113///
114/// `None` when the bytes are not a well-formed single integer element
115/// (bad code byte, truncated payload, or trailing bytes after it).
116pub fn unpack_i64_full(bytes: &[u8]) -> Option<i64> {
117    let (&code, rest) = bytes.split_first()?;
118    if code == CODE_INT_ZERO {
119        return rest.is_empty().then_some(0);
120    }
121    let code = code as i8;
122    let (positive, n) = if code > CODE_INT_ZERO as i8 {
123        (true, (code - CODE_INT_ZERO as i8) as usize)
124    } else if code < CODE_INT_ZERO as i8 {
125        (false, (CODE_INT_ZERO as i8 - code) as usize)
126    } else {
127        return None;
128    };
129    if !(1..=8).contains(&n) || rest.len() != n {
130        return None;
131    }
132    // Sign-extend exactly as `foundationdb-tuple` does (zero for
133    // positives, 0xFF for negatives). Like the FDB decoder, non-minimal
134    // encodings (a leading zero payload byte) decode to the same value
135    // rather than being rejected.
136    let mut arr = [0u8; 8];
137    if !positive {
138        for b in arr.iter_mut() {
139            *b = 0xFF;
140        }
141    }
142    arr[8 - n..].copy_from_slice(rest);
143    let v = i64::from_be_bytes(arr);
144    if positive {
145        (v >= 0).then_some(v)
146    } else {
147        // FDB stores the magnitude of value - 1, so add one back
148        // (wrapping: the all-0xFF 8-byte payload decodes to `i64::MIN`).
149        let x = v.wrapping_add(1);
150        (x <= 0).then_some(x)
151    }
152}
153
154/// Walk an element payload from the start of `rest` (the bytes after
155/// the code byte). Returns the extent of the element in `rest` — up to
156/// and including the terminating 0x00 — or `None` when the payload runs
157/// off the end without a terminator.
158fn element_extent(rest: &[u8]) -> Option<usize> {
159    let mut i = 0;
160    while i < rest.len() {
161        let b = rest[i];
162        if b == 0 {
163            if i + 1 < rest.len() && rest[i + 1] == ESCAPE {
164                i += 2;
165            } else {
166                return Some(i + 1);
167            }
168        } else {
169            i += 1;
170        }
171    }
172    None
173}
174
175/// Unescape a payload (the element bytes without the terminator).
176pub fn unescape_payload(escaped: &[u8]) -> Option<Vec<u8>> {
177    let mut payload = Vec::with_capacity(escaped.len());
178    let mut i = 0;
179    while i < escaped.len() {
180        let b = escaped[i];
181        if b == 0 {
182            if i + 1 < escaped.len() && escaped[i + 1] == ESCAPE {
183                payload.push(0);
184                i += 2;
185            } else {
186                return None;
187            }
188        } else {
189            payload.push(b);
190            i += 1;
191        }
192    }
193    Some(payload)
194}
195
196/// Decode a top-level BYTES or STRING element that fills `bytes`
197/// exactly, returning the unescaped payload (owned: escapes shorten the
198/// payload, so it is not a slice of the input).
199///
200/// `None` on a bad code byte, an unterminated payload, or trailing bytes
201/// after the terminator.
202pub fn unpack_element_full(bytes: &[u8]) -> Option<Vec<u8>> {
203    let (&code, rest) = bytes.split_first()?;
204    if code != CODE_BYTES && code != CODE_STRING {
205        return None;
206    }
207    let extent = element_extent(rest)?;
208    if extent != rest.len() {
209        return None;
210    }
211    unescape_payload(&rest[..extent - 1])
212}
213
214/// Decode the leading BYTES or STRING element of `key` (up to its
215/// terminator) and return the unescaped payload (owned); the bytes after
216/// the terminator are ignored. `None` on a bad code byte or an
217/// unterminated payload.
218pub fn first_element_payload(key: &[u8]) -> Option<Vec<u8>> {
219    let (&code, rest) = key.split_first()?;
220    if code != CODE_BYTES && code != CODE_STRING {
221        return None;
222    }
223    let extent = element_extent(rest)?;
224    unescape_payload(&rest[..extent - 1])
225}
226
227/// Decode a top-level STRING element that fills `bytes` exactly, as UTF-8.
228pub fn unpack_string_full(bytes: &[u8]) -> Option<String> {
229    let (&code, _rest) = bytes.split_first()?;
230    if code != CODE_STRING {
231        return None;
232    }
233    core::str::from_utf8(&unpack_element_full(bytes)?)
234        .ok()
235        .map(str::to_owned)
236}
237/// Decode the child-row key trailing a node subspace: a depth-0 tuple
238/// `(0i64, STRING(name))` filling `bytes` exactly.
239///
240/// Returns the segment name (owned). `None` when the first element is
241/// not the integer `0` or the second is not a well-formed string element.
242pub fn unpack_child_name(bytes: &[u8]) -> Option<String> {
243    let int_zero = pack_i64(0);
244    let (first, rest) = bytes.split_at_checked(int_zero.len())?;
245    if first != int_zero.as_slice() {
246        return None;
247    }
248    unpack_string_full(rest)
249}
250
251/// Decode the first element of a key and return its payload, without
252/// requiring the rest to be well-formed.
253///
254/// Used by the node-region "does an existing node contain this key"
255/// probe, where only the leading element (the node's allocated prefix)
256/// matters. The element must be BYTES or STRING; a key starting with any
257/// other element (an integer, a nested tuple) has no leading byte-string
258/// and returns `None`.
259pub fn first_bytes_element(key: &[u8]) -> Option<&[u8]> {
260    let (&code, rest) = key.split_first()?;
261    if code != CODE_BYTES && code != CODE_STRING {
262        return None;
263    }
264    // Walk to the terminating unescaped 0x00.
265    let mut i = 0;
266    while i < rest.len() {
267        if rest[i] == 0 {
268            if i + 1 < rest.len() && rest[i + 1] == ESCAPE {
269                i += 2;
270            } else {
271                return Some(&rest[..i]);
272            }
273        } else {
274            i += 1;
275        }
276    }
277    None
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    // Vectors pinned from the `foundationdb-tuple` crate's own test
285    // suite (the crate the fdb backend builds against): these are the
286    // byte-identity ground truth for the port.
287
288    #[test]
289    fn integer_vectors() {
290        assert_eq!(pack_i64(0), vec![0x14]);
291        assert_eq!(pack_i64(1), vec![0x15, 0x01]);
292        assert_eq!(pack_i64(-1), vec![0x13, 0xfe]);
293        assert_eq!(pack_i64(100), vec![0x15, 100]);
294        assert_eq!(pack_i64(255), vec![0x15, 0xff]);
295        assert_eq!(pack_i64(256), vec![0x16, 0x01, 0x00]);
296        assert_eq!(pack_i64(-256), vec![0x12, 0xfe, 0xff]);
297        assert_eq!(pack_i64(-257), vec![0x12, 0xfe, 0xfe]);
298        assert_eq!(
299            pack_i64(i64::MAX),
300            vec![0x1c, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
301        );
302        assert_eq!(
303            pack_i64(i64::MIN),
304            vec![0x0c, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
305        );
306    }
307
308    #[test]
309    fn byte_and_string_vectors() {
310        assert_eq!(pack_bytes(b""), vec![0x01, 0x00]);
311        assert_eq!(pack_bytes(b"\0"), vec![0x01, 0x00, 0xff, 0x00]);
312        assert_eq!(
313            pack_bytes(b"foo\0bar"),
314            vec![0x01, 0x66, 0x6f, 0x6f, 0x00, 0xff, 0x62, 0x61, 0x72, 0x00]
315        );
316        assert_eq!(pack_string(""), vec![0x02, 0x00]);
317        // "FÔO\0bar" (Ô = U+00D4 = c3 94 in UTF-8).
318        assert_eq!(
319            pack_string("F\u{00d4}O\0bar"),
320            vec![
321                0x02, 0x46, 0xc3, 0x94, 0x4f, 0x00, 0xff, 0x62, 0x61, 0x72, 0x00
322            ]
323        );
324        assert_eq!(pack_string("hca"), vec![0x02, 0x68, 0x63, 0x61, 0x00]);
325    }
326
327    #[test]
328    fn integer_round_trips() {
329        let values: [i64; 18] = [
330            0,
331            1,
332            -1,
333            2,
334            -2,
335            127,
336            128,
337            -128,
338            129,
339            -129,
340            255,
341            256,
342            -256,
343            -257,
344            0x7fff_ffff,
345            i64::MAX,
346            i64::MIN,
347            -i64::MAX,
348        ];
349        for v in values {
350            let packed = pack_i64(v);
351            assert_eq!(unpack_i64_full(&packed), Some(v), "round trip {v}");
352        }
353    }
354
355    #[test]
356    fn byte_round_trips() {
357        let payloads: [&[u8]; 6] = [
358            b"",
359            b"\0",
360            b"\0\0",
361            b"foo",
362            b"foo\0bar\0",
363            &[0xff, 0x00, 0xff, 0x01, 0x00, 0x02],
364        ];
365        for p in payloads {
366            assert_eq!(
367                unpack_element_full(&pack_bytes(p)),
368                Some(p.to_vec()),
369                "round trip {p:?}"
370            );
371        }
372        for p in ["", "a", "hca", "version", "layer", "\u{00d4}\0"] {
373            assert_eq!(
374                unpack_string_full(&pack_string(p)),
375                Some(p.to_string()),
376                "round trip {p:?}"
377            );
378        }
379    }
380
381    #[test]
382    fn packed_integers_are_prefix_free() {
383        // The layout's core disjointness property: no packed i64 is a
384        // byte-prefix of another, so `prefix ‖ key` needs no separator.
385        let values: Vec<i64> = (0..4000).chain(-4000..0).collect();
386        for (i, &a) in values.iter().enumerate() {
387            let pa = pack_i64(a);
388            for &b in values.iter().skip(i + 1) {
389                let pb = pack_i64(b);
390                assert!(
391                    !pa.starts_with(&pb) && !pb.starts_with(&pa),
392                    "{a} and {b} must not prefix each other"
393                );
394            }
395        }
396    }
397
398    #[test]
399    fn strict_decoders_reject_malformed_input() {
400        assert_eq!(unpack_i64_full(&[]), None);
401        assert_eq!(unpack_i64_full(&[0x14, 0x00]), None); // trailing after zero
402        assert_eq!(unpack_i64_full(&[0x15]), None); // truncated payload
403        assert_eq!(unpack_i64_full(&[0x00]), None); // not an integer code
404        assert_eq!(unpack_i64_full(&[0x01, 0x00]), None); // an element, not an int
405        // Band edges: codes 0x0b and 0x1d imply a 9-byte payload, which
406        // no i64 encoding emits (i64 packs within `0x0c..=0x1c`).
407        assert_eq!(unpack_i64_full(&[0x0b; 10]), None);
408        assert_eq!(unpack_i64_full(&[0x1d, 0, 0, 0, 0, 0, 0, 0, 0, 0]), None);
409        assert_eq!(unpack_element_full(&[]), None);
410        assert_eq!(unpack_element_full(&[0x01]), None); // unterminated
411        assert_eq!(unpack_element_full(&[0x01, 0x00, 0x00]), None); // trailing
412        assert_eq!(unpack_element_full(&[0x14]), None); // integer code
413        // A string element with invalid UTF-8 payload.
414        assert_eq!(unpack_string_full(&[0x02, 0xff, 0x00]), None);
415        assert_eq!(
416            unpack_string_full(&[0x02, 0x41, 0x00]).unwrap(),
417            "A".to_string()
418        );
419    }
420
421    /// Non-minimal integer encodings (a leading zero payload byte)
422    /// decode to the same value rather than being rejected — verbatim
423    /// FDB.
424    #[test]
425    fn non_minimal_integers_decode_to_the_same_value() {
426        // 5 minimally packs as [0x15, 0x05]; the 2-byte form must
427        // decode identically.
428        assert_eq!(unpack_i64_full(&[0x15, 0x05]), Some(5));
429        assert_eq!(unpack_i64_full(&[0x16, 0x00, 0x05]), Some(5));
430        // -1 minimally packs as [0x13, 0xFE]; the 2-byte form must
431        // decode identically.
432        assert_eq!(unpack_i64_full(&[0x13, 0xFE]), Some(-1));
433        assert_eq!(unpack_i64_full(&[0x12, 0xFF, 0xFE]), Some(-1));
434    }
435
436    #[test]
437    fn child_name_round_trips() {
438        for name in ["", "a", "hca", "version", "\u{00d4}\0", "z z"] {
439            let mut key = pack_i64(0);
440            key.extend_from_slice(&pack_string(name));
441            assert_eq!(unpack_child_name(&key), Some(name.to_string()));
442        }
443        // First element not 0.
444        let mut key = pack_i64(1);
445        key.extend_from_slice(&pack_string("a"));
446        assert_eq!(unpack_child_name(&key), None);
447        // Missing the name element.
448        assert_eq!(unpack_child_name(&pack_i64(0)), None);
449    }
450
451    #[test]
452    fn first_element_of_a_node_key() {
453        // A node row: NODE_PREFIX ‖ BYTES(prefix) ‖ child/layer tail.
454        // Only the leading element is needed by the containment probe.
455        let mut key = pack_bytes(&[0x15, 0x01]);
456        key.extend_from_slice(&pack_i64(0));
457        key.extend_from_slice(&pack_string("child"));
458        assert_eq!(first_bytes_element(&key), Some(&[0x15, 0x01][..]));
459        // An integer-led key has no leading byte-string.
460        assert_eq!(first_bytes_element(&pack_i64(5)), None);
461        // Unterminated payload.
462        assert_eq!(first_bytes_element(&[0x01, 0x41]), None);
463    }
464}