Skip to main content

waratah_storage/encode/
encoded_term.rs

1//! Encoded RDF terms and quads.
2
3use std::hash::{Hash, Hasher};
4use std::str::FromStr;
5use std::sync::OnceLock;
6
7use oxrdf::vocab::{rdf, xsd};
8use oxrdf::{BlankNode, GraphName, Literal, NamedNode, NamedOrBlankNode, Quad, Term};
9use oxsdatatypes::*;
10
11use super::small_string::SmallString;
12use super::str_hash::StrHash;
13
14/// Ingest CRS recorded on native geo terms (one byte on the wire).
15///
16/// This is **what was written**, not what is stored: internal coordinates and
17/// blob EWKB are always CRS84 (lon/lat) f64; `crs` only names the ingest CRS
18/// so `geof:getSRID` and WKT/WKB output can transform back. `Other` marks an
19/// unrecognized CRS URI and never appears on a native term — `Other`-CRS (and
20/// untransformable) geometries stay ordinary typed literals.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22#[repr(u8)]
23pub enum CrsId {
24    /// OGC CRS84 — the only listed CRS that is **longitude, latitude** in WKT;
25    /// the internal storage CRS. Absent CRS prefix on `geo:wktLiteral` is this.
26    Crs84 = 0,
27    /// EPSG:4326 (WGS 84 geographic 2D) — **lat/lon** axis order in WKT.
28    Epsg4326 = 1,
29    /// EPSG:4283 (GDA94 geographic 2D).
30    Epsg4283 = 2,
31    /// EPSG:7844 (GDA2020).
32    Epsg7844 = 3,
33    /// EPSG:9309 (ATRF2014).
34    Epsg9309 = 4,
35    /// EPSG:4167 (NZGD2000 geographic 2D).
36    Epsg4167 = 5,
37    /// EPSG:4272 (NZGD1949, often labeled NZGD94).
38    Epsg4272 = 6,
39    /// Unrecognized CRS URI. Never written to a native geo term.
40    Other = 255,
41}
42
43impl CrsId {
44    /// Wire byte.
45    pub const fn as_u8(self) -> u8 {
46        self as u8
47    }
48
49    /// Decode a wire byte. `Other` (255) decodes but is rejected by the geo
50    /// encode plugin before any native term is minted.
51    pub const fn from_u8(byte: u8) -> Self {
52        match byte {
53            0 => Self::Crs84,
54            1 => Self::Epsg4326,
55            2 => Self::Epsg4283,
56            3 => Self::Epsg7844,
57            4 => Self::Epsg9309,
58            5 => Self::Epsg4167,
59            6 => Self::Epsg4272,
60            _ => Self::Other,
61        }
62    }
63
64    /// Canonical GeoSPARQL CRS URI emitted by WKT output
65    /// (`<http://www.opengis.net/def/crs/EPSG/0/{N}>` for EPSG members;
66    /// the OGC 1.3 CRS84 URI for [`CrsId::Crs84`]). Alias spellings are not
67    /// stored on the term, so serialize uses this default.
68    pub const fn canonical_uri(self) -> &'static str {
69        match self {
70            Self::Crs84 => "http://www.opengis.net/def/crs/OGC/0/CRS84",
71            Self::Epsg4326 => "http://www.opengis.net/def/crs/EPSG/0/4326",
72            Self::Epsg4283 => "http://www.opengis.net/def/crs/EPSG/0/4283",
73            Self::Epsg7844 => "http://www.opengis.net/def/crs/EPSG/0/7844",
74            Self::Epsg9309 => "http://www.opengis.net/def/crs/EPSG/0/9309",
75            Self::Epsg4167 => "http://www.opengis.net/def/crs/EPSG/0/4167",
76            Self::Epsg4272 => "http://www.opengis.net/def/crs/EPSG/0/4272",
77            Self::Other => "",
78        }
79    }
80}
81
82/// The `geo:wktLiteral` datatype IRI (GeoSPARQL 1.1 core).
83pub const GEO_WKT_LITERAL: &str = "http://www.opengis.net/ont/geosparql#wktLiteral";
84/// The `geo:wkbLiteral` datatype IRI (GeoSPARQL 1.1 core).
85pub const GEO_WKB_LITERAL: &str = "http://www.opengis.net/ont/geosparql#wkbLiteral";
86
87/// Geo literal datatype recorded on native geo terms (one byte on the wire).
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89#[repr(u8)]
90pub enum GeoDatatype {
91    /// `geo:wktLiteral`.
92    WktLiteral = 0,
93    /// `geo:wkbLiteral`.
94    WkbLiteral = 1,
95}
96
97impl GeoDatatype {
98    /// Wire byte.
99    pub const fn as_u8(self) -> u8 {
100        self as u8
101    }
102
103    /// Decode a wire byte (`255`-style unknowns decode to WktLiteral never —
104    /// the storage layer errors on construction instead; this maps only the
105    /// two minted values).
106    pub fn from_u8(byte: u8) -> Option<Self> {
107        match byte {
108            0 => Some(Self::WktLiteral),
109            1 => Some(Self::WkbLiteral),
110            _ => None,
111        }
112    }
113
114    /// Datatype IRI this geo literal serializes with.
115    pub const fn iri(self) -> &'static str {
116        match self {
117            Self::WktLiteral => GEO_WKT_LITERAL,
118            Self::WkbLiteral => GEO_WKB_LITERAL,
119        }
120    }
121}
122
123/// Low-bit mask for the geometry-kind byte on the wire.
124pub(crate) const GEOM_KIND_WIRE_MASK: u8 = 0x07;
125
126/// High-bit flag: the canonical EWKB retains a tolerated zero-area spike and
127/// must be reduced before spatial evaluation. The flag is part of term identity.
128pub(crate) const GEOM_REQUIRES_SPIKE_REDUCTION_WIRE_FLAG: u8 = 0x80;
129
130/// Geometry shape class recorded on [`EncodedTerm::LiteralGeometry`]
131/// (one byte on the wire; points carry their kind implicitly). The low three
132/// bits carry the kind; the high bits are reserved for geometry flags.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
134#[repr(u8)]
135pub enum GeomKind {
136    /// `POINT`.
137    Point = 0,
138    /// `LINESTRING`.
139    LineString = 1,
140    /// `POLYGON`.
141    Polygon = 2,
142    /// `MULTIPOINT`.
143    MultiPoint = 3,
144    /// `MULTILINESTRING`.
145    MultiLineString = 4,
146    /// `MULTIPOLYGON`.
147    MultiPolygon = 5,
148    /// `GEOMETRYCOLLECTION`.
149    GeometryCollection = 6,
150    /// Anything else (open GeoSPARQL geometry classes).
151    Unknown = 7,
152}
153
154impl GeomKind {
155    /// Wire byte.
156    pub const fn as_u8(self) -> u8 {
157        self as u8
158    }
159
160    /// Decode a wire byte; unknown values decode to [`GeomKind::Unknown`].
161    pub const fn from_u8(byte: u8) -> Self {
162        match byte {
163            0 => Self::Point,
164            1 => Self::LineString,
165            2 => Self::Polygon,
166            3 => Self::MultiPoint,
167            4 => Self::MultiLineString,
168            5 => Self::MultiPolygon,
169            6 => Self::GeometryCollection,
170            _ => Self::Unknown,
171        }
172    }
173}
174
175/// Encoded RDF term for storage keys and wire transfer.
176#[derive(Debug, Clone)]
177pub enum EncodedTerm {
178    /// Default graph (zero bytes on the wire).
179    DefaultGraph,
180    /// Query-local intern sentinel only (TermDict map index `0`; reverse
181    /// lookup returns SPARQL unbound). Never written to hexastore keys.
182    /// Wire type byte 48 ([`TYPE_PLACEHOLDER`]), zero payload.
183    Placeholder,
184    /// Named node (always hash-referenced).
185    NamedNode {
186        /// IRI hash.
187        iri_id: StrHash,
188    },
189    /// Blank node with a numeric unique id.
190    NumericalBlankNode {
191        /// `u128` big-endian id bytes.
192        id: [u8; 16],
193    },
194    /// Blank node with a short inline id.
195    SmallBlankNode(SmallString),
196    /// Blank node with a long hash-referenced id.
197    BigBlankNode {
198        /// Blank-node id hash.
199        id_id: StrHash,
200    },
201    /// Short plain literal.
202    SmallStringLiteral(SmallString),
203    /// Long plain literal.
204    BigStringLiteral {
205        /// Lexical form hash.
206        value_id: StrHash,
207    },
208    /// Lang string: small value, small language.
209    SmallSmallLangStringLiteral {
210        /// Lexical form.
211        value: SmallString,
212        /// Language tag.
213        language: SmallString,
214    },
215    /// Lang string: small value, big language.
216    SmallBigLangStringLiteral {
217        /// Lexical form.
218        value: SmallString,
219        /// Language tag hash.
220        language_id: StrHash,
221    },
222    /// Lang string: big value, small language.
223    BigSmallLangStringLiteral {
224        /// Lexical form hash.
225        value_id: StrHash,
226        /// Language tag.
227        language: SmallString,
228    },
229    /// Lang string: big value, big language.
230    BigBigLangStringLiteral {
231        /// Lexical form hash.
232        value_id: StrHash,
233        /// Language tag hash.
234        language_id: StrHash,
235    },
236    /// Typed literal: small value.
237    SmallTypedLiteral {
238        /// Lexical form.
239        value: SmallString,
240        /// Datatype IRI hash.
241        datatype_id: StrHash,
242    },
243    /// Typed literal: big value.
244    BigTypedLiteral {
245        /// Lexical form hash.
246        value_id: StrHash,
247        /// Datatype IRI hash.
248        datatype_id: StrHash,
249    },
250    /// `xsd:boolean`.
251    BooleanLiteral(Boolean),
252    /// `xsd:float`.
253    FloatLiteral(Float),
254    /// `xsd:double`.
255    DoubleLiteral(Double),
256    /// `xsd:integer` family.
257    IntegerLiteral(Integer),
258    /// `xsd:decimal`.
259    DecimalLiteral(Decimal),
260    /// `xsd:dateTime`.
261    DateTimeLiteral(DateTime),
262    /// `xsd:time`.
263    TimeLiteral(Time),
264    /// `xsd:date`.
265    DateLiteral(Date),
266    /// `xsd:gYearMonth`.
267    GYearMonthLiteral(GYearMonth),
268    /// `xsd:gYear`.
269    GYearLiteral(GYear),
270    /// `xsd:gMonthDay`.
271    GMonthDayLiteral(GMonthDay),
272    /// `xsd:gDay`.
273    GDayLiteral(GDay),
274    /// `xsd:gMonth`.
275    GMonthLiteral(GMonth),
276    /// `xsd:duration`.
277    DurationLiteral(Duration),
278    /// `xsd:yearMonthDuration`.
279    YearMonthDurationLiteral(YearMonthDuration),
280    /// `xsd:dayTimeDuration`.
281    DayTimeDurationLiteral(DayTimeDuration),
282    /// Native 2D geo point: CRS84 lon/lat inline (f64 × 2), ingest `CrsId`
283    /// recorded for output. 19 bytes on the wire. Minted only by the geo
284    /// encode plugin after CRS transform + [`geo::Validation`]-style checks —
285    /// plain `From<&Literal>` never parses GeoSPARQL.
286    LiteralPoint {
287        /// Longitude in CRS84 (degrees).
288        x: f64,
289        /// Latitude in CRS84 (degrees).
290        y: f64,
291        /// Ingest CRS (what `geof:getSRID` and WKT output name).
292        crs: CrsId,
293        /// `geo:wktLiteral` or `geo:wkbLiteral`.
294        geo_datatype: GeoDatatype,
295    },
296    /// Native non-point geometry: `geom_kind` / `crs` / `geo_datatype` inline,
297    /// canonical CRS84 EWKB in the blob store (`blob_id` = SipHash of those
298    /// bytes, same 16-byte layout as `StrHash`). 20 bytes on the wire. The
299    /// spike-reduction flag occupies an otherwise unused high bit of the
300    /// geometry-kind byte, so it adds no width. No inline bbox — the term is
301    /// copied into every hexastore permutation and would blow the 33-byte limit
302    /// once CRS/kind are present.
303    LiteralGeometry {
304        /// Shape class (Point… GeometryCollection; Unknown for open kinds).
305        geom_kind: GeomKind,
306        /// Ingest CRS.
307        crs: CrsId,
308        /// `geo:wktLiteral` or `geo:wkbLiteral`.
309        geo_datatype: GeoDatatype,
310        /// Content-addressed blob id (SipHash of the CRS84 EWKB bytes).
311        blob_id: StrHash,
312        /// The blob retains an exactly retraced zero-area spike. Spatial
313        /// evaluation must derive the reduced geometry before covering or
314        /// Relate; lexical materialization still renders the original blob.
315        requires_spike_reduction: bool,
316    },
317    /// Generic large **binary** typed literal (not UTF-8): datatype IRI hash +
318    /// content-addressed blob id. 33 bytes on the wire. v1 write paths mint
319    /// blobs only for geo EWKB (which uses [`EncodedTerm::LiteralGeometry`] in
320    /// the hexastore); this variant exists so the blob store is not geo-only.
321    BlobLiteral {
322        /// Datatype IRI hash (registered like any datatype IRI).
323        datatype_id: StrHash,
324        /// Content-addressed blob id.
325        blob_id: StrHash,
326    },
327}
328
329impl EncodedTerm {
330    /// Whether this native geometry retains a tolerated zero-area spike that
331    /// must be reduced before spatial evaluation.
332    pub const fn requires_spike_reduction(&self) -> bool {
333        matches!(
334            self,
335            Self::LiteralGeometry {
336                requires_spike_reduction: true,
337                ..
338            }
339        )
340    }
341}
342
343/// Term identity is BIT identity, arm-for-arm with [`Hash`]: the engine's
344/// hash-keyed structures (TermDict interning, DISTINCT seen-sets, join
345/// keys, walker membership sets) find buckets by `Hash` and confirm by
346/// this `PartialEq`, and storage keys plus the wire carry exact bits.
347/// The original derive was IEEE on the float payloads and broke the
348/// `Eq`/`Hash` contract in BOTH directions — `+0.0 == -0.0` compared
349/// true where the bit hashes differ, and `NaN != NaN` compared false
350/// where the bit hashes agree — so one NaN literal double-interned into
351/// two TermIds and counted twice in `COUNT(DISTINCT)`.
352///
353/// Value semantics never lived here and still do not: `equals` /
354/// `value_equals` compare numeric payloads (op:numeric-equal), so
355/// `FILTER =` keeps `+0.0 = -0.0` → true and `NaN = NaN` → false. RDF
356/// term identity is lexical, and bit identity tracks it through the
357/// canonical value encoding: the same lexical parses to the same bits →
358/// one term (`sameTerm("NaN", "NaN")` is true), distinct lexicals
359/// (`+0.0` / `-0.0`) stay distinct terms (`sameTerm` is false). See
360/// `docs/modules/developer/pages/sparql-deviations.adoc`.
361impl PartialEq for EncodedTerm {
362    #[inline]
363    fn eq(&self, other: &Self) -> bool {
364        // Same variant. Each arm compares exactly the bytes the matching
365        // Hash arm hashes: payload `==` where Hash hashes the field
366        // directly, `to_be_bytes()` where Hash hashes bytes. The float
367        // arms and the point coordinates are why this impl is manual —
368        // bit equality where the derived IEEE compare disagreed with the
369        // hash. Exhaustive matching keeps the Eq/Hash pairing a compile
370        // error to drift: a new variant must be added to both.
371        match (self, other) {
372            (Self::FloatLiteral(a), Self::FloatLiteral(b)) => a.to_be_bytes() == b.to_be_bytes(),
373            (Self::DoubleLiteral(a), Self::DoubleLiteral(b)) => a.to_be_bytes() == b.to_be_bytes(),
374            (
375                Self::LiteralPoint {
376                    x: x1,
377                    y: y1,
378                    crs: c1,
379                    geo_datatype: g1,
380                },
381                Self::LiteralPoint {
382                    x: x2,
383                    y: y2,
384                    crs: c2,
385                    geo_datatype: g2,
386                },
387            ) => {
388                // f64 coordinates: bit equality. Validated ingest never
389                // mints a NaN coordinate, but ±0.0 is valid WKT and the
390                // derived IEEE compare called the two zeros equal while
391                // the Hash called them distinct. crs and geo_datatype
392                // are part of the identity too — the same coords under
393                // a different CRS is a different term (different axis
394                // order, different lexical), and the Hash hashes both.
395                x1.to_be_bytes() == x2.to_be_bytes()
396                    && y1.to_be_bytes() == y2.to_be_bytes()
397                    && c1 == c2
398                    && g1 == g2
399            }
400            // Structural arms: payload `==` (ids, byte arrays, tags — no
401            // IEEE fields), the same bytes the matching Hash arm hashes.
402            (Self::DefaultGraph, Self::DefaultGraph) => true,
403            (Self::Placeholder, Self::Placeholder) => true,
404            (Self::NamedNode { iri_id: a }, Self::NamedNode { iri_id: b }) => a == b,
405            (Self::NumericalBlankNode { id: a }, Self::NumericalBlankNode { id: b }) => a == b,
406            (Self::SmallBlankNode(a), Self::SmallBlankNode(b)) => a == b,
407            (Self::BigBlankNode { id_id: a }, Self::BigBlankNode { id_id: b }) => a == b,
408            (Self::SmallStringLiteral(a), Self::SmallStringLiteral(b)) => a == b,
409            (Self::BigStringLiteral { value_id: a }, Self::BigStringLiteral { value_id: b }) => {
410                a == b
411            }
412            (
413                Self::SmallSmallLangStringLiteral {
414                    value: av,
415                    language: al,
416                },
417                Self::SmallSmallLangStringLiteral {
418                    value: bv,
419                    language: bl,
420                },
421            ) => av == bv && al == bl,
422            (
423                Self::SmallBigLangStringLiteral {
424                    value: av,
425                    language_id: al,
426                },
427                Self::SmallBigLangStringLiteral {
428                    value: bv,
429                    language_id: bl,
430                },
431            ) => av == bv && al == bl,
432            (
433                Self::BigSmallLangStringLiteral {
434                    value_id: av,
435                    language: al,
436                },
437                Self::BigSmallLangStringLiteral {
438                    value_id: bv,
439                    language: bl,
440                },
441            ) => av == bv && al == bl,
442            (
443                Self::BigBigLangStringLiteral {
444                    value_id: av,
445                    language_id: al,
446                },
447                Self::BigBigLangStringLiteral {
448                    value_id: bv,
449                    language_id: bl,
450                },
451            ) => av == bv && al == bl,
452            (
453                Self::SmallTypedLiteral {
454                    value: av,
455                    datatype_id: ad,
456                },
457                Self::SmallTypedLiteral {
458                    value: bv,
459                    datatype_id: bd,
460                },
461            ) => av == bv && ad == bd,
462            (
463                Self::BigTypedLiteral {
464                    value_id: av,
465                    datatype_id: ad,
466                },
467                Self::BigTypedLiteral {
468                    value_id: bv,
469                    datatype_id: bd,
470                },
471            ) => av == bv && ad == bd,
472            (Self::BooleanLiteral(a), Self::BooleanLiteral(b)) => a == b,
473            // Integer/Decimal and the duration family: single injective
474            // fields, so byte equality — what the matching Hash arm
475            // hashes — coincides with field equality.
476            (Self::IntegerLiteral(a), Self::IntegerLiteral(b)) => {
477                a.to_be_bytes() == b.to_be_bytes()
478            }
479            (Self::DecimalLiteral(a), Self::DecimalLiteral(b)) => {
480                a.to_be_bytes() == b.to_be_bytes()
481            }
482            // The timestamp family is the item-31-review exception: the
483            // wire bytes are NOT the identity relation.
484            // `Timestamp::to_be_bytes` writes the timezone offset with a
485            // [255, 255] sentinel for "no timezone", byte-identical to a
486            // real -00:01 offset (i16 -1), and the payload's own `==` was
487            // offset-agnostic when both sides carry an offset. Eq is
488            // `is_identical_with`: timeline value + timezone presence +
489            // offset value — identical lexicals stay one term, and the
490            // byte-twin pair (unzoned vs -00:01) and the
491            // same-instant-different-offset pair stay distinct. The
492            // matching Hash arms hash a timezone-presence discriminator
493            // alongside the bytes so this relation and the hash never
494            // disagree.
495            (Self::DateTimeLiteral(a), Self::DateTimeLiteral(b)) => a.is_identical_with(*b),
496            (Self::TimeLiteral(a), Self::TimeLiteral(b)) => a.is_identical_with(*b),
497            (Self::DateLiteral(a), Self::DateLiteral(b)) => a.is_identical_with(*b),
498            (Self::GYearMonthLiteral(a), Self::GYearMonthLiteral(b)) => a.is_identical_with(*b),
499            (Self::GYearLiteral(a), Self::GYearLiteral(b)) => a.is_identical_with(*b),
500            (Self::GMonthDayLiteral(a), Self::GMonthDayLiteral(b)) => a.is_identical_with(*b),
501            (Self::GDayLiteral(a), Self::GDayLiteral(b)) => a.is_identical_with(*b),
502            (Self::GMonthLiteral(a), Self::GMonthLiteral(b)) => a.is_identical_with(*b),
503            (Self::DurationLiteral(a), Self::DurationLiteral(b)) => {
504                a.to_be_bytes() == b.to_be_bytes()
505            }
506            (Self::YearMonthDurationLiteral(a), Self::YearMonthDurationLiteral(b)) => {
507                a.to_be_bytes() == b.to_be_bytes()
508            }
509            (Self::DayTimeDurationLiteral(a), Self::DayTimeDurationLiteral(b)) => {
510                a.to_be_bytes() == b.to_be_bytes()
511            }
512            (
513                Self::LiteralGeometry {
514                    geom_kind: ak,
515                    crs: ac,
516                    geo_datatype: ad,
517                    blob_id: ab,
518                    requires_spike_reduction: ar,
519                },
520                Self::LiteralGeometry {
521                    geom_kind: bk,
522                    crs: bc,
523                    geo_datatype: bd,
524                    blob_id: bb,
525                    requires_spike_reduction: br,
526                },
527            ) => ak == bk && ac == bc && ad == bd && ab == bb && ar == br,
528            (
529                Self::BlobLiteral {
530                    datatype_id: ad,
531                    blob_id: ab,
532                },
533                Self::BlobLiteral {
534                    datatype_id: bd,
535                    blob_id: bb,
536                },
537            ) => ad == bd && ab == bb,
538            // Cross-variant terms never compare equal (the Hash mixes the
539            // discriminant in).
540            _ => false,
541        }
542    }
543}
544
545impl Eq for EncodedTerm {}
546
547impl Hash for EncodedTerm {
548    fn hash<H: Hasher>(&self, state: &mut H) {
549        std::mem::discriminant(self).hash(state);
550        match self {
551            Self::DefaultGraph => {}
552            Self::Placeholder => {}
553            Self::NamedNode { iri_id } => iri_id.hash(state),
554            Self::NumericalBlankNode { id } => id.hash(state),
555            Self::SmallBlankNode(value) => value.hash(state),
556            Self::BigBlankNode { id_id } => id_id.hash(state),
557            Self::SmallStringLiteral(value) => value.hash(state),
558            Self::BigStringLiteral { value_id } => value_id.hash(state),
559            Self::SmallSmallLangStringLiteral { value, language } => {
560                value.hash(state);
561                language.hash(state);
562            }
563            Self::SmallBigLangStringLiteral { value, language_id } => {
564                value.hash(state);
565                language_id.hash(state);
566            }
567            Self::BigSmallLangStringLiteral { value_id, language } => {
568                value_id.hash(state);
569                language.hash(state);
570            }
571            Self::BigBigLangStringLiteral {
572                value_id,
573                language_id,
574            } => {
575                value_id.hash(state);
576                language_id.hash(state);
577            }
578            Self::SmallTypedLiteral { value, datatype_id } => {
579                value.hash(state);
580                datatype_id.hash(state);
581            }
582            Self::BigTypedLiteral {
583                value_id,
584                datatype_id,
585            } => {
586                value_id.hash(state);
587                datatype_id.hash(state);
588            }
589            Self::BooleanLiteral(value) => bool::from(*value).hash(state),
590            Self::FloatLiteral(value) => value.to_be_bytes().hash(state),
591            Self::DoubleLiteral(value) => value.to_be_bytes().hash(state),
592            Self::IntegerLiteral(value) => value.to_be_bytes().hash(state),
593            Self::DecimalLiteral(value) => value.to_be_bytes().hash(state),
594            // The timestamp family: the bytes alone collide "no timezone"
595            // ([255, 255] sentinel) with a real -00:01 offset (i16 -1),
596            // and Eq (is_identical_with) distinguishes them — hash a
597            // timezone-presence discriminator alongside so identical
598            // terms hash identically and the byte-twins land apart.
599            Self::DateTimeLiteral(value) => {
600                value.to_be_bytes().hash(state);
601                value.timezone_offset().is_some().hash(state);
602            }
603            Self::TimeLiteral(value) => {
604                value.to_be_bytes().hash(state);
605                value.timezone_offset().is_some().hash(state);
606            }
607            Self::DateLiteral(value) => {
608                value.to_be_bytes().hash(state);
609                value.timezone_offset().is_some().hash(state);
610            }
611            Self::GYearMonthLiteral(value) => {
612                value.to_be_bytes().hash(state);
613                value.timezone_offset().is_some().hash(state);
614            }
615            Self::GYearLiteral(value) => {
616                value.to_be_bytes().hash(state);
617                value.timezone_offset().is_some().hash(state);
618            }
619            Self::GMonthDayLiteral(value) => {
620                value.to_be_bytes().hash(state);
621                value.timezone_offset().is_some().hash(state);
622            }
623            Self::GDayLiteral(value) => {
624                value.to_be_bytes().hash(state);
625                value.timezone_offset().is_some().hash(state);
626            }
627            Self::GMonthLiteral(value) => {
628                value.to_be_bytes().hash(state);
629                value.timezone_offset().is_some().hash(state);
630            }
631            Self::DurationLiteral(value) => value.to_be_bytes().hash(state),
632            Self::YearMonthDurationLiteral(value) => value.to_be_bytes().hash(state),
633            Self::DayTimeDurationLiteral(value) => value.to_be_bytes().hash(state),
634            // Geo coordinates hash their bit patterns; the PartialEq above
635            // compares them bit-wise too (the original derive compared
636            // them with IEEE equality, disagreeing with this hash for
637            // ±0.0). Validated ingest never mints a NaN coordinate, but
638            // ±0.0 is valid WKT and the two zeros are distinct terms.
639            Self::LiteralPoint {
640                x,
641                y,
642                crs,
643                geo_datatype,
644            } => {
645                x.to_be_bytes().hash(state);
646                y.to_be_bytes().hash(state);
647                crs.hash(state);
648                geo_datatype.hash(state);
649            }
650            Self::LiteralGeometry {
651                geom_kind,
652                crs,
653                geo_datatype,
654                blob_id,
655                requires_spike_reduction,
656            } => {
657                geom_kind.hash(state);
658                crs.hash(state);
659                geo_datatype.hash(state);
660                blob_id.hash(state);
661                requires_spike_reduction.hash(state);
662            }
663            Self::BlobLiteral {
664                datatype_id,
665                blob_id,
666            } => {
667                datatype_id.hash(state);
668                blob_id.hash(state);
669            }
670        }
671    }
672}
673
674/// SipHash-2-4 of `http://www.w3.org/1999/02/22-rdf-syntax-ns#type` (`k0 = k1 = 0`).
675pub const RDF_TYPE_IRI_ID: StrHash = StrHash::from_be_bytes([
676    61, 135, 117, 228, 96, 167, 140, 224, 233, 138, 108, 126, 186, 155, 30, 248,
677]);
678
679/// SipHash-2-4 of SPARQL numeric XSD datatype IRIs (`k0 = k1 = 0`).
680///
681/// Used by `isNUMERIC` on `SmallTypedLiteral` / `BigTypedLiteral` (ill-formed
682/// lexical forms still have a numeric datatype). Well-formed values of these
683/// types encode as native `IntegerLiteral` / `DecimalLiteral` / `FloatLiteral`
684/// / `DoubleLiteral` instead.
685pub const XSD_FLOAT_IRI_ID: StrHash = StrHash::from_be_bytes([
686    52, 189, 74, 142, 222, 69, 100, 195, 100, 69, 183, 110, 132, 250, 117, 2,
687]);
688/// `xsd:double`.
689pub const XSD_DOUBLE_IRI_ID: StrHash = StrHash::from_be_bytes([
690    54, 20, 168, 137, 218, 47, 12, 118, 22, 217, 109, 1, 178, 255, 26, 151,
691]);
692/// `xsd:decimal`.
693pub const XSD_DECIMAL_IRI_ID: StrHash = StrHash::from_be_bytes([
694    181, 11, 255, 237, 253, 8, 69, 40, 255, 137, 33, 115, 220, 13, 31, 173,
695]);
696/// `xsd:integer`.
697pub const XSD_INTEGER_IRI_ID: StrHash = StrHash::from_be_bytes([
698    226, 177, 156, 121, 245, 240, 77, 188, 220, 127, 82, 244, 247, 134, 157, 160,
699]);
700/// `xsd:byte`.
701pub const XSD_BYTE_IRI_ID: StrHash = StrHash::from_be_bytes([
702    145, 174, 75, 5, 72, 217, 173, 50, 161, 191, 212, 57, 1, 144, 107, 64,
703]);
704/// `xsd:short`.
705pub const XSD_SHORT_IRI_ID: StrHash = StrHash::from_be_bytes([
706    194, 122, 162, 123, 175, 34, 235, 94, 115, 8, 202, 31, 246, 93, 174, 77,
707]);
708/// `xsd:int`.
709pub const XSD_INT_IRI_ID: StrHash = StrHash::from_be_bytes([
710    164, 33, 11, 186, 103, 48, 20, 240, 61, 170, 138, 172, 43, 94, 126, 77,
711]);
712/// `xsd:long`.
713pub const XSD_LONG_IRI_ID: StrHash = StrHash::from_be_bytes([
714    206, 83, 99, 125, 169, 206, 239, 177, 102, 120, 82, 47, 226, 43, 112, 3,
715]);
716/// `xsd:unsignedByte`.
717pub const XSD_UNSIGNED_BYTE_IRI_ID: StrHash = StrHash::from_be_bytes([
718    245, 17, 193, 120, 19, 249, 138, 34, 231, 79, 235, 201, 53, 226, 23, 78,
719]);
720/// `xsd:unsignedShort`.
721pub const XSD_UNSIGNED_SHORT_IRI_ID: StrHash = StrHash::from_be_bytes([
722    122, 180, 230, 59, 232, 72, 60, 174, 149, 235, 46, 4, 131, 51, 7, 214,
723]);
724/// `xsd:unsignedInt`.
725pub const XSD_UNSIGNED_INT_IRI_ID: StrHash = StrHash::from_be_bytes([
726    43, 70, 88, 139, 58, 127, 44, 213, 176, 36, 34, 100, 65, 121, 23, 96,
727]);
728/// `xsd:unsignedLong`.
729pub const XSD_UNSIGNED_LONG_IRI_ID: StrHash = StrHash::from_be_bytes([
730    9, 84, 87, 80, 27, 65, 219, 154, 234, 138, 14, 248, 75, 231, 32, 57,
731]);
732/// `xsd:positiveInteger`.
733pub const XSD_POSITIVE_INTEGER_IRI_ID: StrHash = StrHash::from_be_bytes([
734    239, 124, 51, 137, 232, 8, 153, 167, 53, 182, 47, 231, 33, 113, 140, 204,
735]);
736/// `xsd:negativeInteger`.
737pub const XSD_NEGATIVE_INTEGER_IRI_ID: StrHash = StrHash::from_be_bytes([
738    239, 213, 6, 175, 108, 59, 205, 198, 140, 115, 27, 75, 52, 23, 27, 84,
739]);
740/// `xsd:nonPositiveInteger`.
741pub const XSD_NON_POSITIVE_INTEGER_IRI_ID: StrHash = StrHash::from_be_bytes([
742    101, 153, 188, 139, 172, 144, 204, 77, 242, 114, 228, 85, 102, 222, 13, 28,
743]);
744/// `xsd:nonNegativeInteger`.
745pub const XSD_NON_NEGATIVE_INTEGER_IRI_ID: StrHash = StrHash::from_be_bytes([
746    187, 225, 164, 236, 29, 141, 77, 189, 70, 51, 154, 198, 69, 61, 148, 212,
747]);
748/// `xsd:string`.
749pub const XSD_STRING_IRI_ID: StrHash = StrHash::from_be_bytes([
750    231, 35, 0, 151, 14, 233, 191, 119, 242, 223, 123, 219, 48, 14, 61, 132,
751]);
752/// `xsd:boolean`.
753pub const XSD_BOOLEAN_IRI_ID: StrHash = StrHash::from_be_bytes([
754    250, 250, 200, 179, 86, 190, 129, 149, 79, 100, 231, 7, 86, 229, 158, 50,
755]);
756/// `xsd:dateTime`.
757pub const XSD_DATE_TIME_IRI_ID: StrHash = StrHash::from_be_bytes([
758    13, 116, 150, 231, 121, 163, 33, 173, 229, 30, 146, 218, 26, 90, 166, 203,
759]);
760/// `xsd:time`.
761pub const XSD_TIME_IRI_ID: StrHash = StrHash::from_be_bytes([
762    199, 72, 123, 227, 243, 210, 125, 25, 38, 178, 122, 191, 0, 90, 156, 210,
763]);
764/// `xsd:date`.
765pub const XSD_DATE_IRI_ID: StrHash = StrHash::from_be_bytes([
766    8, 124, 67, 81, 222, 164, 185, 143, 89, 162, 47, 123, 99, 109, 64, 49,
767]);
768/// `xsd:gYearMonth`.
769pub const XSD_G_YEAR_MONTH_IRI_ID: StrHash = StrHash::from_be_bytes([
770    40, 255, 130, 145, 60, 167, 199, 97, 195, 207, 234, 155, 9, 252, 92, 86,
771]);
772/// `xsd:gYear`.
773pub const XSD_G_YEAR_IRI_ID: StrHash = StrHash::from_be_bytes([
774    150, 166, 188, 247, 150, 207, 181, 6, 132, 59, 74, 180, 244, 135, 250, 159,
775]);
776/// `xsd:gMonthDay`.
777pub const XSD_G_MONTH_DAY_IRI_ID: StrHash = StrHash::from_be_bytes([
778    82, 121, 170, 185, 204, 154, 238, 189, 112, 205, 188, 30, 163, 200, 245, 59,
779]);
780/// `xsd:gDay`.
781pub const XSD_G_DAY_IRI_ID: StrHash = StrHash::from_be_bytes([
782    24, 70, 103, 62, 146, 149, 197, 46, 55, 114, 89, 128, 63, 58, 41, 9,
783]);
784/// `xsd:gMonth`.
785pub const XSD_G_MONTH_IRI_ID: StrHash = StrHash::from_be_bytes([
786    166, 88, 26, 94, 143, 111, 161, 49, 139, 105, 128, 81, 127, 80, 77, 147,
787]);
788/// `xsd:duration`.
789pub const XSD_DURATION_IRI_ID: StrHash = StrHash::from_be_bytes([
790    34, 106, 240, 142, 165, 183, 230, 176, 140, 238, 214, 3, 12, 114, 18, 40,
791]);
792/// `xsd:yearMonthDuration`.
793pub const XSD_YEAR_MONTH_DURATION_IRI_ID: StrHash = StrHash::from_be_bytes([
794    198, 218, 205, 231, 175, 192, 189, 47, 110, 23, 141, 114, 41, 148, 129, 145,
795]);
796/// `xsd:dayTimeDuration`.
797pub const XSD_DAY_TIME_DURATION_IRI_ID: StrHash = StrHash::from_be_bytes([
798    200, 214, 207, 223, 69, 225, 44, 16, 189, 113, 26, 118, 170, 228, 59, 198,
799]);
800/// `rdf:langString`.
801pub const RDF_LANG_STRING_IRI_ID: StrHash = StrHash::from_be_bytes([
802    143, 171, 107, 193, 80, 29, 109, 17, 78, 93, 78, 1, 22, 246, 122, 73,
803]);
804
805const NUMERIC_DATATYPE_IRI_IDS: [StrHash; 16] = [
806    XSD_FLOAT_IRI_ID,
807    XSD_DOUBLE_IRI_ID,
808    XSD_DECIMAL_IRI_ID,
809    XSD_INTEGER_IRI_ID,
810    XSD_BYTE_IRI_ID,
811    XSD_SHORT_IRI_ID,
812    XSD_INT_IRI_ID,
813    XSD_LONG_IRI_ID,
814    XSD_UNSIGNED_BYTE_IRI_ID,
815    XSD_UNSIGNED_SHORT_IRI_ID,
816    XSD_UNSIGNED_INT_IRI_ID,
817    XSD_UNSIGNED_LONG_IRI_ID,
818    XSD_POSITIVE_INTEGER_IRI_ID,
819    XSD_NEGATIVE_INTEGER_IRI_ID,
820    XSD_NON_POSITIVE_INTEGER_IRI_ID,
821    XSD_NON_NEGATIVE_INTEGER_IRI_ID,
822];
823
824/// SPARQL `isNUMERIC`: native numeric variants, or a typed literal whose
825/// datatype IRI hash is one of the XSD numeric types (including ill-formed
826/// lexicals such as `"foo"^^xsd:integer`).
827pub fn is_numeric_encoded(term: &EncodedTerm) -> bool {
828    match term {
829        EncodedTerm::IntegerLiteral(_)
830        | EncodedTerm::DecimalLiteral(_)
831        | EncodedTerm::FloatLiteral(_)
832        | EncodedTerm::DoubleLiteral(_) => true,
833        EncodedTerm::SmallTypedLiteral { datatype_id, .. }
834        | EncodedTerm::BigTypedLiteral { datatype_id, .. } => {
835            NUMERIC_DATATYPE_IRI_IDS.contains(datatype_id)
836        }
837        _ => false,
838    }
839}
840
841/// SipHash-2-4 of the empty string (`k0 = k1 = 0`).
842pub const EMPTY_STR_HASH: StrHash = StrHash::from_be_bytes([
843    244, 242, 206, 212, 71, 171, 2, 66, 125, 224, 163, 128, 71, 215, 73, 80,
844]);
845
846/// Encoded `rdf:type` named node — equality checks and TSG decode injection.
847pub const RDF_TYPE: EncodedTerm = EncodedTerm::NamedNode {
848    iri_id: RDF_TYPE_IRI_ID,
849};
850/// Encoded `rdf:langString` named node — SPARQL 1.1 `DATATYPE` of a language-tagged string.
851pub const RDF_LANG_STRING: EncodedTerm = EncodedTerm::NamedNode {
852    iri_id: RDF_LANG_STRING_IRI_ID,
853};
854/// Encoded `xsd:string`.
855pub const XSD_STRING: EncodedTerm = EncodedTerm::NamedNode {
856    iri_id: XSD_STRING_IRI_ID,
857};
858/// Encoded `xsd:boolean`.
859pub const XSD_BOOLEAN: EncodedTerm = EncodedTerm::NamedNode {
860    iri_id: XSD_BOOLEAN_IRI_ID,
861};
862/// Encoded `xsd:float`.
863pub const XSD_FLOAT: EncodedTerm = EncodedTerm::NamedNode {
864    iri_id: XSD_FLOAT_IRI_ID,
865};
866/// Encoded `xsd:double`.
867pub const XSD_DOUBLE: EncodedTerm = EncodedTerm::NamedNode {
868    iri_id: XSD_DOUBLE_IRI_ID,
869};
870/// Encoded `xsd:decimal`.
871pub const XSD_DECIMAL: EncodedTerm = EncodedTerm::NamedNode {
872    iri_id: XSD_DECIMAL_IRI_ID,
873};
874/// Encoded `xsd:integer`.
875pub const XSD_INTEGER: EncodedTerm = EncodedTerm::NamedNode {
876    iri_id: XSD_INTEGER_IRI_ID,
877};
878/// Encoded `xsd:dateTime`.
879pub const XSD_DATE_TIME: EncodedTerm = EncodedTerm::NamedNode {
880    iri_id: XSD_DATE_TIME_IRI_ID,
881};
882/// Encoded `xsd:time`.
883pub const XSD_TIME: EncodedTerm = EncodedTerm::NamedNode {
884    iri_id: XSD_TIME_IRI_ID,
885};
886/// Encoded `xsd:date`.
887pub const XSD_DATE: EncodedTerm = EncodedTerm::NamedNode {
888    iri_id: XSD_DATE_IRI_ID,
889};
890/// Encoded `xsd:gYearMonth`.
891pub const XSD_G_YEAR_MONTH: EncodedTerm = EncodedTerm::NamedNode {
892    iri_id: XSD_G_YEAR_MONTH_IRI_ID,
893};
894/// Encoded `xsd:gYear`.
895pub const XSD_G_YEAR: EncodedTerm = EncodedTerm::NamedNode {
896    iri_id: XSD_G_YEAR_IRI_ID,
897};
898/// Encoded `xsd:gMonthDay`.
899pub const XSD_G_MONTH_DAY: EncodedTerm = EncodedTerm::NamedNode {
900    iri_id: XSD_G_MONTH_DAY_IRI_ID,
901};
902/// Encoded `xsd:gDay`.
903pub const XSD_G_DAY: EncodedTerm = EncodedTerm::NamedNode {
904    iri_id: XSD_G_DAY_IRI_ID,
905};
906/// Encoded `xsd:gMonth`.
907pub const XSD_G_MONTH: EncodedTerm = EncodedTerm::NamedNode {
908    iri_id: XSD_G_MONTH_IRI_ID,
909};
910/// Encoded `xsd:duration`.
911pub const XSD_DURATION: EncodedTerm = EncodedTerm::NamedNode {
912    iri_id: XSD_DURATION_IRI_ID,
913};
914/// Encoded `xsd:yearMonthDuration`.
915pub const XSD_YEAR_MONTH_DURATION: EncodedTerm = EncodedTerm::NamedNode {
916    iri_id: XSD_YEAR_MONTH_DURATION_IRI_ID,
917};
918/// Encoded `xsd:dayTimeDuration`.
919pub const XSD_DAY_TIME_DURATION: EncodedTerm = EncodedTerm::NamedNode {
920    iri_id: XSD_DAY_TIME_DURATION_IRI_ID,
921};
922
923/// Const [`EncodedTerm::BooleanLiteral`] when `Boolean::from` is not `const`.
924const fn encoded_term_boolean(value: bool) -> EncodedTerm {
925    // SAFETY: `Boolean` is `#[repr(transparent)]` over `bool` (oxsdatatypes).
926    EncodedTerm::BooleanLiteral(unsafe { std::mem::transmute::<bool, Boolean>(value) })
927}
928
929/// Canonical encoded XSD `true` (wire type 28).
930pub const ENCODED_TERM_TRUE: EncodedTerm = encoded_term_boolean(true);
931/// Canonical encoded XSD `false` (wire type 29).
932pub const ENCODED_TERM_FALSE: EncodedTerm = encoded_term_boolean(false);
933
934/// IRIs that decode without the string registry: the XSD datatype family,
935/// well-known RDF/RDFS terms, and common OWL/SKOS vocabulary.
936///
937/// SipHash digests are computed from these strings once per process (lazily,
938/// sorted) — the table is self-consistent by construction, and the digest of
939/// each entry is exactly what named-node encoding produces, so registered
940/// occurrences of the same IRI share the hash. Entries here bypass the
941/// registry in [`well_known_iri`]: hashes in this table never reach
942/// `ResolveStrings`, and terms carrying them decode even when the dataset
943/// never ingested the IRI (e.g. an `xsd:integer` datatype minted by
944/// `BIND(DATATYPE(?x))` over data with native literals).
945const WELL_KNOWN_IRI_STRINGS: &[&str] = &[
946    // RDF 1.1 core: types, containers, reification, list structure
947    "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
948    "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString",
949    "http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML",
950    "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral",
951    "http://www.w3.org/1999/02/22-rdf-syntax-ns#Property",
952    "http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement",
953    "http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag",
954    "http://www.w3.org/1999/02/22-rdf-syntax-ns#Seq",
955    "http://www.w3.org/1999/02/22-rdf-syntax-ns#Alt",
956    "http://www.w3.org/1999/02/22-rdf-syntax-ns#List",
957    "http://www.w3.org/1999/02/22-rdf-syntax-ns#first",
958    "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest",
959    "http://www.w3.org/1999/02/22-rdf-syntax-ns#value",
960    "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject",
961    "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate",
962    "http://www.w3.org/1999/02/22-rdf-syntax-ns#object",
963    // RDFS 1.1: classes and properties
964    "http://www.w3.org/2000/01/rdf-schema#Resource",
965    "http://www.w3.org/2000/01/rdf-schema#Literal",
966    "http://www.w3.org/2000/01/rdf-schema#Class",
967    "http://www.w3.org/2000/01/rdf-schema#Datatype",
968    "http://www.w3.org/2000/01/rdf-schema#Container",
969    "http://www.w3.org/2000/01/rdf-schema#ContainerMembershipProperty",
970    "http://www.w3.org/2000/01/rdf-schema#subClassOf",
971    "http://www.w3.org/2000/01/rdf-schema#subPropertyOf",
972    "http://www.w3.org/2000/01/rdf-schema#domain",
973    "http://www.w3.org/2000/01/rdf-schema#range",
974    "http://www.w3.org/2000/01/rdf-schema#label",
975    "http://www.w3.org/2000/01/rdf-schema#comment",
976    "http://www.w3.org/2000/01/rdf-schema#member",
977    "http://www.w3.org/2000/01/rdf-schema#seeAlso",
978    "http://www.w3.org/2000/01/rdf-schema#isDefinedBy",
979    // OWL 2
980    "http://www.w3.org/2002/07/owl#Nothing",
981    "http://www.w3.org/2002/07/owl#Thing",
982    "http://www.w3.org/2002/07/owl#rational",
983    "http://www.w3.org/2002/07/owl#real",
984    "http://www.w3.org/2002/07/owl#Class",
985    "http://www.w3.org/2002/07/owl#Datatype",
986    "http://www.w3.org/2002/07/owl#ObjectProperty",
987    "http://www.w3.org/2002/07/owl#DatatypeProperty",
988    "http://www.w3.org/2002/07/owl#AnnotationProperty",
989    "http://www.w3.org/2002/07/owl#Individual",
990    "http://www.w3.org/2002/07/owl#NamedIndividual",
991    "http://www.w3.org/2002/07/owl#AnonymousIndividual",
992    "http://www.w3.org/2002/07/owl#equivalentClass",
993    "http://www.w3.org/2002/07/owl#disjointWith",
994    "http://www.w3.org/2002/07/owl#members",
995    "http://www.w3.org/2002/07/owl#disjointUnionOf",
996    "http://www.w3.org/2002/07/owl#propertyChainAxiom",
997    "http://www.w3.org/2002/07/owl#equivalentProperty",
998    "http://www.w3.org/2002/07/owl#propertyDisjointWith",
999    "http://www.w3.org/2002/07/owl#inverseOf",
1000    "http://www.w3.org/2002/07/owl#FunctionalProperty",
1001    "http://www.w3.org/2002/07/owl#ReflexiveProperty",
1002    "http://www.w3.org/2002/07/owl#TransitiveProperty",
1003    "http://www.w3.org/2002/07/owl#sameAs",
1004    "http://www.w3.org/2002/07/owl#differentFrom",
1005    "http://www.w3.org/2002/07/owl#AllDifferent",
1006    // SKOS core
1007    "http://www.w3.org/2004/02/skos/core#Concept",
1008    "http://www.w3.org/2004/02/skos/core#ConceptScheme",
1009    "http://www.w3.org/2004/02/skos/core#inScheme",
1010    "http://www.w3.org/2004/02/skos/core#hasTopConcept",
1011    "http://www.w3.org/2004/02/skos/core#topConceptOf",
1012    "http://www.w3.org/2004/02/skos/core#prefLabel",
1013    "http://www.w3.org/2004/02/skos/core#altLabel",
1014    "http://www.w3.org/2004/02/skos/core#hiddenLabel",
1015    "http://www.w3.org/2004/02/skos/core#notation",
1016    "http://www.w3.org/2004/02/skos/core#scopeNote",
1017    "http://www.w3.org/2004/02/skos/core#note",
1018    "http://www.w3.org/2004/02/skos/core#changeNote",
1019    "http://www.w3.org/2004/02/skos/core#example",
1020    "http://www.w3.org/2004/02/skos/core#editorialNote",
1021    "http://www.w3.org/2004/02/skos/core#historyNote",
1022    "http://www.w3.org/2004/02/skos/core#broader",
1023    "http://www.w3.org/2004/02/skos/core#narrower",
1024    "http://www.w3.org/2004/02/skos/core#related",
1025    "http://www.w3.org/2004/02/skos/core#exactMatch",
1026    "http://www.w3.org/2004/02/skos/core#Collection",
1027    "http://www.w3.org/2004/02/skos/core#member",
1028    // XSD datatypes
1029    "http://www.w3.org/2001/XMLSchema#string",
1030    "http://www.opengis.net/ont/geosparql#wktLiteral",
1031    "http://www.opengis.net/ont/geosparql#wkbLiteral",
1032    "http://www.opengis.net/ont/geosparql#Geometry",
1033    "http://www.opengis.net/ont/geosparql#Feature",
1034    "http://www.opengis.net/ont/geosparql#hasGeometry",
1035    "http://www.opengis.net/ont/geosparql#asWKT",
1036    "http://www.opengis.net/ont/geosparql#asWKB",
1037    "http://www.opengis.net/ont/geosparql#defaultGeometry",
1038    "http://www.opengis.net/ont/geosparql#sfContains",
1039    "http://www.opengis.net/ont/geosparql#sfWithin",
1040    "http://www.opengis.net/ont/geosparql#sfIntersects",
1041    "http://www.w3.org/2001/XMLSchema#boolean",
1042    "http://www.w3.org/2001/XMLSchema#float",
1043    "http://www.w3.org/2001/XMLSchema#double",
1044    "http://www.w3.org/2001/XMLSchema#decimal",
1045    "http://www.w3.org/2001/XMLSchema#integer",
1046    "http://www.w3.org/2001/XMLSchema#byte",
1047    "http://www.w3.org/2001/XMLSchema#short",
1048    "http://www.w3.org/2001/XMLSchema#int",
1049    "http://www.w3.org/2001/XMLSchema#long",
1050    "http://www.w3.org/2001/XMLSchema#unsignedByte",
1051    "http://www.w3.org/2001/XMLSchema#unsignedShort",
1052    "http://www.w3.org/2001/XMLSchema#unsignedInt",
1053    "http://www.w3.org/2001/XMLSchema#unsignedLong",
1054    "http://www.w3.org/2001/XMLSchema#positiveInteger",
1055    "http://www.w3.org/2001/XMLSchema#negativeInteger",
1056    "http://www.w3.org/2001/XMLSchema#nonPositiveInteger",
1057    "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
1058    "http://www.w3.org/2001/XMLSchema#dateTime",
1059    "http://www.w3.org/2001/XMLSchema#time",
1060    "http://www.w3.org/2001/XMLSchema#date",
1061    "http://www.w3.org/2001/XMLSchema#gYearMonth",
1062    "http://www.w3.org/2001/XMLSchema#gYear",
1063    "http://www.w3.org/2001/XMLSchema#gMonthDay",
1064    "http://www.w3.org/2001/XMLSchema#gDay",
1065    "http://www.w3.org/2001/XMLSchema#gMonth",
1066    "http://www.w3.org/2001/XMLSchema#duration",
1067    "http://www.w3.org/2001/XMLSchema#yearMonthDuration",
1068    "http://www.w3.org/2001/XMLSchema#dayTimeDuration",
1069    // # Schema.org (the http:// version)
1070    "http://schema.org/additionalType",
1071    "http://schema.org/citation",
1072    "http://schema.org/datePublished",
1073    "http://schema.org/pagination",
1074    "http://schema.org/author",
1075    "http://schema.org/inLanguage",
1076    "http://schema.org/containedInPlace",
1077    "http://schema.org/geo",
1078    "http://schema.org/longitude",
1079    "http://schema.org/latitude",
1080    "http://schema.org/gender",
1081    "http://schema.org/about",
1082    "http://schema.org/hasOccupation",
1083    "http://schema.org/birthDate",
1084    "http://schema.org/givenName",
1085    "http://schema.org/nationality",
1086    "http://schema.org/image",
1087    "http://schema.org/familyName",
1088    "http://schema.org/birthPlace",
1089    "http://schema.org/deathDate",
1090    "http://schema.org/memberOf",
1091    "http://schema.org/isPartOf",
1092    "http://schema.org/location",
1093    "http://schema.org/children",
1094    "http://schema.org/parent",
1095    "http://schema.org/actor",
1096    "http://schema.org/url",
1097    "http://schema.org/containsPlace",
1098    "http://schema.org/alumniOf",
1099    "http://schema.org/award",
1100    "http://schema.org/deathPlace",
1101    "http://schema.org/knowsLanguage",
1102    "http://schema.org/creator",
1103    "http://schema.org/foundingDate",
1104    "http://schema.org/genre",
1105    "http://schema.org/dateCreated",
1106    "http://schema.org/countryOfOrigin",
1107    "http://schema.org/startDate",
1108    "http://schema.org/endDate",
1109];
1110
1111/// Lazily built, hash-sorted well-known table (binary-search target).
1112fn well_known_table() -> &'static [(StrHash, &'static str)] {
1113    static TABLE: OnceLock<Vec<(StrHash, &'static str)>> = OnceLock::new();
1114    TABLE.get_or_init(|| {
1115        let mut table: Vec<(StrHash, &'static str)> = WELL_KNOWN_IRI_STRINGS
1116            .iter()
1117            .map(|iri| (StrHash::new(iri), *iri))
1118            .collect();
1119        table.sort_by_key(|(hash, _)| *hash);
1120        table
1121    })
1122}
1123
1124/// Static IRI for a well-known RDF/RDFS/OWL/SKOS/XSD hash.
1125///
1126/// Binary search over the lazily built, hash-sorted [`WELL_KNOWN_IRI_STRINGS`]
1127/// table. Hashes in this table decode registry-free; all other named nodes
1128/// resolve through the string registry as usual.
1129pub fn well_known_iri(hash: StrHash) -> Option<&'static str> {
1130    let table = well_known_table();
1131    let index = table.binary_search_by(|(known, _)| known.cmp(&hash)).ok()?;
1132    Some(table[index].1)
1133}
1134
1135/// Conventional prefix for every namespace covered by
1136/// [`WELL_KNOWN_IRI_STRINGS`].
1137///
1138/// Presentation-only: lets EXPLAIN-style renderers print `owl:Class`
1139/// instead of `<http://www.w3.org/2002/07/owl#Class>`. The namespaces are
1140/// pairwise disjoint, so the first `strip_prefix` hit is unambiguous.
1141const WELL_KNOWN_NAMESPACES: &[(&str, &str)] = &[
1142    ("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf"),
1143    ("http://www.w3.org/2000/01/rdf-schema#", "rdfs"),
1144    ("http://www.w3.org/2002/07/owl#", "owl"),
1145    ("http://www.w3.org/2004/02/skos/core#", "skos"),
1146    ("http://www.w3.org/2001/XMLSchema#", "xsd"),
1147    ("http://schema.org/", "schema"),
1148];
1149
1150/// Prefixed (Turtle/SPARQL-style) name for an IRI under a
1151/// [`WELL_KNOWN_NAMESPACES`] namespace, e.g. `owl:Class` for
1152/// `http://www.w3.org/2002/07/owl#Class`. `None` for IRIs outside those
1153/// namespaces.
1154pub fn prefixed_iri_name(iri: &str) -> Option<String> {
1155    WELL_KNOWN_NAMESPACES
1156        .iter()
1157        .find_map(|(namespace, prefix)| {
1158            iri.strip_prefix(namespace)
1159                .map(|local| format!("{prefix}:{local}"))
1160        })
1161}
1162
1163/// Prefixed name for a well-known RDF/RDFS/OWL/SKOS/XSD hash — the compact
1164/// counterpart of [`well_known_iri`] (`rdfs:label`, `xsd:integer`, …).
1165pub fn well_known_prefixed_iri(hash: StrHash) -> Option<String> {
1166    prefixed_iri_name(well_known_iri(hash)?)
1167}
1168
1169/// Empty small string literal (`""`, SPARQL `LANG` of an untagged literal).
1170pub const EMPTY_STR_LITERAL: EncodedTerm = EncodedTerm::SmallStringLiteral(SmallString::new());
1171
1172/// Deterministic strings-map key for a native geo term's rendered lexical form.
1173///
1174/// Late materialization resolves a geo literal the same way it resolves
1175/// hashed strings: the engine renders the lexical form (ingest-CRS WKT /
1176/// WKB through the geo plugin) and stores it under this key; every consumer
1177/// (API serializer, owned-term decode) recomputes the key from the term.
1178///
1179/// The key is the hash of the FULL encoded term bytes for every geo variant.
1180/// It must not be the `blob_id`: the blob id is the content hash of the
1181/// canonical CRS84 EWKB (which deliberately carries no SRID), so every term
1182/// that renders the same geometry — different ingest `CrsId`, or
1183/// `wktLiteral` vs `wkbLiteral` — shares one blob while requiring a
1184/// different lexical form. Distinct terms must never share a cache slot.
1185pub fn geo_lexical_key(term: &EncodedTerm) -> Option<StrHash> {
1186    match term {
1187        EncodedTerm::LiteralPoint { .. }
1188        | EncodedTerm::LiteralGeometry { .. }
1189        | EncodedTerm::BlobLiteral { .. } => {
1190            Some(StrHash::from_bytes(&super::binary::encode_term_bytes(term)))
1191        }
1192        _ => None,
1193    }
1194}
1195
1196/// Empty big string literal (hash of "").
1197#[allow(dead_code)]
1198pub const EMPTY_BIG_STR_LITERAL: EncodedTerm = EncodedTerm::BigStringLiteral {
1199    value_id: EMPTY_STR_HASH,
1200};
1201
1202impl From<&NamedNode> for EncodedTerm {
1203    fn from(named_node: &NamedNode) -> Self {
1204        Self::NamedNode {
1205            iri_id: StrHash::new(named_node.as_str()),
1206        }
1207    }
1208}
1209
1210impl From<&BlankNode> for EncodedTerm {
1211    fn from(blank_node: &BlankNode) -> Self {
1212        if let Some(id) = blank_node.as_ref().unique_id() {
1213            Self::NumericalBlankNode {
1214                id: id.to_be_bytes(),
1215            }
1216        } else {
1217            let id = blank_node.as_str();
1218            if let Ok(id) = SmallString::try_from(id) {
1219                Self::SmallBlankNode(id)
1220            } else {
1221                Self::BigBlankNode {
1222                    id_id: StrHash::new(id),
1223                }
1224            }
1225        }
1226    }
1227}
1228
1229impl From<&Literal> for EncodedTerm {
1230    fn from(literal: &Literal) -> Self {
1231        let value = literal.value();
1232        let datatype_ref = literal.datatype();
1233        let native_encoding = if datatype_ref == rdf::LANG_STRING {
1234            literal.language().map(|language| {
1235                if let Ok(value) = SmallString::try_from(value) {
1236                    if let Ok(language) = SmallString::try_from(language) {
1237                        Self::SmallSmallLangStringLiteral { value, language }
1238                    } else {
1239                        Self::SmallBigLangStringLiteral {
1240                            value,
1241                            language_id: StrHash::new(language),
1242                        }
1243                    }
1244                } else if let Ok(language) = SmallString::try_from(language) {
1245                    Self::BigSmallLangStringLiteral {
1246                        value_id: StrHash::new(value),
1247                        language,
1248                    }
1249                } else {
1250                    Self::BigBigLangStringLiteral {
1251                        value_id: StrHash::new(value),
1252                        language_id: StrHash::new(language),
1253                    }
1254                }
1255            })
1256        } else if datatype_ref == xsd::BOOLEAN {
1257            parse_boolean_str(value)
1258        } else if datatype_ref == xsd::STRING {
1259            Some(if let Ok(value) = SmallString::try_from(value) {
1260                Self::SmallStringLiteral(value)
1261            } else {
1262                Self::BigStringLiteral {
1263                    value_id: StrHash::new(value),
1264                }
1265            })
1266        } else if datatype_ref == xsd::FLOAT {
1267            parse_float_str(value)
1268        } else if datatype_ref == xsd::DOUBLE {
1269            parse_double_str(value)
1270        } else if is_integer_datatype(datatype_ref) {
1271            parse_integer_str(value)
1272        } else if datatype_ref == xsd::DECIMAL {
1273            parse_decimal_str(value)
1274        } else if datatype_ref == xsd::DATE_TIME || datatype_ref == xsd::DATE_TIME_STAMP {
1275            parse_date_time_str(value)
1276        } else if datatype_ref == xsd::TIME {
1277            parse_time_str(value)
1278        } else if datatype_ref == xsd::DATE {
1279            parse_date_str(value)
1280        } else if datatype_ref == xsd::G_YEAR_MONTH {
1281            parse_g_year_month_str(value)
1282        } else if datatype_ref == xsd::G_YEAR {
1283            parse_g_year_str(value)
1284        } else if datatype_ref == xsd::G_MONTH_DAY {
1285            parse_g_month_day_str(value)
1286        } else if datatype_ref == xsd::G_DAY {
1287            parse_g_day_str(value)
1288        } else if datatype_ref == xsd::G_MONTH {
1289            parse_g_month_str(value)
1290        } else if datatype_ref == xsd::DURATION {
1291            parse_duration_str(value)
1292        } else if datatype_ref == xsd::YEAR_MONTH_DURATION {
1293            parse_year_month_duration_str(value)
1294        } else if datatype_ref == xsd::DAY_TIME_DURATION {
1295            parse_day_time_duration_str(value)
1296        } else {
1297            None
1298        };
1299        match native_encoding {
1300            Some(term) => term,
1301            None => {
1302                let datatype_str = datatype_ref.as_str();
1303                if let Ok(value) = SmallString::try_from(value) {
1304                    Self::SmallTypedLiteral {
1305                        value,
1306                        datatype_id: StrHash::new(datatype_str),
1307                    }
1308                } else {
1309                    Self::BigTypedLiteral {
1310                        value_id: StrHash::new(value),
1311                        datatype_id: StrHash::new(datatype_str),
1312                    }
1313                }
1314            }
1315        }
1316    }
1317}
1318
1319use oxrdf::NamedNodeRef;
1320
1321fn is_integer_datatype(datatype: NamedNodeRef<'_>) -> bool {
1322    datatype == xsd::INTEGER
1323        || datatype == xsd::BYTE
1324        || datatype == xsd::SHORT
1325        || datatype == xsd::INT
1326        || datatype == xsd::LONG
1327        || datatype == xsd::UNSIGNED_BYTE
1328        || datatype == xsd::UNSIGNED_SHORT
1329        || datatype == xsd::UNSIGNED_INT
1330        || datatype == xsd::UNSIGNED_LONG
1331        || datatype == xsd::POSITIVE_INTEGER
1332        || datatype == xsd::NEGATIVE_INTEGER
1333        || datatype == xsd::NON_POSITIVE_INTEGER
1334        || datatype == xsd::NON_NEGATIVE_INTEGER
1335}
1336
1337impl From<&NamedOrBlankNode> for EncodedTerm {
1338    fn from(term: &NamedOrBlankNode) -> Self {
1339        match term {
1340            NamedOrBlankNode::NamedNode(named_node) => named_node.into(),
1341            NamedOrBlankNode::BlankNode(blank_node) => blank_node.into(),
1342        }
1343    }
1344}
1345
1346impl From<&Term> for EncodedTerm {
1347    fn from(term: &Term) -> Self {
1348        match term {
1349            Term::NamedNode(named_node) => named_node.into(),
1350            Term::BlankNode(blank_node) => blank_node.into(),
1351            Term::Literal(literal) => literal.into(),
1352        }
1353    }
1354}
1355
1356impl From<&GraphName> for EncodedTerm {
1357    fn from(name: &GraphName) -> Self {
1358        match name {
1359            GraphName::NamedNode(named_node) => named_node.into(),
1360            GraphName::BlankNode(blank_node) => blank_node.into(),
1361            GraphName::DefaultGraph => Self::DefaultGraph,
1362        }
1363    }
1364}
1365
1366/// Encoded quad (subject, predicate, object, graph).
1367#[derive(Debug, Clone, PartialEq)]
1368pub struct EncodedQuad {
1369    /// Encoded subject.
1370    pub subject: EncodedTerm,
1371    /// Encoded predicate.
1372    pub predicate: EncodedTerm,
1373    /// Encoded object.
1374    pub object: EncodedTerm,
1375    /// Encoded graph name (`DefaultGraph` for the default graph).
1376    pub graph_name: EncodedTerm,
1377}
1378
1379impl EncodedQuad {
1380    /// Build an encoded quad from components.
1381    pub fn new(
1382        subject: EncodedTerm,
1383        predicate: EncodedTerm,
1384        object: EncodedTerm,
1385        graph_name: EncodedTerm,
1386    ) -> Self {
1387        Self {
1388            subject,
1389            predicate,
1390            object,
1391            graph_name,
1392        }
1393    }
1394
1395    /// S/P/O identity, ignoring [`Self::graph_name`].
1396    ///
1397    /// Every hexastore permutation stores G last (`SPOG`, `SOPG`, `PSOG`,
1398    /// `POSG`, `OPSG`, `TSG`), so visible puts for the same triple are
1399    /// adjacent after MVCC. Used when collapsing a merged SPARQL default graph.
1400    pub fn same_triple(&self, other: &Self) -> bool {
1401        self.subject == other.subject
1402            && self.predicate == other.predicate
1403            && self.object == other.object
1404    }
1405
1406    /// Rewrite G to [`EncodedTerm::DefaultGraph`].
1407    ///
1408    /// Merge-default scans return this so compute never sees source-graph
1409    /// identity on a SPARQL default-graph triple. Users never observe G for
1410    /// those scans (`scan.graph` is unset). Do **not** use the rewritten quad
1411    /// as a full-key exclusive `start_after`: DefaultGraph encodes as zero
1412    /// bytes (the *lowest* G), which would re-enter the same triple's named
1413    /// graphs. Resume by skipping every quad with [`Self::same_triple`].
1414    pub fn into_merged_default(mut self) -> Self {
1415        self.graph_name = EncodedTerm::DefaultGraph;
1416        self
1417    }
1418}
1419
1420/// Collapse physical quads to the RDF merge of a SPARQL default graph.
1421///
1422/// Callers must feed quads in index order (G last). Exclusive `start_after`
1423/// skips that S/P/O regardless of G. `limit` of `0` is unlimited unique
1424/// triples. Each kept row has G rewritten to [`EncodedTerm::DefaultGraph`].
1425pub fn collapse_merged_default_triples(
1426    quads: impl IntoIterator<Item = EncodedQuad>,
1427    start_after: Option<&EncodedQuad>,
1428    limit: u64,
1429) -> Vec<EncodedQuad> {
1430    let mut out = Vec::new();
1431    let mut last_triple: Option<EncodedQuad> = None;
1432    let mut dont_skip = start_after.is_none();
1433    for quad in quads {
1434        if !dont_skip {
1435            if start_after.is_some_and(|cursor| quad.same_triple(cursor)) {
1436                continue;
1437            }
1438            dont_skip = true;
1439        }
1440        if last_triple
1441            .as_ref()
1442            .is_some_and(|prev| prev.same_triple(&quad))
1443        {
1444            continue;
1445        }
1446        last_triple = Some(quad.clone());
1447        out.push(quad.into_merged_default());
1448        if limit > 0 && out.len() as u64 >= limit {
1449            break;
1450        }
1451    }
1452    out
1453}
1454
1455impl From<&Quad> for EncodedQuad {
1456    fn from(quad: &Quad) -> Self {
1457        Self {
1458            subject: (&quad.subject).into(),
1459            predicate: (&quad.predicate).into(),
1460            object: (&quad.object).into(),
1461            graph_name: (&quad.graph_name).into(),
1462        }
1463    }
1464}
1465
1466/// Collect `(hash, raw)` pairs that must be registered in "strings" for an encoded term.
1467pub fn strings_entries_for_term(term: &Term, encoded: &EncodedTerm) -> Vec<(StrHash, String)> {
1468    let mut out = Vec::new();
1469    match term {
1470        Term::NamedNode(node) => {
1471            if let EncodedTerm::NamedNode { iri_id } = encoded {
1472                out.push((*iri_id, node.as_str().to_owned()));
1473            }
1474        }
1475        Term::BlankNode(node) => {
1476            if let EncodedTerm::BigBlankNode { id_id } = encoded {
1477                out.push((*id_id, node.as_str().to_owned()));
1478            }
1479        }
1480        Term::Literal(literal) => match encoded {
1481            EncodedTerm::BigStringLiteral { value_id }
1482            | EncodedTerm::BigSmallLangStringLiteral { value_id, .. } => {
1483                out.push((*value_id, literal.value().to_owned()));
1484            }
1485            EncodedTerm::SmallBigLangStringLiteral { language_id, .. } => {
1486                if let Some(language) = literal.language() {
1487                    out.push((*language_id, language.to_owned()));
1488                }
1489            }
1490            EncodedTerm::BigBigLangStringLiteral {
1491                value_id,
1492                language_id,
1493            } => {
1494                out.push((*value_id, literal.value().to_owned()));
1495                if let Some(language) = literal.language() {
1496                    out.push((*language_id, language.to_owned()));
1497                }
1498            }
1499            EncodedTerm::SmallTypedLiteral { datatype_id, .. } => {
1500                out.push((*datatype_id, literal.datatype().as_str().to_owned()));
1501            }
1502            EncodedTerm::BigTypedLiteral {
1503                value_id,
1504                datatype_id,
1505            } => {
1506                out.push((*value_id, literal.value().to_owned()));
1507                out.push((*datatype_id, literal.datatype().as_str().to_owned()));
1508            }
1509            _ => {}
1510        },
1511    }
1512    out
1513}
1514
1515fn parse_boolean_str(value: &str) -> Option<EncodedTerm> {
1516    Boolean::from_str(value)
1517        .ok()
1518        .map(EncodedTerm::BooleanLiteral)
1519}
1520
1521fn parse_float_str(value: &str) -> Option<EncodedTerm> {
1522    Float::from_str(value).ok().map(EncodedTerm::FloatLiteral)
1523}
1524
1525fn parse_double_str(value: &str) -> Option<EncodedTerm> {
1526    Double::from_str(value).ok().map(EncodedTerm::DoubleLiteral)
1527}
1528
1529fn parse_integer_str(value: &str) -> Option<EncodedTerm> {
1530    Integer::from_str(value)
1531        .ok()
1532        .map(EncodedTerm::IntegerLiteral)
1533}
1534
1535fn parse_decimal_str(value: &str) -> Option<EncodedTerm> {
1536    Decimal::from_str(value)
1537        .ok()
1538        .map(EncodedTerm::DecimalLiteral)
1539}
1540
1541fn parse_date_time_str(value: &str) -> Option<EncodedTerm> {
1542    DateTime::from_str(value)
1543        .ok()
1544        .map(EncodedTerm::DateTimeLiteral)
1545}
1546
1547fn parse_time_str(value: &str) -> Option<EncodedTerm> {
1548    Time::from_str(value).ok().map(EncodedTerm::TimeLiteral)
1549}
1550
1551fn parse_date_str(value: &str) -> Option<EncodedTerm> {
1552    Date::from_str(value).ok().map(EncodedTerm::DateLiteral)
1553}
1554
1555fn parse_g_year_month_str(value: &str) -> Option<EncodedTerm> {
1556    GYearMonth::from_str(value)
1557        .ok()
1558        .map(EncodedTerm::GYearMonthLiteral)
1559}
1560
1561fn parse_g_year_str(value: &str) -> Option<EncodedTerm> {
1562    GYear::from_str(value).ok().map(EncodedTerm::GYearLiteral)
1563}
1564
1565fn parse_g_month_day_str(value: &str) -> Option<EncodedTerm> {
1566    GMonthDay::from_str(value)
1567        .ok()
1568        .map(EncodedTerm::GMonthDayLiteral)
1569}
1570
1571fn parse_g_day_str(value: &str) -> Option<EncodedTerm> {
1572    GDay::from_str(value).ok().map(EncodedTerm::GDayLiteral)
1573}
1574
1575fn parse_g_month_str(value: &str) -> Option<EncodedTerm> {
1576    GMonth::from_str(value).ok().map(EncodedTerm::GMonthLiteral)
1577}
1578
1579fn parse_duration_str(value: &str) -> Option<EncodedTerm> {
1580    Duration::from_str(value)
1581        .ok()
1582        .map(EncodedTerm::DurationLiteral)
1583}
1584
1585fn parse_year_month_duration_str(value: &str) -> Option<EncodedTerm> {
1586    YearMonthDuration::from_str(value)
1587        .ok()
1588        .map(EncodedTerm::YearMonthDurationLiteral)
1589}
1590
1591fn parse_day_time_duration_str(value: &str) -> Option<EncodedTerm> {
1592    DayTimeDuration::from_str(value)
1593        .ok()
1594        .map(EncodedTerm::DayTimeDurationLiteral)
1595}
1596
1597#[cfg(test)]
1598mod tests {
1599    use super::*;
1600    use crate::{BlankNode, GraphName, Literal, NamedNode, Quad, Term};
1601
1602    /// Float term identity is BIT identity, arm-for-arm with the
1603    /// manual `Hash`. The IEEE specials must not break the hash-type
1604    /// contract — the pre-fix derive compared `+0.0 == -0.0` true (hash
1605    /// said distinct) and `NaN != NaN` true (hash said identical), which
1606    /// double-interned one NaN literal in the TermDict and counted it
1607    /// twice in `COUNT(DISTINCT)`.
1608    #[test]
1609    fn float_term_identity_is_bit_identity() {
1610        let pos = EncodedTerm::DoubleLiteral(0.0.into());
1611        let neg = EncodedTerm::DoubleLiteral((-0.0).into());
1612        let nan_a = EncodedTerm::DoubleLiteral(f64::NAN.into());
1613        let nan_b = EncodedTerm::DoubleLiteral(f64::NAN.into());
1614        let one = EncodedTerm::DoubleLiteral(1.0.into());
1615        // ±0.0: distinct terms — distinct stored bits, distinct lexicals.
1616        assert_ne!(pos, neg);
1617        // NaN: reflexive — the hash-keyed structures find it again.
1618        assert_eq!(nan_a, nan_b);
1619        // Ordinary values unchanged.
1620        assert_eq!(one, EncodedTerm::DoubleLiteral(1.0.into()));
1621        assert_ne!(one, nan_a);
1622
1623        // eq ⇒ same hash over the specials grid, both float widths.
1624        let grid = [
1625            pos.clone(),
1626            neg.clone(),
1627            nan_a.clone(),
1628            one.clone(),
1629            EncodedTerm::FloatLiteral(0.0.into()),
1630            EncodedTerm::FloatLiteral((-0.0).into()),
1631            EncodedTerm::FloatLiteral(f32::NAN.into()),
1632        ];
1633        for a in &grid {
1634            for b in &grid {
1635                if a == b {
1636                    let mut hash_a = std::collections::hash_map::DefaultHasher::new();
1637                    let mut hash_b = std::collections::hash_map::DefaultHasher::new();
1638                    a.hash(&mut hash_a);
1639                    b.hash(&mut hash_b);
1640                    assert_eq!(
1641                        hash_a.finish(),
1642                        hash_b.finish(),
1643                        "{a:?} == {b:?} must hash equal"
1644                    );
1645                }
1646            }
1647        }
1648
1649        // Behavioral pin for the DISTINCT/COUNT(DISTINCT) shape: a set
1650        // dedups same-bits NaN and keeps the two zeros distinct.
1651        let mut seen = std::collections::HashSet::new();
1652        assert!(seen.insert(nan_a.clone()));
1653        assert!(!seen.insert(nan_b.clone()));
1654        assert!(seen.insert(pos.clone()));
1655        assert!(seen.insert(neg.clone()));
1656        assert_eq!(seen.len(), 3);
1657
1658        // Point coordinates are f64s: bit identity, same contract —
1659        // ±0.0 is valid WKT and the derived IEEE compare called the two
1660        // zeros equal while the Hash called them distinct.
1661        let point = |x: f64| EncodedTerm::LiteralPoint {
1662            x,
1663            y: 1.0,
1664            crs: CrsId::Crs84,
1665            geo_datatype: GeoDatatype::WktLiteral,
1666        };
1667        assert_ne!(point(0.0), point(-0.0));
1668        assert_eq!(point(1.5), point(1.5));
1669        // Same coords under a different CRS is a different term — the
1670        // Hash mixes crs and geo_datatype in; the compare must too.
1671        assert_ne!(
1672            point(1.5),
1673            EncodedTerm::LiteralPoint {
1674                x: 1.5,
1675                y: 1.0,
1676                crs: CrsId::Epsg4326,
1677                geo_datatype: GeoDatatype::WktLiteral,
1678            }
1679        );
1680    }
1681
1682    /// The timestamp family's term identity is
1683    /// NOT the wire bytes. `Timestamp::to_be_bytes` writes "no timezone"
1684    /// as a `[255, 255]` sentinel byte-identical to a real -00:01 offset
1685    /// (i16 -1), so byte equality merged two distinct lexicals; Eq is
1686    /// `is_identical_with` (timeline value + tz presence + offset value)
1687    /// and the Hash adds a tz-presence discriminator so the byte-twins
1688    /// land in different buckets.
1689    #[test]
1690    fn timestamp_term_identity_includes_the_timezone() {
1691        let dt = |lex: &str| EncodedTerm::DateTimeLiteral(lex.parse().unwrap());
1692        // The byte-twin pair: different lexicals, different terms, and —
1693        // with the Hash discriminator — different hash buckets.
1694        let unzoned = dt("2020-01-01T00:01:00");
1695        let twin = dt("2020-01-01T00:00:00-00:01");
1696        assert_ne!(unzoned, twin);
1697        let mut hash_a = std::collections::hash_map::DefaultHasher::new();
1698        let mut hash_b = std::collections::hash_map::DefaultHasher::new();
1699        unzoned.hash(&mut hash_a);
1700        twin.hash(&mut hash_b);
1701        assert_ne!(
1702            hash_a.finish(),
1703            hash_b.finish(),
1704            "the tz-presence discriminator must split the byte-twins"
1705        );
1706        // Same instant, different offsets: different terms (the pre-fix
1707        // field `==` was offset-agnostic and wrongly merged them).
1708        assert_ne!(dt("2020-01-01T00:00:00Z"), dt("2020-01-01T01:00:00+01:00"));
1709        // Identical lexicals stay one term.
1710        assert_eq!(dt("2020-01-01T00:00:00Z"), dt("2020-01-01T00:00:00Z"));
1711    }
1712
1713    /// One sample per `EncodedTerm` variant. A new variant MUST extend
1714    /// this grid — the discriminant-count assert fails until it does
1715    /// (the same drift policy as the exhaustive Eq/Hash matches).
1716    #[test]
1717    fn eq_implies_hash_for_every_variant() {
1718        let long = "a lexical long enough to overflow the small inline slot";
1719        let long_tag = "enx-longtag-enough";
1720        let grid: Vec<EncodedTerm> = vec![
1721            EncodedTerm::DefaultGraph,
1722            EncodedTerm::Placeholder,
1723            EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()),
1724            EncodedTerm::from(&BlankNode::new("42").unwrap()),
1725            EncodedTerm::from(&BlankNode::new("plain").unwrap()),
1726            EncodedTerm::from(&BlankNode::new("0123456789012345678901234567890123456789").unwrap()),
1727            EncodedTerm::from(&Literal::from("short")),
1728            EncodedTerm::from(&Literal::from(long)),
1729            EncodedTerm::from(&Literal::new_language_tagged_literal("hi", "en").unwrap()),
1730            EncodedTerm::from(&Literal::new_language_tagged_literal(long, "en").unwrap()),
1731            EncodedTerm::from(&Literal::new_language_tagged_literal("hi", long_tag).unwrap()),
1732            EncodedTerm::from(&Literal::new_language_tagged_literal(long, long_tag).unwrap()),
1733            EncodedTerm::from(&Literal::new_typed_literal(
1734                "short",
1735                NamedNode::new_unchecked("http://ex/t"),
1736            )),
1737            EncodedTerm::from(&Literal::new_typed_literal(
1738                long,
1739                NamedNode::new_unchecked("http://ex/t"),
1740            )),
1741            EncodedTerm::from(&Literal::from(true)),
1742            EncodedTerm::from(&Literal::new_typed_literal(
1743                "1.5",
1744                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#float"),
1745            )),
1746            EncodedTerm::from(&Literal::new_typed_literal(
1747                "2.5",
1748                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#double"),
1749            )),
1750            EncodedTerm::from(&Literal::new_typed_literal(
1751                "7",
1752                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#integer"),
1753            )),
1754            EncodedTerm::from(&Literal::new_typed_literal(
1755                "1.5",
1756                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#decimal"),
1757            )),
1758            EncodedTerm::from(&Literal::new_typed_literal(
1759                "2020-01-01T00:00:00Z",
1760                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#dateTime"),
1761            )),
1762            EncodedTerm::from(&Literal::new_typed_literal(
1763                "12:00:00",
1764                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#time"),
1765            )),
1766            EncodedTerm::from(&Literal::new_typed_literal(
1767                "2020-01-01",
1768                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#date"),
1769            )),
1770            EncodedTerm::from(&Literal::new_typed_literal(
1771                "2020-01",
1772                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#gYearMonth"),
1773            )),
1774            EncodedTerm::from(&Literal::new_typed_literal(
1775                "2020",
1776                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#gYear"),
1777            )),
1778            EncodedTerm::from(&Literal::new_typed_literal(
1779                "--01-01",
1780                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#gMonthDay"),
1781            )),
1782            EncodedTerm::from(&Literal::new_typed_literal(
1783                "---01",
1784                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#gDay"),
1785            )),
1786            EncodedTerm::from(&Literal::new_typed_literal(
1787                "--01",
1788                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#gMonth"),
1789            )),
1790            EncodedTerm::from(&Literal::new_typed_literal(
1791                "P1DT2H",
1792                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#duration"),
1793            )),
1794            EncodedTerm::from(&Literal::new_typed_literal(
1795                "P1Y",
1796                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#yearMonthDuration"),
1797            )),
1798            EncodedTerm::from(&Literal::new_typed_literal(
1799                "P1DT2H",
1800                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#dayTimeDuration"),
1801            )),
1802            EncodedTerm::LiteralPoint {
1803                x: 1.0,
1804                y: 2.0,
1805                crs: CrsId::Crs84,
1806                geo_datatype: GeoDatatype::WktLiteral,
1807            },
1808            EncodedTerm::LiteralGeometry {
1809                geom_kind: GeomKind::MultiPolygon,
1810                crs: CrsId::Crs84,
1811                geo_datatype: GeoDatatype::WkbLiteral,
1812                blob_id: StrHash::from_bytes(&[7_u8; 32]),
1813                requires_spike_reduction: false,
1814            },
1815            EncodedTerm::BlobLiteral {
1816                datatype_id: StrHash::from_bytes(&[8_u8; 32]),
1817                blob_id: StrHash::from_bytes(&[9_u8; 32]),
1818            },
1819        ];
1820        let distinct: std::collections::HashSet<_> =
1821            grid.iter().map(std::mem::discriminant).collect();
1822        assert_eq!(
1823            distinct.len(),
1824            33,
1825            "one sample per variant — extend this grid when a variant is added"
1826        );
1827        // The invariant over the full grid: equal terms hash equal (and
1828        // every term is reflexive). Cross-variant pairs are structurally
1829        // `false` (the `_ => false` arm), so within-variant consistency is
1830        // what this proves for every arm at once.
1831        for a in &grid {
1832            for b in &grid {
1833                if a == b {
1834                    let mut hash_a = std::collections::hash_map::DefaultHasher::new();
1835                    let mut hash_b = std::collections::hash_map::DefaultHasher::new();
1836                    a.hash(&mut hash_a);
1837                    b.hash(&mut hash_b);
1838                    assert_eq!(
1839                        hash_a.finish(),
1840                        hash_b.finish(),
1841                        "{a:?} == {b:?} must hash equal"
1842                    );
1843                }
1844            }
1845        }
1846    }
1847
1848    #[test]
1849    fn geo_lexical_key_is_term_unique_not_blob_unique() {
1850        // One canonical CRS84 blob (the EWKB carries no SRID) can back
1851        // several distinct terms: the same geometry ingested under two
1852        // CRSs, or once as wktLiteral and once as wkbLiteral. Each term
1853        // renders a different lexical, so each needs its own cache key —
1854        // and none of them may collide with the blob id itself.
1855        let blob_id = StrHash::from_bytes(&[0xAB_u8; 32]);
1856        let key_of = |crs: CrsId, geo_datatype: GeoDatatype| {
1857            geo_lexical_key(&EncodedTerm::LiteralGeometry {
1858                geom_kind: GeomKind::Polygon,
1859                crs,
1860                geo_datatype,
1861                blob_id,
1862                requires_spike_reduction: false,
1863            })
1864            .unwrap()
1865        };
1866        let crs84 = key_of(CrsId::Crs84, GeoDatatype::WktLiteral);
1867        let epsg4326 = key_of(CrsId::Epsg4326, GeoDatatype::WktLiteral);
1868        let wkb = key_of(CrsId::Crs84, GeoDatatype::WkbLiteral);
1869        assert_ne!(crs84, epsg4326);
1870        assert_ne!(crs84, wkb);
1871        assert_ne!(epsg4326, wkb);
1872        assert_ne!(crs84, blob_id, "lexical key must not be the blob id");
1873    }
1874
1875    #[test]
1876    fn encode_term_short_uri_is_named_node_hash() {
1877        let iri = NamedNode::new("http://ex/s").unwrap();
1878        let term = Term::from(iri.clone());
1879        let encoded = EncodedTerm::from(&term);
1880        assert_eq!(
1881            encoded,
1882            EncodedTerm::NamedNode {
1883                iri_id: StrHash::new("http://ex/s")
1884            }
1885        );
1886    }
1887
1888    #[test]
1889    fn encode_term_long_uri_is_named_node_hash() {
1890        let iri =
1891            NamedNode::new("http://example.org/this-is-a-very-long-iri-that-exceeds-fifteen-chars")
1892                .unwrap();
1893        let term = Term::from(iri);
1894        let encoded = EncodedTerm::from(&term);
1895        assert!(matches!(encoded, EncodedTerm::NamedNode { .. }));
1896    }
1897
1898    #[test]
1899    fn encode_term_literals_and_blank_nodes() {
1900        let small_bnode = BlankNode::new("bnode").unwrap();
1901        let small_term = Term::from(small_bnode);
1902        assert!(matches!(
1903            EncodedTerm::from(&small_term),
1904            EncodedTerm::SmallBlankNode(_)
1905        ));
1906
1907        let num_bnode = BlankNode::new_from_unique_id(0x100a);
1908        let num_term = Term::from(num_bnode);
1909        assert!(matches!(
1910            EncodedTerm::from(&num_term),
1911            EncodedTerm::NumericalBlankNode { .. }
1912        ));
1913
1914        let lit = Literal::from(42_i32);
1915        let lit_term = Term::from(lit);
1916        assert!(matches!(
1917            EncodedTerm::from(&lit_term),
1918            EncodedTerm::IntegerLiteral(_)
1919        ));
1920
1921        let bool_lit = Literal::from(true);
1922        let bool_term = Term::from(bool_lit);
1923        assert!(matches!(
1924            EncodedTerm::from(&bool_term),
1925            EncodedTerm::BooleanLiteral(_)
1926        ));
1927    }
1928
1929    #[test]
1930    fn encode_quad_preserves_fields() {
1931        let quad = Quad::new(
1932            NamedNode::new("http://ex/s").unwrap(),
1933            NamedNode::new("http://ex/p").unwrap(),
1934            Literal::from("obj"),
1935            GraphName::DefaultGraph,
1936        );
1937        let encoded = EncodedQuad::from(&quad);
1938        assert_eq!(encoded.subject, (&quad.subject).into());
1939        assert_eq!(encoded.predicate, EncodedTerm::from(&quad.predicate));
1940        assert_eq!(encoded.object, (&quad.object).into());
1941        assert_eq!(encoded.graph_name, EncodedTerm::DefaultGraph);
1942    }
1943
1944    #[test]
1945    fn collapse_merged_default_skips_start_after_triple_and_rewrites_g() {
1946        let spo = |g: EncodedTerm| EncodedQuad {
1947            subject: EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()),
1948            predicate: EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()),
1949            object: EncodedTerm::from(&NamedNode::new("http://ex/o").unwrap()),
1950            graph_name: g,
1951        };
1952        let g1 = EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap());
1953        let g2 = EncodedTerm::from(&NamedNode::new("http://ex/g2").unwrap());
1954        let other = EncodedQuad {
1955            subject: EncodedTerm::from(&NamedNode::new("http://ex/s2").unwrap()),
1956            predicate: EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()),
1957            object: EncodedTerm::from(&NamedNode::new("http://ex/o").unwrap()),
1958            graph_name: g1.clone(),
1959        };
1960        let rows = collapse_merged_default_triples(
1961            vec![spo(g1.clone()), spo(g2), other.clone()],
1962            Some(&spo(EncodedTerm::DefaultGraph)),
1963            0,
1964        );
1965        assert_eq!(rows.len(), 1);
1966        assert!(rows[0].same_triple(&other));
1967        assert_eq!(rows[0].graph_name, EncodedTerm::DefaultGraph);
1968    }
1969
1970    #[test]
1971    fn rdf_type_const_matches_vocab_iri_hash() {
1972        let from_iri = EncodedTerm::from(
1973            &NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
1974        );
1975        assert_eq!(RDF_TYPE, from_iri);
1976        assert_eq!(
1977            RDF_TYPE_IRI_ID,
1978            StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
1979        );
1980    }
1981
1982    #[test]
1983    fn xsd_and_rdf_iri_consts_match_vocab_hashes() {
1984        use oxrdf::vocab::rdf;
1985        let pairs = [
1986            (XSD_FLOAT_IRI_ID, xsd::FLOAT),
1987            (XSD_DOUBLE_IRI_ID, xsd::DOUBLE),
1988            (XSD_DECIMAL_IRI_ID, xsd::DECIMAL),
1989            (XSD_INTEGER_IRI_ID, xsd::INTEGER),
1990            (XSD_BYTE_IRI_ID, xsd::BYTE),
1991            (XSD_SHORT_IRI_ID, xsd::SHORT),
1992            (XSD_INT_IRI_ID, xsd::INT),
1993            (XSD_LONG_IRI_ID, xsd::LONG),
1994            (XSD_UNSIGNED_BYTE_IRI_ID, xsd::UNSIGNED_BYTE),
1995            (XSD_UNSIGNED_SHORT_IRI_ID, xsd::UNSIGNED_SHORT),
1996            (XSD_UNSIGNED_INT_IRI_ID, xsd::UNSIGNED_INT),
1997            (XSD_UNSIGNED_LONG_IRI_ID, xsd::UNSIGNED_LONG),
1998            (XSD_POSITIVE_INTEGER_IRI_ID, xsd::POSITIVE_INTEGER),
1999            (XSD_NEGATIVE_INTEGER_IRI_ID, xsd::NEGATIVE_INTEGER),
2000            (XSD_NON_POSITIVE_INTEGER_IRI_ID, xsd::NON_POSITIVE_INTEGER),
2001            (XSD_NON_NEGATIVE_INTEGER_IRI_ID, xsd::NON_NEGATIVE_INTEGER),
2002            (XSD_STRING_IRI_ID, xsd::STRING),
2003            (XSD_BOOLEAN_IRI_ID, xsd::BOOLEAN),
2004            (XSD_DATE_TIME_IRI_ID, xsd::DATE_TIME),
2005            (XSD_TIME_IRI_ID, xsd::TIME),
2006            (XSD_DATE_IRI_ID, xsd::DATE),
2007            (XSD_G_YEAR_MONTH_IRI_ID, xsd::G_YEAR_MONTH),
2008            (XSD_G_YEAR_IRI_ID, xsd::G_YEAR),
2009            (XSD_G_MONTH_DAY_IRI_ID, xsd::G_MONTH_DAY),
2010            (XSD_G_DAY_IRI_ID, xsd::G_DAY),
2011            (XSD_G_MONTH_IRI_ID, xsd::G_MONTH),
2012            (XSD_DURATION_IRI_ID, xsd::DURATION),
2013            (XSD_YEAR_MONTH_DURATION_IRI_ID, xsd::YEAR_MONTH_DURATION),
2014            (XSD_DAY_TIME_DURATION_IRI_ID, xsd::DAY_TIME_DURATION),
2015            (RDF_LANG_STRING_IRI_ID, rdf::LANG_STRING),
2016        ];
2017        for (constant, iri) in pairs {
2018            assert_eq!(constant, StrHash::new(iri.as_str()), "{}", iri.as_str());
2019            assert_eq!(well_known_iri(constant), Some(iri.as_str()));
2020        }
2021        assert_eq!(
2022            XSD_INTEGER,
2023            EncodedTerm::NamedNode {
2024                iri_id: XSD_INTEGER_IRI_ID,
2025            }
2026        );
2027    }
2028
2029    #[test]
2030    fn well_known_table_is_sorted_unique_and_self_consistent() {
2031        let table = well_known_table();
2032        assert!(
2033            table.len() >= 100,
2034            "expected the extended vocabulary table, got {} entries",
2035            table.len()
2036        );
2037        // Sorted by hash (binary-search precondition) and duplicate-free.
2038        assert!(table.windows(2).all(|window| window[0].0 < window[1].0));
2039        // Self-consistent by construction, and every entry is reachable
2040        // through the public lookup.
2041        for (hash, iri) in table {
2042            assert_eq!(well_known_iri(*hash), Some(*iri), "{iri}");
2043            assert_eq!(StrHash::new(iri), *hash, "{iri}");
2044        }
2045    }
2046
2047    #[test]
2048    fn extended_vocab_decodes_registry_free() {
2049        let samples = [
2050            "http://www.w3.org/2000/01/rdf-schema#label",
2051            "http://www.w3.org/2000/01/rdf-schema#subClassOf",
2052            "http://www.w3.org/2002/07/owl#Class",
2053            "http://www.w3.org/2002/07/owl#sameAs",
2054            "http://www.w3.org/2004/02/skos/core#prefLabel",
2055            "http://www.w3.org/2004/02/skos/core#broader",
2056        ];
2057        for iri in samples {
2058            assert_eq!(
2059                well_known_iri(StrHash::new(iri)),
2060                Some(iri),
2061                "{iri} must decode without the registry"
2062            );
2063        }
2064        // Dataset-specific IRIs still go through the registry.
2065        assert_eq!(
2066            well_known_iri(StrHash::new("http://ex/not-well-known")),
2067            None
2068        );
2069    }
2070
2071    #[test]
2072    fn is_numeric_encoded_native_and_ill_formed_typed() {
2073        assert!(is_numeric_encoded(&EncodedTerm::from(&Term::from(
2074            Literal::from(42_i32)
2075        ))));
2076        assert!(is_numeric_encoded(&EncodedTerm::from(&Term::from(
2077            Literal::new_typed_literal("1.5", xsd::DECIMAL)
2078        ))));
2079        assert!(is_numeric_encoded(&EncodedTerm::from(&Term::from(
2080            Literal::new_typed_literal("1.0", xsd::FLOAT)
2081        ))));
2082        assert!(is_numeric_encoded(&EncodedTerm::from(&Term::from(
2083            Literal::new_typed_literal("1.0", xsd::DOUBLE)
2084        ))));
2085
2086        let ill_formed = EncodedTerm::from(&Term::from(Literal::new_typed_literal("x", xsd::INT)));
2087        assert!(matches!(
2088            ill_formed,
2089            EncodedTerm::SmallTypedLiteral { .. } | EncodedTerm::BigTypedLiteral { .. }
2090        ));
2091        assert!(is_numeric_encoded(&ill_formed));
2092
2093        assert!(!is_numeric_encoded(&EncodedTerm::from(&Term::from(
2094            Literal::from("1")
2095        ))));
2096        assert!(!is_numeric_encoded(&EncodedTerm::from(&Term::from(
2097            Literal::from(true)
2098        ))));
2099        assert!(!is_numeric_encoded(&EncodedTerm::from(
2100            &NamedNode::new_unchecked("http://ex/s")
2101        )));
2102        assert!(!is_numeric_encoded(&EncodedTerm::from(&Term::from(
2103            Literal::new_typed_literal("2010-06-21T11:28:01Z", xsd::DATE_TIME)
2104        ))));
2105    }
2106
2107    #[test]
2108    fn empty_str_hash_matches_generated_hash() {
2109        let from_iri = EncodedTerm::SmallStringLiteral(SmallString::new());
2110        assert_eq!(EMPTY_STR_LITERAL, from_iri);
2111        assert_eq!(EMPTY_STR_HASH, StrHash::new(""));
2112        // Empty big string literal should not match empty small string literal
2113        assert_ne!(from_iri, EMPTY_BIG_STR_LITERAL);
2114    }
2115
2116    #[test]
2117    fn well_known_iris_get_conventional_prefixes() {
2118        assert_eq!(
2119            prefixed_iri_name("http://www.w3.org/2002/07/owl#Class").as_deref(),
2120            Some("owl:Class")
2121        );
2122        assert_eq!(
2123            prefixed_iri_name("http://www.w3.org/2000/01/rdf-schema#label").as_deref(),
2124            Some("rdfs:label")
2125        );
2126        assert_eq!(
2127            prefixed_iri_name("http://schema.org/author").as_deref(),
2128            Some("schema:author")
2129        );
2130        // Hashes in the well-known table resolve through the prefix table too.
2131        assert_eq!(
2132            well_known_prefixed_iri(StrHash::new("http://www.w3.org/2001/XMLSchema#integer"))
2133                .as_deref(),
2134            Some("xsd:integer")
2135        );
2136        // Unknown namespaces (and IRIs outside the table) stay unprefixed.
2137        assert_eq!(prefixed_iri_name("http://ex/livesIn"), None);
2138        assert_eq!(
2139            well_known_prefixed_iri(StrHash::new("http://ex/livesIn")),
2140            None
2141        );
2142    }
2143}