Skip to main content

qualia_core_db/query/
resolver.rs

1//! Zero-allocation Lexicon Resolver.
2//!
3//! Maps 64-bit Quin field values back to human-readable `&[u8]` slices for
4//! serialisation into N-Triples or JSON-LD surface syntaxes.
5//!
6//! # Bit layout of a Quin field value
7//!
8//! ```text
9//! Bit 63  │ Bits 60-63   │ Bits 0-59     │ Interpretation
10//! ────────┼──────────────┼───────────────┼──────────────────────────────────────
11//!   1     │ any          │ payload       │ did:q42 topological pointer (identifier module)
12//!   0     │ 0b0000       │ FNV-1a hash   │ IRI / blank-node → lexicon lookup
13//!   0     │ 0b0001       │ integer       │ Inline xsd:integer literal
14//!   0     │ 0b0010       │ scaled × 10⁶  │ Inline xsd:decimal literal
15//!   0     │ 0b0011       │ 0 or 1        │ Inline xsd:boolean literal
16//!   0     │ 0b001        │ embedded hash │ SPARQL-Star embedded triple <<s p o>>
17//!   0     │ 0b1000       │ webizen id    │ Person-controlled WebID agent identifier
18//!   0     │ 0b0101       │ f32 bits      │ Inline xsd:float literal (computed values)
19//!   0     │ 0b0110–0b0111│ reserved      │ Treated as IRI hash (future use)
20//! ```
21//!
22//! NOTE: `0b0101` (`INLINE_TAG_FLOAT`) was formally allocated to inline `xsd:float`
23//! in 0.0.19 to resolve the float-vs-integer tag clash — computed f32 values used to
24//! squat on the `0b0001` integer tag. The Webizen VM, `frame_layout`, and this
25//! resolver now agree on `0b0101`. See `AGENTS.md §4-D` and `ALGEBRA_MANIFOLD_PLAN.md`.
26//!
27//! The inline-type encoding is applied by the ingest layer, which masks
28//! FNV-1a hash values to 60 bits before storing them so there is no
29//! ambiguity with the type-tag bits.
30//!
31//! # Zero-allocation guarantee
32//! `format_ntriples_to` writes directly to any `impl io::Write` sink and
33//! never touches the heap.  Callers own the output buffer.
34
35use crate::NQuin;
36use std::io;
37
38/// Cold RDF/Q42 lexical binary64 storage; not the inline binary32 encoding.
39#[path = "typed_double.rs"]
40pub mod typed_double;
41
42// ---------------------------------------------------------------------------
43// Bit-layout constants
44// ---------------------------------------------------------------------------
45
46pub const MSB_FLAG: u64 = 1u64 << 63;
47pub const INLINE_TAG_MASK: u64 = 0b111u64 << 60; // bits 60-62 (only when MSB=0)
48pub const INLINE_TAG_INTEGER: u64 = 0b001u64 << 60;
49pub const INLINE_TAG_DECIMAL: u64 = 0b010u64 << 60;
50pub const INLINE_TAG_BOOLEAN: u64 = 0b011u64 << 60;
51/// Inline `xsd:float` literal: bits 0-31 are raw IEEE-754 f32 bits. Allocated 0.0.19 to
52/// end the float-vs-integer clash (formerly squatted on `INLINE_TAG_INTEGER`). Canonical
53/// home for this tag; `frame_layout` re-exports it.
54pub const INLINE_TAG_FLOAT: u64 = 0b101u64 << 60;
55/// SPARQL-Star embedded triple tag: indicates the value is a Virtual ID for `<<s p o>>`
56pub const TAG_EMBEDDED: u64 = 0b001u64 << 60;
57/// Webizen identity tag: indicates the value is a person-controlled WebID agent identifier
58/// Uses 0x8 prefix for instant identification without dictionary lookup
59pub const TAG_WEBIZEN: u64 = 0b1000u64 << 60;
60/// Mask over bits 0-59 — the value payload when an inline tag is present.
61pub const INLINE_VALUE_MASK: u64 = !(MSB_FLAG | INLINE_TAG_MASK);
62
63// ---------------------------------------------------------------------------
64// Demo lexicon
65// ---------------------------------------------------------------------------
66// In production this static table is replaced by a memory-mapped `.q42`
67// dictionary shard with entries sorted by hash for O(log n) binary search.
68// For the current phase a linear scan over this small table is sufficient.
69//
70// Entries are (fnv1a_hash, iri_bytes).  Hashes are computed at compile time
71// via `q_hash`, which is `const fn`.
72
73static DEMO_LEXICON: &[(u64, &[u8])] = &[
74    (crate::q_hash("Alice"), b"http://webizen.org/demo/Alice"),
75    (crate::q_hash("Bob"), b"http://webizen.org/demo/Bob"),
76    (crate::q_hash("Carol"), b"http://webizen.org/demo/Carol"),
77    (crate::q_hash("knows"), b"http://schema.org/knows"),
78    (crate::q_hash("likes"), b"http://schema.org/likes"),
79    (
80        crate::q_hash("type"),
81        b"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
82    ),
83    (
84        crate::q_hash("label"),
85        b"http://www.w3.org/2000/01/rdf-schema#label",
86    ),
87    (crate::q_hash("Person"), b"http://schema.org/Person"),
88    (crate::q_hash("name"), b"http://schema.org/name"),
89    (
90        crate::q_hash("guardian"),
91        b"http://webizen.org/vocab#guardian",
92    ),
93    (crate::q_hash("ward"), b"http://webizen.org/vocab#ward"),
94    (
95        crate::q_hash("has_symptom"),
96        b"http://webizen.org/medical#hasSymptom",
97    ),
98    (crate::q_hash("Fever"), b"http://snomed.info/id/386661006"),
99    (
100        crate::q_hash("income"),
101        b"http://webizen.org/finance#income",
102    ),
103    (
104        crate::q_hash("balance"),
105        b"http://webizen.org/finance#balance",
106    ),
107];
108
109// ---------------------------------------------------------------------------
110// Lexicon struct
111// ---------------------------------------------------------------------------
112
113/// Wraps the persistent dictionary block used for hash → IRI resolution.
114///
115/// In production this struct holds a raw pointer into a memory-mapped `.q42`
116/// dictionary shard and resolves lookups via a binary search over the
117/// sorted `(hash, byte_offset)` index — zero copies, zero allocations.
118///
119/// For the current phase it wraps the compile-time `DEMO_LEXICON` table.
120pub struct Lexicon {
121    entries: &'static [(u64, &'static [u8])],
122}
123
124impl Lexicon {
125    /// Creates a default `Lexicon`.
126    pub const fn new() -> Self {
127        Self {
128            entries: DEMO_LEXICON,
129        }
130    }
131
132    /// Look up `hash` in the dictionary.
133    ///
134    /// Production upgrade: sort `entries` by hash and replace the linear scan
135    /// with `entries.binary_search_by_key(&hash, |&(h, _)| h)`.
136    #[inline]
137    pub fn resolve(&self, hash: u64) -> Option<&'static [u8]> {
138        for &(h, bytes) in self.entries {
139            if h == hash {
140                return Some(bytes);
141            }
142        }
143        None
144    }
145}
146
147const LEXICON: Lexicon = Lexicon::new();
148
149// ---------------------------------------------------------------------------
150// Public resolution API
151// ---------------------------------------------------------------------------
152
153/// Resolve a 64-bit Quin field value to its original URI bytes.
154///
155/// Returns `None` when:
156/// - the value has MSB=1 (topological pointer — not a lexicon entry), or
157/// - the hash is genuinely absent from the dictionary.
158pub fn resolve_hash(hash: u64) -> Option<&'static [u8]> {
159    // Topological pointers (MSB=1 and NOT in the lexicon) are not dictionary
160    // entries.  Check the lexicon first so that hashes whose FNV-1a value
161    // naturally has bit 63 set are still resolved correctly.
162    if let Some(uri) = LEXICON.resolve(hash) {
163        return Some(uri);
164    }
165    if (hash & MSB_FLAG) != 0 {
166        return None; // confirmed topological pointer
167    }
168    None
169}
170
171// ---------------------------------------------------------------------------
172// Term formatters  (all write to impl io::Write — no heap allocation)
173// ---------------------------------------------------------------------------
174
175/// Write a subject or predicate term.
176/// These positions hold only IRI hashes or did:q42 topological pointers —
177/// no inline-typed literals.
178///
179/// **Lexicon takes priority over bit-flag detection.**
180/// A hash stored in the dictionary is always rendered as an IRI, regardless of
181/// which bits happen to be set by FNV-1a.  Only values that are absent from the
182/// lexicon AND have MSB=1 are interpreted as `did:q42` topological pointers.
183/// This correctly handles terms like `q_hash("knows")` whose FNV-1a output
184/// naturally has bit 63 set.
185#[inline]
186pub(crate) fn write_iri_term<W: io::Write>(val: u64, out: &mut W) -> io::Result<()> {
187    // 1. Lexicon lookup — exact value, no bit-stripping.
188    if let Some(uri) = LEXICON.resolve(val) {
189        out.write_all(b"<")?;
190        out.write_all(uri)?;
191        return out.write_all(b">");
192    }
193    // 2. Not in lexicon + MSB set → did:q42 topological pointer.
194    if (val & MSB_FLAG) != 0 {
195        let ptr = val & !MSB_FLAG;
196        return write!(out, "<did:q42:ptr/{ptr:016x}>");
197    }
198    // 3. Unknown hash — hex fallback.
199    write!(out, "<quin:hash/{val:016x}>")
200}
201
202/// An inline-typed literal decoded from a Quin field value's tag bits (60-62).
203/// Allocation-free; the caller formats the lexical/datatype form it needs
204/// (N-Triples surface syntax, SPARQL-Results JSON/XML, etc.).
205#[derive(Debug, Clone, Copy, PartialEq)]
206pub enum InlineLiteral {
207    /// `xsd:integer` (already 60-bit sign-extended to i64).
208    Integer(i64),
209    /// `xsd:decimal` — fixed-point, the value is `raw × 10⁻⁶` (raw sign-extended).
210    Decimal(i64),
211    /// `xsd:boolean`.
212    Boolean(bool),
213    /// `xsd:float` (decoded from the lower 32 bits as IEEE-754 f32).
214    Float(f32),
215}
216
217impl InlineLiteral {
218    /// The XSD datatype IRI (without angle brackets) for this literal.
219    pub fn datatype_iri(&self) -> &'static str {
220        match self {
221            InlineLiteral::Integer(_) => "http://www.w3.org/2001/XMLSchema#integer",
222            InlineLiteral::Decimal(_) => "http://www.w3.org/2001/XMLSchema#decimal",
223            InlineLiteral::Boolean(_) => "http://www.w3.org/2001/XMLSchema#boolean",
224            InlineLiteral::Float(_) => "http://www.w3.org/2001/XMLSchema#float",
225        }
226    }
227}
228
229impl std::fmt::Display for InlineLiteral {
230    /// The canonical lexical form (the string that goes between the quotes).
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        match *self {
233            InlineLiteral::Integer(n) => write!(f, "{n}"),
234            InlineLiteral::Decimal(raw) => {
235                let neg = raw < 0;
236                let abs = raw.unsigned_abs();
237                let whole = abs / 1_000_000;
238                let frac = abs % 1_000_000;
239                if neg {
240                    write!(f, "-{whole}.{frac:06}")
241                } else {
242                    write!(f, "{whole}.{frac:06}")
243                }
244            }
245            InlineLiteral::Boolean(b) => write!(f, "{b}"),
246            InlineLiteral::Float(x) => write!(f, "{x}"),
247        }
248    }
249}
250
251/// Classify a Quin field value as an inline-typed literal, or `None` if it is
252/// not one (an IRI hash / did:q42 pointer / lexicon entry).
253///
254/// IMPORTANT: `INLINE_TAG_INTEGER` and `TAG_EMBEDDED` are the *same* bit pattern
255/// (`0b001 << 60`). A caller that also handles SPARQL-Star embedded triples must
256/// try its embedded-triple lexicon lookup **before** calling this — a resolvable
257/// embedded-triple virtual id would otherwise be reported here as an integer.
258#[inline]
259pub fn classify_inline_literal(val: u64) -> Option<InlineLiteral> {
260    // A value with the MSB set is a topological pointer, never an inline literal.
261    if (val & MSB_FLAG) != 0 {
262        return None;
263    }
264    match val & INLINE_TAG_MASK {
265        INLINE_TAG_INTEGER => {
266            let mut n = (val & INLINE_VALUE_MASK) as i64;
267            if (n & (1i64 << 59)) != 0 {
268                n |= !((1i64 << 60) - 1);
269            }
270            Some(InlineLiteral::Integer(n))
271        }
272        INLINE_TAG_DECIMAL => {
273            let mut raw = (val & INLINE_VALUE_MASK) as i64;
274            if (raw & (1i64 << 59)) != 0 {
275                raw |= !((1i64 << 60) - 1);
276            }
277            Some(InlineLiteral::Decimal(raw))
278        }
279        INLINE_TAG_BOOLEAN => Some(InlineLiteral::Boolean((val & 1) != 0)),
280        INLINE_TAG_FLOAT => Some(InlineLiteral::Float(f32::from_bits(
281            (val & 0xFFFF_FFFF) as u32,
282        ))),
283        _ => None,
284    }
285}
286
287/// Pack a lexical typed literal into the inline object encoding (inverse of
288/// [`classify_inline_literal`]). Returns `None` when the datatype/value pair is
289/// not an admitted inline form (caller should hash the lexical string instead).
290pub fn pack_typed_literal(value: &str, datatype_iri: &str) -> Option<u64> {
291    let dt = datatype_iri.trim();
292    let dt = dt
293        .strip_prefix('<')
294        .and_then(|s| s.strip_suffix('>'))
295        .unwrap_or(dt);
296    if dt == "http://www.w3.org/2001/XMLSchema#integer" || dt == "xsd:integer" {
297        let num = value.parse::<i64>().ok()?;
298        let max_val = (1i64 << 59) - 1;
299        let min_val = -(1i64 << 59);
300        if num < min_val || num > max_val {
301            return None;
302        }
303        let unsigned = (num as u64) & INLINE_VALUE_MASK;
304        return Some(INLINE_TAG_INTEGER | unsigned);
305    }
306    if dt == "http://www.w3.org/2001/XMLSchema#decimal" || dt == "xsd:decimal" {
307        let num = value.parse::<f64>().ok()?;
308        let scaled = num * 1_000_000.0;
309        let max_val = ((1i64 << 59) - 1) as f64;
310        let min_val = (-(1i64 << 59)) as f64;
311        if !(min_val..=max_val).contains(&scaled) {
312            return None;
313        }
314        let num_i64 = scaled.round() as i64;
315        let unsigned = (num_i64 as u64) & INLINE_VALUE_MASK;
316        return Some(INLINE_TAG_DECIMAL | unsigned);
317    }
318    if dt == "http://www.w3.org/2001/XMLSchema#boolean" || dt == "xsd:boolean" {
319        return match value {
320            "true" | "1" => Some(INLINE_TAG_BOOLEAN | 1),
321            "false" | "0" => Some(INLINE_TAG_BOOLEAN | 0),
322            _ => None,
323        };
324    }
325    // A binary64 value cannot fit the binary32 inline payload. The caller must
326    // retain its standard typed lexical term in Q42LEX instead of rounding it.
327    if dt == typed_double::DATATYPE || dt == "xsd:double" {
328        return None;
329    }
330    if dt == "http://www.w3.org/2001/XMLSchema#float" || dt == "xsd:float" {
331        let f = value.parse::<f32>().ok()?;
332        return Some(crate::frame_layout::pack_float_object(f));
333    }
334    None
335}
336
337/// Write an object term, applying inline-type detection on bits 60-62.
338///
339/// Priority order (same lexicon-first reasoning as `write_iri_term`):
340/// 1. Lexicon match → IRI
341/// 2. MSB=1 and not in lexicon → did:q42 pointer
342/// 3. Bits 60-62 match a known inline tag → typed literal
343/// 4. Fallback → hex placeholder
344#[inline]
345pub(crate) fn write_object_term<W: io::Write>(val: u64, out: &mut W) -> io::Result<()> {
346    // 1. Lexicon first — a known IRI hash wins over any bit-pattern check.
347    if let Some(uri) = LEXICON.resolve(val) {
348        out.write_all(b"<")?;
349        out.write_all(uri)?;
350        return out.write_all(b">");
351    }
352    // 2. MSB=1 → topological pointer.
353    if (val & MSB_FLAG) != 0 {
354        let ptr = val & !MSB_FLAG;
355        return write!(out, "<did:q42:ptr/{ptr:016x}>");
356    }
357    // 3. Inline-type detection (only reached for values NOT in the lexicon).
358    //    The ingest layer encodes typed literals with explicit tag bits, so
359    //    there is no ambiguity with normalised IRI hashes in a live database.
360    //    Shares one decoder with `classify_inline_literal` so the (error-prone)
361    //    sign-extension / f32 decode lives in exactly one place.
362    match classify_inline_literal(val) {
363        Some(lit) => write!(out, "\"{lit}\"^^<{}>", lit.datatype_iri()),
364        None => write!(out, "<quin:hash/{val:016x}>"),
365    }
366}
367
368// ---------------------------------------------------------------------------
369// Public streaming formatter
370// ---------------------------------------------------------------------------
371
372/// Serialise `quins` as N-Triples, writing each line directly to `out`.
373///
374/// The function itself performs **no heap allocation** — it writes bytes
375/// directly to the caller-supplied `W` sink.  Callers that need an in-memory
376/// buffer should pass `&mut Vec<u8>`.
377///
378/// Subject values are written via `write_iri_term` (which accounts for the
379/// MSB / did:q42 flag).  Object values additionally check bits 60-62 for
380/// inline-typed literals.
381pub fn format_ntriples_to<W: io::Write>(quins: &[NQuin], out: &mut W) -> io::Result<()> {
382    for q in quins {
383        write_ntriple_line(q, out)?;
384    }
385    Ok(())
386}
387
388/// N-Quads lines with graph context (zero-heap).
389pub fn format_nquads_to<W: io::Write>(quins: &[NQuin], out: &mut W) -> io::Result<()> {
390    for q in quins {
391        write_iri_term(q.subject, out)?;
392        out.write_all(b" ")?;
393        write_iri_term(q.predicate, out)?;
394        out.write_all(b" ")?;
395        write_object_term(q.object, out)?;
396        out.write_all(b" ")?;
397        write_iri_term(q.context, out)?;
398        out.write_all(b" .\n")?;
399    }
400    Ok(())
401}
402
403/// RDF-Star N-Triples line (`<<<...>>>` subject when virtual id).
404pub fn format_ntriples_star_to<W: io::Write>(quins: &[NQuin], out: &mut W) -> io::Result<()> {
405    for q in quins {
406        write_ntriples_star_line(q, out)?;
407    }
408    Ok(())
409}
410
411#[inline]
412fn write_ntriple_line<W: io::Write>(q: &NQuin, out: &mut W) -> io::Result<()> {
413    write_iri_term(q.subject, out)?;
414    out.write_all(b" ")?;
415    write_iri_term(q.predicate, out)?;
416    out.write_all(b" ")?;
417    write_object_term(q.object, out)?;
418    out.write_all(b" .\n")
419}
420
421#[inline]
422fn write_ntriples_star_line<W: io::Write>(q: &NQuin, out: &mut W) -> io::Result<()> {
423    if crate::rdf_star::is_virtual_id(q.subject) {
424        out.write_all(b"<<<")?;
425        write_iri_term(q.subject, out)?;
426        out.write_all(b">>> ")?;
427    } else {
428        write_iri_term(q.subject, out)?;
429        out.write_all(b" ")?;
430    }
431    write_iri_term(q.predicate, out)?;
432    out.write_all(b" ")?;
433    write_object_term(q.object, out)?;
434    out.write_all(b" .\n")
435}
436
437// ---------------------------------------------------------------------------
438// Tests
439// ---------------------------------------------------------------------------
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444
445    fn quin(s: u64, p: u64, o: u64) -> NQuin {
446        NQuin {
447            subject: s,
448            predicate: p,
449            object: o,
450            context: 0,
451            metadata: 0,
452            parity: 0,
453        }
454    }
455
456    fn render(quins: &[NQuin]) -> String {
457        let mut buf = Vec::new();
458        format_ntriples_to(quins, &mut buf).unwrap();
459        String::from_utf8(buf).unwrap()
460    }
461
462    // --- resolve_hash -------------------------------------------------------
463
464    #[test]
465    fn known_hash_resolves_to_uri() {
466        let hash = crate::q_hash("Alice");
467        let result = resolve_hash(hash).unwrap();
468        assert_eq!(result, b"http://webizen.org/demo/Alice");
469    }
470
471    #[test]
472    fn unknown_hash_returns_none() {
473        assert!(resolve_hash(0xDEAD_BEEF_1234_5678).is_none());
474    }
475
476    #[test]
477    fn topological_pointer_returns_none() {
478        let ptr = crate::q_hash("z6Mk") | (1u64 << 63);
479        assert!(resolve_hash(ptr).is_none());
480    }
481
482    // --- write_iri_term / write_object_term ---------------------------------
483
484    #[test]
485    fn known_iri_rendered_with_angle_brackets() {
486        let mut buf = Vec::new();
487        write_iri_term(crate::q_hash("Alice"), &mut buf).unwrap();
488        assert_eq!(buf, b"<http://webizen.org/demo/Alice>");
489    }
490
491    #[test]
492    fn unknown_hash_fallback_is_hex() {
493        let mut buf = Vec::new();
494        write_iri_term(0x00_00_00_00_00_00_00_2A, &mut buf).unwrap();
495        // value 42 decimal = 0x2a hex
496        assert_eq!(buf, b"<quin:hash/000000000000002a>");
497    }
498
499    #[test]
500    fn topological_pointer_renders_as_did_q42_ptr() {
501        let val = 42u64 | (1u64 << 63);
502        let mut buf = Vec::new();
503        write_iri_term(val, &mut buf).unwrap();
504        let s = String::from_utf8(buf).unwrap();
505        assert!(s.starts_with("<did:q42:ptr/"), "got: {s}");
506    }
507
508    #[test]
509    fn inline_integer_object() {
510        let val = INLINE_TAG_INTEGER | 99;
511        let mut buf = Vec::new();
512        write_object_term(val, &mut buf).unwrap();
513        let s = String::from_utf8(buf).unwrap();
514        assert_eq!(s, "\"99\"^^<http://www.w3.org/2001/XMLSchema#integer>");
515    }
516
517    #[test]
518    fn inline_boolean_true() {
519        let val = INLINE_TAG_BOOLEAN | 1;
520        let mut buf = Vec::new();
521        write_object_term(val, &mut buf).unwrap();
522        assert_eq!(
523            String::from_utf8(buf).unwrap(),
524            "\"true\"^^<http://www.w3.org/2001/XMLSchema#boolean>"
525        );
526    }
527
528    #[test]
529    fn inline_boolean_false() {
530        let val = INLINE_TAG_BOOLEAN | 0;
531        let mut buf = Vec::new();
532        write_object_term(val, &mut buf).unwrap();
533        assert_eq!(
534            String::from_utf8(buf).unwrap(),
535            "\"false\"^^<http://www.w3.org/2001/XMLSchema#boolean>"
536        );
537    }
538
539    #[test]
540    fn inline_decimal_object() {
541        // Encode 3.141592 → raw = 3_141_592
542        let val = INLINE_TAG_DECIMAL | 3_141_592u64;
543        let mut buf = Vec::new();
544        write_object_term(val, &mut buf).unwrap();
545        assert_eq!(
546            String::from_utf8(buf).unwrap(),
547            "\"3.141592\"^^<http://www.w3.org/2001/XMLSchema#decimal>"
548        );
549    }
550
551    #[test]
552    fn inline_float_object() {
553        // Computed f32 values carry the 0b101 FLOAT tag (formerly squatted on INTEGER).
554        let val = INLINE_TAG_FLOAT | (3.5f32.to_bits() as u64);
555        let mut buf = Vec::new();
556        write_object_term(val, &mut buf).unwrap();
557        assert_eq!(
558            String::from_utf8(buf).unwrap(),
559            "\"3.5\"^^<http://www.w3.org/2001/XMLSchema#float>"
560        );
561        // Round-trips through the FrameLayout packer too.
562        let packed = crate::frame_layout::pack_float_object(3.5);
563        assert_eq!(
564            packed & crate::frame_layout::INLINE_TAG_MASK,
565            INLINE_TAG_FLOAT
566        );
567    }
568
569    #[test]
570    fn inline_negative_integer_object() {
571        let num = -42i64;
572        let unsigned = (num as u64) & INLINE_VALUE_MASK;
573        let val = INLINE_TAG_INTEGER | unsigned;
574        let mut buf = Vec::new();
575        write_object_term(val, &mut buf).unwrap();
576        assert_eq!(
577            String::from_utf8(buf).unwrap(),
578            "\"-42\"^^<http://www.w3.org/2001/XMLSchema#integer>"
579        );
580    }
581
582    #[test]
583    fn inline_negative_decimal_object() {
584        let num_f64 = -3.141592f64;
585        let num = (num_f64 * 1_000_000.0).round() as i64;
586        let unsigned = (num as u64) & INLINE_VALUE_MASK;
587        let val = INLINE_TAG_DECIMAL | unsigned;
588        let mut buf = Vec::new();
589        write_object_term(val, &mut buf).unwrap();
590        assert_eq!(
591            String::from_utf8(buf).unwrap(),
592            "\"-3.141592\"^^<http://www.w3.org/2001/XMLSchema#decimal>"
593        );
594    }
595
596    // --- format_ntriples_to -------------------------------------------------
597
598    #[test]
599    fn empty_slice_writes_nothing() {
600        assert_eq!(render(&[]), "");
601    }
602
603    #[test]
604    fn known_terms_resolve_to_iris() {
605        let q = quin(
606            crate::q_hash("Alice"),
607            crate::q_hash("knows"),
608            crate::q_hash("Bob"),
609        );
610        let out = render(&[q]);
611        assert!(
612            out.contains("<http://webizen.org/demo/Alice>"),
613            "got: {out}"
614        );
615        assert!(out.contains("<http://schema.org/knows>"), "got: {out}");
616        assert!(out.contains("<http://webizen.org/demo/Bob>"), "got: {out}");
617        assert!(out.ends_with(" .\n"));
618    }
619
620    #[test]
621    fn unknown_terms_use_hex_fallback() {
622        let q = quin(1, 2, 3);
623        let out = render(&[q]);
624        assert!(out.contains("<quin:hash/0000000000000001>"), "got: {out}");
625        assert!(out.contains("<quin:hash/0000000000000002>"), "got: {out}");
626        assert!(out.contains("<quin:hash/0000000000000003>"), "got: {out}");
627    }
628
629    #[test]
630    fn multiple_quins_produce_multiple_lines() {
631        let qs = [quin(1, 2, 3), quin(4, 5, 6)];
632        let out = render(&qs);
633        assert_eq!(out.lines().count(), 2);
634    }
635
636    #[test]
637    fn subject_msb_renders_as_topological_pointer() {
638        // A subject with MSB=1 is a did:q42 coordinate — not a nested-hash lookup.
639        let q = quin((1u64 << 63) | 42, 2, 3);
640        let out = render(&[q]);
641        assert!(out.starts_with("<did:q42:ptr/"), "got: {out}");
642    }
643}