1use crate::NQuin;
36use std::io;
37
38#[path = "typed_double.rs"]
40pub mod typed_double;
41
42pub const MSB_FLAG: u64 = 1u64 << 63;
47pub const INLINE_TAG_MASK: u64 = 0b111u64 << 60; pub const INLINE_TAG_INTEGER: u64 = 0b001u64 << 60;
49pub const INLINE_TAG_DECIMAL: u64 = 0b010u64 << 60;
50pub const INLINE_TAG_BOOLEAN: u64 = 0b011u64 << 60;
51pub const INLINE_TAG_FLOAT: u64 = 0b101u64 << 60;
55pub const TAG_EMBEDDED: u64 = 0b001u64 << 60;
57pub const TAG_WEBIZEN: u64 = 0b1000u64 << 60;
60pub const INLINE_VALUE_MASK: u64 = !(MSB_FLAG | INLINE_TAG_MASK);
62
63static DEMO_LEXICON: &[(u64, &[u8])] = &[
74 (crate::q_hash("Alice"), b"http://webizen.org/demo/Alice"),
75 (crate::q_hash("Bob"), b"http://webizen.org/demo/Bob"),
76 (crate::q_hash("Carol"), b"http://webizen.org/demo/Carol"),
77 (crate::q_hash("knows"), b"http://schema.org/knows"),
78 (crate::q_hash("likes"), b"http://schema.org/likes"),
79 (
80 crate::q_hash("type"),
81 b"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
82 ),
83 (
84 crate::q_hash("label"),
85 b"http://www.w3.org/2000/01/rdf-schema#label",
86 ),
87 (crate::q_hash("Person"), b"http://schema.org/Person"),
88 (crate::q_hash("name"), b"http://schema.org/name"),
89 (
90 crate::q_hash("guardian"),
91 b"http://webizen.org/vocab#guardian",
92 ),
93 (crate::q_hash("ward"), b"http://webizen.org/vocab#ward"),
94 (
95 crate::q_hash("has_symptom"),
96 b"http://webizen.org/medical#hasSymptom",
97 ),
98 (crate::q_hash("Fever"), b"http://snomed.info/id/386661006"),
99 (
100 crate::q_hash("income"),
101 b"http://webizen.org/finance#income",
102 ),
103 (
104 crate::q_hash("balance"),
105 b"http://webizen.org/finance#balance",
106 ),
107];
108
109pub struct Lexicon {
121 entries: &'static [(u64, &'static [u8])],
122}
123
124impl Lexicon {
125 pub const fn new() -> Self {
127 Self {
128 entries: DEMO_LEXICON,
129 }
130 }
131
132 #[inline]
137 pub fn resolve(&self, hash: u64) -> Option<&'static [u8]> {
138 for &(h, bytes) in self.entries {
139 if h == hash {
140 return Some(bytes);
141 }
142 }
143 None
144 }
145}
146
147const LEXICON: Lexicon = Lexicon::new();
148
149pub fn resolve_hash(hash: u64) -> Option<&'static [u8]> {
159 if let Some(uri) = LEXICON.resolve(hash) {
163 return Some(uri);
164 }
165 if (hash & MSB_FLAG) != 0 {
166 return None; }
168 None
169}
170
171#[inline]
186pub(crate) fn write_iri_term<W: io::Write>(val: u64, out: &mut W) -> io::Result<()> {
187 if let Some(uri) = LEXICON.resolve(val) {
189 out.write_all(b"<")?;
190 out.write_all(uri)?;
191 return out.write_all(b">");
192 }
193 if (val & MSB_FLAG) != 0 {
195 let ptr = val & !MSB_FLAG;
196 return write!(out, "<did:q42:ptr/{ptr:016x}>");
197 }
198 write!(out, "<quin:hash/{val:016x}>")
200}
201
202#[derive(Debug, Clone, Copy, PartialEq)]
206pub enum InlineLiteral {
207 Integer(i64),
209 Decimal(i64),
211 Boolean(bool),
213 Float(f32),
215}
216
217impl InlineLiteral {
218 pub fn datatype_iri(&self) -> &'static str {
220 match self {
221 InlineLiteral::Integer(_) => "http://www.w3.org/2001/XMLSchema#integer",
222 InlineLiteral::Decimal(_) => "http://www.w3.org/2001/XMLSchema#decimal",
223 InlineLiteral::Boolean(_) => "http://www.w3.org/2001/XMLSchema#boolean",
224 InlineLiteral::Float(_) => "http://www.w3.org/2001/XMLSchema#float",
225 }
226 }
227}
228
229impl std::fmt::Display for InlineLiteral {
230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232 match *self {
233 InlineLiteral::Integer(n) => write!(f, "{n}"),
234 InlineLiteral::Decimal(raw) => {
235 let neg = raw < 0;
236 let abs = raw.unsigned_abs();
237 let whole = abs / 1_000_000;
238 let frac = abs % 1_000_000;
239 if neg {
240 write!(f, "-{whole}.{frac:06}")
241 } else {
242 write!(f, "{whole}.{frac:06}")
243 }
244 }
245 InlineLiteral::Boolean(b) => write!(f, "{b}"),
246 InlineLiteral::Float(x) => write!(f, "{x}"),
247 }
248 }
249}
250
251#[inline]
259pub fn classify_inline_literal(val: u64) -> Option<InlineLiteral> {
260 if (val & MSB_FLAG) != 0 {
262 return None;
263 }
264 match val & INLINE_TAG_MASK {
265 INLINE_TAG_INTEGER => {
266 let mut n = (val & INLINE_VALUE_MASK) as i64;
267 if (n & (1i64 << 59)) != 0 {
268 n |= !((1i64 << 60) - 1);
269 }
270 Some(InlineLiteral::Integer(n))
271 }
272 INLINE_TAG_DECIMAL => {
273 let mut raw = (val & INLINE_VALUE_MASK) as i64;
274 if (raw & (1i64 << 59)) != 0 {
275 raw |= !((1i64 << 60) - 1);
276 }
277 Some(InlineLiteral::Decimal(raw))
278 }
279 INLINE_TAG_BOOLEAN => Some(InlineLiteral::Boolean((val & 1) != 0)),
280 INLINE_TAG_FLOAT => Some(InlineLiteral::Float(f32::from_bits(
281 (val & 0xFFFF_FFFF) as u32,
282 ))),
283 _ => None,
284 }
285}
286
287pub fn pack_typed_literal(value: &str, datatype_iri: &str) -> Option<u64> {
291 let dt = datatype_iri.trim();
292 let dt = dt
293 .strip_prefix('<')
294 .and_then(|s| s.strip_suffix('>'))
295 .unwrap_or(dt);
296 if dt == "http://www.w3.org/2001/XMLSchema#integer" || dt == "xsd:integer" {
297 let num = value.parse::<i64>().ok()?;
298 let max_val = (1i64 << 59) - 1;
299 let min_val = -(1i64 << 59);
300 if num < min_val || num > max_val {
301 return None;
302 }
303 let unsigned = (num as u64) & INLINE_VALUE_MASK;
304 return Some(INLINE_TAG_INTEGER | unsigned);
305 }
306 if dt == "http://www.w3.org/2001/XMLSchema#decimal" || dt == "xsd:decimal" {
307 let num = value.parse::<f64>().ok()?;
308 let scaled = num * 1_000_000.0;
309 let max_val = ((1i64 << 59) - 1) as f64;
310 let min_val = (-(1i64 << 59)) as f64;
311 if !(min_val..=max_val).contains(&scaled) {
312 return None;
313 }
314 let num_i64 = scaled.round() as i64;
315 let unsigned = (num_i64 as u64) & INLINE_VALUE_MASK;
316 return Some(INLINE_TAG_DECIMAL | unsigned);
317 }
318 if dt == "http://www.w3.org/2001/XMLSchema#boolean" || dt == "xsd:boolean" {
319 return match value {
320 "true" | "1" => Some(INLINE_TAG_BOOLEAN | 1),
321 "false" | "0" => Some(INLINE_TAG_BOOLEAN | 0),
322 _ => None,
323 };
324 }
325 if dt == typed_double::DATATYPE || dt == "xsd:double" {
328 return None;
329 }
330 if dt == "http://www.w3.org/2001/XMLSchema#float" || dt == "xsd:float" {
331 let f = value.parse::<f32>().ok()?;
332 return Some(crate::frame_layout::pack_float_object(f));
333 }
334 None
335}
336
337#[inline]
345pub(crate) fn write_object_term<W: io::Write>(val: u64, out: &mut W) -> io::Result<()> {
346 if let Some(uri) = LEXICON.resolve(val) {
348 out.write_all(b"<")?;
349 out.write_all(uri)?;
350 return out.write_all(b">");
351 }
352 if (val & MSB_FLAG) != 0 {
354 let ptr = val & !MSB_FLAG;
355 return write!(out, "<did:q42:ptr/{ptr:016x}>");
356 }
357 match classify_inline_literal(val) {
363 Some(lit) => write!(out, "\"{lit}\"^^<{}>", lit.datatype_iri()),
364 None => write!(out, "<quin:hash/{val:016x}>"),
365 }
366}
367
368pub fn format_ntriples_to<W: io::Write>(quins: &[NQuin], out: &mut W) -> io::Result<()> {
382 for q in quins {
383 write_ntriple_line(q, out)?;
384 }
385 Ok(())
386}
387
388pub fn format_nquads_to<W: io::Write>(quins: &[NQuin], out: &mut W) -> io::Result<()> {
390 for q in quins {
391 write_iri_term(q.subject, out)?;
392 out.write_all(b" ")?;
393 write_iri_term(q.predicate, out)?;
394 out.write_all(b" ")?;
395 write_object_term(q.object, out)?;
396 out.write_all(b" ")?;
397 write_iri_term(q.context, out)?;
398 out.write_all(b" .\n")?;
399 }
400 Ok(())
401}
402
403pub fn format_ntriples_star_to<W: io::Write>(quins: &[NQuin], out: &mut W) -> io::Result<()> {
405 for q in quins {
406 write_ntriples_star_line(q, out)?;
407 }
408 Ok(())
409}
410
411#[inline]
412fn write_ntriple_line<W: io::Write>(q: &NQuin, out: &mut W) -> io::Result<()> {
413 write_iri_term(q.subject, out)?;
414 out.write_all(b" ")?;
415 write_iri_term(q.predicate, out)?;
416 out.write_all(b" ")?;
417 write_object_term(q.object, out)?;
418 out.write_all(b" .\n")
419}
420
421#[inline]
422fn write_ntriples_star_line<W: io::Write>(q: &NQuin, out: &mut W) -> io::Result<()> {
423 if crate::rdf_star::is_virtual_id(q.subject) {
424 out.write_all(b"<<<")?;
425 write_iri_term(q.subject, out)?;
426 out.write_all(b">>> ")?;
427 } else {
428 write_iri_term(q.subject, out)?;
429 out.write_all(b" ")?;
430 }
431 write_iri_term(q.predicate, out)?;
432 out.write_all(b" ")?;
433 write_object_term(q.object, out)?;
434 out.write_all(b" .\n")
435}
436
437#[cfg(test)]
442mod tests {
443 use super::*;
444
445 fn quin(s: u64, p: u64, o: u64) -> NQuin {
446 NQuin {
447 subject: s,
448 predicate: p,
449 object: o,
450 context: 0,
451 metadata: 0,
452 parity: 0,
453 }
454 }
455
456 fn render(quins: &[NQuin]) -> String {
457 let mut buf = Vec::new();
458 format_ntriples_to(quins, &mut buf).unwrap();
459 String::from_utf8(buf).unwrap()
460 }
461
462 #[test]
465 fn known_hash_resolves_to_uri() {
466 let hash = crate::q_hash("Alice");
467 let result = resolve_hash(hash).unwrap();
468 assert_eq!(result, b"http://webizen.org/demo/Alice");
469 }
470
471 #[test]
472 fn unknown_hash_returns_none() {
473 assert!(resolve_hash(0xDEAD_BEEF_1234_5678).is_none());
474 }
475
476 #[test]
477 fn topological_pointer_returns_none() {
478 let ptr = crate::q_hash("z6Mk") | (1u64 << 63);
479 assert!(resolve_hash(ptr).is_none());
480 }
481
482 #[test]
485 fn known_iri_rendered_with_angle_brackets() {
486 let mut buf = Vec::new();
487 write_iri_term(crate::q_hash("Alice"), &mut buf).unwrap();
488 assert_eq!(buf, b"<http://webizen.org/demo/Alice>");
489 }
490
491 #[test]
492 fn unknown_hash_fallback_is_hex() {
493 let mut buf = Vec::new();
494 write_iri_term(0x00_00_00_00_00_00_00_2A, &mut buf).unwrap();
495 assert_eq!(buf, b"<quin:hash/000000000000002a>");
497 }
498
499 #[test]
500 fn topological_pointer_renders_as_did_q42_ptr() {
501 let val = 42u64 | (1u64 << 63);
502 let mut buf = Vec::new();
503 write_iri_term(val, &mut buf).unwrap();
504 let s = String::from_utf8(buf).unwrap();
505 assert!(s.starts_with("<did:q42:ptr/"), "got: {s}");
506 }
507
508 #[test]
509 fn inline_integer_object() {
510 let val = INLINE_TAG_INTEGER | 99;
511 let mut buf = Vec::new();
512 write_object_term(val, &mut buf).unwrap();
513 let s = String::from_utf8(buf).unwrap();
514 assert_eq!(s, "\"99\"^^<http://www.w3.org/2001/XMLSchema#integer>");
515 }
516
517 #[test]
518 fn inline_boolean_true() {
519 let val = INLINE_TAG_BOOLEAN | 1;
520 let mut buf = Vec::new();
521 write_object_term(val, &mut buf).unwrap();
522 assert_eq!(
523 String::from_utf8(buf).unwrap(),
524 "\"true\"^^<http://www.w3.org/2001/XMLSchema#boolean>"
525 );
526 }
527
528 #[test]
529 fn inline_boolean_false() {
530 let val = INLINE_TAG_BOOLEAN | 0;
531 let mut buf = Vec::new();
532 write_object_term(val, &mut buf).unwrap();
533 assert_eq!(
534 String::from_utf8(buf).unwrap(),
535 "\"false\"^^<http://www.w3.org/2001/XMLSchema#boolean>"
536 );
537 }
538
539 #[test]
540 fn inline_decimal_object() {
541 let val = INLINE_TAG_DECIMAL | 3_141_592u64;
543 let mut buf = Vec::new();
544 write_object_term(val, &mut buf).unwrap();
545 assert_eq!(
546 String::from_utf8(buf).unwrap(),
547 "\"3.141592\"^^<http://www.w3.org/2001/XMLSchema#decimal>"
548 );
549 }
550
551 #[test]
552 fn inline_float_object() {
553 let val = INLINE_TAG_FLOAT | (3.5f32.to_bits() as u64);
555 let mut buf = Vec::new();
556 write_object_term(val, &mut buf).unwrap();
557 assert_eq!(
558 String::from_utf8(buf).unwrap(),
559 "\"3.5\"^^<http://www.w3.org/2001/XMLSchema#float>"
560 );
561 let packed = crate::frame_layout::pack_float_object(3.5);
563 assert_eq!(
564 packed & crate::frame_layout::INLINE_TAG_MASK,
565 INLINE_TAG_FLOAT
566 );
567 }
568
569 #[test]
570 fn inline_negative_integer_object() {
571 let num = -42i64;
572 let unsigned = (num as u64) & INLINE_VALUE_MASK;
573 let val = INLINE_TAG_INTEGER | unsigned;
574 let mut buf = Vec::new();
575 write_object_term(val, &mut buf).unwrap();
576 assert_eq!(
577 String::from_utf8(buf).unwrap(),
578 "\"-42\"^^<http://www.w3.org/2001/XMLSchema#integer>"
579 );
580 }
581
582 #[test]
583 fn inline_negative_decimal_object() {
584 let num_f64 = -3.141592f64;
585 let num = (num_f64 * 1_000_000.0).round() as i64;
586 let unsigned = (num as u64) & INLINE_VALUE_MASK;
587 let val = INLINE_TAG_DECIMAL | unsigned;
588 let mut buf = Vec::new();
589 write_object_term(val, &mut buf).unwrap();
590 assert_eq!(
591 String::from_utf8(buf).unwrap(),
592 "\"-3.141592\"^^<http://www.w3.org/2001/XMLSchema#decimal>"
593 );
594 }
595
596 #[test]
599 fn empty_slice_writes_nothing() {
600 assert_eq!(render(&[]), "");
601 }
602
603 #[test]
604 fn known_terms_resolve_to_iris() {
605 let q = quin(
606 crate::q_hash("Alice"),
607 crate::q_hash("knows"),
608 crate::q_hash("Bob"),
609 );
610 let out = render(&[q]);
611 assert!(
612 out.contains("<http://webizen.org/demo/Alice>"),
613 "got: {out}"
614 );
615 assert!(out.contains("<http://schema.org/knows>"), "got: {out}");
616 assert!(out.contains("<http://webizen.org/demo/Bob>"), "got: {out}");
617 assert!(out.ends_with(" .\n"));
618 }
619
620 #[test]
621 fn unknown_terms_use_hex_fallback() {
622 let q = quin(1, 2, 3);
623 let out = render(&[q]);
624 assert!(out.contains("<quin:hash/0000000000000001>"), "got: {out}");
625 assert!(out.contains("<quin:hash/0000000000000002>"), "got: {out}");
626 assert!(out.contains("<quin:hash/0000000000000003>"), "got: {out}");
627 }
628
629 #[test]
630 fn multiple_quins_produce_multiple_lines() {
631 let qs = [quin(1, 2, 3), quin(4, 5, 6)];
632 let out = render(&qs);
633 assert_eq!(out.lines().count(), 2);
634 }
635
636 #[test]
637 fn subject_msb_renders_as_topological_pointer() {
638 let q = quin((1u64 << 63) | 42, 2, 3);
640 let out = render(&[q]);
641 assert!(out.starts_with("<did:q42:ptr/"), "got: {out}");
642 }
643}