1use std::collections::BTreeMap;
4
5#[derive(Debug, Clone, PartialEq, Eq, Hash)]
7pub enum TimeScale {
8 Unix,
10 Tai,
12 Gps,
14 Monotonic,
16 Proper,
18}
19
20#[derive(Debug, Clone, PartialEq)]
27pub struct Instant {
28 pub scale: TimeScale,
29 pub secs: i64,
30 pub nanos: u32,
31 pub frame: Option<String>,
33 pub seal: Option<[u8; 64]>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Hash)]
39pub struct Duration {
40 pub secs: i64,
41 pub nanos: u32,
42}
43
44#[derive(Debug, Clone, PartialEq)]
49pub struct Quantity {
50 pub value: f64,
51 pub unit: String,
53}
54
55#[derive(Debug, Clone, PartialEq)]
59pub struct Frame {
60 pub origin: Vec<f64>,
62 pub basis: Vec<Vec<f64>>,
64 pub parent: Option<String>,
66}
67
68#[derive(Debug, Clone, PartialEq)]
70pub struct Pose {
71 pub position: Vec<f64>,
72 pub orientation: Vec<f64>,
74 pub frame: Option<String>,
76}
77
78#[derive(Debug, Clone, PartialEq)]
80pub struct Transform {
81 pub translate: Vec<f64>,
82 pub rotate: Vec<f64>,
83 pub scale: Vec<f64>,
84 pub skew: Vec<f64>,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Hash)]
89pub struct FieldRef {
90 pub iri: String,
92 pub hash: u64,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Hash)]
98pub struct MaterialRef {
99 pub iri: String,
101 pub hash: u64,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Hash)]
109pub struct TensorRef {
110 pub handle: u64,
112 pub hash: u64,
114}
115
116#[derive(Debug, Clone, PartialEq, Eq, Hash)]
119pub struct GeometryRef {
120 pub handle: u64,
122 pub hash: u64,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Hash)]
129pub struct AssetRef {
130 pub iri: String,
132 pub hash: u64,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Hash)]
143pub struct SpeciesRef {
144 pub iri: String,
146 pub hash: u64,
148}
149
150#[derive(Debug, Clone, PartialEq)]
156pub struct Mixture {
157 pub iri: Option<String>,
160 pub components: Vec<(SpeciesRef, f64)>,
165 pub phase: MixturePhase,
168 pub miscibility: Miscibility,
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
176pub enum MixturePhase {
177 Solid,
178 Liquid,
179 Gas,
180 Plasma,
181 Supercritical,
182}
183
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
186pub enum Miscibility {
187 Miscible,
189 Immiscible,
191 Partial,
193}
194
195#[derive(Debug, Clone, PartialEq)]
201pub struct ConservationResult {
202 pub quantity: ConservationQuantity,
205 pub before: f64,
207 pub after: f64,
209 pub conserved: bool,
211 pub tolerance: f64,
213}
214
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
217pub enum ConservationQuantity {
218 Mass,
220 Mole,
222 Energy,
224 Charge,
226 Momentum,
228 AngularMomentum,
230}
231
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
241pub enum CausalRelation {
242 Timelike,
244 Lightlike,
246 Spacelike,
248}
249
250impl CausalRelation {
251 pub fn allows_causation(self) -> bool {
253 matches!(self, CausalRelation::Timelike | CausalRelation::Lightlike)
254 }
255
256 pub fn is_causally_disconnected(self) -> bool {
258 matches!(self, CausalRelation::Spacelike)
259 }
260}
261
262#[derive(Debug, Clone, PartialEq, Eq, Default)]
271pub struct DisclosureBoundary {
272 pub publication: bool,
274 pub replication: bool,
276 pub agency: bool,
278 pub exfiltration: bool,
280}
281
282impl DisclosureBoundary {
283 pub fn none() -> Self {
285 Self::default()
286 }
287
288 pub fn public_only() -> Self {
291 Self {
292 publication: true,
293 ..Self::default()
294 }
295 }
296
297 pub fn full() -> Self {
299 Self {
300 publication: true,
301 replication: true,
302 agency: true,
303 exfiltration: true,
304 }
305 }
306
307 pub fn as_bits(&self) -> [bool; 4] {
309 [
310 self.publication,
311 self.replication,
312 self.agency,
313 self.exfiltration,
314 ]
315 }
316}
317
318#[derive(Debug, Clone, PartialEq, Eq, Hash)]
323pub struct WorldLine {
324 pub iri: String,
326 pub asserted_by: String,
328 pub created_at: i64,
330}
331
332#[derive(Debug, Clone, PartialEq)]
335pub struct EnumValue {
336 pub enum_name: String,
337 pub variant_name: String,
338 pub payload: Vec<Value>,
339}
340
341impl EnumValue {
342 pub fn unit(enum_name: &str, variant_name: &str) -> Self {
344 Self {
345 enum_name: enum_name.to_string(),
346 variant_name: variant_name.to_string(),
347 payload: Vec::new(),
348 }
349 }
350
351 pub fn with_payload(enum_name: &str, variant_name: &str, payload: Vec<Value>) -> Self {
353 Self {
354 enum_name: enum_name.to_string(),
355 variant_name: variant_name.to_string(),
356 payload,
357 }
358 }
359}
360
361#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
374pub struct QuinRef {
375 payload: [u64; 6],
378}
379
380impl QuinRef {
381 pub fn from_raw(
383 subject: u64,
384 predicate: u64,
385 object: u64,
386 context: u64,
387 metadata: u64,
388 parity: u64,
389 ) -> Self {
390 Self {
391 payload: [subject, predicate, object, context, metadata, parity],
392 }
393 }
394
395 pub fn from_quin(subject: u64, predicate: u64, object: u64, context: u64) -> Self {
398 let metadata = 0u64;
399 let parity = subject ^ predicate ^ object ^ context ^ metadata;
400 Self::from_raw(subject, predicate, object, context, metadata, parity)
401 }
402
403 pub fn raw_fields(&self) -> [u64; 6] {
406 self.payload
407 }
408
409 pub fn content_hash(&self) -> u64 {
412 let mut h = 0xcbf29ce484222325u64;
413 for &v in &self.payload {
414 h ^= v;
415 h = h.wrapping_mul(0x100000001b3);
416 }
417 h
418 }
419}
420
421#[derive(Debug, Clone, PartialEq)]
422pub enum Value {
423 Null,
424 Bool(bool),
425 I64(i64),
426 U64(u64),
427 F64(f64),
428 String(String),
429 Iri(String),
430 Blank(String),
431 Prefixed(String, String),
432 Var(String),
433 List(Vec<Value>),
434 Record(BTreeMap<String, Value>),
435 Triple(Box<Value>, Box<Value>, Box<Value>),
436 Reified {
437 s: Box<Value>,
438 p: Box<Value>,
439 o: Box<Value>,
440 r: Box<Value>,
441 },
442 Receipt,
443 Ok(Box<Value>),
444 Err(Box<Value>),
445 Instant(Instant),
448 Duration(Duration),
450 Quantity(Quantity),
452 Frame(Frame),
454 Pose(Pose),
456 Transform(Transform),
458 FieldRef(FieldRef),
460 MaterialRef(MaterialRef),
462 TensorRef(TensorRef),
464 GeometryRef(GeometryRef),
466 AssetRef(AssetRef),
468 WorldLine(WorldLine),
470 QuinRef(QuinRef),
473 Enum(EnumValue),
475 Lambda {
477 params: Vec<String>,
478 body: Box<crate::ast::Expr>,
479 },
480 SpeciesRef(SpeciesRef),
482 Mixture(Mixture),
484 Conservation(ConservationResult),
486 Causal(CausalRelation),
488 DisclosureDenied {
493 capability: String,
494 reason: String,
495 },
496 DisclosureBoundary(DisclosureBoundary),
499}
500
501impl Value {
502 pub fn is_truthy(&self) -> bool {
504 match self {
505 Value::Bool(b) => *b,
506 Value::Null => false,
507 Value::I64(0) | Value::U64(0) => false,
508 Value::DisclosureDenied { .. } => false,
510 _ => true,
511 }
512 }
513
514 pub fn as_f64(&self) -> Option<f64> {
516 match self {
517 Value::I64(n) => Some(*n as f64),
518 Value::U64(n) => Some(*n as f64),
519 Value::F64(n) => Some(*n),
520 Value::Quantity(q) => Some(q.value),
521 _ => None,
522 }
523 }
524
525 pub fn as_i64(&self) -> Option<i64> {
527 match self {
528 Value::I64(n) => Some(*n),
529 Value::U64(n) if *n <= i64::MAX as u64 => Some(*n as i64),
530 Value::F64(n) if n.fract() == 0.0 => Some(*n as i64),
531 _ => None,
532 }
533 }
534
535 pub fn as_str(&self) -> Option<&str> {
537 match self {
538 Value::String(s) | Value::Iri(s) => Some(s.as_str()),
539 _ => None,
540 }
541 }
542
543 pub fn as_instant(&self) -> Option<&Instant> {
545 match self {
546 Value::Instant(i) => Some(i),
547 _ => None,
548 }
549 }
550
551 pub fn as_duration(&self) -> Option<&Duration> {
553 match self {
554 Value::Duration(d) => Some(d),
555 _ => None,
556 }
557 }
558
559 pub fn as_quantity(&self) -> Option<&Quantity> {
561 match self {
562 Value::Quantity(q) => Some(q),
563 _ => None,
564 }
565 }
566
567 pub fn as_frame(&self) -> Option<&Frame> {
569 match self {
570 Value::Frame(f) => Some(f),
571 _ => None,
572 }
573 }
574
575 pub fn as_pose(&self) -> Option<&Pose> {
577 match self {
578 Value::Pose(p) => Some(p),
579 _ => None,
580 }
581 }
582
583 pub fn as_transform(&self) -> Option<&Transform> {
585 match self {
586 Value::Transform(t) => Some(t),
587 _ => None,
588 }
589 }
590
591 pub fn as_field_ref(&self) -> Option<&FieldRef> {
593 match self {
594 Value::FieldRef(f) => Some(f),
595 _ => None,
596 }
597 }
598
599 pub fn as_material_ref(&self) -> Option<&MaterialRef> {
601 match self {
602 Value::MaterialRef(m) => Some(m),
603 _ => None,
604 }
605 }
606
607 pub fn as_tensor_ref(&self) -> Option<&TensorRef> {
609 match self {
610 Value::TensorRef(t) => Some(t),
611 _ => None,
612 }
613 }
614
615 pub fn as_geometry_ref(&self) -> Option<&GeometryRef> {
617 match self {
618 Value::GeometryRef(g) => Some(g),
619 _ => None,
620 }
621 }
622
623 pub fn as_asset_ref(&self) -> Option<&AssetRef> {
625 match self {
626 Value::AssetRef(a) => Some(a),
627 _ => None,
628 }
629 }
630
631 pub fn as_worldline(&self) -> Option<&WorldLine> {
633 match self {
634 Value::WorldLine(w) => Some(w),
635 _ => None,
636 }
637 }
638
639 pub fn as_quin_ref(&self) -> Option<&QuinRef> {
641 match self {
642 Value::QuinRef(q) => Some(q),
643 _ => None,
644 }
645 }
646
647 pub fn as_enum(&self) -> Option<&EnumValue> {
649 match self {
650 Value::Enum(e) => Some(e),
651 _ => None,
652 }
653 }
654
655 pub fn as_species_ref(&self) -> Option<&SpeciesRef> {
657 match self {
658 Value::SpeciesRef(s) => Some(s),
659 _ => None,
660 }
661 }
662
663 pub fn as_mixture(&self) -> Option<&Mixture> {
665 match self {
666 Value::Mixture(m) => Some(m),
667 _ => None,
668 }
669 }
670
671 pub fn as_conservation(&self) -> Option<&ConservationResult> {
673 match self {
674 Value::Conservation(c) => Some(c),
675 _ => None,
676 }
677 }
678
679 pub fn as_causal(&self) -> Option<CausalRelation> {
681 match self {
682 Value::Causal(c) => Some(*c),
683 _ => None,
684 }
685 }
686
687 pub fn as_disclosure_denied(&self) -> Option<(&str, &str)> {
690 match self {
691 Value::DisclosureDenied { capability, reason } => {
692 Some((capability.as_str(), reason.as_str()))
693 }
694 _ => None,
695 }
696 }
697
698 pub fn as_disclosure_boundary(&self) -> Option<&DisclosureBoundary> {
700 match self {
701 Value::DisclosureBoundary(b) => Some(b),
702 _ => None,
703 }
704 }
705}
706
707impl Instant {
710 pub fn unix(secs: i64, nanos: u32) -> Self {
712 Self {
713 scale: TimeScale::Unix,
714 secs,
715 nanos,
716 frame: None,
717 seal: None,
718 }
719 }
720
721 pub fn monotonic(nanos: u64) -> Self {
723 Self {
724 scale: TimeScale::Monotonic,
725 secs: (nanos / 1_000_000_000) as i64,
726 nanos: (nanos % 1_000_000_000) as u32,
727 frame: None,
728 seal: None,
729 }
730 }
731}
732
733impl Duration {
734 pub fn from_secs(secs: i64) -> Self {
736 Self { secs, nanos: 0 }
737 }
738
739 pub fn from_nanos(nanos: i64) -> Self {
741 Self {
742 secs: nanos / 1_000_000_000,
743 nanos: (nanos % 1_000_000_000) as u32,
744 }
745 }
746
747 pub fn total_nanos(&self) -> i128 {
749 self.secs as i128 * 1_000_000_000 + self.nanos as i128
750 }
751}
752
753impl std::fmt::Display for Duration {
754 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
755 if self.secs == 0 && self.nanos % 1_000_000 == 0 {
756 write!(f, "{}ms", self.nanos / 1_000_000)
757 } else if self.nanos == 0 {
758 write!(f, "{}s", self.secs)
759 } else {
760 write!(f, "{}.{:09}s", self.secs, self.nanos)
761 }
762 }
763}
764
765impl Quantity {
766 pub fn new(value: f64, unit: &str) -> Self {
768 Self {
769 value,
770 unit: unit.to_string(),
771 }
772 }
773
774 pub fn dimensionless(value: f64) -> Self {
776 Self {
777 value,
778 unit: String::new(),
779 }
780 }
781}
782
783impl std::fmt::Display for Value {
784 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
785 match self {
786 Value::Null => write!(f, "null"),
787 Value::Bool(b) => write!(f, "{b}"),
788 Value::I64(n) => write!(f, "{n}"),
789 Value::U64(n) => write!(f, "{n}"),
790 Value::F64(n) => write!(f, "{n}"),
791 Value::String(s) => write!(f, "\"{s}\""),
792 Value::Iri(s) => write!(f, "<{s}>"),
793 Value::Blank(s) => write!(f, "_:{s}"),
794 Value::Prefixed(p, n) => write!(f, "{p}:{n}"),
795 Value::Var(s) => write!(f, "?{s}"),
796 Value::List(xs) => {
797 write!(f, "[")?;
798 for (i, x) in xs.iter().enumerate() {
799 if i > 0 {
800 write!(f, ", ")?;
801 }
802 write!(f, "{x}")?;
803 }
804 write!(f, "]")
805 }
806 Value::Record(map) => {
807 if let Some(Value::String(hex)) = map.get("hex") {
808 if hex.starts_with('#') {
809 if let Some(Value::String(space)) = map.get("space") {
810 if space == "srgb" {
811 return write!(f, "{hex}");
812 }
813 }
814 }
815 }
816 write!(f, "{{")?;
817 for (i, (k, v)) in map.iter().enumerate() {
818 if i > 0 {
819 write!(f, ", ")?;
820 }
821 write!(f, "{k}: {v}")?;
822 }
823 write!(f, "}}")
824 }
825 Value::Quantity(q) => {
826 if q.value.fract() == 0.0 && q.value.abs() < 1e15 {
827 write!(f, "{}{}", q.value as i64, q.unit)
828 } else {
829 write!(f, "{}{}", q.value, q.unit)
830 }
831 }
832 Value::Duration(d) => write!(f, "{d}"),
833 Value::Instant(i) => {
834 if i.secs == 0 && i.nanos % 1_000_000 == 0 {
835 write!(f, "{}ms", i.nanos / 1_000_000)
836 } else if i.nanos == 0 {
837 write!(f, "{}s", i.secs)
838 } else {
839 write!(f, "{}.{:09}s", i.secs, i.nanos)
840 }
841 }
842 Value::Ok(v) => write!(f, "Ok({v})"),
843 Value::Err(v) => write!(f, "Err({v})"),
844 Value::Receipt => write!(f, "receipt"),
845 other => write!(f, "{other:?}"),
846 }
847 }
848}
849
850#[cfg(test)]
851mod tests {
852 use super::*;
853
854 #[test]
855 fn instant_unix_constructor() {
856 let i = Instant::unix(1000, 500_000);
857 assert_eq!(i.scale, TimeScale::Unix);
858 assert_eq!(i.secs, 1000);
859 assert_eq!(i.nanos, 500_000);
860 assert!(i.seal.is_none());
861 }
862
863 #[test]
864 fn instant_monotonic_constructor() {
865 let i = Instant::monotonic(1_500_000_000);
866 assert_eq!(i.scale, TimeScale::Monotonic);
867 assert_eq!(i.secs, 1);
868 assert_eq!(i.nanos, 500_000_000);
869 }
870
871 #[test]
872 fn duration_from_secs() {
873 let d = Duration::from_secs(60);
874 assert_eq!(d.secs, 60);
875 assert_eq!(d.nanos, 0);
876 }
877
878 #[test]
879 fn duration_from_nanos() {
880 let d = Duration::from_nanos(1_500_000_000);
881 assert_eq!(d.secs, 1);
882 assert_eq!(d.nanos, 500_000_000);
883 }
884
885 #[test]
886 fn duration_total_nanos() {
887 let d = Duration {
888 secs: 2,
889 nanos: 500_000_000,
890 };
891 assert_eq!(d.total_nanos(), 2_500_000_000);
892 }
893
894 #[test]
895 fn quantity_dimensionless() {
896 let q = Quantity::dimensionless(42.0);
897 assert_eq!(q.value, 42.0);
898 assert_eq!(q.unit, "");
899 }
900
901 #[test]
902 fn quantity_with_unit() {
903 let q = Quantity::new(101.325, "qudt:KiloPascal");
904 assert_eq!(q.value, 101.325);
905 assert_eq!(q.unit, "qudt:KiloPascal");
906 }
907
908 #[test]
909 fn value_instant_extract() {
910 let v = Value::Instant(Instant::unix(100, 0));
911 let i = v.as_instant().unwrap();
912 assert_eq!(i.secs, 100);
913 }
914
915 #[test]
916 fn value_duration_extract() {
917 let v = Value::Duration(Duration::from_secs(30));
918 let d = v.as_duration().unwrap();
919 assert_eq!(d.secs, 30);
920 }
921
922 #[test]
923 fn value_quantity_extract() {
924 let v = Value::Quantity(Quantity::new(1.0, "qudt:Meter"));
925 let q = v.as_quantity().unwrap();
926 assert_eq!(q.unit, "qudt:Meter");
927 }
928
929 #[test]
930 fn value_quantity_as_f64() {
931 let v = Value::Quantity(Quantity::new(42.5, "qudt:KiloPascal"));
932 assert_eq!(v.as_f64(), Some(42.5));
933 }
934
935 #[test]
936 fn value_frame_extract() {
937 let f = Frame {
938 origin: vec![0.0, 0.0, 0.0],
939 basis: vec![],
940 parent: None,
941 };
942 let v = Value::Frame(f);
943 assert!(v.as_frame().is_some());
944 }
945
946 #[test]
947 fn value_pose_extract() {
948 let p = Pose {
949 position: vec![1.0, 2.0, 3.0],
950 orientation: vec![1.0, 0.0, 0.0, 0.0],
951 frame: None,
952 };
953 let v = Value::Pose(p);
954 assert!(v.as_pose().is_some());
955 }
956
957 #[test]
958 fn value_transform_extract() {
959 let t = Transform {
960 translate: vec![1.0, 0.0],
961 rotate: vec![0.0],
962 scale: vec![1.0, 1.0],
963 skew: vec![0.0, 0.0],
964 };
965 let v = Value::Transform(t);
966 assert!(v.as_transform().is_some());
967 }
968
969 #[test]
970 fn value_field_ref_extract() {
971 let f = FieldRef {
972 iri: "field:ambient_pressure".to_string(),
973 hash: 0xDEAD_BEEF,
974 };
975 let v = Value::FieldRef(f);
976 let fr = v.as_field_ref().unwrap();
977 assert_eq!(fr.iri, "field:ambient_pressure");
978 }
979
980 #[test]
981 fn value_material_ref_extract() {
982 let m = MaterialRef {
983 iri: "material:sucrose".to_string(),
984 hash: 0xCAFEBABE,
985 };
986 let v = Value::MaterialRef(m);
987 let mr = v.as_material_ref().unwrap();
988 assert_eq!(mr.iri, "material:sucrose");
989 }
990
991 #[test]
994 fn t52_tensor_ref_construction_and_extract() {
995 let t = TensorRef {
996 handle: 42,
997 hash: 0xABCD,
998 };
999 let v = Value::TensorRef(t);
1000 let tr = v.as_tensor_ref().unwrap();
1001 assert_eq!(tr.handle, 42);
1002 assert_eq!(tr.hash, 0xABCD);
1003 }
1004
1005 #[test]
1006 fn t52_geometry_ref_construction_and_extract() {
1007 let g = GeometryRef {
1008 handle: 7,
1009 hash: 0x1234,
1010 };
1011 let v = Value::GeometryRef(g);
1012 let gr = v.as_geometry_ref().unwrap();
1013 assert_eq!(gr.handle, 7);
1014 assert_eq!(gr.hash, 0x1234);
1015 }
1016
1017 #[test]
1018 fn t52_asset_ref_construction_and_extract() {
1019 let a = AssetRef {
1020 iri: "asset:model.glb".to_string(),
1021 hash: 0xBEEF,
1022 };
1023 let v = Value::AssetRef(a);
1024 let ar = v.as_asset_ref().unwrap();
1025 assert_eq!(ar.iri, "asset:model.glb");
1026 assert_eq!(ar.hash, 0xBEEF);
1027 }
1028
1029 #[test]
1030 fn t52_extract_returns_none_on_wrong_type() {
1031 let v = Value::I64(42);
1032 assert!(v.as_tensor_ref().is_none());
1033 assert!(v.as_geometry_ref().is_none());
1034 assert!(v.as_asset_ref().is_none());
1035 }
1036
1037 #[test]
1038 fn t52_tensor_ref_equality() {
1039 let t1 = TensorRef {
1040 handle: 1,
1041 hash: 100,
1042 };
1043 let t2 = TensorRef {
1044 handle: 1,
1045 hash: 100,
1046 };
1047 let t3 = TensorRef {
1048 handle: 2,
1049 hash: 100,
1050 };
1051 assert_eq!(t1, t2);
1052 assert_ne!(t1, t3);
1053 }
1054
1055 #[test]
1056 fn value_worldline_extract() {
1057 let w = WorldLine {
1058 iri: "worldline:observer-1".to_string(),
1059 asserted_by: "did:qualia:root:alice".to_string(),
1060 created_at: 1000,
1061 };
1062 let v = Value::WorldLine(w);
1063 let wl = v.as_worldline().unwrap();
1064 assert_eq!(wl.iri, "worldline:observer-1");
1065 }
1066
1067 #[test]
1068 fn value_quantity_truthy() {
1069 let v = Value::Quantity(Quantity::new(0.0, "qudt:Meter"));
1071 assert!(v.is_truthy());
1073 }
1074
1075 #[test]
1078 fn quin_ref_from_raw() {
1079 let q = QuinRef::from_raw(1, 2, 3, 4, 5, 6);
1080 let fields = q.raw_fields();
1081 assert_eq!(fields, [1, 2, 3, 4, 5, 6]);
1082 }
1083
1084 #[test]
1085 fn quin_ref_from_quin_computes_parity() {
1086 let q = QuinRef::from_quin(10, 20, 30, 40);
1087 let fields = q.raw_fields();
1088 assert_eq!(fields[0], 10);
1090 assert_eq!(fields[1], 20);
1091 assert_eq!(fields[2], 30);
1092 assert_eq!(fields[3], 40);
1093 assert_eq!(fields[4], 0); assert_eq!(fields[5], 10 ^ 20 ^ 30 ^ 40); }
1096
1097 #[test]
1098 fn quin_ref_content_hash_deterministic() {
1099 let q1 = QuinRef::from_raw(1, 2, 3, 4, 5, 6);
1100 let q2 = QuinRef::from_raw(1, 2, 3, 4, 5, 6);
1101 assert_eq!(q1.content_hash(), q2.content_hash());
1102 }
1103
1104 #[test]
1105 fn quin_ref_different_payloads_different_hash() {
1106 let q1 = QuinRef::from_raw(1, 2, 3, 4, 5, 6);
1107 let q2 = QuinRef::from_raw(6, 5, 4, 3, 2, 1);
1108 assert_ne!(q1.content_hash(), q2.content_hash());
1109 }
1110
1111 #[test]
1112 fn value_quin_ref_extract() {
1113 let q = QuinRef::from_raw(100, 200, 300, 400, 0, 0);
1114 let v = Value::QuinRef(q);
1115 let extracted = v.as_quin_ref().unwrap();
1116 assert_eq!(extracted.raw_fields(), [100, 200, 300, 400, 0, 0]);
1117 }
1118
1119 #[test]
1120 fn value_quin_ref_is_copy() {
1121 let q = QuinRef::from_raw(1, 2, 3, 4, 5, 6);
1122 let v1 = Value::QuinRef(q);
1123 let v2 = v1.clone();
1124 assert_eq!(v1, v2);
1126 }
1127
1128 #[test]
1131 fn value_species_ref_extract() {
1132 let s = SpeciesRef {
1133 iri: "qudt:CHEBI_17716".to_string(),
1134 hash: 0xCAFE_BABE,
1135 };
1136 let v = Value::SpeciesRef(s);
1137 let sr = v.as_species_ref().unwrap();
1138 assert_eq!(sr.iri, "qudt:CHEBI_17716");
1139 assert_eq!(sr.hash, 0xCAFE_BABE);
1140 }
1141
1142 #[test]
1143 fn value_species_ref_equality() {
1144 let s1 = SpeciesRef {
1145 iri: "qudt:CHEBI_15377".to_string(), hash: 1,
1147 };
1148 let s2 = SpeciesRef {
1149 iri: "qudt:CHEBI_15377".to_string(),
1150 hash: 1,
1151 };
1152 let s3 = SpeciesRef {
1153 iri: "qudt:CHEBI_17716".to_string(), hash: 2,
1155 };
1156 assert_eq!(s1, s2);
1157 assert_ne!(s1, s3);
1158 }
1159
1160 #[test]
1161 fn value_mixture_extract() {
1162 let water = SpeciesRef {
1163 iri: "qudt:CHEBI_15377".to_string(),
1164 hash: 1,
1165 };
1166 let ethanol = SpeciesRef {
1167 iri: "qudt:CHEBI_16236".to_string(),
1168 hash: 2,
1169 };
1170 let m = Mixture {
1171 iri: Some("mixture:water_ethanol".to_string()),
1172 components: vec![(water, 0.7), (ethanol, 0.3)],
1173 phase: MixturePhase::Liquid,
1174 miscibility: Miscibility::Miscible,
1175 };
1176 let v = Value::Mixture(m);
1177 let mx = v.as_mixture().unwrap();
1178 assert_eq!(mx.components.len(), 2);
1179 assert_eq!(mx.phase, MixturePhase::Liquid);
1180 assert_eq!(mx.miscibility, Miscibility::Miscible);
1181 assert_eq!(mx.components[0].1, 0.7);
1182 assert_eq!(mx.components[1].1, 0.3);
1183 }
1184
1185 #[test]
1186 fn value_mixture_oil_water_immiscible() {
1187 let oil = SpeciesRef {
1188 iri: "qudt:CHEBI_15889".to_string(),
1189 hash: 1,
1190 };
1191 let water = SpeciesRef {
1192 iri: "qudt:CHEBI_15377".to_string(),
1193 hash: 2,
1194 };
1195 let m = Mixture {
1196 iri: None,
1197 components: vec![(oil, 0.5), (water, 0.5)],
1198 phase: MixturePhase::Liquid,
1199 miscibility: Miscibility::Immiscible,
1200 };
1201 let v = Value::Mixture(m);
1202 let mx = v.as_mixture().unwrap();
1203 assert_eq!(mx.miscibility, Miscibility::Immiscible);
1204 assert!(mx.iri.is_none());
1205 }
1206
1207 #[test]
1208 fn value_mixture_partial_miscibility() {
1209 let salt = SpeciesRef {
1210 iri: "qudt:CHEBI_36757".to_string(),
1211 hash: 1,
1212 };
1213 let water = SpeciesRef {
1214 iri: "qudt:CHEBI_15377".to_string(),
1215 hash: 2,
1216 };
1217 let m = Mixture {
1218 iri: None,
1219 components: vec![(salt, 0.1), (water, 0.9)],
1220 phase: MixturePhase::Liquid,
1221 miscibility: Miscibility::Partial,
1222 };
1223 assert_eq!(m.miscibility, Miscibility::Partial);
1224 }
1225
1226 #[test]
1227 fn value_mixture_phase_variants() {
1228 let s = SpeciesRef {
1229 iri: "qudt:CHEBI_15377".to_string(),
1230 hash: 1,
1231 };
1232 let solid = Mixture {
1233 iri: None,
1234 components: vec![(s.clone(), 1.0)],
1235 phase: MixturePhase::Solid,
1236 miscibility: Miscibility::Miscible,
1237 };
1238 let gas = Mixture {
1239 iri: None,
1240 components: vec![(s.clone(), 1.0)],
1241 phase: MixturePhase::Gas,
1242 miscibility: Miscibility::Miscible,
1243 };
1244 let plasma = Mixture {
1245 iri: None,
1246 components: vec![(s.clone(), 1.0)],
1247 phase: MixturePhase::Plasma,
1248 miscibility: Miscibility::Miscible,
1249 };
1250 let supercritical = Mixture {
1251 iri: None,
1252 components: vec![(s, 1.0)],
1253 phase: MixturePhase::Supercritical,
1254 miscibility: Miscibility::Miscible,
1255 };
1256 assert_ne!(solid.phase, gas.phase);
1257 assert_ne!(gas.phase, plasma.phase);
1258 assert_ne!(plasma.phase, supercritical.phase);
1259 }
1260
1261 #[test]
1262 fn value_species_ref_not_mixture() {
1263 let s = SpeciesRef {
1264 iri: "qudt:CHEBI_15377".to_string(),
1265 hash: 1,
1266 };
1267 let v = Value::SpeciesRef(s);
1268 assert!(v.as_mixture().is_none());
1269 }
1270
1271 #[test]
1272 fn value_mixture_not_species_ref() {
1273 let m = Mixture {
1274 iri: None,
1275 components: vec![],
1276 phase: MixturePhase::Liquid,
1277 miscibility: Miscibility::Miscible,
1278 };
1279 let v = Value::Mixture(m);
1280 assert!(v.as_species_ref().is_none());
1281 }
1282
1283 #[test]
1286 fn value_conservation_result_mass_conserved() {
1287 let r = ConservationResult {
1288 quantity: ConservationQuantity::Mass,
1289 before: 100.0,
1290 after: 100.0,
1291 conserved: true,
1292 tolerance: 1e-9,
1293 };
1294 let v = Value::Conservation(r);
1295 let c = v.as_conservation().unwrap();
1296 assert_eq!(c.quantity, ConservationQuantity::Mass);
1297 assert!(c.conserved);
1298 assert!((c.before - c.after).abs() < c.tolerance);
1299 }
1300
1301 #[test]
1302 fn value_conservation_result_energy_violated() {
1303 let r = ConservationResult {
1304 quantity: ConservationQuantity::Energy,
1305 before: 500.0,
1306 after: 499.5,
1307 conserved: false,
1308 tolerance: 1e-9,
1309 };
1310 let v = Value::Conservation(r);
1311 let c = v.as_conservation().unwrap();
1312 assert!(!c.conserved);
1313 assert!((c.before - c.after).abs() > c.tolerance);
1314 }
1315
1316 #[test]
1317 fn value_conservation_quantity_variants() {
1318 assert_ne!(ConservationQuantity::Mass, ConservationQuantity::Mole);
1319 assert_ne!(ConservationQuantity::Mole, ConservationQuantity::Energy);
1320 assert_ne!(ConservationQuantity::Energy, ConservationQuantity::Charge);
1321 assert_ne!(ConservationQuantity::Charge, ConservationQuantity::Momentum);
1322 assert_ne!(
1323 ConservationQuantity::Momentum,
1324 ConservationQuantity::AngularMomentum
1325 );
1326 }
1327
1328 #[test]
1331 fn value_causal_timelike_allows_causation() {
1332 let v = Value::Causal(CausalRelation::Timelike);
1333 let r = v.as_causal().unwrap();
1334 assert!(r.allows_causation());
1335 assert!(!r.is_causally_disconnected());
1336 }
1337
1338 #[test]
1339 fn value_causal_lightlike_allows_causation() {
1340 let v = Value::Causal(CausalRelation::Lightlike);
1341 let r = v.as_causal().unwrap();
1342 assert!(r.allows_causation());
1343 assert!(!r.is_causally_disconnected());
1344 }
1345
1346 #[test]
1347 fn value_causal_spacelike_disconnected() {
1348 let v = Value::Causal(CausalRelation::Spacelike);
1349 let r = v.as_causal().unwrap();
1350 assert!(!r.allows_causation());
1351 assert!(r.is_causally_disconnected());
1352 }
1353
1354 #[test]
1355 fn value_causal_relation_equality() {
1356 assert_eq!(CausalRelation::Timelike, CausalRelation::Timelike);
1357 assert_ne!(CausalRelation::Timelike, CausalRelation::Lightlike);
1358 assert_ne!(CausalRelation::Lightlike, CausalRelation::Spacelike);
1359 assert_ne!(CausalRelation::Timelike, CausalRelation::Spacelike);
1360 }
1361
1362 #[test]
1363 fn value_conservation_not_causal() {
1364 let r = ConservationResult {
1365 quantity: ConservationQuantity::Mass,
1366 before: 1.0,
1367 after: 1.0,
1368 conserved: true,
1369 tolerance: 1e-9,
1370 };
1371 let v = Value::Conservation(r);
1372 assert!(v.as_causal().is_none());
1373 }
1374
1375 #[test]
1376 fn value_causal_not_conservation() {
1377 let v = Value::Causal(CausalRelation::Timelike);
1378 assert!(v.as_conservation().is_none());
1379 }
1380
1381 #[test]
1384 fn value_disclosure_denied_construction() {
1385 let v = Value::DisclosureDenied {
1386 capability: "graph.query".to_string(),
1387 reason: "requester lacks consent".to_string(),
1388 };
1389 let (cap, reason) = v.as_disclosure_denied().unwrap();
1390 assert_eq!(cap, "graph.query");
1391 assert_eq!(reason, "requester lacks consent");
1392 }
1393
1394 #[test]
1395 fn value_disclosure_denied_is_falsy() {
1396 let v = Value::DisclosureDenied {
1397 capability: "graph.query".to_string(),
1398 reason: "denied".to_string(),
1399 };
1400 assert!(!v.is_truthy());
1401 }
1402
1403 #[test]
1404 fn value_disclosure_denied_not_numeric() {
1405 let v = Value::DisclosureDenied {
1406 capability: "x".to_string(),
1407 reason: "y".to_string(),
1408 };
1409 assert!(v.as_f64().is_none());
1410 assert!(v.as_i64().is_none());
1411 }
1412
1413 #[test]
1414 fn value_disclosure_denied_not_other_type() {
1415 let v = Value::DisclosureDenied {
1416 capability: "x".to_string(),
1417 reason: "y".to_string(),
1418 };
1419 assert!(v.as_causal().is_none());
1420 assert!(v.as_conservation().is_none());
1421 assert!(v.as_mixture().is_none());
1422 }
1423
1424 #[test]
1427 fn value_disclosure_boundary_default_is_none() {
1428 let b = DisclosureBoundary::default();
1429 assert_eq!(b.as_bits(), [false, false, false, false]);
1430 }
1431
1432 #[test]
1433 fn value_disclosure_boundary_none() {
1434 let b = DisclosureBoundary::none();
1435 assert!(!b.publication);
1436 assert!(!b.replication);
1437 assert!(!b.agency);
1438 assert!(!b.exfiltration);
1439 }
1440
1441 #[test]
1442 fn value_disclosure_boundary_public_only() {
1443 let b = DisclosureBoundary::public_only();
1444 assert!(b.publication);
1445 assert!(!b.replication);
1446 assert!(!b.agency);
1447 assert!(!b.exfiltration);
1448 }
1449
1450 #[test]
1451 fn value_disclosure_boundary_full() {
1452 let b = DisclosureBoundary::full();
1453 assert!(b.publication);
1454 assert!(b.replication);
1455 assert!(b.agency);
1456 assert!(b.exfiltration);
1457 }
1458
1459 #[test]
1460 fn value_disclosure_boundary_as_bits() {
1461 let b = DisclosureBoundary {
1462 publication: true,
1463 replication: false,
1464 agency: true,
1465 exfiltration: false,
1466 };
1467 assert_eq!(b.as_bits(), [true, false, true, false]);
1468 }
1469
1470 #[test]
1471 fn value_disclosure_boundary_extract() {
1472 let b = DisclosureBoundary::public_only();
1473 let v = Value::DisclosureBoundary(b);
1474 let extracted = v.as_disclosure_boundary().unwrap();
1475 assert!(extracted.publication);
1476 assert!(!extracted.replication);
1477 }
1478
1479 #[test]
1480 fn value_disclosure_boundary_equality() {
1481 let a = DisclosureBoundary {
1482 publication: true,
1483 replication: false,
1484 agency: true,
1485 exfiltration: false,
1486 };
1487 let b = DisclosureBoundary {
1488 publication: true,
1489 replication: false,
1490 agency: true,
1491 exfiltration: false,
1492 };
1493 let c = DisclosureBoundary::full();
1494 assert_eq!(a, b);
1495 assert_ne!(a, c);
1496 }
1497
1498 #[test]
1499 fn display_duration_as_ms() {
1500 assert_eq!(
1501 format!("{}", Value::Duration(Duration::from_nanos(500_000_000))),
1502 "500ms"
1503 );
1504 }
1505
1506 #[test]
1507 fn display_quantity_keeps_unit() {
1508 assert_eq!(
1509 format!("{}", Value::Quantity(Quantity::new(500.0, "ms"))),
1510 "500ms"
1511 );
1512 }
1513
1514 #[test]
1515 fn display_srgb_color_as_hex() {
1516 let mut rec = BTreeMap::new();
1517 rec.insert("space".into(), Value::String("srgb".into()));
1518 rec.insert("hex".into(), Value::String("#ff2d95".into()));
1519 rec.insert("r".into(), Value::U64(255));
1520 rec.insert("g".into(), Value::U64(45));
1521 rec.insert("b".into(), Value::U64(149));
1522 rec.insert("a".into(), Value::U64(255));
1523 assert_eq!(format!("{}", Value::Record(rec)), "#ff2d95");
1524 }
1525}