1use std::collections::HashMap;
23use std::io::Write;
24
25use crate::query::resolver::{classify_inline_literal, write_iri_term, write_object_term};
26use crate::NQuin;
27
28pub fn serialize_to_ntriples<W: Write>(writer: &mut W, quins: &[NQuin]) -> Result<(), String> {
30 crate::resolver::format_ntriples_to(quins, writer)
31 .map_err(|e| format!("Failed to write N-Triples: {e}"))
32}
33
34fn group_by<'a>(quins: &'a [NQuin], key: impl Fn(&NQuin) -> u64) -> Vec<(u64, Vec<&'a NQuin>)> {
37 let mut order: Vec<u64> = Vec::new();
38 let mut map: HashMap<u64, Vec<&NQuin>> = HashMap::new();
39 for quin in quins {
40 let k = key(quin);
41 let bucket = map.entry(k).or_default();
42 if bucket.is_empty() {
43 order.push(k);
44 }
45 bucket.push(quin);
46 }
47 order
48 .into_iter()
49 .map(|k| {
50 let v = map.remove(&k).unwrap_or_default();
51 (k, v)
52 })
53 .collect()
54}
55
56fn write_subject_block<W: Write>(
60 writer: &mut W,
61 subject: u64,
62 rows: &[&NQuin],
63 indent: &str,
64) -> std::io::Result<()> {
65 write!(writer, "{indent}")?;
66 write_iri_term(subject, writer)?;
67 for (i, quin) in rows.iter().enumerate() {
68 if i == 0 {
69 write!(writer, " ")?;
70 } else {
71 write!(writer, " ;\n{indent} ")?;
72 }
73 write_iri_term(quin.predicate, writer)?;
74 write!(writer, " ")?;
75 write_object_term(quin.object, writer)?;
76 }
77 writeln!(writer, " .")
78}
79
80pub fn serialize_to_turtle<W: Write>(writer: &mut W, quins: &[NQuin]) -> Result<(), String> {
82 for (subject, rows) in group_by(quins, |q| q.subject) {
83 write_subject_block(writer, subject, &rows, "")
84 .map_err(|e| format!("Failed to write Turtle: {e}"))?;
85 }
86 Ok(())
87}
88
89pub fn serialize_to_nquads<W: Write>(writer: &mut W, quins: &[NQuin]) -> Result<(), String> {
91 crate::resolver::format_nquads_to(quins, writer)
92 .map_err(|e| format!("Failed to write N-Quads: {e}"))
93}
94
95pub fn serialize_to_trig<W: Write>(writer: &mut W, quins: &[NQuin]) -> Result<(), String> {
97 for (context, ctx_quins) in group_by(quins, |q| q.context) {
98 write!(writer, "").map_err(|e| format!("Failed to write TriG: {e}"))?;
99 write_iri_term(context, writer).map_err(|e| format!("Failed to write TriG graph: {e}"))?;
100 writeln!(writer, " {{").map_err(|e| format!("Failed to write TriG graph: {e}"))?;
101
102 let owned: Vec<NQuin> = ctx_quins.iter().map(|q| **q).collect();
104 for (subject, rows) in group_by(&owned, |q| q.subject) {
105 write_subject_block(writer, subject, &rows, " ")
106 .map_err(|e| format!("Failed to write TriG statement: {e}"))?;
107 }
108
109 writeln!(writer, "}}").map_err(|e| format!("Failed to write TriG graph end: {e}"))?;
110 }
111 Ok(())
112}
113
114pub fn serialize_to_n3<W: Write>(writer: &mut W, quins: &[NQuin]) -> Result<(), String> {
120 let err = |e: std::io::Error| format!("Failed to write N3: {e}");
121 writeln!(
122 writer,
123 "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ."
124 )
125 .map_err(err)?;
126 writeln!(
127 writer,
128 "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> ."
129 )
130 .map_err(err)?;
131 writeln!(writer, "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .").map_err(err)?;
132 writeln!(writer, "@prefix owl: <http://www.w3.org/2002/07/owl#> .").map_err(err)?;
133 writeln!(writer).map_err(err)?;
134 for (subject, rows) in group_by(quins, |q| q.subject) {
135 write_subject_block(writer, subject, &rows, "")
136 .map_err(|e| format!("Failed to write N3: {e}"))?;
137 }
138 Ok(())
139}
140
141enum JsonLdTerm {
143 Iri(String),
144 Literal { value: String, datatype: String },
145}
146
147fn jsonld_term(hash: u64) -> JsonLdTerm {
150 if let Some(bytes) = crate::resolver::resolve_hash(hash) {
151 return JsonLdTerm::Iri(String::from_utf8_lossy(bytes).into_owned());
152 }
153 if (hash & crate::resolver::MSB_FLAG) != 0 {
154 return JsonLdTerm::Iri(format!(
155 "did:q42:ptr/{:016x}",
156 hash & !crate::resolver::MSB_FLAG
157 ));
158 }
159 if let Some(lit) = classify_inline_literal(hash) {
160 return JsonLdTerm::Literal {
161 value: lit.to_string(),
162 datatype: lit.datatype_iri().to_string(),
163 };
164 }
165 JsonLdTerm::Iri(format!("quin:hash/{hash:016x}"))
166}
167
168fn json_escape(s: &str) -> String {
170 let mut out = String::with_capacity(s.len() + 2);
171 for c in s.chars() {
172 match c {
173 '"' => out.push_str("\\\""),
174 '\\' => out.push_str("\\\\"),
175 '\n' => out.push_str("\\n"),
176 '\r' => out.push_str("\\r"),
177 '\t' => out.push_str("\\t"),
178 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
179 c => out.push(c),
180 }
181 }
182 out
183}
184
185pub fn serialize_to_jsonld<W: Write>(writer: &mut W, quins: &[NQuin]) -> Result<(), String> {
190 let err = |e: std::io::Error| format!("Failed to write JSON-LD: {e}");
191 writeln!(writer, "[").map_err(err)?;
192
193 let subjects = group_by(quins, |q| q.subject);
194 for (si, (subject, rows)) in subjects.iter().enumerate() {
195 if si > 0 {
196 writeln!(writer, ",").map_err(err)?;
197 }
198 let subj_iri = match jsonld_term(*subject) {
199 JsonLdTerm::Iri(s) => s,
200 JsonLdTerm::Literal { value, .. } => value,
204 };
205 writeln!(writer, " {{").map_err(err)?;
206 write!(writer, " \"@id\": \"{}\"", json_escape(&subj_iri)).map_err(err)?;
207
208 let owned: Vec<NQuin> = rows.iter().map(|q| **q).collect();
210 let by_pred = group_by(&owned, |q| q.predicate);
211 for (predicate, pred_rows) in &by_pred {
212 let pred_iri = match jsonld_term(*predicate) {
213 JsonLdTerm::Iri(s) => s,
214 JsonLdTerm::Literal { value, .. } => value,
215 };
216 writeln!(writer, ",").map_err(err)?;
217 writeln!(writer, " \"{}\": [", json_escape(&pred_iri)).map_err(err)?;
218 for (oi, quin) in pred_rows.iter().enumerate() {
219 if oi > 0 {
220 writeln!(writer, ",").map_err(err)?;
221 }
222 match jsonld_term(quin.object) {
223 JsonLdTerm::Iri(iri) => {
224 write!(writer, " {{ \"@id\": \"{}\" }}", json_escape(&iri))
225 .map_err(err)?;
226 }
227 JsonLdTerm::Literal { value, datatype } => {
228 write!(
229 writer,
230 " {{ \"@value\": \"{}\", \"@type\": \"{}\" }}",
231 json_escape(&value),
232 json_escape(&datatype)
233 )
234 .map_err(err)?;
235 }
236 }
237 }
238 write!(writer, "\n ]").map_err(err)?;
239 }
240 write!(writer, "\n }}").map_err(err)?;
241 }
242
243 writeln!(writer, "\n]").map_err(err)?;
244 Ok(())
245}
246
247pub fn serialize_to_jsonld_compact<W: Write>(
255 writer: &mut W,
256 quins: &[NQuin],
257) -> Result<(), String> {
258 use crate::sparql_library::rdf_formats::QUALIA_JSONLD_CONTEXT_V1;
259 let err = |e: std::io::Error| format!("Failed to write compact JSON-LD: {e}");
260
261 let ctx_fragment = if let Some(start) = QUALIA_JSONLD_CONTEXT_V1.find("\"@context\"") {
264 let after = &QUALIA_JSONLD_CONTEXT_V1[start..];
265 if let Some(brace) = after.find('{') {
266 let rest = &after[brace..];
267 let mut depth = 0i32;
268 let mut end = None;
269 for (i, c) in rest.char_indices() {
270 match c {
271 '{' => depth += 1,
272 '}' => {
273 depth -= 1;
274 if depth == 0 {
275 end = Some(i + 1);
276 break;
277 }
278 }
279 _ => {}
280 }
281 }
282 end.map(|e| rest[..e].to_string())
283 } else {
284 None
285 }
286 } else {
287 None
288 };
289 let ctx_json = ctx_fragment.unwrap_or_else(|| QUALIA_JSONLD_CONTEXT_V1.to_string());
290
291 write!(writer, "{{\n \"@context\": ").map_err(err)?;
292 write!(writer, "{ctx_json}").map_err(err)?;
293 write!(writer, ",\n \"@graph\": ").map_err(err)?;
294 serialize_to_jsonld(writer, quins)?;
295 write!(writer, "}}\n").map_err(err)?;
297 Ok(())
298}
299
300pub fn serialize_to_cborld<W: Write>(writer: &mut W, quins: &[NQuin]) -> Result<(), String> {
311 use ciborium::value::Value;
312
313 let cbor_object_term = |h: u64| -> Value {
314 match jsonld_term(h) {
315 JsonLdTerm::Iri(s) => {
316 Value::Map(vec![(Value::Text("@id".to_string()), Value::Text(s))])
317 }
318 JsonLdTerm::Literal { value, datatype } => Value::Map(vec![
319 (Value::Text("@value".to_string()), Value::Text(value)),
320 (Value::Text("@type".to_string()), Value::Text(datatype)),
321 ]),
322 }
323 };
324
325 let mut arr: Vec<Value> = Vec::with_capacity(quins.len());
326 for q in quins {
327 let subj = match jsonld_term(q.subject) {
328 JsonLdTerm::Iri(s) => s,
329 JsonLdTerm::Literal { value, .. } => value,
330 };
331 let pred = match jsonld_term(q.predicate) {
332 JsonLdTerm::Iri(s) => s,
333 JsonLdTerm::Literal { value, .. } => value,
334 };
335 arr.push(Value::Map(vec![
336 (Value::Text("@id".to_string()), Value::Text(subj)),
337 (Value::Text(pred), cbor_object_term(q.object)),
338 ]));
339 }
340
341 ciborium::ser::into_writer(&Value::Array(arr), writer)
342 .map_err(|e| format!("Failed to write vendor nquin-CBOR: {e}"))
343}
344
345#[cfg(test)]
346mod tests {
347 use super::*;
348 use crate::query::resolver::{INLINE_TAG_INTEGER, MSB_FLAG};
349
350 fn s(quins: &[NQuin], f: impl Fn(&mut Vec<u8>, &[NQuin]) -> Result<(), String>) -> String {
351 let mut buf = Vec::new();
352 f(&mut buf, quins).unwrap();
353 String::from_utf8(buf).unwrap()
354 }
355
356 fn quin(subject: u64, predicate: u64, object: u64) -> NQuin {
358 NQuin {
359 subject,
360 predicate,
361 object,
362 context: 0,
363 metadata: 0,
364 parity: 0,
365 }
366 }
367
368 #[test]
369 fn turtle_is_valid_and_groups_by_subject() {
370 let s1 = MSB_FLAG | 0x11;
372 let quins = [
373 quin(s1, MSB_FLAG | 0x22, MSB_FLAG | 0x33),
374 quin(s1, MSB_FLAG | 0x44, MSB_FLAG | 0x55),
375 ];
376 let out = s(&quins, serialize_to_turtle);
377 assert_eq!(out.matches(" .\n").count(), 1, "one '.' per subject: {out}");
379 assert!(out.contains(" ;\n"), "predicate list uses ';': {out}");
381 assert!(
383 !out.lines().next().unwrap().trim_end().ends_with("> ."),
384 "subject must not be terminated alone: {out}"
385 );
386 }
387
388 #[test]
389 fn turtle_object_integer_is_typed_literal_not_iri() {
390 let quins = [quin(
391 MSB_FLAG | 0x11,
392 MSB_FLAG | 0x22,
393 INLINE_TAG_INTEGER | 42,
394 )];
395 let out = s(&quins, serialize_to_turtle);
396 assert!(
397 out.contains(r#""42"^^<"#),
398 "integer object as typed literal: {out}"
399 );
400 assert!(out.contains("XMLSchema#integer"), "{out}");
401 }
402
403 #[test]
404 fn jsonld_literal_object_uses_value_and_type() {
405 let quins = [quin(
406 MSB_FLAG | 0x11,
407 MSB_FLAG | 0x22,
408 INLINE_TAG_INTEGER | 7,
409 )];
410 let out = s(&quins, serialize_to_jsonld);
411 assert!(out.contains(r#""@value": "7""#), "{out}");
412 assert!(out.contains(r#""@type""#), "{out}");
413 assert!(out.contains("XMLSchema#integer"), "{out}");
414 }
415
416 #[test]
417 fn jsonld_iri_object_uses_id() {
418 let quins = [quin(MSB_FLAG | 0x11, MSB_FLAG | 0x22, MSB_FLAG | 0x33)];
419 let out = s(&quins, serialize_to_jsonld);
420 assert!(out.contains(r#""@id""#), "{out}");
421 assert!(out.contains("did:q42:ptr/"), "{out}");
423 }
424
425 #[test]
426 fn trig_wraps_statements_in_graph_braces() {
427 let quins = [quin(MSB_FLAG | 0x11, MSB_FLAG | 0x22, MSB_FLAG | 0x33)];
428 let out = s(&quins, serialize_to_trig);
429 assert!(out.contains(" {\n"), "graph opens with '{{': {out}");
430 assert!(
431 out.trim_end().ends_with('}'),
432 "graph closes with '}}': {out}"
433 );
434 }
435
436 #[test]
437 fn cborld_emits_decodable_cbor_array_of_maps() {
438 let quins = [
440 quin(MSB_FLAG | 0x11, MSB_FLAG | 0x22, MSB_FLAG | 0x33),
441 quin(MSB_FLAG | 0x44, MSB_FLAG | 0x55, INLINE_TAG_INTEGER | 9),
442 ];
443 let mut buf = Vec::new();
444 serialize_to_cborld(&mut buf, &quins).unwrap();
445 assert_eq!(buf[0], 0x82, "expected CBOR array(2), got {:#x}", buf[0]);
447 let val: ciborium::value::Value = ciborium::de::from_reader(&buf[..]).unwrap();
449 match val {
450 ciborium::value::Value::Array(a) => {
451 assert_eq!(a.len(), 2, "one map per triple");
452 match &a[0] {
453 ciborium::value::Value::Map(m) => assert_eq!(m.len(), 2, "@id + one predicate"),
454 other => panic!("expected map, got {other:?}"),
455 }
456 match &a[1] {
458 ciborium::value::Value::Map(m) => {
459 let obj = m
460 .iter()
461 .find(|(k, _)| !matches!(k, ciborium::value::Value::Text(t) if t == "@id"))
462 .map(|(_, v)| v)
463 .expect("predicate entry");
464 match obj {
465 ciborium::value::Value::Map(om) => {
466 let keys: Vec<_> = om
467 .iter()
468 .filter_map(|(k, _)| match k {
469 ciborium::value::Value::Text(t) => Some(t.as_str()),
470 _ => None,
471 })
472 .collect();
473 assert!(keys.contains(&"@value"), "{om:?}");
474 assert!(keys.contains(&"@type"), "{om:?}");
475 }
476 other => panic!("typed literal must be a map, got {other:?}"),
477 }
478 }
479 other => panic!("expected map, got {other:?}"),
480 }
481 }
482 other => panic!("expected array, got {other:?}"),
483 }
484 }
485
486 #[test]
487 fn cborld_inline_integer_round_trips_bit_exact() {
488 use crate::sparql_library::parsers::cbor_parser::parse_cbor_ld_into;
489 use crate::sparql_library::rdf_formats::QuinCollector;
490 use std::io::Cursor;
491
492 let quins = [quin(
493 MSB_FLAG | 0x11,
494 MSB_FLAG | 0x22,
495 INLINE_TAG_INTEGER | 42,
496 )];
497 let mut buf = Vec::new();
498 serialize_to_cborld(&mut buf, &quins).unwrap();
499 let mut out = QuinCollector::new();
500 let n = parse_cbor_ld_into(Cursor::new(&buf[..]), 0, &mut out).unwrap();
501 assert_eq!(n, 1);
502 assert_eq!(out.as_slice()[0].object, INLINE_TAG_INTEGER | 42);
503 }
504
505 #[test]
506 fn cborld_inline_bool_decimal_float_round_trip_bit_exact() {
507 use crate::query::resolver::{INLINE_TAG_BOOLEAN, INLINE_TAG_DECIMAL};
508 use crate::sparql_library::parsers::cbor_parser::parse_cbor_ld_into;
509 use crate::sparql_library::rdf_formats::QuinCollector;
510 use std::io::Cursor;
511
512 let cases = [
513 INLINE_TAG_BOOLEAN | 1,
514 INLINE_TAG_DECIMAL | 3_500_000, crate::frame_layout::pack_float_object(0.5),
516 ];
517 for object in cases {
518 let quins = [quin(MSB_FLAG | 0x11, MSB_FLAG | 0x22, object)];
519 let mut buf = Vec::new();
520 serialize_to_cborld(&mut buf, &quins).unwrap();
521 let mut out = QuinCollector::new();
522 let n = parse_cbor_ld_into(Cursor::new(&buf[..]), 0, &mut out).unwrap();
523 assert_eq!(n, 1, "object={object:#x}");
524 assert_eq!(out.as_slice()[0].object, object, "object={object:#x}");
525 }
526 }
527
528 #[test]
529 fn solid_turtle_n3_jsonld_round_trip_preserve_triple_count() {
530 use crate::sparql_library::rdf_formats::{parse_rdf, QuinCollector, RdfFormat};
531 use std::io::Cursor;
532
533 let s1 = MSB_FLAG | 0xAB;
534 let quins = [
535 quin(s1, MSB_FLAG | 0x11, MSB_FLAG | 0x21),
536 quin(s1, MSB_FLAG | 0x12, INLINE_TAG_INTEGER | 7),
537 ];
538
539 assert_eq!(
540 RdfFormat::from_media_type("text/turtle; charset=utf-8"),
541 Some(RdfFormat::Turtle)
542 );
543 assert_eq!(
544 RdfFormat::from_media_type("application/ld+json"),
545 Some(RdfFormat::JsonLd)
546 );
547 assert_eq!(RdfFormat::from_media_type("text/n3"), Some(RdfFormat::N3));
548
549 let turtle = s(&quins, serialize_to_turtle);
550 let mut out = QuinCollector::new();
551 let n = parse_rdf(
552 RdfFormat::Turtle,
553 Cursor::new(turtle.as_bytes()),
554 0,
555 &mut out,
556 )
557 .unwrap();
558 assert_eq!(n, 2, "turtle round-trip: {turtle}");
559
560 let n3 = s(&quins, serialize_to_n3);
561 assert!(n3.contains("@prefix"), "n3 emits prefixes: {n3}");
562 let mut out = QuinCollector::new();
563 let n = parse_rdf(RdfFormat::N3, Cursor::new(n3.as_bytes()), 0, &mut out).unwrap();
564 assert_eq!(n, 2, "n3 round-trip count={n}: {n3}");
565
566 let compact = s(&quins, serialize_to_jsonld_compact);
567 assert!(
568 compact.contains("\"@context\""),
569 "compact json-ld has @context: {compact}"
570 );
571 assert!(
572 compact.contains("\"@graph\""),
573 "compact json-ld has @graph: {compact}"
574 );
575 let mut out = QuinCollector::new();
576 let n = parse_rdf(
577 RdfFormat::JsonLd,
578 Cursor::new(compact.as_bytes()),
579 0,
580 &mut out,
581 )
582 .unwrap();
583 assert_eq!(n, 2, "compact json-ld round-trip: {compact}");
584 }
585}