Skip to main content

waratah_storage/encode/
binary.rs

1//! Binary wire encoding for terms and hexastore index keys.
2
3use std::io::Read;
4use std::mem::size_of;
5
6use oxsdatatypes::*;
7
8use super::encoded_term::{
9    CrsId, ENCODED_TERM_FALSE, ENCODED_TERM_TRUE, EncodedQuad, EncodedTerm, GEOM_KIND_WIRE_MASK,
10    GEOM_REQUIRES_SPIKE_REDUCTION_WIRE_FLAG, GeoDatatype, GeomKind, RDF_TYPE,
11};
12use super::pattern::EncodedTriplePattern;
13use super::small_string::SmallString;
14use super::str_hash::StrHash;
15use crate::StorageError;
16
17/// Upper bound on encoded term size for buffer pre-allocation.
18///
19/// The largest variants (the two-term lang-string / typed-literal families,
20/// type byte + two 16-byte halves) encode to 33 bytes — reserving only
21/// `16 + 16` overflowed the reservation into the first `grow_one` on exactly
22/// those rows.
23pub const WRITTEN_TERM_MAX_SIZE: usize = 1 + 2 * size_of::<u128>();
24
25/// Type byte of [`EncodedTerm::NamedNode`] — the only variant that begins a
26/// predicate slot, and the segment shape of named graphs (`1 ‖ 16-byte hash`).
27pub(crate) const TYPE_NAMED_NODE_ID: u8 = 1;
28const TYPE_NUMERICAL_BLANK_NODE_ID: u8 = 8;
29const TYPE_SMALL_BLANK_NODE_ID: u8 = 9;
30const TYPE_BIG_BLANK_NODE_ID: u8 = 10;
31const TYPE_SMALL_STRING_LITERAL: u8 = 16;
32const TYPE_BIG_STRING_LITERAL: u8 = 17;
33const TYPE_SMALL_SMALL_LANG_STRING_LITERAL: u8 = 20;
34const TYPE_SMALL_BIG_LANG_STRING_LITERAL: u8 = 21;
35const TYPE_BIG_SMALL_LANG_STRING_LITERAL: u8 = 22;
36const TYPE_BIG_BIG_LANG_STRING_LITERAL: u8 = 23;
37const TYPE_SMALL_TYPED_LITERAL: u8 = 24;
38const TYPE_BIG_TYPED_LITERAL: u8 = 25;
39/// Native 2D geo point: type + `f64` lon + `f64` lat + CRS byte + geo
40/// datatype byte (19 bytes total). Uses the 26–27 gap.
41pub(crate) const TYPE_LITERAL_POINT: u8 = 26;
42/// Native non-point geometry: type + geom-kind/flags + CRS + geo-datatype
43/// bytes + 16-byte blob id (20 bytes total).
44pub(crate) const TYPE_LITERAL_GEOMETRY: u8 = 27;
45/// Generic binary blob typed literal: type + 16-byte datatype hash + 16-byte
46/// blob id (33 bytes total).
47pub(crate) const TYPE_BLOB_LITERAL: u8 = 45;
48const TYPE_BOOLEAN_LITERAL_TRUE: u8 = 28;
49const TYPE_BOOLEAN_LITERAL_FALSE: u8 = 29;
50const TYPE_FLOAT_LITERAL: u8 = 30;
51const TYPE_DOUBLE_LITERAL: u8 = 31;
52const TYPE_INTEGER_LITERAL: u8 = 32;
53const TYPE_DECIMAL_LITERAL: u8 = 33;
54const TYPE_DATE_TIME_LITERAL: u8 = 34;
55const TYPE_TIME_LITERAL: u8 = 35;
56const TYPE_DATE_LITERAL: u8 = 36;
57const TYPE_G_YEAR_MONTH_LITERAL: u8 = 37;
58const TYPE_G_YEAR_LITERAL: u8 = 38;
59const TYPE_G_MONTH_DAY_LITERAL: u8 = 39;
60const TYPE_G_DAY_LITERAL: u8 = 40;
61const TYPE_G_MONTH_LITERAL: u8 = 41;
62const TYPE_DURATION_LITERAL: u8 = 42;
63const TYPE_YEAR_MONTH_DURATION_LITERAL: u8 = 43;
64const TYPE_DAY_TIME_DURATION_LITERAL: u8 = 44;
65/// Compute-only intern sentinel (TermDict index `0`); not stored in hexastore keys.
66///
67/// Reuses Oxigraph's deprecated star-triple type id; [`TERM_WIDTH`] keeps this
68/// at [`TERM_WIDTH_UNKNOWN`] so [`term_width_at`] rejects keys that begin with it.
69pub const TYPE_PLACEHOLDER: u8 = 48;
70/// Reserved for RDF 1.2 triple terms — aligns with Oxigraph [`TYPE_TRIPLE`] (49).
71///
72/// Not written by the current encoder; [`TERM_WIDTH_UNKNOWN`] until RDF-star lands.
73pub const TYPE_TRIPLE: u8 = 49;
74
75/// `TERM_WIDTH` entry for type ids that never begin a stored term:
76/// unassigned ids, [`TYPE_PLACEHOLDER`], and reserved [`TYPE_TRIPLE`].
77pub const TERM_WIDTH_UNKNOWN: u8 = 0xFF;
78
79/// Total encoded width in bytes (type byte included) per term type id.
80///
81/// Index by the leading type byte of an encoded term. Widths follow
82/// [`write_term`]: one fixed-size payload per variant, no length prefixes,
83/// so the table is the definitive byte-walk map for hexastore keys.
84/// [`EncodedTerm::DefaultGraph`] encodes as zero bytes and has no type byte.
85pub const TERM_WIDTH: [u8; 256] = {
86    let mut table = [TERM_WIDTH_UNKNOWN; 256];
87    table[TYPE_NAMED_NODE_ID as usize] = 17;
88    table[TYPE_NUMERICAL_BLANK_NODE_ID as usize] = 17;
89    table[TYPE_SMALL_BLANK_NODE_ID as usize] = 17;
90    table[TYPE_BIG_BLANK_NODE_ID as usize] = 17;
91    table[TYPE_SMALL_STRING_LITERAL as usize] = 17;
92    table[TYPE_BIG_STRING_LITERAL as usize] = 17;
93    table[TYPE_SMALL_SMALL_LANG_STRING_LITERAL as usize] = 33;
94    table[TYPE_SMALL_BIG_LANG_STRING_LITERAL as usize] = 33;
95    table[TYPE_BIG_SMALL_LANG_STRING_LITERAL as usize] = 33;
96    table[TYPE_BIG_BIG_LANG_STRING_LITERAL as usize] = 33;
97    table[TYPE_SMALL_TYPED_LITERAL as usize] = 33;
98    table[TYPE_BIG_TYPED_LITERAL as usize] = 33;
99    table[TYPE_LITERAL_POINT as usize] = 19;
100    table[TYPE_LITERAL_GEOMETRY as usize] = 20;
101    table[TYPE_BLOB_LITERAL as usize] = 33;
102    table[TYPE_BOOLEAN_LITERAL_TRUE as usize] = 1;
103    table[TYPE_BOOLEAN_LITERAL_FALSE as usize] = 1;
104    table[TYPE_FLOAT_LITERAL as usize] = 5;
105    table[TYPE_DOUBLE_LITERAL as usize] = 9;
106    table[TYPE_INTEGER_LITERAL as usize] = 9;
107    table[TYPE_DECIMAL_LITERAL as usize] = 17;
108    table[TYPE_DATE_TIME_LITERAL as usize] = 19;
109    table[TYPE_TIME_LITERAL as usize] = 19;
110    table[TYPE_DATE_LITERAL as usize] = 19;
111    table[TYPE_G_YEAR_MONTH_LITERAL as usize] = 19;
112    table[TYPE_G_YEAR_LITERAL as usize] = 19;
113    table[TYPE_G_MONTH_DAY_LITERAL as usize] = 19;
114    table[TYPE_G_DAY_LITERAL as usize] = 19;
115    table[TYPE_G_MONTH_LITERAL as usize] = 19;
116    table[TYPE_DURATION_LITERAL as usize] = 25;
117    table[TYPE_YEAR_MONTH_DURATION_LITERAL as usize] = 9;
118    table[TYPE_DAY_TIME_DURATION_LITERAL as usize] = 17;
119    table
120};
121
122/// Total encoded width of the term starting at `key[offset]` (type byte included).
123///
124/// Width-table walk primitive for locating slot offsets inside hexastore keys.
125/// Returns [`StorageError::Corrupt`] when `off` is past the end of `key` or
126/// the type byte is unknown / reserved ([`TYPE_TRIPLE`], RDF-star, not yet
127/// implemented — see appendix D2).
128///
129/// Called one to three times per walked row by the head scans, so the
130/// table lookup stays inlinable across the crate's codegen units.
131#[inline]
132pub fn term_width_at(key: &[u8], offset: usize) -> Result<usize, StorageError> {
133    let type_byte = *key.get(offset).ok_or_else(|| {
134        StorageError::Corrupt(format!(
135            "term offset {offset} past end of key ({} bytes)",
136            key.len()
137        ))
138    })?;
139    let width = TERM_WIDTH[type_byte as usize];
140    if width == TERM_WIDTH_UNKNOWN {
141        return Err(StorageError::Corrupt(format!(
142            "invalid encoded term type id: {type_byte}"
143        )));
144    }
145    Ok(usize::from(width))
146}
147
148/// Hexastore index key permutation.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150pub enum IndexPermutation {
151    /// Subject-first named-graph index (`SPOG`).
152    Spog,
153    /// Subject-first object swap (`SOPG`) — Waratah S-axis.
154    Sopg,
155    /// Predicate-first subject swap (`PSOG`) — Waratah P-axis.
156    Psog,
157    /// Predicate-first (`POSG`).
158    Posg,
159    /// Object-first predicate swap (`OPSG`) — Waratah O-axis.
160    Opsg,
161    /// Type→Subject→Graph (`TSG`) — O-axis, `rdf:type` quads only (`P` omitted from key).
162    Tsg,
163}
164
165impl From<IndexPermutation> for crate::types::PartitionAxis {
166    fn from(permutation: IndexPermutation) -> Self {
167        permutation.axis()
168    }
169}
170
171impl IndexPermutation {
172    /// All named index permutations (general hexastore + O-axis `TSG`).
173    pub const ALL: [Self; 6] = [
174        Self::Spog,
175        Self::Sopg,
176        Self::Psog,
177        Self::Posg,
178        Self::Opsg,
179        Self::Tsg,
180    ];
181
182    /// RocksDB column-family name for this permutation.
183    pub const fn cf_name(self) -> &'static str {
184        match self {
185            Self::Spog => "spog",
186            Self::Sopg => "sopg",
187            Self::Psog => "psog",
188            Self::Posg => "posg",
189            Self::Opsg => "opsg",
190            Self::Tsg => "tsg",
191        }
192    }
193
194    /// Index permutations owned by a partition axis.
195    pub const fn for_axis(axis: crate::types::PartitionAxis) -> [Self; 2] {
196        use crate::types::PartitionAxis;
197        match axis {
198            PartitionAxis::S => [Self::Spog, Self::Sopg],
199            PartitionAxis::P => [Self::Psog, Self::Posg],
200            PartitionAxis::O => [Self::Opsg, Self::Tsg],
201        }
202    }
203
204    /// The partition axis that owns this permutation's CF.
205    pub const fn axis(self) -> crate::types::PartitionAxis {
206        use crate::types::PartitionAxis;
207        match self {
208            Self::Spog | Self::Sopg => PartitionAxis::S,
209            Self::Psog | Self::Posg => PartitionAxis::P,
210            Self::Opsg | Self::Tsg => PartitionAxis::O,
211        }
212    }
213
214    /// Canonical stats CF for an axis (`for_axis` `[0]`: SPOG / PSOG / OPSG).
215    ///
216    /// Table-properties collectors attach only here so each logical write is
217    /// counted once (the second index CF would double-count).
218    pub const fn is_stats_canonical(self) -> bool {
219        matches!(self, Self::Spog | Self::Psog | Self::Opsg)
220    }
221
222    /// Slot order for this permutation (`TSG` has three slots; others have four).
223    pub fn slot_order(self) -> &'static [QuadSlot] {
224        match self {
225            Self::Spog => &[
226                QuadSlot::Subject,
227                QuadSlot::Predicate,
228                QuadSlot::Object,
229                QuadSlot::Graph,
230            ],
231            Self::Sopg => &[
232                QuadSlot::Subject,
233                QuadSlot::Object,
234                QuadSlot::Predicate,
235                QuadSlot::Graph,
236            ],
237            Self::Psog => &[
238                QuadSlot::Predicate,
239                QuadSlot::Subject,
240                QuadSlot::Object,
241                QuadSlot::Graph,
242            ],
243            Self::Posg => &[
244                QuadSlot::Predicate,
245                QuadSlot::Object,
246                QuadSlot::Subject,
247                QuadSlot::Graph,
248            ],
249            Self::Opsg => &[
250                QuadSlot::Object,
251                QuadSlot::Predicate,
252                QuadSlot::Subject,
253                QuadSlot::Graph,
254            ],
255            Self::Tsg => &[QuadSlot::Object, QuadSlot::Subject, QuadSlot::Graph],
256        }
257    }
258}
259
260/// Slot within an encoded quad.
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
262pub enum QuadSlot {
263    /// Subject position.
264    Subject,
265    /// Predicate position.
266    Predicate,
267    /// Object position.
268    Object,
269    /// Graph name position.
270    Graph,
271}
272
273/// Read encoded terms from a byte buffer.
274pub trait TermReader {
275    /// Read the next encoded term.
276    fn read_term(&mut self) -> Result<EncodedTerm, StorageError>;
277}
278
279impl TermReader for &[u8] {
280    fn read_term(&mut self) -> Result<EncodedTerm, StorageError> {
281        let mut type_buffer = [0];
282        self.read_exact(&mut type_buffer)
283            .map_err(|e| StorageError::Corrupt(format!("unexpected end of term buffer: {e}")))?;
284        match type_buffer[0] {
285            TYPE_NAMED_NODE_ID => {
286                let mut buffer = [0; 16];
287                self.read_exact(&mut buffer).map_err(corrupt)?;
288                Ok(EncodedTerm::NamedNode {
289                    iri_id: StrHash::from_be_bytes(buffer),
290                })
291            }
292            TYPE_NUMERICAL_BLANK_NODE_ID => {
293                let mut id = [0; 16];
294                self.read_exact(&mut id).map_err(corrupt)?;
295                Ok(EncodedTerm::NumericalBlankNode { id })
296            }
297            TYPE_SMALL_BLANK_NODE_ID => {
298                let mut buffer = [0; 16];
299                self.read_exact(&mut buffer).map_err(corrupt)?;
300                Ok(EncodedTerm::SmallBlankNode(
301                    SmallString::from_be_bytes(buffer)
302                        .map_err(|e| StorageError::Corrupt(e.to_string()))?,
303                ))
304            }
305            TYPE_BIG_BLANK_NODE_ID => {
306                let mut buffer = [0; 16];
307                self.read_exact(&mut buffer).map_err(corrupt)?;
308                Ok(EncodedTerm::BigBlankNode {
309                    id_id: StrHash::from_be_bytes(buffer),
310                })
311            }
312            TYPE_SMALL_SMALL_LANG_STRING_LITERAL => {
313                let mut language_buffer = [0; 16];
314                self.read_exact(&mut language_buffer).map_err(corrupt)?;
315                let mut value_buffer = [0; 16];
316                self.read_exact(&mut value_buffer).map_err(corrupt)?;
317                Ok(EncodedTerm::SmallSmallLangStringLiteral {
318                    value: SmallString::from_be_bytes(value_buffer)
319                        .map_err(|e| StorageError::Corrupt(e.to_string()))?,
320                    language: SmallString::from_be_bytes(language_buffer)
321                        .map_err(|e| StorageError::Corrupt(e.to_string()))?,
322                })
323            }
324            TYPE_SMALL_BIG_LANG_STRING_LITERAL => {
325                let mut language_buffer = [0; 16];
326                self.read_exact(&mut language_buffer).map_err(corrupt)?;
327                let mut value_buffer = [0; 16];
328                self.read_exact(&mut value_buffer).map_err(corrupt)?;
329                Ok(EncodedTerm::SmallBigLangStringLiteral {
330                    value: SmallString::from_be_bytes(value_buffer)
331                        .map_err(|e| StorageError::Corrupt(e.to_string()))?,
332                    language_id: StrHash::from_be_bytes(language_buffer),
333                })
334            }
335            TYPE_BIG_SMALL_LANG_STRING_LITERAL => {
336                let mut language_buffer = [0; 16];
337                self.read_exact(&mut language_buffer).map_err(corrupt)?;
338                let mut value_buffer = [0; 16];
339                self.read_exact(&mut value_buffer).map_err(corrupt)?;
340                Ok(EncodedTerm::BigSmallLangStringLiteral {
341                    value_id: StrHash::from_be_bytes(value_buffer),
342                    language: SmallString::from_be_bytes(language_buffer)
343                        .map_err(|e| StorageError::Corrupt(e.to_string()))?,
344                })
345            }
346            TYPE_BIG_BIG_LANG_STRING_LITERAL => {
347                let mut language_buffer = [0; 16];
348                self.read_exact(&mut language_buffer).map_err(corrupt)?;
349                let mut value_buffer = [0; 16];
350                self.read_exact(&mut value_buffer).map_err(corrupt)?;
351                Ok(EncodedTerm::BigBigLangStringLiteral {
352                    value_id: StrHash::from_be_bytes(value_buffer),
353                    language_id: StrHash::from_be_bytes(language_buffer),
354                })
355            }
356            TYPE_SMALL_TYPED_LITERAL => {
357                let mut datatype_buffer = [0; 16];
358                self.read_exact(&mut datatype_buffer).map_err(corrupt)?;
359                let mut value_buffer = [0; 16];
360                self.read_exact(&mut value_buffer).map_err(corrupt)?;
361                Ok(EncodedTerm::SmallTypedLiteral {
362                    datatype_id: StrHash::from_be_bytes(datatype_buffer),
363                    value: SmallString::from_be_bytes(value_buffer)
364                        .map_err(|e| StorageError::Corrupt(e.to_string()))?,
365                })
366            }
367            TYPE_BIG_TYPED_LITERAL => {
368                let mut datatype_buffer = [0; 16];
369                self.read_exact(&mut datatype_buffer).map_err(corrupt)?;
370                let mut value_buffer = [0; 16];
371                self.read_exact(&mut value_buffer).map_err(corrupt)?;
372                Ok(EncodedTerm::BigTypedLiteral {
373                    datatype_id: StrHash::from_be_bytes(datatype_buffer),
374                    value_id: StrHash::from_be_bytes(value_buffer),
375                })
376            }
377            TYPE_SMALL_STRING_LITERAL => {
378                let mut buffer = [0; 16];
379                self.read_exact(&mut buffer).map_err(corrupt)?;
380                Ok(EncodedTerm::SmallStringLiteral(
381                    SmallString::from_be_bytes(buffer)
382                        .map_err(|e| StorageError::Corrupt(e.to_string()))?,
383                ))
384            }
385            TYPE_BIG_STRING_LITERAL => {
386                let mut buffer = [0; 16];
387                self.read_exact(&mut buffer).map_err(corrupt)?;
388                Ok(EncodedTerm::BigStringLiteral {
389                    value_id: StrHash::from_be_bytes(buffer),
390                })
391            }
392            TYPE_BOOLEAN_LITERAL_TRUE => Ok(ENCODED_TERM_TRUE),
393            TYPE_BOOLEAN_LITERAL_FALSE => Ok(ENCODED_TERM_FALSE),
394            TYPE_FLOAT_LITERAL => {
395                let mut buffer = [0; 4];
396                self.read_exact(&mut buffer).map_err(corrupt)?;
397                Ok(EncodedTerm::FloatLiteral(Float::from_be_bytes(buffer)))
398            }
399            TYPE_DOUBLE_LITERAL => {
400                let mut buffer = [0; 8];
401                self.read_exact(&mut buffer).map_err(corrupt)?;
402                Ok(EncodedTerm::DoubleLiteral(Double::from_be_bytes(buffer)))
403            }
404            TYPE_INTEGER_LITERAL => {
405                let mut buffer = [0; 8];
406                self.read_exact(&mut buffer).map_err(corrupt)?;
407                Ok(EncodedTerm::IntegerLiteral(Integer::from_be_bytes(buffer)))
408            }
409            TYPE_DECIMAL_LITERAL => {
410                let mut buffer = [0; 16];
411                self.read_exact(&mut buffer).map_err(corrupt)?;
412                Ok(EncodedTerm::DecimalLiteral(Decimal::from_be_bytes(buffer)))
413            }
414            TYPE_DATE_TIME_LITERAL => {
415                let mut buffer = [0; 18];
416                self.read_exact(&mut buffer).map_err(corrupt)?;
417                Ok(EncodedTerm::DateTimeLiteral(DateTime::from_be_bytes(
418                    buffer,
419                )))
420            }
421            TYPE_TIME_LITERAL => {
422                let mut buffer = [0; 18];
423                self.read_exact(&mut buffer).map_err(corrupt)?;
424                Ok(EncodedTerm::TimeLiteral(Time::from_be_bytes(buffer)))
425            }
426            TYPE_DATE_LITERAL => {
427                let mut buffer = [0; 18];
428                self.read_exact(&mut buffer).map_err(corrupt)?;
429                Ok(EncodedTerm::DateLiteral(Date::from_be_bytes(buffer)))
430            }
431            TYPE_G_YEAR_MONTH_LITERAL => {
432                let mut buffer = [0; 18];
433                self.read_exact(&mut buffer).map_err(corrupt)?;
434                Ok(EncodedTerm::GYearMonthLiteral(GYearMonth::from_be_bytes(
435                    buffer,
436                )))
437            }
438            TYPE_G_YEAR_LITERAL => {
439                let mut buffer = [0; 18];
440                self.read_exact(&mut buffer).map_err(corrupt)?;
441                Ok(EncodedTerm::GYearLiteral(GYear::from_be_bytes(buffer)))
442            }
443            TYPE_G_MONTH_DAY_LITERAL => {
444                let mut buffer = [0; 18];
445                self.read_exact(&mut buffer).map_err(corrupt)?;
446                Ok(EncodedTerm::GMonthDayLiteral(GMonthDay::from_be_bytes(
447                    buffer,
448                )))
449            }
450            TYPE_G_DAY_LITERAL => {
451                let mut buffer = [0; 18];
452                self.read_exact(&mut buffer).map_err(corrupt)?;
453                Ok(EncodedTerm::GDayLiteral(GDay::from_be_bytes(buffer)))
454            }
455            TYPE_G_MONTH_LITERAL => {
456                let mut buffer = [0; 18];
457                self.read_exact(&mut buffer).map_err(corrupt)?;
458                Ok(EncodedTerm::GMonthLiteral(GMonth::from_be_bytes(buffer)))
459            }
460            TYPE_DURATION_LITERAL => {
461                let mut buffer = [0; 24];
462                self.read_exact(&mut buffer).map_err(corrupt)?;
463                Ok(EncodedTerm::DurationLiteral(Duration::from_be_bytes(
464                    buffer,
465                )))
466            }
467            TYPE_YEAR_MONTH_DURATION_LITERAL => {
468                let mut buffer = [0; 8];
469                self.read_exact(&mut buffer).map_err(corrupt)?;
470                Ok(EncodedTerm::YearMonthDurationLiteral(
471                    YearMonthDuration::from_be_bytes(buffer),
472                ))
473            }
474            TYPE_DAY_TIME_DURATION_LITERAL => {
475                let mut buffer = [0; 16];
476                self.read_exact(&mut buffer).map_err(corrupt)?;
477                Ok(EncodedTerm::DayTimeDurationLiteral(
478                    DayTimeDuration::from_be_bytes(buffer),
479                ))
480            }
481            TYPE_LITERAL_POINT => {
482                let mut buffer = [0; 18];
483                self.read_exact(&mut buffer).map_err(corrupt)?;
484                let Some(&geo_datatype_byte) = buffer.last() else {
485                    unreachable!("buffer is 18 bytes");
486                };
487                let Some(geo_datatype) = GeoDatatype::from_u8(geo_datatype_byte) else {
488                    return Err(StorageError::Corrupt(format!(
489                        "invalid geo datatype byte {geo_datatype_byte}"
490                    )));
491                };
492                let crs = CrsId::from_u8(buffer[16]);
493                let x = f64::from_be_bytes(buffer[0..8].try_into().expect("8-byte slice"));
494                let y = f64::from_be_bytes(buffer[8..16].try_into().expect("8-byte slice"));
495                Ok(EncodedTerm::LiteralPoint {
496                    x,
497                    y,
498                    crs,
499                    geo_datatype,
500                })
501            }
502            TYPE_LITERAL_GEOMETRY => {
503                let mut buffer = [0; 19];
504                self.read_exact(&mut buffer).map_err(corrupt)?;
505                let kind_flags = buffer[0];
506                let known_flags = GEOM_KIND_WIRE_MASK | GEOM_REQUIRES_SPIKE_REDUCTION_WIRE_FLAG;
507                if kind_flags & !known_flags != 0 {
508                    return Err(StorageError::Corrupt(format!(
509                        "unsupported geo geometry flags 0x{kind_flags:02x}"
510                    )));
511                }
512                let geom_kind = GeomKind::from_u8(kind_flags & GEOM_KIND_WIRE_MASK);
513                let requires_spike_reduction =
514                    kind_flags & GEOM_REQUIRES_SPIKE_REDUCTION_WIRE_FLAG != 0;
515                let crs = CrsId::from_u8(buffer[1]);
516                let Some(geo_datatype) = GeoDatatype::from_u8(buffer[2]) else {
517                    return Err(StorageError::Corrupt(format!(
518                        "invalid geo datatype byte {}",
519                        buffer[2]
520                    )));
521                };
522                let blob_id =
523                    StrHash::from_be_bytes(buffer[3..19].try_into().expect("16-byte slice"));
524                Ok(EncodedTerm::LiteralGeometry {
525                    geom_kind,
526                    crs,
527                    geo_datatype,
528                    blob_id,
529                    requires_spike_reduction,
530                })
531            }
532            TYPE_BLOB_LITERAL => {
533                let mut buffer = [0; 32];
534                self.read_exact(&mut buffer).map_err(corrupt)?;
535                Ok(EncodedTerm::BlobLiteral {
536                    datatype_id: StrHash::from_be_bytes(
537                        buffer[0..16].try_into().expect("16-byte slice"),
538                    ),
539                    blob_id: StrHash::from_be_bytes(
540                        buffer[16..32].try_into().expect("16-byte slice"),
541                    ),
542                })
543            }
544            TYPE_PLACEHOLDER => Err(StorageError::Corrupt(
545                "internal Placeholder type must not appear in stored terms".into(),
546            )),
547            TYPE_TRIPLE => Err(StorageError::Corrupt(
548                "RDF triple term type is not implemented".into(),
549            )),
550            other => Err(StorageError::Corrupt(format!(
551                "invalid encoded term type id: {other}"
552            ))),
553        }
554    }
555}
556
557fn corrupt(error: std::io::Error) -> StorageError {
558    StorageError::Corrupt(error.to_string())
559}
560
561fn quad_slot(quad: &EncodedQuad, slot: QuadSlot) -> &EncodedTerm {
562    match slot {
563        QuadSlot::Subject => &quad.subject,
564        QuadSlot::Predicate => &quad.predicate,
565        QuadSlot::Object => &quad.object,
566        QuadSlot::Graph => &quad.graph_name,
567    }
568}
569
570/// Write an encoded term to `sink`.
571pub fn write_term(sink: &mut Vec<u8>, term: &EncodedTerm) {
572    match term {
573        EncodedTerm::DefaultGraph => (),
574        EncodedTerm::Placeholder => {
575            panic!("EncodedTerm::Placeholder must not be written to storage keys")
576        }
577        EncodedTerm::NamedNode { iri_id } => {
578            sink.push(TYPE_NAMED_NODE_ID);
579            sink.extend_from_slice(&iri_id.to_be_bytes());
580        }
581        EncodedTerm::NumericalBlankNode { id } => {
582            sink.push(TYPE_NUMERICAL_BLANK_NODE_ID);
583            sink.extend_from_slice(id);
584        }
585        EncodedTerm::SmallBlankNode(id) => {
586            sink.push(TYPE_SMALL_BLANK_NODE_ID);
587            sink.extend_from_slice(&id.to_be_bytes());
588        }
589        EncodedTerm::BigBlankNode { id_id } => {
590            sink.push(TYPE_BIG_BLANK_NODE_ID);
591            sink.extend_from_slice(&id_id.to_be_bytes());
592        }
593        EncodedTerm::SmallStringLiteral(value) => {
594            sink.push(TYPE_SMALL_STRING_LITERAL);
595            sink.extend_from_slice(&value.to_be_bytes());
596        }
597        EncodedTerm::BigStringLiteral { value_id } => {
598            sink.push(TYPE_BIG_STRING_LITERAL);
599            sink.extend_from_slice(&value_id.to_be_bytes());
600        }
601        EncodedTerm::SmallSmallLangStringLiteral { value, language } => {
602            sink.push(TYPE_SMALL_SMALL_LANG_STRING_LITERAL);
603            sink.extend_from_slice(&language.to_be_bytes());
604            sink.extend_from_slice(&value.to_be_bytes());
605        }
606        EncodedTerm::SmallBigLangStringLiteral { value, language_id } => {
607            sink.push(TYPE_SMALL_BIG_LANG_STRING_LITERAL);
608            sink.extend_from_slice(&language_id.to_be_bytes());
609            sink.extend_from_slice(&value.to_be_bytes());
610        }
611        EncodedTerm::BigSmallLangStringLiteral { value_id, language } => {
612            sink.push(TYPE_BIG_SMALL_LANG_STRING_LITERAL);
613            sink.extend_from_slice(&language.to_be_bytes());
614            sink.extend_from_slice(&value_id.to_be_bytes());
615        }
616        EncodedTerm::BigBigLangStringLiteral {
617            value_id,
618            language_id,
619        } => {
620            sink.push(TYPE_BIG_BIG_LANG_STRING_LITERAL);
621            sink.extend_from_slice(&language_id.to_be_bytes());
622            sink.extend_from_slice(&value_id.to_be_bytes());
623        }
624        EncodedTerm::SmallTypedLiteral { value, datatype_id } => {
625            sink.push(TYPE_SMALL_TYPED_LITERAL);
626            sink.extend_from_slice(&datatype_id.to_be_bytes());
627            sink.extend_from_slice(&value.to_be_bytes());
628        }
629        EncodedTerm::BigTypedLiteral {
630            value_id,
631            datatype_id,
632        } => {
633            sink.push(TYPE_BIG_TYPED_LITERAL);
634            sink.extend_from_slice(&datatype_id.to_be_bytes());
635            sink.extend_from_slice(&value_id.to_be_bytes());
636        }
637        EncodedTerm::BooleanLiteral(value) => sink.push(if bool::from(*value) {
638            TYPE_BOOLEAN_LITERAL_TRUE
639        } else {
640            TYPE_BOOLEAN_LITERAL_FALSE
641        }),
642        EncodedTerm::FloatLiteral(value) => {
643            sink.push(TYPE_FLOAT_LITERAL);
644            sink.extend_from_slice(&value.to_be_bytes());
645        }
646        EncodedTerm::DoubleLiteral(value) => {
647            sink.push(TYPE_DOUBLE_LITERAL);
648            sink.extend_from_slice(&value.to_be_bytes());
649        }
650        EncodedTerm::IntegerLiteral(value) => {
651            sink.push(TYPE_INTEGER_LITERAL);
652            sink.extend_from_slice(&value.to_be_bytes());
653        }
654        EncodedTerm::DecimalLiteral(value) => {
655            sink.push(TYPE_DECIMAL_LITERAL);
656            sink.extend_from_slice(&value.to_be_bytes());
657        }
658        EncodedTerm::DateTimeLiteral(value) => {
659            sink.push(TYPE_DATE_TIME_LITERAL);
660            sink.extend_from_slice(&value.to_be_bytes());
661        }
662        EncodedTerm::TimeLiteral(value) => {
663            sink.push(TYPE_TIME_LITERAL);
664            sink.extend_from_slice(&value.to_be_bytes());
665        }
666        EncodedTerm::DateLiteral(value) => {
667            sink.push(TYPE_DATE_LITERAL);
668            sink.extend_from_slice(&value.to_be_bytes());
669        }
670        EncodedTerm::GYearMonthLiteral(value) => {
671            sink.push(TYPE_G_YEAR_MONTH_LITERAL);
672            sink.extend_from_slice(&value.to_be_bytes());
673        }
674        EncodedTerm::GYearLiteral(value) => {
675            sink.push(TYPE_G_YEAR_LITERAL);
676            sink.extend_from_slice(&value.to_be_bytes());
677        }
678        EncodedTerm::GMonthDayLiteral(value) => {
679            sink.push(TYPE_G_MONTH_DAY_LITERAL);
680            sink.extend_from_slice(&value.to_be_bytes());
681        }
682        EncodedTerm::GDayLiteral(value) => {
683            sink.push(TYPE_G_DAY_LITERAL);
684            sink.extend_from_slice(&value.to_be_bytes());
685        }
686        EncodedTerm::GMonthLiteral(value) => {
687            sink.push(TYPE_G_MONTH_LITERAL);
688            sink.extend_from_slice(&value.to_be_bytes());
689        }
690        EncodedTerm::DurationLiteral(value) => {
691            sink.push(TYPE_DURATION_LITERAL);
692            sink.extend_from_slice(&value.to_be_bytes());
693        }
694        EncodedTerm::YearMonthDurationLiteral(value) => {
695            sink.push(TYPE_YEAR_MONTH_DURATION_LITERAL);
696            sink.extend_from_slice(&value.to_be_bytes());
697        }
698        EncodedTerm::DayTimeDurationLiteral(value) => {
699            sink.push(TYPE_DAY_TIME_DURATION_LITERAL);
700            sink.extend_from_slice(&value.to_be_bytes());
701        }
702        EncodedTerm::LiteralPoint {
703            x,
704            y,
705            crs,
706            geo_datatype,
707        } => {
708            sink.push(TYPE_LITERAL_POINT);
709            sink.extend_from_slice(&x.to_be_bytes());
710            sink.extend_from_slice(&y.to_be_bytes());
711            sink.push(crs.as_u8());
712            sink.push(geo_datatype.as_u8());
713        }
714        EncodedTerm::LiteralGeometry {
715            geom_kind,
716            crs,
717            geo_datatype,
718            blob_id,
719            requires_spike_reduction,
720        } => {
721            sink.push(TYPE_LITERAL_GEOMETRY);
722            let mut kind_flags = geom_kind.as_u8() & GEOM_KIND_WIRE_MASK;
723            if *requires_spike_reduction {
724                kind_flags |= GEOM_REQUIRES_SPIKE_REDUCTION_WIRE_FLAG;
725            }
726            sink.push(kind_flags);
727            sink.push(crs.as_u8());
728            sink.push(geo_datatype.as_u8());
729            sink.extend_from_slice(&blob_id.to_be_bytes());
730        }
731        EncodedTerm::BlobLiteral {
732            datatype_id,
733            blob_id,
734        } => {
735            sink.push(TYPE_BLOB_LITERAL);
736            sink.extend_from_slice(&datatype_id.to_be_bytes());
737            sink.extend_from_slice(&blob_id.to_be_bytes());
738        }
739    }
740}
741
742/// Encode a single term to bytes.
743pub fn encode_term_bytes(term: &EncodedTerm) -> Vec<u8> {
744    let mut vec = Vec::with_capacity(WRITTEN_TERM_MAX_SIZE);
745    write_term(&mut vec, term);
746    vec
747}
748
749/// Increment-with-carry exclusive successor of `key`.
750///
751/// Trailing `0xFF` bytes wrap to `0` (unlike RocksDB iterate-upper-bound,
752/// which only bumps the first non-`0xFF`). `None` if every byte is `0xFF`.
753pub fn byte_successor(key: &[u8]) -> Option<Vec<u8>> {
754    let mut bound = key.to_vec();
755    for c in bound.iter_mut().rev() {
756        if *c < u8::MAX {
757            *c += 1;
758            return Some(bound);
759        }
760        *c = 0;
761    }
762    None
763}
764
765/// Decode exactly one [`EncodedTerm::NamedNode`] from `bytes`.
766///
767/// Rejects empty input, trailing bytes, and any non-IRI term (literals,
768/// blanks, default graph). PredicateDomain prefixes must not be an arbitrary
769/// byte string.
770pub fn decode_named_node_term(bytes: &[u8]) -> Result<EncodedTerm, StorageError> {
771    if bytes.is_empty() {
772        return Err(StorageError::Corrupt(
773            "predicate term must be a NamedNode (empty bytes)".to_owned(),
774        ));
775    }
776    let mut cursor = bytes;
777    let term = cursor.read_term()?;
778    if !cursor.is_empty() {
779        return Err(StorageError::Corrupt(format!(
780            "predicate term has {} trailing byte(s)",
781            cursor.len()
782        )));
783    }
784    match term {
785        EncodedTerm::NamedNode { .. } => Ok(term),
786        other => Err(StorageError::Corrupt(format!(
787            "predicate term must be a NamedNode, got {other:?}"
788        ))),
789    }
790}
791
792/// Build a hexastore index key for `quad` in `permutation` order.
793pub fn encode_index_key(permutation: IndexPermutation, quad: &EncodedQuad) -> Vec<u8> {
794    // Four terms, each at most [`WRITTEN_TERM_MAX_SIZE`] (DefaultGraph writes
795    // zero bytes): reserving up front keeps the insert path and every resume
796    // seek off the grow/realloc path.
797    let mut sink = Vec::with_capacity(4 * WRITTEN_TERM_MAX_SIZE);
798    for slot in permutation.slot_order() {
799        write_term(&mut sink, quad_slot(quad, *slot));
800    }
801    sink
802}
803
804/// `omitted_slots` bit for the subject slot.
805pub const OMIT_SUBJECT: u8 = 1 << 0;
806/// `omitted_slots` bit for the predicate slot.
807pub const OMIT_PREDICATE: u8 = 1 << 1;
808/// `omitted_slots` bit for the object slot.
809pub const OMIT_OBJECT: u8 = 1 << 2;
810/// `omitted_slots` bit for the graph slot.
811pub const OMIT_GRAPH: u8 = 1 << 3;
812/// No slot omitted.
813pub const OMIT_NONE: u8 = 0;
814
815/// Term a receiver puts back for a slot the sender omitted.
816///
817/// A bound slot restores its request term exactly; a slot nothing reads reads
818/// as the counted-presence sentinel ([`ENCODED_TERM_TRUE`]) rather than as a
819/// value that could be mistaken for data. `EncodedTerm::Placeholder` is not
820/// usable here: it neither encodes to nor decodes from a key.
821pub fn omitted_slot_term(bound: Option<&EncodedTerm>) -> EncodedTerm {
822    bound.cloned().unwrap_or(ENCODED_TERM_TRUE)
823}
824
825/// [`decode_index_key`] for a request that may omit slots.
826///
827/// A masked slot is skipped without constructing its term (the width table
828/// advances the cursor) and restored with [`omitted_slot_term`]. This is the
829/// in-process twin of `waratah_proto::quad_from_proto_omitting`: one rule, two
830/// transports, so the wire and in-process paths cannot disagree.
831pub fn decode_index_key_omitting(
832    permutation: IndexPermutation,
833    key: &[u8],
834    pattern: &EncodedTriplePattern,
835    omitted: u8,
836) -> Result<EncodedQuad, StorageError> {
837    let order = permutation.slot_order();
838    let mut terms = [
839        EncodedTerm::DefaultGraph,
840        EncodedTerm::DefaultGraph,
841        EncodedTerm::DefaultGraph,
842        EncodedTerm::DefaultGraph,
843    ];
844    let mut offset = 0usize;
845    for slot in order {
846        let bit = match slot {
847            QuadSlot::Subject => OMIT_SUBJECT,
848            QuadSlot::Predicate => OMIT_PREDICATE,
849            QuadSlot::Object => OMIT_OBJECT,
850            QuadSlot::Graph => OMIT_GRAPH,
851        };
852        let masked = omitted & bit != 0;
853        let bound = match slot {
854            QuadSlot::Subject => pattern.subject.as_ref(),
855            QuadSlot::Predicate => pattern.predicate.as_ref(),
856            QuadSlot::Object => pattern.object.as_ref(),
857            QuadSlot::Graph => pattern.graph_name.as_ref(),
858        };
859        let term = if *slot == QuadSlot::Graph && offset >= key.len() {
860            // The default graph's zero-length encoding.
861            if masked {
862                omitted_slot_term(bound)
863            } else {
864                EncodedTerm::DefaultGraph
865            }
866        } else if masked {
867            offset += term_width_at(key, offset)?;
868            omitted_slot_term(bound)
869        } else {
870            let mut cursor = &key[offset..];
871            let term = cursor.read_term()?;
872            offset = key.len() - cursor.len();
873            term
874        };
875        match slot {
876            QuadSlot::Subject => terms[0] = term,
877            QuadSlot::Predicate => terms[1] = term,
878            QuadSlot::Object => terms[2] = term,
879            QuadSlot::Graph => terms[3] = term,
880        }
881    }
882    if permutation == IndexPermutation::Tsg {
883        terms[1] = if omitted & OMIT_PREDICATE != 0 {
884            omitted_slot_term(pattern.predicate.as_ref())
885        } else {
886            RDF_TYPE.clone()
887        };
888    }
889    Ok(EncodedQuad::new(
890        terms[0].clone(),
891        terms[1].clone(),
892        terms[2].clone(),
893        terms[3].clone(),
894    ))
895}
896
897/// Decode a hexastore index key written in `permutation` order.
898///
899/// Graph is always the last slot. [`EncodedTerm::DefaultGraph`] writes zero
900/// bytes, so an exhausted buffer at the graph slot means the default graph
901/// (Oxigraph-compatible). [`IndexPermutation::Tsg`] omits the predicate from
902/// the key and injects [`RDF_TYPE`] on decode.
903pub fn decode_index_key(
904    permutation: IndexPermutation,
905    mut key: &[u8],
906) -> Result<EncodedQuad, StorageError> {
907    let order = permutation.slot_order();
908    let mut terms = [
909        EncodedTerm::DefaultGraph,
910        EncodedTerm::DefaultGraph,
911        EncodedTerm::DefaultGraph,
912        EncodedTerm::DefaultGraph,
913    ];
914    for slot in order {
915        let term = if *slot == QuadSlot::Graph && key.is_empty() {
916            EncodedTerm::DefaultGraph
917        } else {
918            key.read_term()?
919        };
920        match slot {
921            QuadSlot::Subject => terms[0] = term,
922            QuadSlot::Predicate => terms[1] = term,
923            QuadSlot::Object => terms[2] = term,
924            QuadSlot::Graph => terms[3] = term,
925        }
926    }
927    if permutation == IndexPermutation::Tsg {
928        terms[1] = RDF_TYPE.clone();
929    }
930    Ok(EncodedQuad::new(
931        terms[0].clone(),
932        terms[1].clone(),
933        terms[2].clone(),
934        terms[3].clone(),
935    ))
936}
937
938#[cfg(test)]
939mod tests {
940    use super::*;
941    use crate::{GraphName, Literal, NamedNode, Quad};
942    use pretty_assertions::assert_eq;
943
944    /// A masked slot is skipped (never constructed) and restored from the
945    /// request's own bound term; a masked free slot reads as the
946    /// counted-presence sentinel. This is the in-process twin of the wire
947    /// reassembly, so both paths decode an omitted slot identically.
948    #[test]
949    fn omitted_slots_decode_without_constructing_the_term() {
950        let s = EncodedTerm::from(&crate::NamedNode::new("http://ex/s").unwrap());
951        let p = EncodedTerm::from(&crate::NamedNode::new("http://ex/p").unwrap());
952        let o = EncodedTerm::from(&crate::NamedNode::new("http://ex/o").unwrap());
953        let quad = EncodedQuad::new(s.clone(), p.clone(), o.clone(), EncodedTerm::DefaultGraph);
954        let key = encode_index_key(IndexPermutation::Spog, &quad);
955
956        let bound = EncodedTriplePattern {
957            subject: Some(s.clone()),
958            predicate: Some(p.clone()),
959            object: None,
960            graph_name: Some(EncodedTerm::DefaultGraph),
961        };
962        let decoded = decode_index_key_omitting(
963            IndexPermutation::Spog,
964            &key,
965            &bound,
966            OMIT_SUBJECT | OMIT_PREDICATE | OMIT_GRAPH,
967        )
968        .unwrap();
969        assert_eq!(decoded, quad, "bound slots reassemble exactly");
970
971        let free = EncodedTriplePattern::default();
972        let decoded =
973            decode_index_key_omitting(IndexPermutation::Spog, &key, &free, OMIT_OBJECT).unwrap();
974        assert_eq!(decoded.object, ENCODED_TERM_TRUE);
975        assert_eq!(decoded.subject, quad.subject);
976        assert_eq!(decoded.predicate, quad.predicate);
977        assert_eq!(decoded.graph_name, quad.graph_name);
978
979        assert_eq!(
980            decode_index_key_omitting(IndexPermutation::Spog, &key, &free, OMIT_NONE).unwrap(),
981            quad,
982            "no mask decodes exactly as the plain decoder"
983        );
984    }
985
986    fn round_trip(term: EncodedTerm) {
987        let mut buffer = Vec::new();
988        write_term(&mut buffer, &term);
989        let decoded = buffer.as_slice().read_term().unwrap();
990        assert_eq!(term, decoded);
991    }
992
993    #[test]
994    fn geometry_spike_flag_packs_into_the_kind_byte_without_widening() {
995        let blob_id = StrHash::from_bytes(&[0xAB_u8; 32]);
996        let plain = EncodedTerm::LiteralGeometry {
997            geom_kind: GeomKind::Polygon,
998            crs: CrsId::Crs84,
999            geo_datatype: GeoDatatype::WktLiteral,
1000            blob_id,
1001            requires_spike_reduction: false,
1002        };
1003        let flagged = EncodedTerm::LiteralGeometry {
1004            geom_kind: GeomKind::Polygon,
1005            crs: CrsId::Crs84,
1006            geo_datatype: GeoDatatype::WktLiteral,
1007            blob_id,
1008            requires_spike_reduction: true,
1009        };
1010        let plain_bytes = encode_term_bytes(&plain);
1011        let flagged_bytes = encode_term_bytes(&flagged);
1012        assert_eq!(plain_bytes.len(), 20);
1013        assert_eq!(flagged_bytes.len(), 20);
1014        assert_eq!(
1015            plain_bytes[1],
1016            GeomKind::Polygon.as_u8() & GEOM_KIND_WIRE_MASK
1017        );
1018        assert_eq!(
1019            flagged_bytes[1],
1020            (GeomKind::Polygon.as_u8() & GEOM_KIND_WIRE_MASK)
1021                | GEOM_REQUIRES_SPIKE_REDUCTION_WIRE_FLAG
1022        );
1023        assert_ne!(plain, flagged, "the flag is part of term identity");
1024        round_trip(flagged);
1025
1026        let mut unknown_flag = flagged_bytes.clone();
1027        unknown_flag[1] |= 0x40;
1028        assert!(matches!(
1029            unknown_flag.as_slice().read_term(),
1030            Err(StorageError::Corrupt(_))
1031        ));
1032    }
1033
1034    /// Writer byte-idempotence: `write ∘ read ∘ write` is byte-stable.
1035    ///
1036    /// The head walks' region-based run and distinct detection compares
1037    /// encoded byte regions as term identity — sound because the writer's
1038    /// byte form is a deterministic, byte-faithful function of the term
1039    /// (e.g. `SmallString::from_str` zeroes the bytes past the length, so
1040    /// the canonical form never carries junk a decode could drop). This
1041    /// test pins that property: if an encoder change ever makes
1042    /// decode-then-rewrite produce different bytes, key-region equality
1043    /// stops implying term equality and the walks above would silently
1044    /// split runs.
1045    #[test]
1046    fn write_is_byte_idempotent_over_decoded_terms() {
1047        for term in every_encoded_variant() {
1048            let bytes = encode_term_bytes(&term);
1049            let decoded = {
1050                let mut rest: &[u8] = &bytes;
1051                rest.read_term().unwrap()
1052            };
1053            assert_eq!(
1054                encode_term_bytes(&decoded),
1055                bytes,
1056                "write ∘ read ∘ write must be byte-stable for {term:?}"
1057            );
1058        }
1059    }
1060
1061    /// One fixture per [`EncodedTerm`] variant that writes bytes (DefaultGraph
1062    /// writes zero bytes and has no type byte). Booleans are listed twice so
1063    /// both type bytes (28 true / 29 false) are covered.
1064    fn every_encoded_variant() -> Vec<EncodedTerm> {
1065        vec![
1066            EncodedTerm::NamedNode {
1067                iri_id: StrHash::new("http://foo.com"),
1068            },
1069            EncodedTerm::NumericalBlankNode {
1070                id: 0x100a_u128.to_be_bytes(),
1071            },
1072            EncodedTerm::SmallBlankNode("bnode".try_into().unwrap()),
1073            EncodedTerm::BigBlankNode {
1074                id_id: StrHash::new("a blank node id far longer than sixteen bytes"),
1075            },
1076            EncodedTerm::SmallStringLiteral("literal".try_into().unwrap()),
1077            EncodedTerm::BigStringLiteral {
1078                value_id: StrHash::new("a plain literal value far longer than sixteen bytes"),
1079            },
1080            // Geo/blob variants — OPSG head terms in geo corpora, and the
1081            // exact 33-byte wire width (`WRITTEN_TERM_MAX_SIZE`) for
1082            // BlobLiteral. Non-zero CRS/kind/datatype bytes exercise the
1083            // field encodings rather than defaults.
1084            EncodedTerm::LiteralPoint {
1085                x: 149.1234,
1086                y: -35.5678,
1087                crs: CrsId::Epsg4326,
1088                geo_datatype: GeoDatatype::WkbLiteral,
1089            },
1090            EncodedTerm::LiteralGeometry {
1091                geom_kind: GeomKind::LineString,
1092                crs: CrsId::Epsg4283,
1093                geo_datatype: GeoDatatype::WktLiteral,
1094                blob_id: StrHash::new("canonical crs84 ewkb bytes of a linestring"),
1095                requires_spike_reduction: false,
1096            },
1097            EncodedTerm::BlobLiteral {
1098                datatype_id: StrHash::new("http://example.com/datatypes/shacl-shape"),
1099                blob_id: StrHash::new("content-addressed binary payload of any length"),
1100            },
1101            EncodedTerm::SmallSmallLangStringLiteral {
1102                value: "chat".try_into().unwrap(),
1103                language: "en".try_into().unwrap(),
1104            },
1105            EncodedTerm::SmallBigLangStringLiteral {
1106                value: "chat".try_into().unwrap(),
1107                language_id: StrHash::new("a language tag far longer than sixteen bytes"),
1108            },
1109            EncodedTerm::BigSmallLangStringLiteral {
1110                value_id: StrHash::new("a literal value far longer than sixteen bytes"),
1111                language: "en".try_into().unwrap(),
1112            },
1113            EncodedTerm::BigBigLangStringLiteral {
1114                value_id: StrHash::new("a literal value far longer than sixteen bytes"),
1115                language_id: StrHash::new("a language tag far longer than sixteen bytes"),
1116            },
1117            EncodedTerm::SmallTypedLiteral {
1118                value: "42".try_into().unwrap(),
1119                datatype_id: StrHash::new("http://www.w3.org/2001/XMLSchema#nonNegativeInteger"),
1120            },
1121            EncodedTerm::BigTypedLiteral {
1122                value_id: StrHash::new("a typed literal value far longer than sixteen bytes"),
1123                datatype_id: StrHash::new("http://www.w3.org/2001/XMLSchema#nonNegativeInteger"),
1124            },
1125            ENCODED_TERM_TRUE,
1126            ENCODED_TERM_FALSE,
1127            EncodedTerm::FloatLiteral(Float::from(1.5)),
1128            EncodedTerm::DoubleLiteral(Double::from(2.5)),
1129            EncodedTerm::IntegerLiteral(Integer::from(7)),
1130            EncodedTerm::DecimalLiteral("1.5".parse().unwrap()),
1131            EncodedTerm::DateTimeLiteral("2010-06-21T11:28:01Z".parse().unwrap()),
1132            EncodedTerm::TimeLiteral("11:28:01Z".parse().unwrap()),
1133            EncodedTerm::DateLiteral("2010-06-21".parse().unwrap()),
1134            EncodedTerm::GYearMonthLiteral("2010-06".parse().unwrap()),
1135            EncodedTerm::GYearLiteral("2010".parse().unwrap()),
1136            EncodedTerm::GMonthDayLiteral("--06-21".parse().unwrap()),
1137            EncodedTerm::GDayLiteral("---21".parse().unwrap()),
1138            EncodedTerm::GMonthLiteral("--06".parse().unwrap()),
1139            EncodedTerm::DurationLiteral("P1Y2M3DT10H30M".parse().unwrap()),
1140            EncodedTerm::YearMonthDurationLiteral("P1Y2M".parse().unwrap()),
1141            EncodedTerm::DayTimeDurationLiteral("P1DT10H".parse().unwrap()),
1142        ]
1143    }
1144
1145    #[test]
1146    fn term_width_table_covers_every_encoded_variant() {
1147        // Buffer-sizing invariant, checked at the table level so it holds
1148        // for every type byte — fixture coverage cannot be relied on,
1149        // because a new variant can land in the table before its fixture
1150        // row does. The head walks hold saved terms in
1151        // `[u8; WRITTEN_TERM_MAX_SIZE]` stack buffers (run heads, last
1152        // slot-1/slot-2 regions) and `MERGE_TRIPLE_PREFIX_MAX` is
1153        // `3 * WRITTEN_TERM_MAX_SIZE`; a table width above the constant
1154        // turns those `copy_from_slice` sites into panics on *valid*
1155        // rows — strictly worse than any corruption they would report.
1156        let max_width = TERM_WIDTH
1157            .iter()
1158            .filter(|&&w| w != TERM_WIDTH_UNKNOWN)
1159            .copied()
1160            .max()
1161            .expect("TERM_WIDTH holds at least one known width");
1162        assert!(
1163            usize::from(max_width) <= WRITTEN_TERM_MAX_SIZE,
1164            "a {max_width}-byte term exceeds WRITTEN_TERM_MAX_SIZE \
1165             ({WRITTEN_TERM_MAX_SIZE}): the walk buffers and \
1166             MERGE_TRIPLE_PREFIX_MAX are sized by the constant and would \
1167             panic on valid rows"
1168        );
1169        for term in every_encoded_variant() {
1170            let bytes = encode_term_bytes(&term);
1171            let width = term_width_at(&bytes, 0).unwrap();
1172            assert_eq!(bytes.len(), width, "{term:?}");
1173            assert!(
1174                width <= WRITTEN_TERM_MAX_SIZE,
1175                "{term:?} writes {width} bytes: the constant, not the \
1176                 table alone, is what the walk buffers trust"
1177            );
1178            // The table walk and the decoder agree on where the term ends.
1179            let mut cursor = &bytes[..];
1180            let decoded = cursor.read_term().unwrap();
1181            assert_eq!(decoded, term, "{term:?}");
1182            assert!(cursor.is_empty(), "decoder consumed {term:?} exactly");
1183        }
1184    }
1185
1186    #[test]
1187    fn boolean_variants_use_two_distinct_type_bytes() {
1188        let truthy = encode_term_bytes(&ENCODED_TERM_TRUE);
1189        let falsy = encode_term_bytes(&ENCODED_TERM_FALSE);
1190        assert_ne!(truthy[0], falsy[0], "true and false must be distinct ids");
1191        assert_eq!(truthy[0], TYPE_BOOLEAN_LITERAL_TRUE);
1192        assert_eq!(falsy[0], TYPE_BOOLEAN_LITERAL_FALSE);
1193        assert_eq!(term_width_at(&truthy, 0).unwrap(), 1);
1194        assert_eq!(term_width_at(&falsy, 0).unwrap(), 1);
1195    }
1196
1197    #[test]
1198    fn term_width_walks_a_chained_two_term_buffer_exactly() {
1199        let first = EncodedTerm::SmallStringLiteral("first".try_into().unwrap());
1200        let second = EncodedTerm::SmallSmallLangStringLiteral {
1201            value: "deuxième".try_into().unwrap(),
1202            language: "fr".try_into().unwrap(),
1203        };
1204        let mut buffer = encode_term_bytes(&first);
1205        buffer.extend_from_slice(&encode_term_bytes(&second));
1206
1207        let w1 = term_width_at(&buffer, 0).unwrap();
1208        let w2 = term_width_at(&buffer, w1).unwrap();
1209        assert_eq!(w1 + w2, buffer.len(), "the walk must cover the buffer");
1210        let mut cursor = &buffer[w1..];
1211        assert_eq!(cursor.read_term().unwrap(), second);
1212        assert!(cursor.is_empty());
1213    }
1214
1215    #[test]
1216    fn term_width_rejects_unknown_reserved_and_out_of_range() {
1217        // Unassigned type byte.
1218        let unknown = [7_u8, 0, 0];
1219        assert!(term_width_at(&unknown, 0).is_err());
1220        // Internal placeholder and RDF 1.2 triple type bytes are not stored yet.
1221        assert!(term_width_at(&[TYPE_PLACEHOLDER], 0).is_err());
1222        let reserved = [TYPE_TRIPLE, 0];
1223        assert!(term_width_at(&reserved, 0).is_err());
1224        // Offset at / past the end.
1225        let empty: [u8; 0] = [];
1226        assert!(term_width_at(&empty, 0).is_err());
1227        assert!(term_width_at(&[TYPE_NAMED_NODE_ID], 1).is_err());
1228    }
1229
1230    #[test]
1231    fn term_round_trip_variants() {
1232        round_trip(EncodedTerm::NamedNode {
1233            iri_id: StrHash::new("http://foo.com"),
1234        });
1235        round_trip(EncodedTerm::SmallBlankNode("bnode".try_into().unwrap()));
1236        round_trip(EncodedTerm::NumericalBlankNode {
1237            id: 0x100a_u128.to_be_bytes(),
1238        });
1239        round_trip(EncodedTerm::SmallStringLiteral(
1240            "literal".try_into().unwrap(),
1241        ));
1242        round_trip(ENCODED_TERM_TRUE);
1243        round_trip(EncodedTerm::IntegerLiteral(Integer::from(7)));
1244    }
1245
1246    #[test]
1247    fn node_encodings_are_exactly_17_bytes() {
1248        // The spog/sopg/psog/posg/tsg column families configure a fixed
1249        // 17-byte prefix extractor on the assumption that every node
1250        // encoding — named node plus all three blank-node variants — is
1251        // exactly one type byte + 16 payload bytes, so the 17-byte slice
1252        // always ends at a slot-0 term boundary. (For tsg this holds only
1253        // because the compute write funnel rejects rdf:type quads whose
1254        // object is a literal.) A future node variant with any other width
1255        // would silently misalign every prefix, so the widths are pinned
1256        // here.
1257        let nodes = [
1258            EncodedTerm::NamedNode {
1259                iri_id: StrHash::new("http://foo.com"),
1260            },
1261            EncodedTerm::NumericalBlankNode {
1262                id: 0x100a_u128.to_be_bytes(),
1263            },
1264            EncodedTerm::SmallBlankNode("bnode".try_into().unwrap()),
1265            EncodedTerm::BigBlankNode {
1266                id_id: StrHash::new("a blank node id far longer than sixteen bytes"),
1267            },
1268        ];
1269        for node in nodes {
1270            let mut buffer = Vec::new();
1271            write_term(&mut buffer, &node);
1272            assert_eq!(
1273                buffer.len(),
1274                17,
1275                "node encoding must stay exactly 17 bytes: {node:?}"
1276            );
1277            assert_eq!(
1278                TERM_WIDTH[buffer[0] as usize], 17,
1279                "TERM_WIDTH must agree with the written width for {node:?}"
1280            );
1281        }
1282    }
1283
1284    #[test]
1285    fn index_key_ordering_spog_prefixes_sort_lexicographically() {
1286        let s = NamedNode::new("http://ex/s").unwrap();
1287        let p = NamedNode::new("http://ex/p").unwrap();
1288
1289        let q1 = EncodedQuad::from(&Quad::new(
1290            s.clone(),
1291            p.clone(),
1292            Literal::from("a"),
1293            GraphName::DefaultGraph,
1294        ));
1295        let q2 = EncodedQuad::from(&Quad::new(
1296            s,
1297            p,
1298            Literal::from("b"),
1299            GraphName::DefaultGraph,
1300        ));
1301
1302        let k1 = encode_index_key(IndexPermutation::Spog, &q1);
1303        let k2 = encode_index_key(IndexPermutation::Spog, &q2);
1304        assert!(k1 < k2);
1305    }
1306}