Skip to main content

reddb_types/
document_body_codec.rs

1//! Native binary container for document bodies (PRD-1398, ADR-0063).
2//!
3//! Encodes a named-field document (`&[(&str, &Value)]`) into a compact binary
4//! container with a **header offset table** that enables O(1) access to any
5//! top-level field value without decoding the entire document.
6//!
7//! ## Format — version 3
8//!
9//! ```text
10//! [0..4]  magic        = b"RDOC"
11//! [4]     version      = 0x03
12//! [5..7]  num_fields   : u16 LE          (max 65 535 fields per document)
13//! [7..]   offset table : num_fields × [key_len: u16 LE, val_offset: u32 LE]
14//!         keys section : concatenated UTF-8 field name bytes (key_len[i] each)
15//!         values section: concatenated value_codec-encoded bytes
16//! ```
17//!
18//! `val_offset` is an **absolute** byte offset from byte 0 of the container,
19//! allowing a single value to be decoded with [`decode_value_at_offset`] after
20//! reading only the header — the rest of the payload stays untouched.
21//!
22//! ## Flag-dark
23//!
24//! This codec is compiled and tested but not yet wired into any storage or
25//! query path.  Behaviour cutover happens in a later PRD-1398 slice.
26
27use crate::json::{Map, Value as JsonValue};
28use crate::key_dictionary::KeyDictionary;
29use crate::types::Value;
30use crate::value_codec;
31
32/// Decode a self-describing binary document body into its canonical JSON value.
33/// Returns `None` for non-container bytes or invalid container data.
34pub fn decode_container_to_json(bytes: &[u8]) -> Option<JsonValue> {
35    if !bytes.starts_with(MAGIC) {
36        return None;
37    }
38    let fields = decode(bytes).ok()?;
39    let mut map = Map::new();
40    for (key, value) in fields {
41        let json = match &value {
42            Value::Integer(n) => JsonValue::Integer(*n),
43            other => other.to_json(),
44        };
45        map.insert(key, json);
46    }
47    Some(JsonValue::Object(map))
48}
49
50/// Magic bytes at the start of every document body container.
51pub const MAGIC: &[u8; 4] = b"RDOC";
52
53/// Format version byte for the plain (inline-keys-only) container.
54pub const VERSION: u8 = 0x03;
55
56/// Format version byte for the dictionary-aware container (PRD-1398).
57///
58/// Identical layout to the plain container except each offset-table entry carries a key *kind*
59/// tag: a field name is either a key-id into the per-collection
60/// [`KeyDictionary`] (common keys) or stored inline (rare/unique keys).
61pub const VERSION_DICT: u8 = 0x04;
62
63const SUPERSEDED_VERSION: u8 = 0x01;
64const SUPERSEDED_VERSION_DICT: u8 = 0x02;
65
66/// Byte size of one entry in the offset table: u16 key_len + u32 val_offset.
67const ENTRY_SIZE: usize = 6;
68
69/// Byte size of one v2 offset-table entry: u8 key_kind + u32 key_ref + u32 val_offset.
70///
71/// The key-id is stored as a fixed `u32` (rather than a varint) so the table
72/// keeps a fixed stride and field access stays O(1); homogeneous collections
73/// never approach `u32::MAX` distinct common keys.
74const DICT_ENTRY_SIZE: usize = 9;
75
76/// `key_kind` tag: the field name is a key-id into the [`KeyDictionary`].
77const KEY_KIND_DICT: u8 = 0x00;
78
79/// `key_kind` tag: the field name is stored inline in the keys section.
80const KEY_KIND_INLINE: u8 = 0x01;
81
82/// One parsed v2 offset-table entry: `(key_kind, key_ref, val_offset)`.
83///
84/// `key_ref` is a dictionary key-id when `key_kind == KEY_KIND_DICT`, or the
85/// inline key length when `key_kind == KEY_KIND_INLINE`.
86pub type DictEntry = (u8, u32, u32);
87
88/// Errors produced by the document body codec.
89#[derive(Debug, PartialEq)]
90pub enum DocBodyError {
91    /// Buffer is too short to hold the header or offset table.
92    TruncatedData,
93    /// First 4 bytes do not match `b"RDOC"`.
94    BadMagic,
95    /// Version byte is not a version this codec understands.
96    UnsupportedVersion(u8),
97    /// Version byte is from a pre-lossless-integer format that must not be reinterpreted.
98    SupersededVersion(u8),
99    /// A field name or value points outside the container buffer.
100    OffsetOutOfBounds,
101    /// A field name is not valid UTF-8.
102    InvalidFieldName,
103    /// The document has more than 65 535 fields, or a field name exceeds 65 535 bytes.
104    FieldLimitExceeded,
105    /// A dictionary key-id in the body is absent from the supplied dictionary.
106    UnknownKeyId(u32),
107    /// A v2 offset-table entry carried an unrecognised key-kind tag.
108    BadKeyKind(u8),
109    /// The underlying value codec rejected a value.
110    ValueCodecError(crate::types::ValueError),
111}
112
113impl From<crate::types::ValueError> for DocBodyError {
114    fn from(e: crate::types::ValueError) -> Self {
115        DocBodyError::ValueCodecError(e)
116    }
117}
118
119impl std::fmt::Display for DocBodyError {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        match self {
122            Self::TruncatedData => write!(f, "document body: truncated data"),
123            Self::BadMagic => write!(f, "document body: bad magic bytes (expected RDOC)"),
124            Self::UnsupportedVersion(v) => write!(f, "document body: unsupported version {v}"),
125            Self::SupersededVersion(v) => write!(
126                f,
127                "document body: format version {v} is superseded by version {VERSION} for the \
128                 lossless-integer clean break (#1768). Pre-bump bodies stored numbers as f64, \
129                 so they are refused rather than silently reinterpreted; re-insert the document \
130                 to rewrite it in the current format."
131            ),
132            Self::OffsetOutOfBounds => write!(f, "document body: offset points outside buffer"),
133            Self::InvalidFieldName => write!(f, "document body: field name is not valid UTF-8"),
134            Self::FieldLimitExceeded => {
135                write!(f, "document body: field or key-length limit exceeded")
136            }
137            Self::UnknownKeyId(id) => {
138                write!(f, "document body: key-id {id} not found in dictionary")
139            }
140            Self::BadKeyKind(k) => write!(f, "document body: unrecognised key kind {k:#04x}"),
141            Self::ValueCodecError(e) => write!(f, "document body: value codec error: {e}"),
142        }
143    }
144}
145
146impl std::error::Error for DocBodyError {}
147
148/// Encode `fields` as a document body container, appending bytes to `out`.
149///
150/// Fields are written in iteration order.  Duplicate field names are allowed
151/// (deduplication is the caller's responsibility).
152///
153/// Returns an error only if `fields.len() > 65535` or a field name is longer
154/// than 65535 bytes; both are pathological in practice.
155pub fn encode(fields: &[(&str, &Value)], out: &mut Vec<u8>) -> Result<(), DocBodyError> {
156    let n = fields.len();
157    if n > u16::MAX as usize {
158        return Err(DocBodyError::FieldLimitExceeded);
159    }
160
161    // Encode all keys and values into scratch buffers, tracking per-field
162    // sizes so we can compute absolute offsets before writing anything.
163    let mut key_buf: Vec<u8> = Vec::new();
164    let mut val_buf: Vec<u8> = Vec::new();
165    let mut key_lens: Vec<u16> = Vec::with_capacity(n);
166    let mut val_starts: Vec<u32> = Vec::with_capacity(n);
167
168    for (key, value) in fields {
169        let kb = key.as_bytes();
170        if kb.len() > u16::MAX as usize {
171            return Err(DocBodyError::FieldLimitExceeded);
172        }
173        key_lens.push(kb.len() as u16);
174        key_buf.extend_from_slice(kb);
175
176        val_starts.push(val_buf.len() as u32); // relative for now
177        value_codec::encode(value, &mut val_buf);
178    }
179
180    // Absolute offset of the values section within the final container:
181    //   magic(4) + version(1) + num_fields(2) + table(n * ENTRY_SIZE) + keys
182    let vals_abs_start = 4 + 1 + 2 + n * ENTRY_SIZE + key_buf.len();
183
184    // Write header
185    out.extend_from_slice(MAGIC);
186    out.push(VERSION);
187    out.extend_from_slice(&(n as u16).to_le_bytes());
188
189    // Write offset table
190    for i in 0..n {
191        let abs_val_offset = vals_abs_start + val_starts[i] as usize;
192        out.extend_from_slice(&key_lens[i].to_le_bytes());
193        out.extend_from_slice(&(abs_val_offset as u32).to_le_bytes());
194    }
195
196    // Write keys then values
197    out.extend_from_slice(&key_buf);
198    out.extend_from_slice(&val_buf);
199
200    Ok(())
201}
202
203/// Decode all fields from a document body container.
204///
205/// Fields are returned in the same order they were encoded.
206pub fn decode(data: &[u8]) -> Result<Vec<(String, Value)>, DocBodyError> {
207    let fields = named_offsets(data)?;
208    let mut result = Vec::with_capacity(fields.len());
209    for field in fields {
210        let (name, offset) = field?;
211        result.push((name.to_owned(), decode_value_at_offset(data, offset)?));
212    }
213    Ok(result)
214}
215
216/// Visit selected top-level values in encode order, retaining duplicate names.
217pub fn visit_selected_fields(
218    data: &[u8],
219    includes: impl Fn(&str) -> bool,
220    mut visit: impl FnMut(&str, Value),
221) -> Result<(), DocBodyError> {
222    for field in named_offsets(data)? {
223        let (name, offset) = field?;
224        if includes(name) {
225            visit(name, decode_value_at_offset(data, offset)?);
226        }
227    }
228    Ok(())
229}
230
231fn named_offsets(
232    data: &[u8],
233) -> Result<impl ExactSizeIterator<Item = Result<(&str, u32), DocBodyError>> + '_, DocBodyError> {
234    let (count, entries) = parse_header_entries(data)?;
235    let mut key_start = 7 + count * ENTRY_SIZE;
236    Ok(entries.map(move |(key_len, offset)| {
237        let end = key_start + usize::from(key_len);
238        let name = data
239            .get(key_start..end)
240            .ok_or(DocBodyError::OffsetOutOfBounds)?;
241        key_start = end;
242        let name = std::str::from_utf8(name).map_err(|_| DocBodyError::InvalidFieldName)?;
243        Ok((name, offset))
244    }))
245}
246
247/// Return the top-level field names in encode order without decoding any value.
248///
249/// Reads only the offset table and the keys section — the values section is
250/// never touched. Used to build a field-name index/bloom over a stored body
251/// (e.g. so a `WHERE`/projection on a promoted field can route to the body)
252/// without paying the cost of a full [`decode`].
253pub fn field_names(data: &[u8]) -> Result<Vec<String>, DocBodyError> {
254    let (n, table) = parse_header_entries(data)?;
255    let header_end = 7 + n * ENTRY_SIZE; // where the keys section begins
256    let mut key_cursor = header_end;
257    let mut names = Vec::with_capacity(n);
258
259    for (key_len, _val_offset) in table {
260        let key_end = key_cursor + key_len as usize;
261        if key_end > data.len() {
262            return Err(DocBodyError::OffsetOutOfBounds);
263        }
264        let key = std::str::from_utf8(&data[key_cursor..key_end])
265            .map_err(|_| DocBodyError::InvalidFieldName)?
266            .to_string();
267        key_cursor = key_end;
268        names.push(key);
269    }
270
271    Ok(names)
272}
273
274/// Read a single field by name without decoding any other value.
275///
276/// Returns `None` when the field is absent.  Only the matching field's
277/// encoded bytes are passed to [`value_codec::decode`]; everything else
278/// is skipped as raw bytes.
279pub fn read_field_by_name(data: &[u8], name: &str) -> Result<Option<Value>, DocBodyError> {
280    let (n, table) = parse_header_entries(data)?;
281    let header_end = 7 + n * ENTRY_SIZE;
282    let mut key_cursor = header_end;
283
284    for (key_len, val_offset) in table {
285        let key_end = key_cursor + key_len as usize;
286        if key_end > data.len() {
287            return Err(DocBodyError::OffsetOutOfBounds);
288        }
289        let key_bytes = &data[key_cursor..key_end];
290        key_cursor = key_end;
291
292        if key_bytes == name.as_bytes() {
293            let value = decode_value_at_offset(data, val_offset)?;
294            return Ok(Some(value));
295        }
296    }
297
298    Ok(None)
299}
300
301/// Decode a single value using its **absolute** byte offset within the
302/// container.
303///
304/// This is the O(1) access path once the caller has read the offset table
305/// (e.g. via [`parse_header`]).  No other field is decoded.
306pub fn decode_value_at_offset(data: &[u8], val_offset: u32) -> Result<Value, DocBodyError> {
307    let off = val_offset as usize;
308    if off >= data.len() {
309        return Err(DocBodyError::OffsetOutOfBounds);
310    }
311    let (value, _) = value_codec::decode(&data[off..])?;
312    Ok(value)
313}
314
315fn version_error(version: u8) -> DocBodyError {
316    if version == SUPERSEDED_VERSION || version == SUPERSEDED_VERSION_DICT {
317        DocBodyError::SupersededVersion(version)
318    } else {
319        DocBodyError::UnsupportedVersion(version)
320    }
321}
322
323/// Parse the container header and return `(num_fields, offset_table)`.
324///
325/// Each table entry is `(key_len: u16, val_offset: u32)`.  The table may be
326/// empty for zero-field documents.
327///
328/// Does **not** validate that field names or values are within bounds — that
329/// is deferred to the decode functions that actually walk those sections.
330pub fn parse_header(data: &[u8]) -> Result<(usize, Vec<(u16, u32)>), DocBodyError> {
331    let (count, entries) = parse_header_entries(data)?;
332    Ok((count, entries.collect()))
333}
334
335/// Borrow the validated offset table; field reads need no temporary index allocation.
336fn parse_header_entries(
337    data: &[u8],
338) -> Result<(usize, impl ExactSizeIterator<Item = (u16, u32)> + '_), DocBodyError> {
339    if data.len() < 7 {
340        return Err(DocBodyError::TruncatedData);
341    }
342    if &data[0..4] != MAGIC.as_slice() {
343        return Err(DocBodyError::BadMagic);
344    }
345    if data[4] != VERSION {
346        return Err(version_error(data[4]));
347    }
348
349    let n = u16::from_le_bytes([data[5], data[6]]) as usize;
350    let table_end = 7 + n * ENTRY_SIZE;
351    if data.len() < table_end {
352        return Err(DocBodyError::TruncatedData);
353    }
354
355    let entries = data[7..table_end].chunks_exact(ENTRY_SIZE).map(|entry| {
356        let key_len = u16::from_le_bytes([entry[0], entry[1]]);
357        let val_offset = u32::from_le_bytes([entry[2], entry[3], entry[4], entry[5]]);
358        (key_len, val_offset)
359    });
360    Ok((n, entries))
361}
362
363/// Encode `fields` as a **dictionary-aware** (v2) document body container.
364///
365/// For each field `classify(name)` decides how the key is stored:
366///
367/// * `true`  — the key is *common*: it is interned into `dict` (appending a new
368///   id transactionally if it is not already present) and the body stores the
369///   compact key-id.
370/// * `false` — the key is *rare/unique*: it is stored **inline** in the body
371///   and never enters `dict`, so a heterogeneous collection cannot bloat the
372///   shared catalogue.
373///
374/// Decode with [`decode_with_dictionary`] using the (post-encode) dictionary.
375pub fn encode_with_dictionary(
376    fields: &[(&str, &Value)],
377    dict: &mut KeyDictionary,
378    classify: impl Fn(&str) -> bool,
379    out: &mut Vec<u8>,
380) -> Result<(), DocBodyError> {
381    let n = fields.len();
382    if n > u16::MAX as usize {
383        return Err(DocBodyError::FieldLimitExceeded);
384    }
385
386    // Inline key bytes (only for rare keys) and value bytes, plus per-field
387    // table data, are staged so absolute offsets can be computed up front.
388    let mut key_buf: Vec<u8> = Vec::new();
389    let mut val_buf: Vec<u8> = Vec::new();
390    let mut kinds: Vec<u8> = Vec::with_capacity(n);
391    let mut refs: Vec<u32> = Vec::with_capacity(n);
392    let mut val_starts: Vec<u32> = Vec::with_capacity(n);
393
394    for (key, value) in fields {
395        if classify(key) {
396            let id = dict.intern(key);
397            kinds.push(KEY_KIND_DICT);
398            refs.push(id);
399        } else {
400            let kb = key.as_bytes();
401            if kb.len() > u16::MAX as usize {
402                return Err(DocBodyError::FieldLimitExceeded);
403            }
404            kinds.push(KEY_KIND_INLINE);
405            refs.push(kb.len() as u32);
406            key_buf.extend_from_slice(kb);
407        }
408        val_starts.push(val_buf.len() as u32); // relative for now
409        value_codec::encode(value, &mut val_buf);
410    }
411
412    // Absolute offset of the values section within the final container:
413    //   magic(4) + version(1) + num_fields(2) + table(n * DICT_ENTRY_SIZE) + inline keys
414    let vals_abs_start = 4 + 1 + 2 + n * DICT_ENTRY_SIZE + key_buf.len();
415
416    out.extend_from_slice(MAGIC);
417    out.push(VERSION_DICT);
418    out.extend_from_slice(&(n as u16).to_le_bytes());
419
420    for i in 0..n {
421        let abs_val_offset = vals_abs_start + val_starts[i] as usize;
422        out.push(kinds[i]);
423        out.extend_from_slice(&refs[i].to_le_bytes());
424        out.extend_from_slice(&(abs_val_offset as u32).to_le_bytes());
425    }
426
427    out.extend_from_slice(&key_buf);
428    out.extend_from_slice(&val_buf);
429
430    Ok(())
431}
432
433/// Decode all fields from a **dictionary-aware** (v2) document body container.
434///
435/// `dict` must be the per-collection dictionary that was used (and possibly
436/// extended) during [`encode_with_dictionary`]; dictionary key-ids are resolved
437/// back to field names through it, while inline keys are read straight from the
438/// body.  Fields are returned in encode order.
439pub fn decode_with_dictionary(
440    data: &[u8],
441    dict: &KeyDictionary,
442) -> Result<Vec<(String, Value)>, DocBodyError> {
443    let (n, table) = parse_dict_header(data)?;
444    let header_end = 7 + n * DICT_ENTRY_SIZE; // where the inline-keys section begins
445    let mut key_cursor = header_end;
446    let mut result = Vec::with_capacity(n);
447
448    for &(kind, key_ref, val_offset) in &table {
449        let key = match kind {
450            KEY_KIND_DICT => dict
451                .name_of(key_ref)
452                .ok_or(DocBodyError::UnknownKeyId(key_ref))?
453                .to_string(),
454            KEY_KIND_INLINE => {
455                let key_end = key_cursor + key_ref as usize;
456                if key_end > data.len() {
457                    return Err(DocBodyError::OffsetOutOfBounds);
458                }
459                let name = std::str::from_utf8(&data[key_cursor..key_end])
460                    .map_err(|_| DocBodyError::InvalidFieldName)?
461                    .to_string();
462                key_cursor = key_end;
463                name
464            }
465            other => return Err(DocBodyError::BadKeyKind(other)),
466        };
467
468        let value = decode_value_at_offset(data, val_offset)?;
469        result.push((key, value));
470    }
471
472    Ok(result)
473}
474
475/// Parse a **v2** container header, returning `(num_fields, table)` where each
476/// table entry is `(key_kind, key_ref, val_offset)`.
477///
478/// As with [`parse_header`], inline key names and values are not validated
479/// here — that is deferred to [`decode_with_dictionary`].
480pub fn parse_dict_header(data: &[u8]) -> Result<(usize, Vec<DictEntry>), DocBodyError> {
481    if data.len() < 7 {
482        return Err(DocBodyError::TruncatedData);
483    }
484    if &data[0..4] != MAGIC.as_slice() {
485        return Err(DocBodyError::BadMagic);
486    }
487    if data[4] != VERSION_DICT {
488        return Err(version_error(data[4]));
489    }
490
491    let n = u16::from_le_bytes([data[5], data[6]]) as usize;
492    let table_end = 7 + n * DICT_ENTRY_SIZE;
493    if data.len() < table_end {
494        return Err(DocBodyError::TruncatedData);
495    }
496
497    let mut table = Vec::with_capacity(n);
498    for i in 0..n {
499        let base = 7 + i * DICT_ENTRY_SIZE;
500        let kind = data[base];
501        let key_ref = u32::from_le_bytes([
502            data[base + 1],
503            data[base + 2],
504            data[base + 3],
505            data[base + 4],
506        ]);
507        let val_offset = u32::from_le_bytes([
508            data[base + 5],
509            data[base + 6],
510            data[base + 7],
511            data[base + 8],
512        ]);
513        table.push((kind, key_ref, val_offset));
514    }
515
516    Ok((n, table))
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522    use crate::types::Value;
523    use std::net::{IpAddr, Ipv4Addr};
524
525    fn round_trip(fields: &[(&str, Value)]) -> Vec<(String, Value)> {
526        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
527        let mut buf = Vec::new();
528        encode(&refs, &mut buf).expect("encode");
529        decode(&buf).expect("decode")
530    }
531
532    #[test]
533    fn empty_document_round_trips() {
534        let got = round_trip(&[]);
535        assert!(got.is_empty());
536    }
537
538    #[test]
539    fn single_field_round_trip() {
540        let fields = [("name", Value::text("Alice"))];
541        let got = round_trip(&fields);
542        assert_eq!(got.len(), 1);
543        assert_eq!(got[0].0, "name");
544        assert_eq!(got[0].1, Value::text("Alice"));
545    }
546
547    #[test]
548    fn multi_field_round_trip() {
549        let fields = [
550            ("id", Value::Integer(42)),
551            ("email", Value::Email("a@example.com".to_string())),
552            ("active", Value::Boolean(true)),
553            ("score", Value::Float(9.5)),
554        ];
555        let got = round_trip(&fields);
556        assert_eq!(got.len(), 4);
557        for (i, (k, v)) in fields.iter().enumerate() {
558            assert_eq!(got[i].0, *k);
559            assert_eq!(got[i].1, *v);
560        }
561    }
562
563    /// Every rich semantic type must survive the round-trip unchanged.
564    #[test]
565    fn rich_semantic_types_round_trip() {
566        let fields = [
567            ("email", Value::Email("user@example.com".to_string())),
568            ("ipv4", Value::Ipv4(0x7f000001)),
569            ("subnet", Value::Subnet(0x0a000000, 0xff000000)),
570            ("color", Value::Color([0xDE, 0xAD, 0xBE])),
571            ("phone", Value::Phone(5511999000000)),
572            ("semver", Value::Semver(1_002_003)),
573            ("uuid", Value::Uuid([0xAB; 16])),
574            (
575                "money",
576                Value::Money {
577                    asset_code: "USD".to_string(),
578                    minor_units: 9999,
579                    scale: 2,
580                },
581            ),
582            ("geo", Value::GeoPoint(-23_550_520, -46_633_308)),
583            (
584                "ip_mixed",
585                Value::IpAddr(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))),
586            ),
587            ("url", Value::Url("https://reddb.io".to_string())),
588            ("color_alpha", Value::ColorAlpha([1, 2, 3, 255])),
589            ("lang", Value::Lang2(*b"en")),
590            ("country", Value::Country3(*b"USA")),
591        ];
592        let got = round_trip(&fields);
593        assert_eq!(got.len(), fields.len());
594        for (i, (k, v)) in fields.iter().enumerate() {
595            assert_eq!(got[i].0, *k, "key mismatch at {i}");
596            assert_eq!(got[i].1, *v, "value mismatch for field {k}");
597        }
598    }
599
600    /// A single field can be read by name without decoding the rest.
601    #[test]
602    fn read_field_by_name_skips_other_fields() {
603        let fields = [
604            ("a", Value::Integer(1)),
605            ("b", Value::text("hello")),
606            ("c", Value::Boolean(false)),
607        ];
608        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
609        let mut buf = Vec::new();
610        encode(&refs, &mut buf).expect("encode");
611
612        let v = read_field_by_name(&buf, "b")
613            .expect("lookup")
614            .expect("found");
615        assert_eq!(v, Value::text("hello"));
616
617        let missing = read_field_by_name(&buf, "z").expect("lookup");
618        assert!(missing.is_none());
619    }
620
621    #[test]
622    fn selected_fields_preserve_types_and_duplicate_order() {
623        let fields = [
624            ("owner", Value::text("São Paulo")),
625            ("payload", Value::text("skip")),
626            ("owner", Value::text("Recife")),
627            ("seq", Value::UnsignedInteger(u64::MAX)),
628        ];
629        let refs: Vec<_> = fields.iter().map(|(name, value)| (*name, value)).collect();
630        let mut bytes = Vec::new();
631        encode(&refs, &mut bytes).expect("encode fixture");
632
633        let mut selected = Vec::new();
634        visit_selected_fields(
635            &bytes,
636            |name| matches!(name, "owner" | "seq"),
637            |name, value| selected.push((name.to_owned(), value)),
638        )
639        .expect("project fields");
640        let expected: Vec<_> = decode(&bytes)
641            .expect("full decode")
642            .into_iter()
643            .filter(|(name, _)| name != "payload")
644            .collect();
645        assert_eq!(selected, expected);
646    }
647
648    #[test]
649    fn borrowed_field_reads_match_owned_offsets_and_preserve_first_duplicate() {
650        let fields = [
651            ("", Value::Null),
652            ("cidade", Value::text("São Paulo")),
653            ("重复", Value::Integer(7)),
654            ("cidade", Value::text("Recife")),
655        ];
656        let references: Vec<_> = fields.iter().map(|(key, value)| (*key, value)).collect();
657        let mut bytes = Vec::new();
658        encode(&references, &mut bytes).expect("encode fixture");
659        let (_, offsets) = parse_header(&bytes).expect("owned header");
660        for (index, (name, _)) in fields[..3].iter().enumerate() {
661            assert_eq!(
662                read_field_by_name(&bytes, name).expect("borrowed lookup"),
663                Some(decode_value_at_offset(&bytes, offsets[index].1).expect("owned offset"))
664            );
665        }
666        assert_eq!(read_field_by_name(&bytes, "absent"), Ok(None));
667
668        // Reading an early field must not decode an unrelated corrupt value.
669        bytes[7 + 3 * ENTRY_SIZE + 2..7 + 4 * ENTRY_SIZE].copy_from_slice(&u32::MAX.to_le_bytes());
670        assert_eq!(
671            read_field_by_name(&bytes, "cidade"),
672            Ok(Some(Value::text("São Paulo")))
673        );
674        assert!(decode(&bytes).is_err());
675    }
676
677    #[test]
678    fn borrowed_field_reads_reject_truncated_headers_and_out_of_bounds_fields() {
679        let mut bytes = Vec::new();
680        encode(&[("x", &Value::Integer(1))], &mut bytes).expect("encode fixture");
681        for length in 0..7 + ENTRY_SIZE {
682            assert_eq!(
683                read_field_by_name(&bytes[..length], "x"),
684                Err(DocBodyError::TruncatedData)
685            );
686        }
687        let mut invalid = bytes.clone();
688        invalid[7..9].copy_from_slice(&u16::MAX.to_le_bytes());
689        assert_eq!(
690            read_field_by_name(&invalid, "x"),
691            Err(DocBodyError::OffsetOutOfBounds)
692        );
693        bytes[9..13].copy_from_slice(&u32::MAX.to_le_bytes());
694        assert_eq!(
695            read_field_by_name(&bytes, "x"),
696            Err(DocBodyError::OffsetOutOfBounds)
697        );
698    }
699
700    /// `field_names` lists the keys in encode order without decoding values.
701    #[test]
702    fn field_names_lists_keys_in_encode_order() {
703        let fields = [
704            ("name", Value::text("Alice")),
705            ("score", Value::Integer(30)),
706            ("active", Value::Boolean(true)),
707        ];
708        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
709        let mut buf = Vec::new();
710        encode(&refs, &mut buf).expect("encode");
711
712        let names = field_names(&buf).expect("field_names");
713        assert_eq!(names, vec!["name", "score", "active"]);
714
715        assert!(field_names(&[]).is_err());
716    }
717
718    /// decode_value_at_offset provides direct O(1) access given a known offset.
719    #[test]
720    fn decode_value_at_offset_matches_full_decode() {
721        let fields = [("x", Value::Integer(100)), ("y", Value::Float(1.5))];
722        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
723        let mut buf = Vec::new();
724        encode(&refs, &mut buf).expect("encode");
725
726        let (n, table) = parse_header(&buf).expect("parse_header");
727        assert_eq!(n, 2);
728
729        for (i, (k, v)) in fields.iter().enumerate() {
730            let (_key_len, val_offset) = table[i];
731            let got = decode_value_at_offset(&buf, val_offset).expect("decode_at_offset");
732            assert_eq!(got, *v, "field {k} mismatch");
733        }
734    }
735
736    #[test]
737    fn rejects_bad_magic() {
738        let mut buf = vec![b'X', b'X', b'X', b'X', VERSION, 0, 0];
739        assert_eq!(decode(&buf), Err(DocBodyError::BadMagic));
740        buf[0..4].copy_from_slice(MAGIC);
741        buf[4] = 0x99;
742        assert_eq!(decode(&buf), Err(DocBodyError::UnsupportedVersion(0x99)));
743    }
744
745    #[test]
746    fn superseded_plain_version_is_rejected_didactically() {
747        let fields = [("id", Value::Integer(1))];
748        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
749        let mut buf = Vec::new();
750        encode(&refs, &mut buf).expect("encode");
751        assert_eq!(buf[4], VERSION);
752
753        buf[4] = SUPERSEDED_VERSION;
754        let err = decode(&buf).expect_err("pre-bump body must be refused");
755        assert_eq!(err, DocBodyError::SupersededVersion(SUPERSEDED_VERSION));
756
757        let msg = err.to_string();
758        assert!(msg.contains("superseded"), "{msg}");
759        assert!(msg.contains("#1768"), "{msg}");
760        assert!(msg.contains("re-insert"), "{msg}");
761    }
762
763    #[test]
764    fn superseded_dict_version_is_rejected_didactically() {
765        let fields = [("id", Value::Integer(1))];
766        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
767        let mut dict = KeyDictionary::new();
768        let mut buf = Vec::new();
769        encode_with_dictionary(&refs, &mut dict, |_| true, &mut buf).expect("encode");
770        assert_eq!(buf[4], VERSION_DICT);
771
772        buf[4] = SUPERSEDED_VERSION_DICT;
773        let err = decode_with_dictionary(&buf, &dict).expect_err("pre-bump body must be refused");
774        assert_eq!(
775            err,
776            DocBodyError::SupersededVersion(SUPERSEDED_VERSION_DICT)
777        );
778    }
779
780    #[test]
781    fn rejects_truncated_buffer() {
782        assert_eq!(decode(&[]), Err(DocBodyError::TruncatedData));
783        assert_eq!(
784            decode(&[b'R', b'D', b'O', b'C', 1, 0]),
785            Err(DocBodyError::TruncatedData)
786        );
787    }
788
789    #[test]
790    fn null_values_round_trip() {
791        let fields = [("nothing", Value::Null), ("something", Value::Integer(7))];
792        let got = round_trip(&fields);
793        assert_eq!(got[0].1, Value::Null);
794        assert_eq!(got[1].1, Value::Integer(7));
795    }
796
797    #[test]
798    fn array_value_round_trip() {
799        let fields = [(
800            "tags",
801            Value::Array(vec![Value::text("a"), Value::text("b"), Value::Integer(3)]),
802        )];
803        let got = round_trip(&fields);
804        assert_eq!(
805            got[0].1,
806            Value::Array(vec![Value::text("a"), Value::text("b"), Value::Integer(3)])
807        );
808    }
809
810    /// Verify the offset table points to the correct byte positions.
811    #[test]
812    fn offset_table_offsets_are_valid() {
813        let fields = [("k", Value::Boolean(true))];
814        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
815        let mut buf = Vec::new();
816        encode(&refs, &mut buf).expect("encode");
817
818        let (n, table) = parse_header(&buf).expect("header");
819        assert_eq!(n, 1);
820        let (_klen, val_offset) = table[0];
821        // The value bytes at val_offset must decode to Boolean(true)
822        let (v, _) = value_codec::decode(&buf[val_offset as usize..]).expect("decode at offset");
823        assert_eq!(v, Value::Boolean(true));
824    }
825
826    // ---- Dictionary-aware (v2) container ----------------------------------
827
828    /// Classify every key as common — exercises the homogeneous-collection path.
829    fn all_common(_: &str) -> bool {
830        true
831    }
832
833    /// Common field names are interned in the dictionary and the body stores
834    /// compact key-ids, not the key strings.
835    #[test]
836    fn common_keys_are_interned_as_key_ids() {
837        let fields = [
838            ("id", Value::Integer(1)),
839            ("name", Value::text("Alice")),
840            ("active", Value::Boolean(true)),
841        ];
842        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
843        let mut dict = KeyDictionary::new();
844        let mut buf = Vec::new();
845        encode_with_dictionary(&refs, &mut dict, all_common, &mut buf).expect("encode");
846
847        // All three keys entered the dictionary with dense ids.
848        assert_eq!(dict.len(), 3);
849        assert_eq!(dict.id_of("id"), Some(0));
850        assert_eq!(dict.id_of("name"), Some(1));
851        assert_eq!(dict.id_of("active"), Some(2));
852
853        // Every table entry is a dictionary reference, no inline keys.
854        let (n, table) = parse_dict_header(&buf).expect("header");
855        assert_eq!(n, 3);
856        for (kind, _key_ref, _off) in &table {
857            assert_eq!(*kind, KEY_KIND_DICT);
858        }
859        // The string "name" is not repeated in the body bytes — only its id is.
860        assert!(!buf.windows(4).any(|w| w == b"name"));
861    }
862
863    /// Encoding a second document with a new common key appends to the existing
864    /// dictionary transactionally (alongside the write), reusing prior ids.
865    #[test]
866    fn new_common_key_appends_to_dictionary() {
867        let mut dict = KeyDictionary::new();
868
869        let doc1 = [("id", Value::Integer(1)), ("name", Value::text("Alice"))];
870        let r1: Vec<(&str, &Value)> = doc1.iter().map(|(k, v)| (*k, v)).collect();
871        let mut b1 = Vec::new();
872        encode_with_dictionary(&r1, &mut dict, all_common, &mut b1).expect("encode 1");
873        assert_eq!(dict.len(), 2);
874
875        // Second document reuses id/name and introduces a brand-new common key.
876        let doc2 = [
877            ("id", Value::Integer(2)),
878            ("name", Value::text("Bob")),
879            ("email", Value::Email("bob@example.com".to_string())),
880        ];
881        let r2: Vec<(&str, &Value)> = doc2.iter().map(|(k, v)| (*k, v)).collect();
882        let mut b2 = Vec::new();
883        encode_with_dictionary(&r2, &mut dict, all_common, &mut b2).expect("encode 2");
884
885        // Only the new key appended; existing ids are stable.
886        assert_eq!(dict.len(), 3);
887        assert_eq!(dict.id_of("id"), Some(0));
888        assert_eq!(dict.id_of("name"), Some(1));
889        assert_eq!(dict.id_of("email"), Some(2));
890
891        // Both documents decode losslessly against the shared dictionary.
892        let g1 = decode_with_dictionary(&b1, &dict).expect("decode 1");
893        assert_eq!(g1[1], ("name".to_string(), Value::text("Alice")));
894        let g2 = decode_with_dictionary(&b2, &dict).expect("decode 2");
895        assert_eq!(
896            g2[2],
897            (
898                "email".to_string(),
899                Value::Email("bob@example.com".to_string())
900            )
901        );
902    }
903
904    /// A rare/unique key is stored inline and never enters the dictionary.
905    #[test]
906    fn rare_key_stays_inline_and_out_of_dictionary() {
907        // "id"/"name" are common; anything else is rare.
908        let common = |k: &str| k == "id" || k == "name";
909        let fields = [
910            ("id", Value::Integer(7)),
911            ("name", Value::text("Carol")),
912            ("x9f3_one_off_attr", Value::text("rare-value")),
913        ];
914        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
915        let mut dict = KeyDictionary::new();
916        let mut buf = Vec::new();
917        encode_with_dictionary(&refs, &mut dict, common, &mut buf).expect("encode");
918
919        // The rare key never entered the catalogue.
920        assert_eq!(dict.len(), 2);
921        assert_eq!(dict.id_of("x9f3_one_off_attr"), None);
922
923        // Its kind tag is inline and its name bytes live in the body.
924        let (_n, table) = parse_dict_header(&buf).expect("header");
925        assert_eq!(table[0].0, KEY_KIND_DICT);
926        assert_eq!(table[1].0, KEY_KIND_DICT);
927        assert_eq!(table[2].0, KEY_KIND_INLINE);
928        assert!(buf
929            .windows("x9f3_one_off_attr".len())
930            .any(|w| w == b"x9f3_one_off_attr"));
931
932        // And it round-trips losslessly.
933        let got = decode_with_dictionary(&buf, &dict).expect("decode");
934        assert_eq!(
935            got[2],
936            ("x9f3_one_off_attr".to_string(), Value::text("rare-value"))
937        );
938    }
939
940    /// Round-trip mixing dictionary keys and inline keys is lossless, including
941    /// rich semantic types and after persisting/reloading the dictionary.
942    #[test]
943    fn mixed_dictionary_and_inline_round_trip() {
944        let common = |k: &str| matches!(k, "id" | "email" | "active");
945        let fields = [
946            ("id", Value::Integer(42)),
947            ("email", Value::Email("a@example.com".to_string())),
948            ("active", Value::Boolean(true)),
949            ("one_off_color", Value::Color([0xDE, 0xAD, 0xBE])),
950            ("rare_geo", Value::GeoPoint(-23_550_520, -46_633_308)),
951        ];
952        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
953        let mut dict = KeyDictionary::new();
954        let mut buf = Vec::new();
955        encode_with_dictionary(&refs, &mut dict, common, &mut buf).expect("encode");
956
957        // Persist and reload the dictionary, then decode against the reloaded copy.
958        let mut dict_bytes = Vec::new();
959        dict.encode(&mut dict_bytes);
960        let reloaded = KeyDictionary::decode(&dict_bytes).expect("reload dict");
961
962        let got = decode_with_dictionary(&buf, &reloaded).expect("decode");
963        assert_eq!(got.len(), fields.len());
964        for (i, (k, v)) in fields.iter().enumerate() {
965            assert_eq!(got[i].0, *k, "key mismatch at {i}");
966            assert_eq!(got[i].1, *v, "value mismatch for field {k}");
967        }
968    }
969
970    #[test]
971    fn empty_dictionary_document_round_trips() {
972        let mut dict = KeyDictionary::new();
973        let mut buf = Vec::new();
974        encode_with_dictionary(&[], &mut dict, all_common, &mut buf).expect("encode");
975        let got = decode_with_dictionary(&buf, &dict).expect("decode");
976        assert!(got.is_empty());
977        assert!(dict.is_empty());
978    }
979
980    /// A v2 body decoded against a dictionary that lacks the id is rejected,
981    /// not silently mis-decoded.
982    #[test]
983    fn unknown_key_id_is_rejected() {
984        let fields = [("only_key", Value::Integer(1))];
985        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
986        let mut dict = KeyDictionary::new();
987        let mut buf = Vec::new();
988        encode_with_dictionary(&refs, &mut dict, all_common, &mut buf).expect("encode");
989
990        let empty = KeyDictionary::new();
991        assert_eq!(
992            decode_with_dictionary(&buf, &empty),
993            Err(DocBodyError::UnknownKeyId(0))
994        );
995    }
996
997    /// v1 and v2 containers are distinguished by their version byte; decoding a
998    /// v2 body with the v1 path (and vice versa) fails on the version check.
999    #[test]
1000    fn v1_and_v2_versions_do_not_alias() {
1001        let fields = [("k", Value::Integer(1))];
1002        let refs: Vec<(&str, &Value)> = fields.iter().map(|(k, v)| (*k, v)).collect();
1003
1004        let mut v1 = Vec::new();
1005        encode(&refs, &mut v1).expect("v1");
1006        assert_eq!(v1[4], VERSION);
1007
1008        let mut dict = KeyDictionary::new();
1009        let mut v2 = Vec::new();
1010        encode_with_dictionary(&refs, &mut dict, all_common, &mut v2).expect("v2");
1011        assert_eq!(v2[4], VERSION_DICT);
1012
1013        // Cross-decoding hits the version guard.
1014        assert_eq!(
1015            decode(&v2),
1016            Err(DocBodyError::UnsupportedVersion(VERSION_DICT))
1017        );
1018        assert_eq!(
1019            parse_dict_header(&v1),
1020            Err(DocBodyError::UnsupportedVersion(VERSION))
1021        );
1022    }
1023}