Skip to main content

vibe/
value.rs

1//! Runtime values.
2
3use std::collections::BTreeMap;
4
5/// Time scale for an [`Value::Instant`].
6#[derive(Debug, Clone, PartialEq, Eq, Hash)]
7pub enum TimeScale {
8    /// Unix epoch seconds + nanos.
9    Unix,
10    /// International Atomic Time.
11    Tai,
12    /// GPS time.
13    Gps,
14    /// Monotonic clock (never goes backwards; epoch arbitrary).
15    Monotonic,
16    /// Proper time along a worldline (from 10D manifold metric).
17    Proper,
18}
19
20/// A point in time with a known scale, exact secs+nanos, and an optional
21/// cryptographic seal (T1).
22///
23/// Replaces `time.unix() -> i64` as the primitive. The seal is a
24/// signature over `(scale, secs, nanos, frame)` proving the instant was
25/// asserted by a specific authority.
26#[derive(Debug, Clone, PartialEq)]
27pub struct Instant {
28    pub scale: TimeScale,
29    pub secs: i64,
30    pub nanos: u32,
31    /// Optional reference frame (e.g. a worldline ID or observer DID).
32    pub frame: Option<String>,
33    /// Optional ed25519 signature over the instant's canonical encoding.
34    pub seal: Option<[u8; 64]>,
35}
36
37/// An exact duration: secs + nanos. No float subtraction (T2).
38#[derive(Debug, Clone, PartialEq, Eq, Hash)]
39pub struct Duration {
40    pub secs: i64,
41    pub nanos: u32,
42}
43
44/// A physical quantity: a value with a required unit IRI (T3).
45///
46/// Mixing `kPa` and `Pa` without conversion is a type error. Dimensionless
47/// quantities have an explicit empty unit IRI.
48#[derive(Debug, Clone, PartialEq)]
49pub struct Quantity {
50    pub value: f64,
51    /// Unit IRI (e.g. `"qudt:KiloPascal"`). Empty string = dimensionless.
52    pub unit: String,
53}
54
55/// A reference frame: origin + basis vectors (T4).
56///
57/// Local by default. A morphism, not a naked mat4.
58#[derive(Debug, Clone, PartialEq)]
59pub struct Frame {
60    /// Origin as [x, y, z, t] (or fewer dimensions as needed).
61    pub origin: Vec<f64>,
62    /// Basis vectors as rows of a matrix. Empty = identity.
63    pub basis: Vec<Vec<f64>>,
64    /// Optional parent frame IRI (for nested frames).
65    pub parent: Option<String>,
66}
67
68/// A pose: position + orientation within a frame (T4).
69#[derive(Debug, Clone, PartialEq)]
70pub struct Pose {
71    pub position: Vec<f64>,
72    /// Orientation as a quaternion [w, x, y, z] or rotation matrix.
73    pub orientation: Vec<f64>,
74    /// The frame this pose is relative to.
75    pub frame: Option<String>,
76}
77
78/// A transform: translation + rotation + scale (T4).
79#[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/// An opaque handle to a sampled field (T5). Scripts do not see the grid.
88#[derive(Debug, Clone, PartialEq, Eq, Hash)]
89pub struct FieldRef {
90    /// The field's IRI identifier.
91    pub iri: String,
92    /// A content hash of the field data (for provenance).
93    pub hash: u64,
94}
95
96/// An opaque handle to a material signature (T5).
97#[derive(Debug, Clone, PartialEq, Eq, Hash)]
98pub struct MaterialRef {
99    /// The material's IRI identifier.
100    pub iri: String,
101    /// A content hash of the material definition.
102    pub hash: u64,
103}
104
105/// An opaque handle to a 10D tensor on the host (T52).
106/// Scripts never see the raw tensor data — they see this handle
107/// and can pass it to host capabilities that accept TensorRef.
108#[derive(Debug, Clone, PartialEq, Eq, Hash)]
109pub struct TensorRef {
110    /// A host-side handle ID (opaque to VibeScript).
111    pub handle: u64,
112    /// A content hash of the tensor data (for provenance).
113    pub hash: u64,
114}
115
116/// An opaque handle to a geometry asset on the host (T52).
117/// Scripts never see the raw geometry — they see this handle.
118#[derive(Debug, Clone, PartialEq, Eq, Hash)]
119pub struct GeometryRef {
120    /// A host-side handle ID (opaque to VibeScript).
121    pub handle: u64,
122    /// A content hash of the geometry data (for provenance).
123    pub hash: u64,
124}
125
126/// An opaque handle to a digital asset on the host (T52).
127/// Scripts never see the raw asset bytes — they see this handle.
128#[derive(Debug, Clone, PartialEq, Eq, Hash)]
129pub struct AssetRef {
130    /// The asset's IRI identifier.
131    pub iri: String,
132    /// A content hash of the asset content.
133    pub hash: u64,
134}
135
136/// An opaque handle to a chemical species (T33).
137///
138/// A species is a distinct chemical entity (e.g. H₂O, NaCl, sucrose).
139/// The handle carries an IRI and a content hash for provenance. Scripts
140/// do not see the full species definition — they reference it by handle
141/// and the host resolves it via `field.sample()` or `law.apply()`.
142#[derive(Debug, Clone, PartialEq, Eq, Hash)]
143pub struct SpeciesRef {
144    /// The species' IRI identifier (e.g. `qudt:CHEBI_17716` for sucrose).
145    pub iri: String,
146    /// A content hash of the species definition (for provenance).
147    pub hash: u64,
148}
149
150/// A mixture of chemical species with composition data (T33).
151///
152/// Solubility-as-boolean cannot express oil/water. A mixture carries mole
153/// fractions (or mass fractions) for each species, plus phase information
154/// and miscibility data.
155#[derive(Debug, Clone, PartialEq)]
156pub struct Mixture {
157    /// The mixture's IRI identifier (optional — anonymous mixtures are
158    /// allowed).
159    pub iri: Option<String>,
160    /// Components: species handle + mole fraction (0.0–1.0).
161    /// Mole fractions should sum to 1.0 for a closed mixture, but this
162    /// is not enforced at construction — the host's `law.apply()` can
163    /// check conservation.
164    pub components: Vec<(SpeciesRef, f64)>,
165    /// The phase of this mixture: solid, liquid, gas, plasma, or
166    /// supercritical.
167    pub phase: MixturePhase,
168    /// Miscibility with other mixtures. `Miscible` means fully mixable,
169    /// `Immiscible` means forms separate layers, `Partial` means limited
170    /// solubility.
171    pub miscibility: Miscibility,
172}
173
174/// Phase of a mixture (T33).
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
176pub enum MixturePhase {
177    Solid,
178    Liquid,
179    Gas,
180    Plasma,
181    Supercritical,
182}
183
184/// Miscibility between mixtures (T33).
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
186pub enum Miscibility {
187    /// Fully mixable in all proportions.
188    Miscible,
189    /// Forms separate layers (e.g. oil and water).
190    Immiscible,
191    /// Limited solubility — dissolves up to a saturation point.
192    Partial,
193}
194
195/// A conservation law check result (T34).
196///
197/// When a law transforms a mixture (or any state with conserved quantities),
198/// the host's `conservation_check` method returns this value to indicate
199/// whether the transformation preserves the conserved quantity.
200#[derive(Debug, Clone, PartialEq)]
201pub struct ConservationResult {
202    /// The conserved quantity being checked: "mass", "mole", "energy",
203    /// "charge", "momentum", or "angular_momentum".
204    pub quantity: ConservationQuantity,
205    /// The value before the transformation.
206    pub before: f64,
207    /// The value after the transformation.
208    pub after: f64,
209    /// Whether the quantity is conserved (within tolerance).
210    pub conserved: bool,
211    /// The tolerance used for the check (absolute).
212    pub tolerance: f64,
213}
214
215/// The conserved quantity being checked (T34).
216#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
217pub enum ConservationQuantity {
218    /// Mass (kg).
219    Mass,
220    /// Moles (mol).
221    Mole,
222    /// Energy (J).
223    Energy,
224    /// Electric charge (C).
225    Charge,
226    /// Linear momentum (kg·m/s).
227    Momentum,
228    /// Angular momentum (kg·m²/s).
229    AngularMomentum,
230}
231
232/// A causal relation between two events in spacetime (T35).
233///
234/// Given two events (Instant + Pose), their separation determines whether
235/// one can causally influence the other. The light cone divides spacetime
236/// into:
237/// - **Timelike**: inside the cone — subluminal signal can connect them
238/// - **Lightlike (null)**: on the cone — only light can connect them
239/// - **Spacelike**: outside the cone — no causal connection possible
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
241pub enum CausalRelation {
242    /// Inside the light cone — a subluminal signal can connect the events.
243    Timelike,
244    /// On the light cone — only a light signal can connect the events.
245    Lightlike,
246    /// Outside the light cone — no causal connection is possible.
247    Spacelike,
248}
249
250impl CausalRelation {
251    /// Returns true if the earlier event can causally influence the later.
252    pub fn allows_causation(self) -> bool {
253        matches!(self, CausalRelation::Timelike | CausalRelation::Lightlike)
254    }
255
256    /// Returns true if the events are causally disconnected.
257    pub fn is_causally_disconnected(self) -> bool {
258        matches!(self, CausalRelation::Spacelike)
259    }
260}
261
262/// Four-bit disclosure boundary (T56). Each bit is independent.
263///
264/// `.gitignore` is publication only. This struct tracks all four
265/// dimensions of disclosure control:
266/// - **Publication**: visible in public outputs (reports, UI).
267/// - **Replication**: may be copied to other nodes/stores.
268/// - **Agency**: may be acted upon by agents (inference, hooks).
269/// - **Exfiltration**: may leave the principal's trust boundary.
270#[derive(Debug, Clone, PartialEq, Eq, Default)]
271pub struct DisclosureBoundary {
272    /// Publication: visible in public outputs (reports, UI).
273    pub publication: bool,
274    /// Replication: may be copied to other nodes/stores.
275    pub replication: bool,
276    /// Agency: may be acted upon by agents (inference, hooks).
277    pub agency: bool,
278    /// Exfiltration: may leave the principal's trust boundary.
279    pub exfiltration: bool,
280}
281
282impl DisclosureBoundary {
283    /// All four bits false — no disclosure allowed.
284    pub fn none() -> Self {
285        Self::default()
286    }
287
288    /// Only publication is true — visible but not replicable,
289    /// actionable, or exfiltrable.
290    pub fn public_only() -> Self {
291        Self {
292            publication: true,
293            ..Self::default()
294        }
295    }
296
297    /// All four bits true — full disclosure.
298    pub fn full() -> Self {
299        Self {
300            publication: true,
301            replication: true,
302            agency: true,
303            exfiltration: true,
304        }
305    }
306
307    /// Returns the four bits as `[publication, replication, agency, exfiltration]`.
308    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/// A worldline: a continuant through Instant × Pose (T6).
319///
320/// Kills UUID-as-identity. A worldline is the identity of a thing that
321/// persists through time, anchored to its spatiotemporal trajectory.
322#[derive(Debug, Clone, PartialEq, Eq, Hash)]
323pub struct WorldLine {
324    /// Stable IRI for this worldline.
325    pub iri: String,
326    /// The principal or observer DID that asserted this worldline.
327    pub asserted_by: String,
328    /// Creation instant (Unix secs).
329    pub created_at: i64,
330}
331
332/// A user-defined enum value (T9). Carries the enum name, variant name,
333/// and optional payload values. Unit variants have an empty payload.
334#[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    /// Unit value.
343    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    /// Builder — sets payload.
352    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/// An opaque 48-byte handle to a Super-Quin / NQuin (T7).
362///
363/// Scripts do not see the raw `subject`/`predicate`/`object`/`context`/
364/// `metadata`/`parity` fields. The handle is a content-addressed reference
365/// that the host resolves. This replaces `Value::Quin { s, p, o, c }` as
366/// the preferred representation — `Quin` remains for backward compatibility
367/// but new code should use `QuinRef`.
368///
369/// The 6 × `u64` fields are the full NQuin payload (subject, predicate,
370/// object, context, metadata, parity) but they are opaque to scripts —
371/// the `as_quin_ref()` accessor returns the handle, not the fields.
372/// Host code can access the raw fields via `raw_fields()`.
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
374pub struct QuinRef {
375    /// Opaque payload — 6 × u64 = 48 bytes. Scripts must not access this
376    /// directly. The host resolves the handle to graph data.
377    payload: [u64; 6],
378}
379
380impl QuinRef {
381    /// Create a QuinRef from raw NQuin fields (host-side only).
382    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    /// Create a QuinRef from a `Value::Quin` (which has 4 fields; metadata
396    /// and parity are computed).
397    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    /// Access the raw 6 × u64 payload (host-side only). Scripts never
404    /// see this — it's for the host to resolve the handle to graph data.
405    pub fn raw_fields(&self) -> [u64; 6] {
406        self.payload
407    }
408
409    /// The content hash of this QuinRef — used for deduplication and
410    /// provenance tracking. Position-dependent (FNV-1a style).
411    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    // ── T1–T6: Type lattice extensions ────────────────────────────────
446    /// A point in time with scale, exact secs+nanos, and optional seal (T1).
447    Instant(Instant),
448    /// An exact duration: secs + nanos (T2).
449    Duration(Duration),
450    /// A physical quantity with a required unit IRI (T3).
451    Quantity(Quantity),
452    /// A reference frame: origin + basis (T4).
453    Frame(Frame),
454    /// A pose within a frame (T4).
455    Pose(Pose),
456    /// A transform: translate/rotate/scale/skew (T4).
457    Transform(Transform),
458    /// An opaque handle to a sampled field (T5).
459    FieldRef(FieldRef),
460    /// An opaque handle to a material signature (T5).
461    MaterialRef(MaterialRef),
462    /// An opaque handle to a 10D tensor on the host (T52).
463    TensorRef(TensorRef),
464    /// An opaque handle to a geometry asset on the host (T52).
465    GeometryRef(GeometryRef),
466    /// An opaque handle to a digital asset on the host (T52).
467    AssetRef(AssetRef),
468    /// A worldline: continuant through Instant × Pose (T6).
469    WorldLine(WorldLine),
470    /// An opaque 48-byte handle to a Super-Quin (T7). Scripts do not see
471    /// the raw s/p/o/c/metadata/parity fields.
472    QuinRef(QuinRef),
473    /// A user-defined enum value (T9).
474    Enum(EnumValue),
475    /// Non-capturing lambda (body is AST; eval uses a fresh env of params only).
476    Lambda {
477        params: Vec<String>,
478        body: Box<crate::ast::Expr>,
479    },
480    /// A chemical species reference (T33).
481    SpeciesRef(SpeciesRef),
482    /// A mixture of chemical species with composition data (T33).
483    Mixture(Mixture),
484    /// A conservation law check result (T34).
485    Conservation(ConservationResult),
486    /// A causal relation between two events (T35).
487    Causal(CausalRelation),
488    /// A credentialed disclosure refusal (T55). The agent/host refused
489    /// to disclose content because the requester lacks the required
490    /// capability, consent, or authority. This is a first-class rights
491    /// enforcement value, not a "file not found" error.
492    DisclosureDenied {
493        capability: String,
494        reason: String,
495    },
496    /// Four-bit disclosure boundary (T56). Each bit is independent:
497    /// publication, replication, agency, exfiltration.
498    DisclosureBoundary(DisclosureBoundary),
499}
500
501impl Value {
502    /// `true` when truthy.
503    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            // A disclosure denial is falsy — the disclosure did not happen.
509            Value::DisclosureDenied { .. } => false,
510            _ => true,
511        }
512    }
513
514    /// `f64` form.
515    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    /// `i64` form.
526    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    /// Extract a string slice if this value is a `String` or `Iri`.
536    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    /// Extract an Instant if this value is one.
544    pub fn as_instant(&self) -> Option<&Instant> {
545        match self {
546            Value::Instant(i) => Some(i),
547            _ => None,
548        }
549    }
550
551    /// Extract a Duration if this value is one.
552    pub fn as_duration(&self) -> Option<&Duration> {
553        match self {
554            Value::Duration(d) => Some(d),
555            _ => None,
556        }
557    }
558
559    /// Extract a Quantity if this value is one.
560    pub fn as_quantity(&self) -> Option<&Quantity> {
561        match self {
562            Value::Quantity(q) => Some(q),
563            _ => None,
564        }
565    }
566
567    /// Extract a Frame if this value is one.
568    pub fn as_frame(&self) -> Option<&Frame> {
569        match self {
570            Value::Frame(f) => Some(f),
571            _ => None,
572        }
573    }
574
575    /// Extract a Pose if this value is one.
576    pub fn as_pose(&self) -> Option<&Pose> {
577        match self {
578            Value::Pose(p) => Some(p),
579            _ => None,
580        }
581    }
582
583    /// Extract a Transform if this value is one.
584    pub fn as_transform(&self) -> Option<&Transform> {
585        match self {
586            Value::Transform(t) => Some(t),
587            _ => None,
588        }
589    }
590
591    /// Extract a FieldRef if this value is one.
592    pub fn as_field_ref(&self) -> Option<&FieldRef> {
593        match self {
594            Value::FieldRef(f) => Some(f),
595            _ => None,
596        }
597    }
598
599    /// Extract a MaterialRef if this value is one.
600    pub fn as_material_ref(&self) -> Option<&MaterialRef> {
601        match self {
602            Value::MaterialRef(m) => Some(m),
603            _ => None,
604        }
605    }
606
607    /// Extract a TensorRef if this value is one (T52).
608    pub fn as_tensor_ref(&self) -> Option<&TensorRef> {
609        match self {
610            Value::TensorRef(t) => Some(t),
611            _ => None,
612        }
613    }
614
615    /// Extract a GeometryRef if this value is one (T52).
616    pub fn as_geometry_ref(&self) -> Option<&GeometryRef> {
617        match self {
618            Value::GeometryRef(g) => Some(g),
619            _ => None,
620        }
621    }
622
623    /// Extract an AssetRef if this value is one (T52).
624    pub fn as_asset_ref(&self) -> Option<&AssetRef> {
625        match self {
626            Value::AssetRef(a) => Some(a),
627            _ => None,
628        }
629    }
630
631    /// Extract a WorldLine if this value is one.
632    pub fn as_worldline(&self) -> Option<&WorldLine> {
633        match self {
634            Value::WorldLine(w) => Some(w),
635            _ => None,
636        }
637    }
638
639    /// Extract a QuinRef if this value is one (T7).
640    pub fn as_quin_ref(&self) -> Option<&QuinRef> {
641        match self {
642            Value::QuinRef(q) => Some(q),
643            _ => None,
644        }
645    }
646
647    /// Extract an EnumValue if this value is one (T9).
648    pub fn as_enum(&self) -> Option<&EnumValue> {
649        match self {
650            Value::Enum(e) => Some(e),
651            _ => None,
652        }
653    }
654
655    /// Extract a SpeciesRef if this value is one (T33).
656    pub fn as_species_ref(&self) -> Option<&SpeciesRef> {
657        match self {
658            Value::SpeciesRef(s) => Some(s),
659            _ => None,
660        }
661    }
662
663    /// Extract a Mixture if this value is one (T33).
664    pub fn as_mixture(&self) -> Option<&Mixture> {
665        match self {
666            Value::Mixture(m) => Some(m),
667            _ => None,
668        }
669    }
670
671    /// Extract a ConservationResult if this value is one (T34).
672    pub fn as_conservation(&self) -> Option<&ConservationResult> {
673        match self {
674            Value::Conservation(c) => Some(c),
675            _ => None,
676        }
677    }
678
679    /// Extract a CausalRelation if this value is one (T35).
680    pub fn as_causal(&self) -> Option<CausalRelation> {
681        match self {
682            Value::Causal(c) => Some(*c),
683            _ => None,
684        }
685    }
686
687    /// Extract a DisclosureDenied if this value is one (T55).
688    /// Returns (capability, reason).
689    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    /// Extract a DisclosureBoundary if this value is one (T56).
699    pub fn as_disclosure_boundary(&self) -> Option<&DisclosureBoundary> {
700        match self {
701            Value::DisclosureBoundary(b) => Some(b),
702            _ => None,
703        }
704    }
705}
706
707// ── Convenience constructors ───────────────────────────────────────────────
708
709impl Instant {
710    /// Unix timestamp.
711    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    /// Monotonic timestamp.
722    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    /// Constructs from secs.
735    pub fn from_secs(secs: i64) -> Self {
736        Self { secs, nanos: 0 }
737    }
738
739    /// Constructs from nanos.
740    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    /// Total nanoseconds (may overflow for very large durations).
748    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    /// Creates a new `Quantity`.
767    pub fn new(value: f64, unit: &str) -> Self {
768        Self {
769            value,
770            unit: unit.to_string(),
771        }
772    }
773
774    /// Dimensionless quantity.
775    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    // ── T52: Heavy returns as opaque handles ──────────────────────────
992
993    #[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        // A quantity with non-zero value is truthy.
1070        let v = Value::Quantity(Quantity::new(0.0, "qudt:Meter"));
1071        // Zero quantity — is_truthy returns true for non-I64/U64/Null/Bool(false).
1072        assert!(v.is_truthy());
1073    }
1074
1075    // ── T7: QuinRef ──────────────────────────────────────────────────────
1076
1077    #[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        // metadata = 0, parity = 10 ^ 20 ^ 30 ^ 40 ^ 0 = 10 ^ 20 ^ 30 ^ 40
1089        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); // metadata
1094        assert_eq!(fields[5], 10 ^ 20 ^ 30 ^ 40); // parity
1095    }
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        // QuinRef is Copy — both should be equal.
1125        assert_eq!(v1, v2);
1126    }
1127
1128    // ── T33: SpeciesRef + Mixture tests ───────────────────────────────
1129
1130    #[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(), // water
1146            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(), // sucrose
1154            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    // ── T34: Conservation tests ───────────────────────────────────────
1284
1285    #[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    // ── T35: Causal relation tests ────────────────────────────────────
1329
1330    #[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    // ── T55: DisclosureDenied tests ───────────────────────────────────
1382
1383    #[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    // ── T56: DisclosureBoundary tests ─────────────────────────────────
1425
1426    #[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}