Skip to main content

qualia_core_db/sparql_library/parsers/
turtle_star.rs

1//! Turtle-Star Parser for QualiaDB
2//!
3//! Implements RDF-Star (SPARQL 1.2) parsing for Turtle syntax with embedded triples.
4//! Stack-based state machine for zero-allocation handling of deeply nested structures.
5//!
6//! Architecture:
7//! - Fixed-size stack array [StackFrame; 16] for nested embedded triples
8//! - No heap allocations in hot path
9//! - Virtual IDs minted via generate_embedded_triple_id()
10//! - Context stored separately in NQuin field (not in Virtual ID hash)
11
12use crate::lexicon::{generate_60bit_token, generate_embedded_triple_id};
13use crate::rdf_star::{RdfStarParseError, RdfStarParser};
14use crate::NQuin;
15use std::io::{BufRead, BufReader, Read};
16
17/// Maximum nesting depth for embedded triples
18const MAX_NESTING_DEPTH: usize = 16;
19
20/// Parsing state for a single frame
21#[repr(C)]
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23enum ParsingState {
24    ExpectSubject,
25    ExpectPredicate,
26    ExpectObject,
27    ExpectEmbeddedEnd,
28}
29
30/// Stack frame for tracking nested embedded triple parsing
31#[repr(C)]
32#[derive(Debug, Clone, Copy)]
33struct StackFrame {
34    subject: Option<u64>,
35    predicate: Option<u64>,
36    object: Option<u64>,
37    parsing_state: ParsingState,
38}
39
40impl StackFrame {
41    /// Empty frame awaiting a subject token.
42    fn new() -> Self {
43        Self {
44            subject: None,
45            predicate: None,
46            object: None,
47            parsing_state: ParsingState::ExpectSubject,
48        }
49    }
50}
51
52/// Zero-allocation parser stack
53#[repr(C)]
54struct ParserStack {
55    frames: [StackFrame; MAX_NESTING_DEPTH],
56    depth: usize,
57}
58
59impl ParserStack {
60    /// Empty fixed-size stack of `MAX_NESTING_DEPTH` frames.
61    fn new() -> Self {
62        Self {
63            frames: [StackFrame::new(); MAX_NESTING_DEPTH],
64            depth: 0,
65        }
66    }
67
68    /// Push a frame; `BufferOverflow` past `MAX_NESTING_DEPTH`.
69    fn push(&mut self, frame: StackFrame) -> Result<(), RdfStarParseError> {
70        if self.depth >= MAX_NESTING_DEPTH {
71            return Err(RdfStarParseError::BufferOverflow);
72        }
73        self.frames[self.depth] = frame;
74        self.depth += 1;
75        Ok(())
76    }
77
78    /// Pop the top frame, or `None` when empty.
79    fn pop(&mut self) -> Option<StackFrame> {
80        if self.depth == 0 {
81            return None;
82        }
83        self.depth -= 1;
84        Some(self.frames[self.depth])
85    }
86
87    /// Mutable borrow of the top frame — caller must ensure non-empty.
88    fn current(&mut self) -> &mut StackFrame {
89        &mut self.frames[self.depth - 1]
90    }
91
92    /// Whether no frames are in flight.
93    fn is_empty(&self) -> bool {
94        self.depth == 0
95    }
96
97    /// Current nesting depth (frames pushed).
98    fn depth(&self) -> usize {
99        self.depth
100    }
101}
102
103/// Turtle-Star parser implementation
104pub struct TurtleStarParser {
105    /// Context hash for the current parsing session
106    context_hash: u64,
107    /// Stack for nested embedded triple parsing
108    stack: ParserStack,
109}
110
111impl TurtleStarParser {
112    /// Create a new Turtle-Star parser
113    pub fn new(context_hash: u64) -> Self {
114        Self {
115            context_hash,
116            stack: ParserStack::new(),
117        }
118    }
119
120    /// Session context hash stamped onto emitted quads.
121    pub fn session_context(&self) -> u64 {
122        self.context_hash
123    }
124
125    /// Whether the embedded-triple stack is empty (no in-flight `<<` frames).
126    pub fn stack_is_empty(&self) -> bool {
127        self.stack.is_empty()
128    }
129
130    /// Advance `frame` from `expected` to `next`, or
131    /// `MalformedEmbeddedTriple` when the token order is wrong.
132    fn expect_state(
133        frame: &mut StackFrame,
134        expected: ParsingState,
135        next: ParsingState,
136    ) -> Result<(), RdfStarParseError> {
137        if frame.parsing_state != expected {
138            return Err(RdfStarParseError::MalformedEmbeddedTriple);
139        }
140        frame.parsing_state = next;
141        Ok(())
142    }
143
144    /// Parse a Turtle-Star token (IRI, literal, or delimiter)
145    ///
146    /// Returns Ok(Some(hash)) for valid IRIs/literals, Ok(None) for delimiters
147    fn parse_token(&self, input: &[u8], pos: &mut usize) -> Result<Option<u64>, RdfStarParseError> {
148        let bytes = &input[*pos..];
149
150        // Skip whitespace
151        let mut start = 0;
152        while start < bytes.len() && bytes[start].is_ascii_whitespace() {
153            start += 1;
154        }
155
156        if start >= bytes.len() {
157            return Ok(None);
158        }
159
160        let ch = bytes[start];
161
162        // Check for embedded triple start
163        if ch == b'<' && start + 1 < bytes.len() && bytes[start + 1] == b'<' {
164            *pos += start + 2;
165            return Ok(None); // Signal embedded triple start
166        }
167
168        // Check for embedded triple end
169        if ch == b'>' && start + 1 < bytes.len() && bytes[start + 1] == b'>' {
170            *pos += start + 2;
171            return Ok(None); // Signal embedded triple end
172        }
173
174        // Check for statement terminator
175        if ch == b'.' {
176            *pos += start + 1;
177            return Ok(None);
178        }
179
180        // Check for semicolon (predicate separator in Turtle)
181        if ch == b';' {
182            *pos += start + 1;
183            return Ok(None);
184        }
185
186        // Parse IRI or literal (simplified - proper Turtle would have <> delimiters)
187        let mut end = start;
188        while end < bytes.len()
189            && !bytes[end].is_ascii_whitespace()
190            && bytes[end] != b'.'
191            && bytes[end] != b';'
192        {
193            end += 1;
194        }
195
196        if start == end {
197            return Ok(None);
198        }
199
200        *pos += end;
201
202        // Hash the token
203        let token =
204            std::str::from_utf8(&bytes[start..end]).map_err(|_| RdfStarParseError::InvalidUtf8)?;
205        let hash = generate_60bit_token(token.as_bytes());
206
207        Ok(Some(hash))
208    }
209
210    /// Parse an embedded triple using stack-based state machine
211    fn parse_embedded_triple_internal(
212        &mut self,
213        input: &[u8],
214        pos: &mut usize,
215    ) -> Result<(u64, [u64; 3]), RdfStarParseError> {
216        // Push new frame for embedded triple
217        let frame = StackFrame::new();
218        self.stack.push(frame)?;
219
220        let _start_depth = self.stack.depth();
221
222        // Parse subject
223        {
224            let frame = self.stack.current();
225            Self::expect_state(
226                frame,
227                ParsingState::ExpectSubject,
228                ParsingState::ExpectPredicate,
229            )?;
230        }
231        while *pos < input.len() && input[*pos].is_ascii_whitespace() {
232            *pos += 1;
233        }
234        if *pos + 1 < input.len() && input[*pos] == b'<' && input[*pos + 1] == b'<' {
235            *pos += 2; // skip <<
236            let (hash, _) = self.parse_embedded_triple_internal(input, pos)?;
237            self.stack.current().subject = Some(hash);
238        } else {
239            match self.parse_token(input, pos)? {
240                Some(hash) => self.stack.current().subject = Some(hash),
241                None => return Err(RdfStarParseError::MalformedEmbeddedTriple),
242            }
243        }
244
245        // Parse predicate
246        {
247            let frame = self.stack.current();
248            Self::expect_state(
249                frame,
250                ParsingState::ExpectPredicate,
251                ParsingState::ExpectObject,
252            )?;
253        }
254        match self.parse_token(input, pos)? {
255            Some(hash) => self.stack.current().predicate = Some(hash),
256            None => return Err(RdfStarParseError::MalformedEmbeddedTriple),
257        }
258
259        // Parse object (could be another embedded triple)
260        {
261            let frame = self.stack.current();
262            Self::expect_state(
263                frame,
264                ParsingState::ExpectObject,
265                ParsingState::ExpectEmbeddedEnd,
266            )?;
267        }
268        while *pos < input.len() && input[*pos].is_ascii_whitespace() {
269            *pos += 1;
270        }
271        if *pos + 1 < input.len() && input[*pos] == b'<' && input[*pos + 1] == b'<' {
272            *pos += 2; // skip <<
273            let (hash, _) = self.parse_embedded_triple_internal(input, pos)?;
274            self.stack.current().object = Some(hash);
275        } else {
276            match self.parse_token(input, pos)? {
277                Some(hash) => self.stack.current().object = Some(hash),
278                None => {
279                    return Err(RdfStarParseError::MalformedEmbeddedTriple);
280                }
281            }
282        }
283
284        // Expect >> terminator
285        {
286            let frame = self.stack.current();
287            Self::expect_state(
288                frame,
289                ParsingState::ExpectEmbeddedEnd,
290                ParsingState::ExpectSubject,
291            )?;
292        }
293        while *pos + 1 < input.len() && input[*pos].is_ascii_whitespace() {
294            *pos += 1;
295        }
296        if *pos + 1 >= input.len() || input[*pos] != b'>' || input[*pos + 1] != b'>' {
297            return Err(RdfStarParseError::MalformedEmbeddedTriple);
298        }
299        *pos += 2;
300
301        // Pop frame and get components
302        if !self.stack.is_empty() && self.stack.depth() > 1 {
303            // Nested frames remain for future recursive `<<` support.
304        }
305        let frame = self
306            .stack
307            .pop()
308            .ok_or(RdfStarParseError::MalformedEmbeddedTriple)?;
309
310        let subject = frame
311            .subject
312            .ok_or(RdfStarParseError::MalformedEmbeddedTriple)?;
313        let predicate = frame
314            .predicate
315            .ok_or(RdfStarParseError::MalformedEmbeddedTriple)?;
316        let object = frame
317            .object
318            .ok_or(RdfStarParseError::MalformedEmbeddedTriple)?;
319
320        // Generate Virtual ID (context-independent per architectural decision)
321        let virtual_id = generate_embedded_triple_id(subject, predicate, object);
322
323        Ok((virtual_id, [subject, predicate, object]))
324    }
325
326    /// Parse a full Turtle-Star annotation statement: `<< s p o >> annP annO [.]`.
327    ///
328    /// Returns `(virtual_id, [s,p,o], Option<(ann_predicate, ann_object)>)`. Unlike
329    /// `parse_embedded_triple` (which stops at `>>` and drops everything after),
330    /// this captures the outer predicate/object when present, so the caller can
331    /// emit the linking statement `virtual_id annP annO` — reaching parity with
332    /// the N-Quads-Star parser. A single parse pass handles both the annotated
333    /// and the bare-embedded-triple cases (the latter yields `None` for the
334    /// annotation), so there is no stateful re-parse of the same line.
335    fn parse_star_annotation(
336        &mut self,
337        input: &[u8],
338    ) -> Result<(u64, [u64; 3], Option<(u64, u64)>), RdfStarParseError> {
339        let mut pos = 0;
340        while pos < input.len() && input[pos].is_ascii_whitespace() {
341            pos += 1;
342        }
343        if pos + 1 < input.len() && input[pos] == b'<' && input[pos + 1] == b'<' {
344            pos += 2;
345        } else {
346            return Err(RdfStarParseError::MalformedEmbeddedTriple);
347        }
348        let (virtual_id, components) = self.parse_embedded_triple_internal(input, &mut pos)?;
349        // Outer predicate + object are optional: a line may be a bare `<< s p o >>`.
350        let annotation = match self.parse_token(input, &mut pos)? {
351            Some(ann_predicate) => self
352                .parse_token(input, &mut pos)?
353                .map(|ann_object| (ann_predicate, ann_object)),
354            None => None,
355        };
356        Ok((virtual_id, components, annotation))
357    }
358}
359
360impl RdfStarParser for TurtleStarParser {
361    /// Parse one `<< s p o >>` embedded triple (leading `<<` optional),
362    /// returning the minted virtual ID and its component hashes.
363    fn parse_embedded_triple(
364        &mut self,
365        input: &[u8],
366    ) -> Result<(u64, [u64; 3]), RdfStarParseError> {
367        let mut pos = 0;
368        while pos < input.len() && input[pos].is_ascii_whitespace() {
369            pos += 1;
370        }
371        if pos + 1 < input.len() && input[pos] == b'<' && input[pos + 1] == b'<' {
372            pos += 2;
373        }
374        self.parse_embedded_triple_internal(input, &mut pos)
375    }
376
377    /// Parse one Turtle-Star statement into `(subject, predicate,
378    /// object)` hashes; `<<…>>` terms are minted as virtual IDs.
379    /// `InvalidSyntax` on missing terms.
380    fn parse_triple(&mut self, input: &[u8]) -> Result<(u64, u64, u64), RdfStarParseError> {
381        let mut pos = 0;
382
383        let skip_ws = |p: &mut usize| {
384            while *p < input.len() && input[*p].is_ascii_whitespace() {
385                *p += 1;
386            }
387        };
388
389        skip_ws(&mut pos);
390        let subject = if pos + 1 < input.len() && input[pos] == b'<' && input[pos + 1] == b'<' {
391            pos += 2; // skip <<
392            let (hash, _) = self.parse_embedded_triple_internal(input, &mut pos)?;
393            // parse_token might have stopped at '>>'
394            // skip '>>'
395            skip_ws(&mut pos);
396            if pos + 1 < input.len() && input[pos] == b'>' && input[pos + 1] == b'>' {
397                pos += 2;
398            }
399            hash
400        } else {
401            match self.parse_token(input, &mut pos)? {
402                Some(h) => h,
403                None => return Err(RdfStarParseError::InvalidSyntax),
404            }
405        };
406
407        skip_ws(&mut pos);
408        let predicate = match self.parse_token(input, &mut pos)? {
409            Some(h) => h,
410            None => return Err(RdfStarParseError::InvalidSyntax),
411        };
412
413        skip_ws(&mut pos);
414        let object = if pos + 1 < input.len() && input[pos] == b'<' && input[pos + 1] == b'<' {
415            pos += 2; // skip <<
416            let (hash, _) = self.parse_embedded_triple_internal(input, &mut pos)?;
417            skip_ws(&mut pos);
418            if pos + 1 < input.len() && input[pos] == b'>' && input[pos + 1] == b'>' {
419                pos += 2;
420            }
421            hash
422        } else {
423            match self.parse_token(input, &mut pos)? {
424                Some(h) => h,
425                None => return Err(RdfStarParseError::InvalidSyntax),
426            }
427        };
428
429        // The object is the final token; this parser returns the triple, not the cursor,
430        // so `pos`'s final position is intentionally not propagated past here.
431        let _ = pos;
432        Ok((subject, predicate, object))
433    }
434
435    /// Always `UnsupportedFeature` — Turtle-Star has no quads
436    /// (TriG-Star handles named graphs).
437    fn parse_quad(&mut self, _input: &[u8]) -> Result<(u64, u64, u64, u64), RdfStarParseError> {
438        // Turtle-Star doesn't support quads natively (use Trig-Star for that)
439        Err(RdfStarParseError::UnsupportedFeature)
440    }
441
442    /// `false` — no quad support in Turtle-Star.
443    fn supports_quads(&self) -> bool {
444        false
445    }
446
447    /// `false` — no named-graph support.
448    fn supports_named_graphs(&self) -> bool {
449        false
450    }
451
452    /// `"Turtle-Star"`.
453    fn format_name(&self) -> &'static str {
454        "Turtle-Star"
455    }
456}
457
458/// Legacy function for backward compatibility with existing ingest pipeline
459///
460/// TODO: This should be refactored to use the RdfStarParser trait properly
461/// and integrate with the lexicon writing layer for 24-byte embedded triple storage.
462pub fn parse_turtle_star_into<R: Read, S: crate::sparql_library::quin_sink::QuinSink>(
463    reader: R,
464    context_hash: u64,
465    sink: &mut S,
466) -> Result<u64, Box<dyn std::error::Error>> {
467    let mut parser = TurtleStarParser::new(context_hash);
468    let mut count = 0;
469    let buf_reader = BufReader::new(reader);
470
471    for line in buf_reader.lines() {
472        let line = line?;
473        let l = line.trim();
474        if l.is_empty() || l.starts_with('#') || l.starts_with('@') {
475            continue;
476        }
477
478        // Convert to bytes for parser
479        let bytes = l.as_bytes();
480
481        // Check if line contains embedded triple marker
482        if l.contains("<<") {
483            // Parse the full annotation form `<< s p o >> annP annO` in one pass.
484            if let Ok((virtual_id, components, annotation)) = parser.parse_star_annotation(bytes) {
485                // Linking statement: the quoted triple's virtual id is the subject
486                // of the outer annotation (parity with the N-Quads-Star parser).
487                // This is what lets `lookup_embedded_triple` — and hence the
488                // result serializer — resolve `<<s p o>>` instead of falling back
489                // to a raw `<<{hex}>>` placeholder. Bare `<< s p o >>` lines with
490                // no outer predicate/object yield `None` and just emit the inner
491                // triple, as before.
492                if let Some((ann_predicate, ann_object)) = annotation {
493                    sink.push(NQuin {
494                        subject: virtual_id,
495                        predicate: ann_predicate,
496                        object: ann_object,
497                        context: context_hash,
498                        metadata: 0b10 << 61,
499                        parity: 0,
500                    })?;
501                    count += 1;
502                }
503
504                // Inner triple (its components), so the quoted triple is itself
505                // a real, queryable statement in the graph.
506                sink.push(NQuin {
507                    subject: components[0],
508                    predicate: components[1],
509                    object: components[2],
510                    context: context_hash, // Context in NQuin field, not Virtual ID
511                    metadata: 0b10 << 61,
512                    parity: 0,
513                })?;
514                count += 1;
515
516                // NOTE: the durable `virtual_id -> [s,p,o]` lexicon entry
517                // (`LexiconEntry::EmbeddedTriple`) is written by the volume
518                // builder (`q42/q42_volume.rs`), which now sees the virtual id via
519                // the linking statement above; the streaming sink itself has no
520                // embedded-entry channel yet (a future expansion).
521            }
522        } else {
523            // Parse regular triple
524            if let Ok((subject, predicate, object)) = parser.parse_triple(bytes) {
525                sink.push(NQuin {
526                    subject,
527                    predicate,
528                    object,
529                    context: context_hash,
530                    metadata: 0b10 << 61,
531                    parity: 0,
532                })?;
533                count += 1;
534            }
535        }
536    }
537
538    Ok(count)
539}
540
541/// Streaming Turtle-Star ingest — reads statements from `reader`,
542/// emits quins into `sorter` under `context_hash`, and returns the
543/// quin count. Thin shim over [`parse_turtle_star_into`].
544pub fn parse_turtle_star_stream<R: Read>(
545    reader: R,
546    context_hash: u64,
547    sorter: &mut crate::external_sort::ExternalSorter,
548) -> Result<u64, Box<dyn std::error::Error>> {
549    parse_turtle_star_into(reader, context_hash, sorter)
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555    use crate::rdf_star::RdfStarParser;
556
557    #[test]
558    fn test_turtle_star_parser_creation() {
559        let parser = TurtleStarParser::new(0);
560        assert_eq!(parser.format_name(), "Turtle-Star");
561        assert!(!parser.supports_quads());
562        assert!(!parser.supports_named_graphs());
563        assert_eq!(parser.stack.depth(), 0);
564    }
565
566    #[test]
567    fn test_parser_stack_push_pop() {
568        let mut stack = ParserStack::new();
569        assert!(stack.is_empty());
570
571        let frame = StackFrame::new();
572        stack.push(frame).unwrap();
573        assert_eq!(stack.depth(), 1);
574        assert!(!stack.is_empty());
575
576        let popped = stack.pop();
577        assert!(popped.is_some());
578        assert!(stack.is_empty());
579    }
580
581    #[test]
582    fn test_parser_stack_overflow() {
583        let mut stack = ParserStack::new();
584        let frame = StackFrame::new();
585
586        // Fill to capacity
587        for _ in 0..MAX_NESTING_DEPTH {
588            stack.push(frame).unwrap();
589        }
590
591        // Should overflow
592        assert!(stack.push(frame).is_err());
593    }
594
595    #[test]
596    fn test_parse_simple_triple() {
597        let mut parser = TurtleStarParser::new(0);
598        let input = b"Alice knows Bob";
599        let result = parser.parse_triple(input);
600        assert!(result.is_ok());
601        let (s, p, o) = result.unwrap();
602        assert_ne!(s, 0);
603        assert_ne!(p, 0);
604        assert_ne!(o, 0);
605    }
606
607    #[test]
608    fn test_parse_embedded_triple() {
609        let mut parser = TurtleStarParser::new(0);
610        let input = b"<< Alice knows Bob >>"; // Simplified for testing
611        let result = parser.parse_embedded_triple(input);
612        assert!(result.is_ok());
613        let (virtual_id, components) = result.unwrap();
614        assert_ne!(virtual_id, 0);
615        assert_ne!(components[0], 0);
616        assert_ne!(components[1], 0);
617        assert_ne!(components[2], 0);
618
619        // Verify stack was properly managed
620        assert_eq!(parser.stack.depth(), 0);
621    }
622
623    struct VecSink(Vec<NQuin>);
624    impl crate::sparql_library::quin_sink::QuinSink for VecSink {
625        fn push(&mut self, q: NQuin) -> std::io::Result<()> {
626            self.0.push(q);
627            Ok(())
628        }
629    }
630
631    #[test]
632    fn parse_star_annotation_captures_outer_predicate_object() {
633        let mut parser = TurtleStarParser::new(0);
634        let (virtual_id, components, ann) = parser
635            .parse_star_annotation(b"<< Alice knows Bob >> certainty high")
636            .unwrap();
637        assert_eq!(
638            virtual_id,
639            generate_embedded_triple_id(components[0], components[1], components[2])
640        );
641        let (ann_p, ann_o) = ann.expect("outer annotation predicate/object");
642        assert_ne!(ann_p, 0);
643        assert_ne!(ann_o, 0);
644        assert_eq!(parser.stack.depth(), 0);
645    }
646
647    #[test]
648    fn parse_turtle_star_into_emits_linking_statement_and_inner_triple() {
649        let mut sink = VecSink(Vec::new());
650        let count =
651            parse_turtle_star_into(&b"<< Alice knows Bob >> certainty high\n"[..], 0, &mut sink)
652                .unwrap();
653        assert_eq!(count, 2, "expected outer linking statement + inner triple");
654        // sink[0] is the outer statement; its subject must be the virtual id of
655        // the inner triple (sink[1]) so lookup_embedded_triple can resolve it.
656        let inner = sink.0[1];
657        let vid = generate_embedded_triple_id(inner.subject, inner.predicate, inner.object);
658        assert_eq!(sink.0[0].subject, vid);
659    }
660
661    #[test]
662    fn parse_turtle_star_into_bare_embedded_triple_emits_only_inner() {
663        let mut sink = VecSink(Vec::new());
664        let count = parse_turtle_star_into(&b"<< Alice knows Bob >>\n"[..], 0, &mut sink).unwrap();
665        assert_eq!(count, 1, "bare embedded triple → just the inner triple");
666    }
667
668    #[test]
669    fn test_virtual_id_context_independence() {
670        use crate::lexicon::TAG_EMBEDDED;
671
672        // Same triple should generate same Virtual ID regardless of context
673        let context1 = 12345u64;
674        let context2 = 67890u64;
675
676        let mut parser1 = TurtleStarParser::new(context1);
677        let mut parser2 = TurtleStarParser::new(context2);
678
679        let input = b"<< Alice knows Bob >>";
680        let (vid1, _) = parser1.parse_embedded_triple(input).unwrap();
681        let (vid2, _) = parser2.parse_embedded_triple(input).unwrap();
682
683        assert_eq!(vid1, vid2, "Virtual ID should be context-independent");
684        assert_ne!(vid1 & TAG_EMBEDDED, 0, "TAG_EMBEDDED bit should be set");
685    }
686}
687
688/// Turtle-Star Serializer
689///
690/// Converts Virtual IDs and component hashes back to Turtle-Star syntax.
691// ---------------------------------------------------------------------------
692// Shared term-resolution helpers for the RDF-Star text serializers.
693//
694// Every text serializer below previously emitted the raw u64 term *hash* as a
695// decimal number (e.g. `<1> <2> <3> .`), which is not valid RDF and cannot be
696// consumed by any RDF tool — and the quoted-triple form used a non-standard,
697// non-round-tripping `<<<…>>>` (the parser reads `<<…>>`). These resolve each
698// hash to its real surface form through the same resolver used by the
699// N-Triples fast path: subjects/predicates as `<iri>` (or a `did:q42:ptr/…`
700// pointer), objects additionally distinguishing inline-typed literals
701// (`"42"^^<…#integer>`).
702// ---------------------------------------------------------------------------
703
704/// Resolve a subject/predicate term to its bracketed surface form.
705fn star_iri_term(val: u64) -> String {
706    let mut buf = Vec::new();
707    let _ = crate::query::resolver::write_iri_term(val, &mut buf);
708    String::from_utf8_lossy(&buf).into_owned()
709}
710
711/// Resolve an object term, distinguishing inline-typed literals from IRIs.
712fn star_object_term(val: u64) -> String {
713    let mut buf = Vec::new();
714    let _ = crate::query::resolver::write_object_term(val, &mut buf);
715    String::from_utf8_lossy(&buf).into_owned()
716}
717
718/// Resolve a term to a bare IRI string (no angle brackets), for JSON-LD.
719fn star_iri_bare(val: u64) -> String {
720    if let Some(bytes) = crate::resolver::resolve_hash(val) {
721        String::from_utf8_lossy(bytes).into_owned()
722    } else if (val & crate::resolver::MSB_FLAG) != 0 {
723        format!("did:q42:ptr/{:016x}", val & !crate::resolver::MSB_FLAG)
724    } else {
725        format!("quin:hash/{val:016x}")
726    }
727}
728
729/// Minimal JSON string escaping.
730fn star_json_escape(s: &str) -> String {
731    let mut out = String::with_capacity(s.len() + 2);
732    for c in s.chars() {
733        match c {
734            '"' => out.push_str("\\\""),
735            '\\' => out.push_str("\\\\"),
736            '\n' => out.push_str("\\n"),
737            '\r' => out.push_str("\\r"),
738            '\t' => out.push_str("\\t"),
739            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
740            c => out.push(c),
741        }
742    }
743    out
744}
745
746/// Resolve an object term as a JSON-LD value node (`{"@id": …}` for IRIs,
747/// `{"@value": …, "@type": …}` for inline-typed literals). Lexicon-first, to
748/// match `write_object_term`.
749fn star_object_jsonld(val: u64) -> String {
750    if crate::resolver::resolve_hash(val).is_some() || (val & crate::resolver::MSB_FLAG) != 0 {
751        return format!(
752            r#"{{ "@id": "{}" }}"#,
753            star_json_escape(&star_iri_bare(val))
754        );
755    }
756    if let Some(lit) = crate::resolver::classify_inline_literal(val) {
757        return format!(
758            r#"{{ "@value": "{}", "@type": "{}" }}"#,
759            star_json_escape(&lit.to_string()),
760            star_json_escape(lit.datatype_iri())
761        );
762    }
763    format!(
764        r#"{{ "@id": "{}" }}"#,
765        star_json_escape(&star_iri_bare(val))
766    )
767}
768
769pub struct TurtleStarSerializer;
770
771impl TurtleStarSerializer {
772    /// Creates a default `TurtleStarSerializer`.
773    pub fn new() -> Self {
774        Self
775    }
776}
777
778impl crate::rdf_star::RdfStarSerializer for TurtleStarSerializer {
779    fn serialize_embedded_triple(
780        &self,
781        _virtual_id: u64,
782        components: &[u64; 3],
783    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
784        // Quoted triple: << <s> <p> o >> with resolved terms.
785        let output = format!(
786            "<< {} {} {} >>",
787            star_iri_term(components[0]),
788            star_iri_term(components[1]),
789            star_object_term(components[2])
790        );
791        Ok(output.into_bytes())
792    }
793
794    fn serialize_triple(
795        &self,
796        subject: u64,
797        predicate: u64,
798        object: u64,
799    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
800        let output = format!(
801            "{} {} {} .",
802            star_iri_term(subject),
803            star_iri_term(predicate),
804            star_object_term(object)
805        );
806        Ok(output.into_bytes())
807    }
808
809    fn serialize_quad(
810        &self,
811        _subject: u64,
812        _predicate: u64,
813        _object: u64,
814        _graph: u64,
815    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
816        // Turtle-Star doesn't support quads natively
817        Err(crate::rdf_star::RdfStarSerializeError::UnsupportedFeature)
818    }
819
820    fn supports_quads(&self) -> bool {
821        false
822    }
823
824    fn format_name(&self) -> &'static str {
825        "Turtle-Star"
826    }
827}
828
829/// CBOR-LD Serializer for SPARQL-Star
830///
831/// Implements CBOR-LD tags 103-106 for embedded triples per the RDF-Star CBOR-LD spec:
832/// - Tag 103: Triple (`<<s p o>>`)
833/// - Tag 104: Subject (s of `<<s p o>>`)
834/// - Tag 105: Predicate (p of `<<s p o>>`)
835/// - Tag 106: Object (o of `<<s p o>>`)
836pub struct CborLdStarSerializer;
837
838impl CborLdStarSerializer {
839    /// Builds a CBOR-LD* serializer.
840    pub fn new() -> Self {
841        Self
842    }
843}
844
845impl crate::rdf_star::RdfStarSerializer for CborLdStarSerializer {
846    fn serialize_embedded_triple(
847        &self,
848        _virtual_id: u64,
849        components: &[u64; 3],
850    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
851        // CBOR-LD Tag 103: Triple
852        // Format: 103(3-array of [subject, predicate, object])
853        use ciborium::ser;
854
855        let mut buffer = Vec::new();
856        let tagged = ciborium::tag::Required::<[u64; 3], 103>(*components);
857        ser::into_writer(&tagged, &mut buffer)
858            .map_err(|_| crate::rdf_star::RdfStarSerializeError::BufferTooSmall)?;
859
860        Ok(buffer)
861    }
862
863    fn serialize_triple(
864        &self,
865        subject: u64,
866        predicate: u64,
867        object: u64,
868    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
869        use ciborium::ser;
870        let mut buffer = Vec::new();
871        ser::into_writer(&[subject, predicate, object], &mut buffer)
872            .map_err(|_| crate::rdf_star::RdfStarSerializeError::BufferTooSmall)?;
873        Ok(buffer)
874    }
875
876    fn serialize_quad(
877        &self,
878        subject: u64,
879        predicate: u64,
880        object: u64,
881        graph: u64,
882    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
883        use ciborium::ser;
884        let mut buffer = Vec::new();
885        ser::into_writer(&[subject, predicate, object, graph], &mut buffer)
886            .map_err(|_| crate::rdf_star::RdfStarSerializeError::BufferTooSmall)?;
887        Ok(buffer)
888    }
889
890    fn supports_quads(&self) -> bool {
891        true
892    }
893
894    fn format_name(&self) -> &'static str {
895        "CBOR-LD-Star"
896    }
897}
898
899#[cfg(test)]
900mod cbor_serializer_tests {
901    use super::*;
902    use crate::rdf_star::RdfStarSerializer;
903
904    #[test]
905    fn test_cbor_serializer_creation() {
906        let serializer = CborLdStarSerializer::new();
907        assert_eq!(serializer.format_name(), "CBOR-LD-Star");
908        assert!(serializer.supports_quads());
909    }
910
911    #[test]
912    fn test_serialize_embedded_triple() {
913        let serializer = CborLdStarSerializer::new();
914        let components = [1u64, 2, 3];
915        let result = serializer.serialize_embedded_triple(0, &components);
916        assert!(result.is_ok());
917        let bytes = result.unwrap();
918        // CBOR tag 103 encodes as 0xd8 (major-type 6, one-byte follows) + 0x67 (value 103)
919        assert_eq!(bytes[0], 0xd8);
920        assert_eq!(bytes[1], 0x67);
921    }
922
923    #[test]
924    fn test_serialize_triple() {
925        let serializer = CborLdStarSerializer::new();
926        let result = serializer.serialize_triple(1, 2, 3);
927        assert!(result.is_ok());
928        let bytes = result.unwrap();
929        // Should be CBOR array of 3 integers
930        assert_eq!(bytes[0], 0x83); // Array of 3 in CBOR
931    }
932
933    #[test]
934    fn test_serialize_quad() {
935        let serializer = CborLdStarSerializer::new();
936        let result = serializer.serialize_quad(1, 2, 3, 4);
937        assert!(result.is_ok());
938        let bytes = result.unwrap();
939        // Should be CBOR array of 4 integers
940        assert_eq!(bytes[0], 0x84); // Array of 4 in CBOR
941    }
942}
943
944/// N-Triples-Star Serializer
945///
946/// Serializes to N-Triples-Star format: `<<<s p o>>> p o .`
947pub struct NTriplesStarSerializer;
948
949impl NTriplesStarSerializer {
950    /// Builds an N-Triples* serializer.
951    pub fn new() -> Self {
952        Self
953    }
954}
955
956impl crate::rdf_star::RdfStarSerializer for NTriplesStarSerializer {
957    fn serialize_embedded_triple(
958        &self,
959        _virtual_id: u64,
960        components: &[u64; 3],
961    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
962        // Quoted triple: << <s> <p> o >> with resolved terms (round-trips with
963        // the `<<`/`>>` parser).
964        let output = format!(
965            "<< {} {} {} >>",
966            star_iri_term(components[0]),
967            star_iri_term(components[1]),
968            star_object_term(components[2])
969        );
970        Ok(output.into_bytes())
971    }
972
973    fn serialize_triple(
974        &self,
975        subject: u64,
976        predicate: u64,
977        object: u64,
978    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
979        // Format: <subject> <predicate> <object> . (terms self-bracketing).
980        let output = format!(
981            "{} {} {} .",
982            star_iri_term(subject),
983            star_iri_term(predicate),
984            star_object_term(object)
985        );
986        Ok(output.into_bytes())
987    }
988
989    fn serialize_quad(
990        &self,
991        _subject: u64,
992        _predicate: u64,
993        _object: u64,
994        _graph: u64,
995    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
996        // N-Triples-Star doesn't support quads natively
997        Err(crate::rdf_star::RdfStarSerializeError::UnsupportedFeature)
998    }
999
1000    fn supports_quads(&self) -> bool {
1001        false
1002    }
1003
1004    fn format_name(&self) -> &'static str {
1005        "N-Triples-Star"
1006    }
1007}
1008
1009/// N-Quads-Star Serializer
1010///
1011/// Serializes to N-Quads-Star format: `<<<s p o>>> p o <g> .`
1012pub struct NQuadsStarSerializer;
1013
1014impl NQuadsStarSerializer {
1015    /// Builds an N-Quads* serializer.
1016    pub fn new() -> Self {
1017        Self
1018    }
1019}
1020
1021impl crate::rdf_star::RdfStarSerializer for NQuadsStarSerializer {
1022    fn serialize_embedded_triple(
1023        &self,
1024        _virtual_id: u64,
1025        components: &[u64; 3],
1026    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1027        // Quoted triple: << <s> <p> o >> with resolved terms.
1028        let output = format!(
1029            "<< {} {} {} >>",
1030            star_iri_term(components[0]),
1031            star_iri_term(components[1]),
1032            star_object_term(components[2])
1033        );
1034        Ok(output.into_bytes())
1035    }
1036
1037    fn serialize_triple(
1038        &self,
1039        subject: u64,
1040        predicate: u64,
1041        object: u64,
1042    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1043        // Format: <subject> <predicate> <object> . (graph omitted → default).
1044        let output = format!(
1045            "{} {} {} .",
1046            star_iri_term(subject),
1047            star_iri_term(predicate),
1048            star_object_term(object)
1049        );
1050        Ok(output.into_bytes())
1051    }
1052
1053    fn serialize_quad(
1054        &self,
1055        subject: u64,
1056        predicate: u64,
1057        object: u64,
1058        graph: u64,
1059    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1060        // Format: <subject> <predicate> <object> <graph> .
1061        let output = format!(
1062            "{} {} {} {} .",
1063            star_iri_term(subject),
1064            star_iri_term(predicate),
1065            star_object_term(object),
1066            star_iri_term(graph)
1067        );
1068        Ok(output.into_bytes())
1069    }
1070
1071    fn supports_quads(&self) -> bool {
1072        true
1073    }
1074
1075    fn format_name(&self) -> &'static str {
1076        "N-Quads-Star"
1077    }
1078}
1079
1080/// JSON-LD Serializer for SPARQL-Star
1081///
1082/// Serializes to JSON-LD format with @annotation for embedded triples.
1083pub struct JsonLdStarSerializer;
1084
1085impl JsonLdStarSerializer {
1086    /// Builds a JSON-LD* serializer.
1087    pub fn new() -> Self {
1088        Self
1089    }
1090}
1091
1092impl crate::rdf_star::RdfStarSerializer for JsonLdStarSerializer {
1093    fn serialize_embedded_triple(
1094        &self,
1095        _virtual_id: u64,
1096        components: &[u64; 3],
1097    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1098        // JSON-LD format with @annotation
1099        // {
1100        //   "@id": "_:b1",
1101        //   "@annotation": {
1102        //     "@id": "_:b2",
1103        //     "@type": "@id",
1104        //     "@value": { "subject": s, "predicate": p, "object": o }
1105        //   }
1106        // }
1107        // JSON-LD-Star annotation node with resolved terms (object may be a
1108        // typed-literal value node).
1109        let output = format!(
1110            "{{ \"@annotation\": {{ \"subject\": \"{}\", \"predicate\": \"{}\", \"object\": {} }} }}",
1111            star_json_escape(&star_iri_bare(components[0])),
1112            star_json_escape(&star_iri_bare(components[1])),
1113            star_object_jsonld(components[2])
1114        );
1115        Ok(output.into_bytes())
1116    }
1117
1118    fn serialize_triple(
1119        &self,
1120        subject: u64,
1121        predicate: u64,
1122        object: u64,
1123    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1124        // Expanded JSON-LD node object: subject @id, predicate → [ value ].
1125        let output = format!(
1126            "{{ \"@id\": \"{}\", \"{}\": [ {} ] }}",
1127            star_json_escape(&star_iri_bare(subject)),
1128            star_json_escape(&star_iri_bare(predicate)),
1129            star_object_jsonld(object)
1130        );
1131        Ok(output.into_bytes())
1132    }
1133
1134    fn serialize_quad(
1135        &self,
1136        subject: u64,
1137        predicate: u64,
1138        object: u64,
1139        graph: u64,
1140    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1141        // Node object carrying its named graph via @graph.
1142        let output = format!(
1143            "{{ \"@id\": \"{}\", \"{}\": [ {} ], \"@graph\": \"{}\" }}",
1144            star_json_escape(&star_iri_bare(subject)),
1145            star_json_escape(&star_iri_bare(predicate)),
1146            star_object_jsonld(object),
1147            star_json_escape(&star_iri_bare(graph))
1148        );
1149        Ok(output.into_bytes())
1150    }
1151
1152    fn supports_quads(&self) -> bool {
1153        true
1154    }
1155
1156    fn format_name(&self) -> &'static str {
1157        "JSON-LD-Star"
1158    }
1159}
1160
1161#[cfg(test)]
1162mod additional_serializer_tests {
1163    use super::*;
1164    use crate::rdf_star::RdfStarSerializer;
1165
1166    #[test]
1167    fn test_ntriples_serializer() {
1168        let serializer = NTriplesStarSerializer::new();
1169        assert_eq!(serializer.format_name(), "N-Triples-Star");
1170        assert!(!serializer.supports_quads());
1171
1172        let components = [1u64, 2, 3];
1173        let result = serializer.serialize_embedded_triple(0, &components);
1174        assert!(result.is_ok());
1175        let output = String::from_utf8(result.unwrap()).unwrap();
1176        // Standard RDF-Star quoted-triple delimiter (round-trips with the parser).
1177        assert!(output.starts_with("<< "), "got: {output}");
1178        // Terms are resolved, not raw decimals.
1179        assert!(output.contains("quin:hash/"), "resolved terms: {output}");
1180    }
1181
1182    #[test]
1183    fn test_nquads_serializer() {
1184        let serializer = NQuadsStarSerializer::new();
1185        assert_eq!(serializer.format_name(), "N-Quads-Star");
1186        assert!(serializer.supports_quads());
1187
1188        let result = serializer.serialize_quad(1, 2, 3, 4);
1189        assert!(result.is_ok());
1190        let output = String::from_utf8(result.unwrap()).unwrap();
1191        // Graph term 4 resolves to its IRI surface form, not the bare `<4>` hash.
1192        assert!(
1193            output.contains("quin:hash/0000000000000004"),
1194            "graph term must be resolved: {output}"
1195        );
1196    }
1197
1198    #[test]
1199    fn test_jsonld_serializer() {
1200        let serializer = JsonLdStarSerializer::new();
1201        assert_eq!(serializer.format_name(), "JSON-LD-Star");
1202        assert!(serializer.supports_quads());
1203
1204        let components = [1u64, 2, 3];
1205        let result = serializer.serialize_embedded_triple(0, &components);
1206        assert!(result.is_ok());
1207        let output = String::from_utf8(result.unwrap()).unwrap();
1208        assert!(output.contains("@annotation"));
1209    }
1210}
1211
1212/// Trig-Star Serializer
1213///
1214/// Serializes to Trig-Star format with named graphs.
1215pub struct TrigStarSerializer {
1216    current_graph: u64,
1217}
1218
1219impl TrigStarSerializer {
1220    /// Creates a default `TrigStarSerializer`.
1221    pub fn new() -> Self {
1222        Self { current_graph: 0 }
1223    }
1224
1225    /// Sets the current graph hash.
1226    pub fn set_current_graph(&mut self, graph_hash: u64) {
1227        self.current_graph = graph_hash;
1228    }
1229}
1230
1231impl crate::rdf_star::RdfStarSerializer for TrigStarSerializer {
1232    fn serialize_embedded_triple(
1233        &self,
1234        _virtual_id: u64,
1235        components: &[u64; 3],
1236    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1237        // Quoted triple: << <s> <p> o >> with resolved terms.
1238        let output = format!(
1239            "<< {} {} {} >>",
1240            star_iri_term(components[0]),
1241            star_iri_term(components[1]),
1242            star_object_term(components[2])
1243        );
1244        Ok(output.into_bytes())
1245    }
1246
1247    fn serialize_triple(
1248        &self,
1249        subject: u64,
1250        predicate: u64,
1251        object: u64,
1252    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1253        let output = format!(
1254            "{} {} {} .",
1255            star_iri_term(subject),
1256            star_iri_term(predicate),
1257            star_object_term(object)
1258        );
1259        Ok(output.into_bytes())
1260    }
1261
1262    fn serialize_quad(
1263        &self,
1264        subject: u64,
1265        predicate: u64,
1266        object: u64,
1267        graph: u64,
1268    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1269        let triple = format!(
1270            "{} {} {} .",
1271            star_iri_term(subject),
1272            star_iri_term(predicate),
1273            star_object_term(object)
1274        );
1275        // Default graph → bare triple; named graph → GRAPH <g> { … } wrapper.
1276        let output = if graph == 0 {
1277            triple
1278        } else {
1279            format!("GRAPH {} {{ {} }}", star_iri_term(graph), triple)
1280        };
1281        Ok(output.into_bytes())
1282    }
1283
1284    fn supports_quads(&self) -> bool {
1285        true
1286    }
1287
1288    fn format_name(&self) -> &'static str {
1289        "Trig-Star"
1290    }
1291}
1292
1293#[cfg(test)]
1294mod trig_serializer_tests {
1295    use super::*;
1296    use crate::rdf_star::RdfStarSerializer;
1297
1298    #[test]
1299    fn test_trig_serializer() {
1300        let serializer = TrigStarSerializer::new();
1301        assert_eq!(serializer.format_name(), "Trig-Star");
1302        assert!(serializer.supports_quads());
1303
1304        let result = serializer.serialize_quad(1, 2, 3, 0);
1305        assert!(result.is_ok());
1306    }
1307}
1308
1309/// N3-Star Serializer
1310///
1311/// Serializes to N3-Star format with formulae and rules support.
1312pub struct N3StarSerializer {
1313    /// Current variable bindings
1314    variables: std::collections::HashMap<u64, String>,
1315}
1316
1317impl N3StarSerializer {
1318    /// Builds an N3* serializer.
1319    pub fn new() -> Self {
1320        Self {
1321            variables: std::collections::HashMap::new(),
1322        }
1323    }
1324
1325    /// Binds a variable.
1326    pub fn bind_variable(&mut self, hash: u64, name: String) {
1327        self.variables.insert(hash, name);
1328    }
1329}
1330
1331impl crate::rdf_star::RdfStarSerializer for N3StarSerializer {
1332    fn serialize_embedded_triple(
1333        &self,
1334        _virtual_id: u64,
1335        components: &[u64; 3],
1336    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1337        // Quoted triple: << <s> <p> o >> with resolved terms.
1338        let output = format!(
1339            "<< {} {} {} >>",
1340            star_iri_term(components[0]),
1341            star_iri_term(components[1]),
1342            star_object_term(components[2])
1343        );
1344        Ok(output.into_bytes())
1345    }
1346
1347    fn serialize_triple(
1348        &self,
1349        subject: u64,
1350        predicate: u64,
1351        object: u64,
1352    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1353        // A bound N3 variable renders as its `?name`; otherwise the term is
1354        // resolved to its IRI / typed-literal surface form (never a bare
1355        // `_:hash` blank node, which was the previous — invalid — fallback).
1356        let s = self
1357            .variables
1358            .get(&subject)
1359            .cloned()
1360            .unwrap_or_else(|| star_iri_term(subject));
1361        let p = self
1362            .variables
1363            .get(&predicate)
1364            .cloned()
1365            .unwrap_or_else(|| star_iri_term(predicate));
1366        let o = self
1367            .variables
1368            .get(&object)
1369            .cloned()
1370            .unwrap_or_else(|| star_object_term(object));
1371
1372        let output = format!("{} {} {} .", s, p, o);
1373        Ok(output.into_bytes())
1374    }
1375
1376    fn serialize_quad(
1377        &self,
1378        subject: u64,
1379        predicate: u64,
1380        object: u64,
1381        _graph: u64,
1382    ) -> Result<Vec<u8>, crate::rdf_star::RdfStarSerializeError> {
1383        // N3 doesn't have named graphs, so serialize as triple
1384        self.serialize_triple(subject, predicate, object)
1385    }
1386
1387    fn supports_quads(&self) -> bool {
1388        false
1389    }
1390
1391    fn format_name(&self) -> &'static str {
1392        "N3-Star"
1393    }
1394}
1395
1396#[cfg(test)]
1397mod n3_serializer_tests {
1398    use super::*;
1399    use crate::rdf_star::RdfStarSerializer;
1400
1401    #[test]
1402    fn test_n3_serializer() {
1403        let serializer = N3StarSerializer::new();
1404        assert_eq!(serializer.format_name(), "N3-Star");
1405        assert!(!serializer.supports_quads());
1406
1407        let result = serializer.serialize_triple(1, 2, 3);
1408        assert!(result.is_ok());
1409    }
1410
1411    #[test]
1412    fn test_n3_serializer_variables() {
1413        let mut serializer = N3StarSerializer::new();
1414        serializer.bind_variable(1, "x".to_string());
1415        serializer.bind_variable(2, "knows".to_string());
1416        serializer.bind_variable(3, "y".to_string());
1417
1418        let result = serializer.serialize_triple(1, 2, 3);
1419        assert!(result.is_ok());
1420        let output = String::from_utf8(result.unwrap()).unwrap();
1421        assert!(output.contains("x"));
1422    }
1423}