oxirs-star 0.2.4

RDF-star and SPARQL-star grammar support for quoted triples
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
//! Utility functions for RDF-star serialization

use super::super::config::SerializationOptions;
use super::StarSerializer;
use crate::model::{StarGraph, StarTerm, StarTriple};
use crate::parser::StarFormat;
use crate::{StarError, StarResult};

impl StarSerializer {
    /// Check if a graph is suitable for pretty printing
    pub fn can_pretty_print(&self, graph: &StarGraph) -> bool {
        // Simple heuristic: if graph is small and doesn't have deeply nested quoted triples
        graph.len() < 1000 && graph.max_nesting_depth() < 3
    }

    /// Estimate serialized size for a graph
    pub fn estimate_size(&self, graph: &StarGraph, format: StarFormat) -> usize {
        let base_size_per_triple = match format {
            StarFormat::TurtleStar => 50,   // Turtle is more compact
            StarFormat::NTriplesStar => 80, // N-Triples uses full IRIs
            StarFormat::TrigStar => 60,     // TriG has graph context
            StarFormat::NQuadsStar => 90,   // N-Quads uses full IRIs + graph
            StarFormat::JsonLdStar => 120,  // JSON-LD has overhead from JSON structure
        };

        let quoted_triple_multiplier = 1.5; // Quoted triples add overhead

        let mut total_size = graph.len() * base_size_per_triple;

        // Add overhead for quoted triples
        let quoted_count = graph.count_quoted_triples();
        total_size +=
            (quoted_count as f64 * quoted_triple_multiplier * base_size_per_triple as f64) as usize;

        total_size
    }

    /// Validate that a graph can be serialized in the given format
    pub fn validate_for_format(&self, graph: &StarGraph, format: StarFormat) -> StarResult<()> {
        // Check nesting depth
        let max_depth = graph.max_nesting_depth();
        if max_depth > self.config.max_nesting_depth {
            return Err(StarError::serialization_error(format!(
                "Graph nesting depth {} exceeds maximum {}",
                max_depth, self.config.max_nesting_depth
            )));
        }

        // Format-specific validation
        match format {
            StarFormat::TurtleStar | StarFormat::NTriplesStar => {
                // These formats support quoted triples in any position
                Ok(())
            }
            StarFormat::TrigStar | StarFormat::NQuadsStar => {
                // Validate quad-specific constraints
                self.validate_quad_constraints(graph, format)
            }
            StarFormat::JsonLdStar => {
                // JSON-LD-star supports quoted triples as annotations
                Ok(())
            }
        }
    }

    /// Validate quad-specific constraints for TriG-star and N-Quads-star formats
    fn validate_quad_constraints(&self, graph: &StarGraph, format: StarFormat) -> StarResult<()> {
        match format {
            StarFormat::NQuadsStar => {
                // Validate N-Quads-star specific constraints
                for quad in graph.quads() {
                    // Validate subject (must be IRI or blank node, can be quoted triple)
                    match &quad.subject {
                        StarTerm::NamedNode(_) | StarTerm::BlankNode(_) => {}
                        StarTerm::QuotedTriple(inner_triple) => {
                            // Validate the quoted triple structure
                            self.validate_quoted_triple_structure(inner_triple)?;
                        }
                        StarTerm::Literal(_) => {
                            return Err(StarError::serialization_error(
                                "N-Quads-star: Literals cannot be subjects in quads".to_string(),
                            ));
                        }
                        StarTerm::Variable(_) => {
                            return Err(StarError::serialization_error(
                                "N-Quads-star: Variables cannot be serialized in concrete data"
                                    .to_string(),
                            ));
                        }
                    }

                    // Validate predicate (must be IRI only)
                    match &quad.predicate {
                        StarTerm::NamedNode(_) => {}
                        _ => {
                            return Err(StarError::serialization_error(
                                "N-Quads-star: Predicates must be IRIs".to_string(),
                            ));
                        }
                    }

                    // Validate object (can be any term including quoted triples)
                    match &quad.object {
                        StarTerm::QuotedTriple(inner_triple) => {
                            self.validate_quoted_triple_structure(inner_triple)?;
                        }
                        StarTerm::Variable(_) => {
                            return Err(StarError::serialization_error(
                                "N-Quads-star: Variables cannot be serialized in concrete data"
                                    .to_string(),
                            ));
                        }
                        _ => {} // Other terms are valid as objects
                    }

                    // Validate graph component if present
                    if let Some(ref graph_term) = quad.graph {
                        match graph_term {
                            StarTerm::NamedNode(_) | StarTerm::BlankNode(_) => {}
                            StarTerm::QuotedTriple(_) => {
                                return Err(StarError::serialization_error(
                                    "N-Quads-star: Quoted triples cannot be used as graph names"
                                        .to_string(),
                                ));
                            }
                            StarTerm::Literal(_) => {
                                return Err(StarError::serialization_error(
                                    "N-Quads-star: Literals cannot be used as graph names"
                                        .to_string(),
                                ));
                            }
                            StarTerm::Variable(_) => {
                                return Err(StarError::serialization_error(
                                    "N-Quads-star: Variables cannot be serialized in concrete data"
                                        .to_string(),
                                ));
                            }
                        }
                    }
                }
            }
            StarFormat::TrigStar => {
                // Validate TriG-star specific constraints

                // Check that all graph names are valid
                for graph_name in graph.named_graph_names() {
                    if graph_name.is_empty() {
                        return Err(StarError::serialization_error(
                            "TriG-star: Empty graph names are not allowed".to_string(),
                        ));
                    }

                    // Validate that graph name is a valid IRI or blank node identifier
                    if !graph_name.starts_with("http://")
                        && !graph_name.starts_with("https://")
                        && !graph_name.starts_with("_:")
                        && !graph_name.starts_with("urn:")
                    {
                        return Err(StarError::serialization_error(format!(
                            "TriG-star: Invalid graph name format: {graph_name}"
                        )));
                    }
                }

                // Validate all triples in default and named graphs
                for triple in graph.triples() {
                    self.validate_triple_for_trig(triple)?;
                }

                // Validate triples in named graphs
                for graph_name in graph.named_graph_names() {
                    if let Some(named_triples) = graph.named_graph_triples(graph_name) {
                        for triple in named_triples {
                            self.validate_triple_for_trig(triple)?;
                        }
                    }
                }

                // Check for excessive graph nesting (TriG typically doesn't support nested graphs)
                let graph_count = graph.named_graph_names().len();
                if graph_count > 1000 {
                    return Err(StarError::serialization_error(
                        format!("TriG-star: Too many named graphs ({graph_count}), consider using streaming serialization")
                    ));
                }
            }
            _ => {
                return Err(StarError::serialization_error(
                    "Internal error: validate_quad_constraints called for non-quad format"
                        .to_string(),
                ));
            }
        }

        Ok(())
    }

    /// Validate a quoted triple structure for proper nesting and term constraints
    #[allow(clippy::only_used_in_recursion)]
    fn validate_quoted_triple_structure(&self, triple: &StarTriple) -> StarResult<()> {
        // Validate subject of quoted triple
        match &triple.subject {
            StarTerm::Literal(_) => {
                return Err(StarError::serialization_error(
                    "Quoted triple: Literals cannot be subjects".to_string(),
                ));
            }
            StarTerm::Variable(_) => {
                return Err(StarError::serialization_error(
                    "Quoted triple: Variables cannot be serialized in concrete data".to_string(),
                ));
            }
            StarTerm::QuotedTriple(nested) => {
                // Recursively validate nested quoted triples
                self.validate_quoted_triple_structure(nested)?;
            }
            _ => {} // NamedNode and BlankNode are valid
        }

        // Validate predicate (must be IRI)
        match &triple.predicate {
            StarTerm::NamedNode(_) => {}
            _ => {
                return Err(StarError::serialization_error(
                    "Quoted triple: Predicates must be IRIs".to_string(),
                ));
            }
        }

        // Validate object
        match &triple.object {
            StarTerm::Variable(_) => {
                return Err(StarError::serialization_error(
                    "Quoted triple: Variables cannot be serialized in concrete data".to_string(),
                ));
            }
            StarTerm::QuotedTriple(nested) => {
                // Recursively validate nested quoted triples
                self.validate_quoted_triple_structure(nested)?;
            }
            _ => {} // All other terms are valid as objects
        }

        Ok(())
    }

    /// Validate a triple for TriG-star format constraints
    fn validate_triple_for_trig(&self, triple: &StarTriple) -> StarResult<()> {
        // Validate subject
        match &triple.subject {
            StarTerm::Literal(_) => {
                return Err(StarError::serialization_error(
                    "TriG-star: Literals cannot be subjects".to_string(),
                ));
            }
            StarTerm::Variable(_) => {
                return Err(StarError::serialization_error(
                    "TriG-star: Variables cannot be serialized in concrete data".to_string(),
                ));
            }
            StarTerm::QuotedTriple(inner) => {
                self.validate_quoted_triple_structure(inner)?;
            }
            _ => {} // NamedNode and BlankNode are valid
        }

        // Validate predicate (must be IRI)
        match &triple.predicate {
            StarTerm::NamedNode(_) => {}
            _ => {
                return Err(StarError::serialization_error(
                    "TriG-star: Predicates must be IRIs".to_string(),
                ));
            }
        }

        // Validate object
        match &triple.object {
            StarTerm::Variable(_) => {
                return Err(StarError::serialization_error(
                    "TriG-star: Variables cannot be serialized in concrete data".to_string(),
                ));
            }
            StarTerm::QuotedTriple(inner) => {
                self.validate_quoted_triple_structure(inner)?;
            }
            _ => {} // All other terms are valid as objects
        }

        Ok(())
    }

    /// Serialize a graph to string using the specified format and options
    pub fn serialize_graph(
        &self,
        graph: &StarGraph,
        format: StarFormat,
        _options: &SerializationOptions,
    ) -> StarResult<String> {
        // For now, this is a wrapper around serialize_to_string
        // In a more complete implementation, this would use the options parameter
        self.serialize_to_string(graph, format)
    }
}

/// Iterator that yields chunks of items from an underlying iterator.
///
/// This utility is useful for batch processing operations where you want to
/// process data in fixed-size chunks for better memory efficiency and performance.
///
/// # Examples
///
/// ```
/// use oxirs_star::serializer::star_serializer::utils::ChunkedIterator;
///
/// let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
/// let mut chunked = ChunkedIterator::new(data.into_iter(), 3);
///
/// assert_eq!(chunked.next(), Some(vec![1, 2, 3]));
/// assert_eq!(chunked.next(), Some(vec![4, 5, 6]));
/// assert_eq!(chunked.next(), Some(vec![7, 8, 9]));
/// assert_eq!(chunked.next(), Some(vec![10]));
/// assert_eq!(chunked.next(), None);
/// ```
pub struct ChunkedIterator<I: Iterator> {
    inner: I,
    chunk_size: usize,
}

impl<I: Iterator> ChunkedIterator<I> {
    /// Create a new ChunkedIterator that yields chunks of the specified size.
    ///
    /// # Arguments
    ///
    /// * `iter` - The underlying iterator to chunk
    /// * `chunk_size` - The maximum size of each chunk (must be > 0)
    ///
    /// # Panics
    ///
    /// Panics if `chunk_size` is 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use oxirs_star::serializer::star_serializer::utils::ChunkedIterator;
    ///
    /// let data = vec![1, 2, 3, 4, 5];
    /// let chunked = ChunkedIterator::new(data.into_iter(), 2);
    /// let chunks: Vec<_> = chunked.collect();
    ///
    /// assert_eq!(chunks.len(), 3);
    /// assert_eq!(chunks[0], vec![1, 2]);
    /// assert_eq!(chunks[1], vec![3, 4]);
    /// assert_eq!(chunks[2], vec![5]);
    /// ```
    pub fn new(iter: I, chunk_size: usize) -> Self {
        assert!(chunk_size > 0, "chunk_size must be greater than 0");
        Self {
            inner: iter,
            chunk_size,
        }
    }

    /// Get the configured chunk size
    pub fn chunk_size(&self) -> usize {
        self.chunk_size
    }
}

impl<I: Iterator> Iterator for ChunkedIterator<I> {
    type Item = Vec<I::Item>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut chunk = Vec::with_capacity(self.chunk_size);

        for _ in 0..self.chunk_size {
            match self.inner.next() {
                Some(item) => chunk.push(item),
                None => break,
            }
        }

        if chunk.is_empty() {
            None
        } else {
            Some(chunk)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let (lower, upper) = self.inner.size_hint();

        let lower_chunks = (lower + self.chunk_size - 1) / self.chunk_size;
        let upper_chunks = upper.map(|u| (u + self.chunk_size - 1) / self.chunk_size);

        (lower_chunks, upper_chunks)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::StarTerm;
    use crate::parser::StarParser;
    use crate::serializer::CompressionType;
    use crate::StarQuad;

    #[test]
    fn test_simple_triple_serialization() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        let triple = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/knows").unwrap(),
            StarTerm::iri("http://example.org/bob").unwrap(),
        );

        graph.insert(triple).unwrap();

        // Test N-Triples-star
        let result = serializer
            .serialize_to_string(&graph, StarFormat::NTriplesStar)
            .unwrap();
        assert!(result.contains("<http://example.org/alice>"));
        assert!(result.contains("<http://example.org/knows>"));
        assert!(result.contains("<http://example.org/bob>"));
        assert!(result.ends_with(" .\n"));

        // Test Turtle-star
        let result = serializer
            .serialize_to_string(&graph, StarFormat::TurtleStar)
            .unwrap();
        assert!(result.contains("@prefix"));
    }

    #[test]
    fn test_quoted_triple_serialization() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        let inner = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("25").unwrap(),
        );

        let outer = StarTriple::new(
            StarTerm::quoted_triple(inner),
            StarTerm::iri("http://example.org/certainty").unwrap(),
            StarTerm::literal("0.9").unwrap(),
        );

        graph.insert(outer).unwrap();

        let result = serializer
            .serialize_to_string(&graph, StarFormat::NTriplesStar)
            .unwrap();
        assert!(result.contains("<<"));
        assert!(result.contains(">>"));
        assert!(result.contains("\"25\""));
        assert!(result.contains("\"0.9\""));
    }

    #[test]
    fn test_literal_escaping() {
        let test_cases = vec![
            ("simple", "simple"),
            ("with\nnewline", "with\\nnewline"),
            ("with\ttab", "with\\ttab"),
            ("with\"quote", "with\\\"quote"),
            ("with\\backslash", "with\\\\backslash"),
        ];

        for (input, expected) in test_cases {
            let escaped = StarSerializer::escape_literal_static(input);
            assert_eq!(escaped, expected);
        }
    }

    #[test]
    fn test_literal_with_language_and_datatype() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Literal with language tag
        let triple1 = StarTriple::new(
            StarTerm::iri("http://example.org/resource").unwrap(),
            StarTerm::iri("http://example.org/label").unwrap(),
            StarTerm::literal_with_language("Hello", "en").unwrap(),
        );

        // Literal with datatype
        let triple2 = StarTriple::new(
            StarTerm::iri("http://example.org/resource").unwrap(),
            StarTerm::iri("http://example.org/count").unwrap(),
            StarTerm::literal_with_datatype("42", "http://www.w3.org/2001/XMLSchema#integer")
                .unwrap(),
        );

        graph.insert(triple1).unwrap();
        graph.insert(triple2).unwrap();

        let result = serializer
            .serialize_to_string(&graph, StarFormat::NTriplesStar)
            .unwrap();
        assert!(result.contains("\"Hello\"@en"));
        assert!(result.contains("\"42\"^^<http://www.w3.org/2001/XMLSchema#integer>"));
    }

    #[test]
    fn test_format_validation() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Create deeply nested quoted triples
        let mut current_triple = StarTriple::new(
            StarTerm::iri("http://example.org/s").unwrap(),
            StarTerm::iri("http://example.org/p").unwrap(),
            StarTerm::iri("http://example.org/o").unwrap(),
        );

        // Nest it multiple times
        for _ in 0..15 {
            current_triple = StarTriple::new(
                StarTerm::quoted_triple(current_triple),
                StarTerm::iri("http://example.org/meta").unwrap(),
                StarTerm::literal("value").unwrap(),
            );
        }

        graph.insert(current_triple).unwrap();

        // Should fail validation due to excessive nesting
        let result = serializer.validate_for_format(&graph, StarFormat::NTriplesStar);
        assert!(result.is_err());
    }

    #[test]
    fn test_size_estimation() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        let triple = StarTriple::new(
            StarTerm::iri("http://example.org/s").unwrap(),
            StarTerm::iri("http://example.org/p").unwrap(),
            StarTerm::iri("http://example.org/o").unwrap(),
        );

        graph.insert(triple).unwrap();

        let turtle_size = serializer.estimate_size(&graph, StarFormat::TurtleStar);
        let ntriples_size = serializer.estimate_size(&graph, StarFormat::NTriplesStar);

        // N-Triples should be larger due to full IRIs
        assert!(ntriples_size > turtle_size);
    }

    #[test]
    fn test_enhanced_trig_star_serialization() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Add triple to default graph
        let default_triple = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/knows").unwrap(),
            StarTerm::iri("http://example.org/bob").unwrap(),
        );
        graph.insert(default_triple).unwrap();

        // Add quad to named graph
        let named_quad = StarQuad::new(
            StarTerm::iri("http://example.org/charlie").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("30").unwrap(),
            Some(StarTerm::iri("http://example.org/graph1").unwrap()),
        );
        graph.insert_quad(named_quad).unwrap();

        let result = serializer
            .serialize_to_string(&graph, StarFormat::TrigStar)
            .unwrap();

        // Should contain prefix declarations
        assert!(result.contains("@prefix"));

        // Should contain default graph block
        assert!(result.contains("{"));
        assert!(result.contains("alice"));

        // Should contain named graph declaration
        assert!(result.contains("http://example.org/graph1"));
        assert!(result.contains("charlie"));
    }

    #[test]
    fn test_enhanced_nquads_star_serialization() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Add triple to default graph
        let default_triple = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/knows").unwrap(),
            StarTerm::iri("http://example.org/bob").unwrap(),
        );
        graph.insert(default_triple).unwrap();

        // Add quad to named graph
        let named_quad = StarQuad::new(
            StarTerm::iri("http://example.org/charlie").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("30").unwrap(),
            Some(StarTerm::iri("http://example.org/graph1").unwrap()),
        );
        graph.insert_quad(named_quad).unwrap();

        let result = serializer
            .serialize_to_string(&graph, StarFormat::NQuadsStar)
            .unwrap();

        // Should contain default graph triple (3 terms)
        assert!(result.contains(
            "<http://example.org/alice> <http://example.org/knows> <http://example.org/bob> ."
        ));

        // Should contain named graph quad (4 terms)
        assert!(result.contains("<http://example.org/charlie> <http://example.org/age> \"30\" <http://example.org/graph1> ."));
    }

    #[test]
    fn test_quoted_triple_serialization_roundtrip() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Create a complex quoted triple structure
        let inner = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/says").unwrap(),
            StarTerm::literal("Hello").unwrap(),
        );

        let outer = StarTriple::new(
            StarTerm::quoted_triple(inner),
            StarTerm::iri("http://example.org/certainty").unwrap(),
            StarTerm::literal("0.95").unwrap(),
        );

        graph.insert(outer).unwrap();

        // Test all formats
        for format in [
            StarFormat::TurtleStar,
            StarFormat::NTriplesStar,
            StarFormat::TrigStar,
            StarFormat::NQuadsStar,
        ] {
            let serialized = serializer.serialize_to_string(&graph, format).unwrap();

            // Should contain quoted triple markers
            assert!(serialized.contains("<<"));
            assert!(serialized.contains(">>"));

            // Should contain the nested content
            assert!(serialized.contains("alice"));
            assert!(serialized.contains("says"));
            assert!(serialized.contains("Hello"));
            assert!(serialized.contains("certainty"));
        }
    }

    #[test]
    fn test_nquads_star_serialization() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Add triples to default graph
        let triple1 = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/knows").unwrap(),
            StarTerm::iri("http://example.org/bob").unwrap(),
        );
        graph.insert(triple1).unwrap();

        // Add quad with named graph
        let quad1 = StarQuad::new(
            StarTerm::iri("http://example.org/charlie").unwrap(),
            StarTerm::iri("http://example.org/likes").unwrap(),
            StarTerm::iri("http://example.org/dave").unwrap(),
            Some(StarTerm::iri("http://example.org/graph1").unwrap()),
        );
        graph.insert_quad(quad1).unwrap();

        // Add quad with quoted triple
        let quoted = StarTriple::new(
            StarTerm::iri("http://example.org/eve").unwrap(),
            StarTerm::iri("http://example.org/says").unwrap(),
            StarTerm::literal("hello").unwrap(),
        );
        let quad2 = StarQuad::new(
            StarTerm::quoted_triple(quoted),
            StarTerm::iri("http://example.org/certainty").unwrap(),
            StarTerm::literal("0.8").unwrap(),
            Some(StarTerm::iri("http://example.org/graph2").unwrap()),
        );
        graph.insert_quad(quad2).unwrap();

        let serialized = serializer
            .serialize_to_string(&graph, StarFormat::NQuadsStar)
            .unwrap();

        // Verify each quad is on its own line
        let lines: Vec<&str> = serialized
            .lines()
            .filter(|l| !l.trim().is_empty())
            .collect();
        assert_eq!(lines.len(), 3);

        // Verify graph contexts are present
        assert!(serialized.contains("<http://example.org/graph1>"));
        assert!(serialized.contains("<http://example.org/graph2>"));

        // Verify quoted triple syntax
        assert!(serialized.contains("<< "));
        assert!(serialized.contains(" >>"));
    }

    #[test]
    fn test_trig_star_serialization_with_multiple_graphs() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Add to default graph
        let triple1 = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("30").unwrap(),
        );
        graph.insert(triple1).unwrap();

        // Add to named graph 1
        let quad1 = StarQuad::new(
            StarTerm::iri("http://example.org/bob").unwrap(),
            StarTerm::iri("http://example.org/likes").unwrap(),
            StarTerm::iri("http://example.org/coffee").unwrap(),
            Some(StarTerm::iri("http://example.org/preferences").unwrap()),
        );
        graph.insert_quad(quad1).unwrap();

        // Add quoted triple to named graph 2
        let inner = StarTriple::new(
            StarTerm::iri("http://example.org/charlie").unwrap(),
            StarTerm::iri("http://example.org/believes").unwrap(),
            StarTerm::literal("earth is round").unwrap(),
        );
        let quad2 = StarQuad::new(
            StarTerm::quoted_triple(inner),
            StarTerm::iri("http://example.org/confidence").unwrap(),
            StarTerm::literal("1.0").unwrap(),
            Some(StarTerm::iri("http://example.org/beliefs").unwrap()),
        );
        graph.insert_quad(quad2).unwrap();

        let serialized = serializer
            .serialize_to_string(&graph, StarFormat::TrigStar)
            .unwrap();

        // Verify prefixes are included
        assert!(serialized.contains("@prefix"));

        // Verify default graph block
        assert!(serialized.contains("{\n"));
        assert!(serialized.contains("alice"));

        // Verify named graph blocks
        assert!(serialized.contains("<http://example.org/preferences> {"));
        assert!(serialized.contains("<http://example.org/beliefs> {"));

        // Verify quoted triple in TriG format
        assert!(serialized.contains("<<"));
        assert!(serialized.contains(">>"));
    }

    #[test]
    fn test_streaming_serialization() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Create a larger graph for streaming test
        for i in 0..1000 {
            let triple = StarTriple::new(
                StarTerm::iri(&format!("http://example.org/s{i}")).unwrap(),
                StarTerm::iri("http://example.org/p").unwrap(),
                StarTerm::literal(&format!("value{i}")).unwrap(),
            );
            graph.insert(triple).unwrap();
        }

        let mut output = Vec::new();
        serializer
            .serialize_streaming(&graph, &mut output, StarFormat::NTriplesStar, 100)
            .unwrap();

        let output_str = String::from_utf8(output).unwrap();
        let lines: Vec<&str> = output_str
            .lines()
            .filter(|l| !l.trim().is_empty())
            .collect();
        assert_eq!(lines.len(), 1000);

        // Verify each line is a valid N-Triples statement
        for line in lines {
            assert!(line.ends_with(" ."));
            assert!(line.contains("http://example.org/"));
        }
    }

    #[test]
    fn test_parallel_serialization() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Create a graph suitable for parallel processing
        for i in 0..500 {
            let triple = StarTriple::new(
                StarTerm::iri(&format!("http://example.org/subject{i}")).unwrap(),
                StarTerm::iri("http://example.org/predicate").unwrap(),
                StarTerm::iri(&format!("http://example.org/object{i}")).unwrap(),
            );
            graph.insert(triple).unwrap();
        }

        let output = Box::leak(Box::new(Vec::new()));
        let output_ptr = output as *const Vec<u8>;
        serializer
            .serialize_parallel(&graph, output, StarFormat::NTriplesStar, 4, 100)
            .unwrap();

        // Safe because we know the serialize method completed and output is still valid
        let output_data = unsafe { &*output_ptr };
        let output_str = String::from_utf8(output_data.clone()).unwrap();
        let lines: Vec<&str> = output_str
            .lines()
            .filter(|l| !l.trim().is_empty())
            .collect();
        assert_eq!(lines.len(), 500);
    }

    #[test]
    fn test_serialization_with_options() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Create test graph
        for i in 0..100 {
            let triple = StarTriple::new(
                StarTerm::iri(&format!("http://example.org/s{i}")).unwrap(),
                StarTerm::iri("http://example.org/p").unwrap(),
                StarTerm::literal(&format!("test{i}")).unwrap(),
            );
            graph.insert(triple).unwrap();
        }

        let options = SerializationOptions {
            streaming: true,
            batch_size: 25,
            buffer_size: 1024,
            ..Default::default()
        };

        let output = Box::leak(Box::new(Vec::new()));
        let output_ptr = output as *const Vec<u8>;
        serializer
            .serialize_with_options(&graph, output, StarFormat::NTriplesStar, &options)
            .unwrap();

        // Safe because we know the serialize method completed and output is still valid
        let output_data = unsafe { &*output_ptr };
        let output_str = String::from_utf8(output_data.clone()).unwrap();
        let lines: Vec<&str> = output_str
            .lines()
            .filter(|l| !l.trim().is_empty())
            .collect();
        assert_eq!(lines.len(), 100);
    }

    #[test]
    fn test_optimized_serialization() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Create a complex graph with quoted triples
        for i in 0..50 {
            let inner = StarTriple::new(
                StarTerm::iri(&format!("http://example.org/alice{i}")).unwrap(),
                StarTerm::iri("http://example.org/says").unwrap(),
                StarTerm::literal(&format!("statement{i}")).unwrap(),
            );
            let outer = StarTriple::new(
                StarTerm::quoted_triple(inner),
                StarTerm::iri("http://example.org/certainty").unwrap(),
                StarTerm::literal("0.9").unwrap(),
            );
            graph.insert(outer).unwrap();
        }

        let output = Box::leak(Box::new(Vec::new()));
        let output_ptr = output as *const Vec<u8>;
        serializer
            .serialize_optimized(&graph, output, StarFormat::NTriplesStar)
            .unwrap();

        // Safe because we know the serialize method completed and output is still valid
        let output_data = unsafe { &*output_ptr };
        let output_str = String::from_utf8(output_data.clone()).unwrap();

        // Should contain quoted triple syntax
        assert!(output_str.contains("<<"));
        assert!(output_str.contains(">>"));

        let lines: Vec<&str> = output_str
            .lines()
            .filter(|l| !l.trim().is_empty())
            .collect();
        assert_eq!(lines.len(), 50);
    }

    #[test]
    fn test_memory_usage_estimation() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        for i in 0..100 {
            let triple = StarTriple::new(
                StarTerm::iri(&format!("http://example.org/s{i}")).unwrap(),
                StarTerm::iri("http://example.org/p").unwrap(),
                StarTerm::literal(&format!("value{i}")).unwrap(),
            );
            graph.insert(triple).unwrap();
        }

        let options = SerializationOptions::default();
        let memory_estimate =
            serializer.estimate_memory_usage(&graph, StarFormat::NTriplesStar, &options);

        // Should provide reasonable estimate (not zero, not excessive)
        assert!(memory_estimate > 1000);
        assert!(memory_estimate < 10_000_000);

        let streaming_options = SerializationOptions {
            streaming: true,
            ..Default::default()
        };
        let streaming_estimate =
            serializer.estimate_memory_usage(&graph, StarFormat::NTriplesStar, &streaming_options);

        // Streaming should use reasonable memory (may not be less for small datasets due to overhead)
        assert!(streaming_estimate > 0);
        assert!(streaming_estimate < 10_000_000);
    }

    #[test]
    fn test_chunked_iterator() {
        let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        let chunked = ChunkedIterator::new(data.into_iter(), 3);

        let chunks: Vec<_> = chunked.collect();
        assert_eq!(chunks.len(), 4);
        assert_eq!(chunks[0], vec![1, 2, 3]);
        assert_eq!(chunks[1], vec![4, 5, 6]);
        assert_eq!(chunks[2], vec![7, 8, 9]);
        assert_eq!(chunks[3], vec![10]);
    }

    #[test]
    fn test_chunked_iterator_exact_chunks() {
        let data = vec![1, 2, 3, 4, 5, 6];
        let chunked = ChunkedIterator::new(data.into_iter(), 2);

        let chunks: Vec<_> = chunked.collect();
        assert_eq!(chunks.len(), 3);
        assert_eq!(chunks[0], vec![1, 2]);
        assert_eq!(chunks[1], vec![3, 4]);
        assert_eq!(chunks[2], vec![5, 6]);
    }

    #[test]
    fn test_chunked_iterator_single_item() {
        let data = vec![42];
        let chunked = ChunkedIterator::new(data.into_iter(), 10);

        let chunks: Vec<_> = chunked.collect();
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0], vec![42]);
    }

    #[test]
    fn test_chunked_iterator_empty() {
        let data: Vec<i32> = vec![];
        let chunked = ChunkedIterator::new(data.into_iter(), 5);

        let chunks: Vec<_> = chunked.collect();
        assert_eq!(chunks.len(), 0);
    }

    #[test]
    fn test_chunked_iterator_size_hint() {
        let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        let chunked = ChunkedIterator::new(data.into_iter(), 3);

        let (lower, upper) = chunked.size_hint();
        assert_eq!(lower, 4); // 10 items / 3 chunk_size = 4 chunks
        assert_eq!(upper, Some(4));
    }

    #[test]
    #[should_panic(expected = "chunk_size must be greater than 0")]
    fn test_chunked_iterator_zero_chunk_size() {
        let data = vec![1, 2, 3];
        let _chunked = ChunkedIterator::new(data.into_iter(), 0);
    }

    #[test]
    fn test_compression_type_selection() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        let triple = StarTriple::new(
            StarTerm::iri("http://example.org/s").unwrap(),
            StarTerm::iri("http://example.org/p").unwrap(),
            StarTerm::literal("test").unwrap(),
        );
        graph.insert(triple).unwrap();

        // Test different compression types (placeholder implementations)
        for compression in [
            CompressionType::None,
            CompressionType::Gzip,
            CompressionType::Zstd,
            CompressionType::Lz4,
        ] {
            let options = SerializationOptions {
                compression,
                ..Default::default()
            };

            let output = Box::leak(Box::new(Vec::new()));
            let result = serializer.serialize_with_options(
                &graph,
                output,
                StarFormat::NTriplesStar,
                &options,
            );

            // Should not fail even with unimplemented compression
            assert!(result.is_ok());
        }
    }

    #[test]
    fn test_serialization_roundtrip() {
        let parser = StarParser::new();
        let serializer = StarSerializer::new();
        let mut original_graph = StarGraph::new();

        // Create complex graph with various features
        let simple = StarTriple::new(
            StarTerm::iri("http://example.org/s1").unwrap(),
            StarTerm::iri("http://example.org/p1").unwrap(),
            StarTerm::literal("test").unwrap(),
        );
        original_graph.insert(simple).unwrap();

        // Quoted triple
        let inner = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/says").unwrap(),
            StarTerm::literal("hello").unwrap(),
        );
        let quoted = StarTriple::new(
            StarTerm::quoted_triple(inner),
            StarTerm::iri("http://example.org/certainty").unwrap(),
            StarTerm::literal("0.9").unwrap(),
        );
        original_graph.insert(quoted).unwrap();

        // Test roundtrip for each format
        for format in [
            StarFormat::TurtleStar,
            StarFormat::NTriplesStar,
            StarFormat::TrigStar,
            StarFormat::NQuadsStar,
        ] {
            let serialized = serializer
                .serialize_to_string(&original_graph, format)
                .unwrap();
            let parsed_graph = parser.parse_str(&serialized, format).unwrap();

            // Verify same number of triples
            assert_eq!(
                original_graph.total_len(),
                parsed_graph.total_len(),
                "Roundtrip failed for format {format:?}"
            );
        }
    }

    #[test]
    fn test_quad_validation() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Create valid quad
        let valid_quad = StarQuad::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/knows").unwrap(),
            StarTerm::iri("http://example.org/bob").unwrap(),
            Some(StarTerm::iri("http://example.org/graph1").unwrap()),
        );
        graph.insert_quad(valid_quad).unwrap();

        // Valid quad should pass validation
        assert!(serializer
            .validate_for_format(&graph, StarFormat::NQuadsStar)
            .is_ok());
        assert!(serializer
            .validate_for_format(&graph, StarFormat::TrigStar)
            .is_ok());

        // Test validation methods directly without going through graph insertion
        // (since graph insertion itself validates and rejects invalid quads)

        // Test quoted triple validation with invalid subject (literal)
        let invalid_inner = StarTriple::new(
            StarTerm::literal("invalid_subject").unwrap(), // Invalid: literal as subject
            StarTerm::iri("http://example.org/predicate").unwrap(),
            StarTerm::literal("object").unwrap(),
        );

        // Test the quoted triple validation directly
        let result = serializer.validate_quoted_triple_structure(&invalid_inner);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Literals cannot be subjects"));

        // Test quoted triple validation with invalid predicate
        let invalid_predicate_triple = StarTriple::new(
            StarTerm::iri("http://example.org/subject").unwrap(),
            StarTerm::literal("invalid_predicate").unwrap(), // Invalid: literal as predicate
            StarTerm::literal("object").unwrap(),
        );

        let result = serializer.validate_quoted_triple_structure(&invalid_predicate_triple);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Predicates must be IRIs"));

        // Test TriG validation directly
        let invalid_trig_triple = StarTriple::new(
            StarTerm::variable("invalid_subject").unwrap(), // Invalid: variable in concrete data
            StarTerm::iri("http://example.org/predicate").unwrap(),
            StarTerm::literal("object").unwrap(),
        );

        let result = serializer.validate_triple_for_trig(&invalid_trig_triple);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Variables cannot be serialized"));
    }

    #[test]
    fn test_quoted_triple_validation() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Create valid quoted triple
        let inner_triple = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/says").unwrap(),
            StarTerm::literal("hello").unwrap(),
        );
        let quoted_triple = StarTriple::new(
            StarTerm::quoted_triple(inner_triple),
            StarTerm::iri("http://example.org/certainty").unwrap(),
            StarTerm::literal("0.9").unwrap(),
        );
        graph.insert(quoted_triple).unwrap();

        // Should pass validation for all formats
        assert!(serializer
            .validate_for_format(&graph, StarFormat::TurtleStar)
            .is_ok());
        assert!(serializer
            .validate_for_format(&graph, StarFormat::NTriplesStar)
            .is_ok());
        assert!(serializer
            .validate_for_format(&graph, StarFormat::TrigStar)
            .is_ok());
        assert!(serializer
            .validate_for_format(&graph, StarFormat::NQuadsStar)
            .is_ok());

        // Test invalid quoted triple with literal as subject
        let mut invalid_graph = StarGraph::new();
        let invalid_inner = StarTriple::new(
            StarTerm::literal("invalid_subject").unwrap(), // Invalid: literal as subject
            StarTerm::iri("http://example.org/predicate").unwrap(),
            StarTerm::literal("object").unwrap(),
        );
        let invalid_quoted = StarTriple::new(
            StarTerm::quoted_triple(invalid_inner),
            StarTerm::iri("http://example.org/certainty").unwrap(),
            StarTerm::literal("0.9").unwrap(),
        );
        invalid_graph.insert(invalid_quoted).unwrap();

        // Should fail validation
        let result = serializer.validate_for_format(&invalid_graph, StarFormat::NQuadsStar);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Literals cannot be subjects"));
    }

    #[test]
    fn test_trig_star_graph_name_validation() {
        let serializer = StarSerializer::new();
        let mut graph = StarGraph::new();

        // Add quad with valid graph name
        let valid_quad = StarQuad::new(
            StarTerm::iri("http://example.org/subject").unwrap(),
            StarTerm::iri("http://example.org/predicate").unwrap(),
            StarTerm::iri("http://example.org/object").unwrap(),
            Some(StarTerm::iri("http://example.org/valid_graph").unwrap()),
        );
        graph.insert_quad(valid_quad).unwrap();

        // Should pass validation
        assert!(serializer
            .validate_for_format(&graph, StarFormat::TrigStar)
            .is_ok());

        // Test with blank node graph name
        let mut graph_with_bnode = StarGraph::new();
        let bnode_quad = StarQuad::new(
            StarTerm::iri("http://example.org/subject").unwrap(),
            StarTerm::iri("http://example.org/predicate").unwrap(),
            StarTerm::iri("http://example.org/object").unwrap(),
            Some(StarTerm::blank_node("graph1").unwrap()),
        );
        graph_with_bnode.insert_quad(bnode_quad).unwrap();

        // Should also pass validation (blank nodes are valid graph names)
        assert!(serializer
            .validate_for_format(&graph_with_bnode, StarFormat::TrigStar)
            .is_ok());
    }
}