Skip to main content

moonproof_runtime_ir/
value.rs

1//! [`RuntimeValue`] — the dynamically-typed value enum the IR
2//! interpreter and witness backends carry on the operand stack.
3//!
4//! Replaces the previous `serde_json::Value`-as-stack-value design
5//! (which forced every byte buffer through hex-string round-trips
6//! and coupled the IR interpreter to the `serde_json` crate). The
7//! new enum is byte-honest: `Bytes(Vec<u8>)` keeps bytes as bytes,
8//! `Int(i128)` covers every Compact `Uint<…>` rung, and `Object` is
9//! a `BTreeMap` so iteration order is deterministic across runs.
10//!
11//! `From<serde_json::Value>` / `Into<serde_json::Value>`
12//! conversions exist as a migration aid — call sites that haven't
13//! crossed over yet stage at the boundary. Long-term every IR
14//! interpreter / witness call should be `RuntimeValue` end-to-end and
15//! the conversions become display-only (`runtime::ledger`'s
16//! human-surface projector).
17
18use std::collections::BTreeMap;
19
20use serde::{Deserialize, Serialize};
21use serde_json::Value as JsonValue;
22
23/// Dynamically-typed value carried by the IR interpreter and witness
24/// backends. See module docs for design notes.
25///
26/// `Deserialize` is hand-written (see below) rather than derived
27/// `#[serde(untagged)]` because serde's untagged dispatch buffers
28/// integers through its internal `Content` enum, which has no
29/// `i128` variant. CBOR integers (the IR-on-disk format) would
30/// silently fail to match the `Int(i128)` variant. The hand-written
31/// visitor accepts every CBOR / JSON primitive and chooses the
32/// `RuntimeValue` variant directly.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
34#[serde(untagged)]
35pub enum RuntimeValue {
36    Null,
37    Bool(bool),
38    /// All Compact `Uint<…>` rungs fit; values above i128 (which
39    /// Compact doesn't emit at the value layer) are not
40    /// representable.
41    Int(i128),
42    /// Raw byte buffer — `Bytes<N>`, `Opaque<Uint8Array>`, `Field`
43    /// (32-byte LE), `JubjubPoint` coords.
44    #[serde(serialize_with = "byte_buf_serde::serialize")]
45    Bytes(Vec<u8>),
46    /// `Opaque<string>` and enum variant names.
47    String(String),
48    /// `Vector<…, T>` and `Tuple<…>` payloads.
49    Array(Vec<RuntimeValue>),
50    /// Struct payloads keyed by IR field name. Ordered for
51    /// determinism across runs.
52    Object(BTreeMap<String, RuntimeValue>),
53}
54
55impl<'de> Deserialize<'de> for RuntimeValue {
56    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
57        use serde::de::{Error, MapAccess, SeqAccess, Visitor};
58
59        struct RvVisitor;
60
61        impl<'de> Visitor<'de> for RvVisitor {
62            type Value = RuntimeValue;
63
64            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
65                f.write_str(
66                    "any RuntimeValue (null, bool, integer, bytes, string, array, or object)",
67                )
68            }
69
70            fn visit_unit<E: Error>(self) -> Result<RuntimeValue, E> {
71                Ok(RuntimeValue::Null)
72            }
73
74            fn visit_none<E: Error>(self) -> Result<RuntimeValue, E> {
75                Ok(RuntimeValue::Null)
76            }
77
78            fn visit_some<D: serde::Deserializer<'de>>(
79                self,
80                d: D,
81            ) -> Result<RuntimeValue, D::Error> {
82                d.deserialize_any(self)
83            }
84
85            fn visit_bool<E: Error>(self, v: bool) -> Result<RuntimeValue, E> {
86                Ok(RuntimeValue::Bool(v))
87            }
88
89            fn visit_i64<E: Error>(self, v: i64) -> Result<RuntimeValue, E> {
90                Ok(RuntimeValue::Int(i128::from(v)))
91            }
92
93            fn visit_u64<E: Error>(self, v: u64) -> Result<RuntimeValue, E> {
94                Ok(RuntimeValue::Int(i128::from(v)))
95            }
96
97            fn visit_i128<E: Error>(self, v: i128) -> Result<RuntimeValue, E> {
98                Ok(RuntimeValue::Int(v))
99            }
100
101            fn visit_u128<E: Error>(self, v: u128) -> Result<RuntimeValue, E> {
102                i128::try_from(v)
103                    .map(RuntimeValue::Int)
104                    .map_err(|_| Error::custom(format!("u128 value {v} exceeds i128 range")))
105            }
106
107            fn visit_f64<E: Error>(self, v: f64) -> Result<RuntimeValue, E> {
108                // Compact has no float type; encode as String so the
109                // host can surface unexpected upstream payloads
110                // without losing information. This matches the
111                // `From<JsonValue> for RuntimeValue` shim.
112                Ok(RuntimeValue::String(format!("{v}")))
113            }
114
115            fn visit_str<E: Error>(self, v: &str) -> Result<RuntimeValue, E> {
116                Ok(RuntimeValue::String(v.to_owned()))
117            }
118
119            fn visit_string<E: Error>(self, v: String) -> Result<RuntimeValue, E> {
120                Ok(RuntimeValue::String(v))
121            }
122
123            fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<RuntimeValue, E> {
124                Ok(RuntimeValue::Bytes(v.to_vec()))
125            }
126
127            fn visit_byte_buf<E: Error>(self, v: Vec<u8>) -> Result<RuntimeValue, E> {
128                Ok(RuntimeValue::Bytes(v))
129            }
130
131            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<RuntimeValue, A::Error> {
132                let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0));
133                while let Some(elem) = seq.next_element::<RuntimeValue>()? {
134                    out.push(elem);
135                }
136                Ok(RuntimeValue::Array(out))
137            }
138
139            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<RuntimeValue, A::Error> {
140                let mut out = BTreeMap::new();
141                while let Some((k, v)) = map.next_entry::<String, RuntimeValue>()? {
142                    out.insert(k, v);
143                }
144                Ok(RuntimeValue::Object(out))
145            }
146        }
147
148        d.deserialize_any(RvVisitor)
149    }
150}
151
152impl RuntimeValue {
153    /// Convenience constructor for unit / `Tuple<>` results.
154    #[must_use]
155    pub fn unit() -> Self {
156        RuntimeValue::Array(Vec::new())
157    }
158
159    /// Borrow a struct field by name. Returns `None` if `self` is
160    /// not an object or the field is absent.
161    #[must_use]
162    pub fn field(&self, name: &str) -> Option<&RuntimeValue> {
163        match self {
164            RuntimeValue::Object(o) => o.get(name),
165            _ => None,
166        }
167    }
168
169    /// Type tag string for diagnostics.
170    #[must_use]
171    pub fn type_label(&self) -> &'static str {
172        match self {
173            RuntimeValue::Null => "null",
174            RuntimeValue::Bool(_) => "bool",
175            RuntimeValue::Int(_) => "int",
176            RuntimeValue::Bytes(_) => "bytes",
177            RuntimeValue::String(_) => "string",
178            RuntimeValue::Array(_) => "array",
179            RuntimeValue::Object(_) => "object",
180        }
181    }
182
183    // ----- serde_json::Value-style accessors (migration aid) -----
184
185    #[must_use]
186    pub fn is_null(&self) -> bool {
187        matches!(self, RuntimeValue::Null)
188    }
189
190    #[must_use]
191    pub fn is_number(&self) -> bool {
192        matches!(self, RuntimeValue::Int(_))
193    }
194
195    #[must_use]
196    pub fn is_string(&self) -> bool {
197        matches!(self, RuntimeValue::String(_))
198    }
199
200    #[must_use]
201    pub fn is_array(&self) -> bool {
202        matches!(self, RuntimeValue::Array(_))
203    }
204
205    #[must_use]
206    pub fn is_object(&self) -> bool {
207        matches!(self, RuntimeValue::Object(_))
208    }
209
210    #[must_use]
211    pub fn is_bool(&self) -> bool {
212        matches!(self, RuntimeValue::Bool(_))
213    }
214
215    #[must_use]
216    pub fn as_bool(&self) -> Option<bool> {
217        match self {
218            RuntimeValue::Bool(b) => Some(*b),
219            _ => None,
220        }
221    }
222
223    #[must_use]
224    pub fn as_i128(&self) -> Option<i128> {
225        match self {
226            RuntimeValue::Int(i) => Some(*i),
227            _ => None,
228        }
229    }
230
231    #[must_use]
232    pub fn as_u64(&self) -> Option<u64> {
233        match self {
234            RuntimeValue::Int(i) if *i >= 0 => u64::try_from(*i).ok(),
235            _ => None,
236        }
237    }
238
239    #[must_use]
240    pub fn as_u128(&self) -> Option<u128> {
241        match self {
242            RuntimeValue::Int(i) if *i >= 0 => u128::try_from(*i).ok(),
243            _ => None,
244        }
245    }
246
247    #[must_use]
248    pub fn as_str(&self) -> Option<&str> {
249        match self {
250            RuntimeValue::String(s) => Some(s.as_str()),
251            _ => None,
252        }
253    }
254
255    #[must_use]
256    pub fn as_bytes(&self) -> Option<&[u8]> {
257        match self {
258            RuntimeValue::Bytes(b) => Some(b.as_slice()),
259            _ => None,
260        }
261    }
262
263    #[must_use]
264    pub fn as_array(&self) -> Option<&Vec<RuntimeValue>> {
265        match self {
266            RuntimeValue::Array(a) => Some(a),
267            _ => None,
268        }
269    }
270
271    #[must_use]
272    pub fn as_array_mut(&mut self) -> Option<&mut Vec<RuntimeValue>> {
273        match self {
274            RuntimeValue::Array(a) => Some(a),
275            _ => None,
276        }
277    }
278
279    #[must_use]
280    pub fn as_object(&self) -> Option<&BTreeMap<String, RuntimeValue>> {
281        match self {
282            RuntimeValue::Object(o) => Some(o),
283            _ => None,
284        }
285    }
286
287    #[must_use]
288    pub fn as_object_mut(&mut self) -> Option<&mut BTreeMap<String, RuntimeValue>> {
289        match self {
290            RuntimeValue::Object(o) => Some(o),
291            _ => None,
292        }
293    }
294
295    /// Object field / array index lookup. Mirrors
296    /// `serde_json::Value::get`. Accepts a `&str` (object key) or
297    /// `usize` (array index).
298    #[must_use]
299    #[expect(
300        clippy::needless_pass_by_value,
301        reason = "mirrors `serde_json::Value::get`: callers pass `\"key\"` or `0` by value through `ValueIndex`"
302    )]
303    pub fn get<I: ValueIndex>(&self, idx: I) -> Option<&RuntimeValue> {
304        idx.get_in(self)
305    }
306}
307
308/// Index trait for [`RuntimeValue::get`]. Mirrors
309/// `serde_json::value::Index` — `&str` indexes objects, `usize`
310/// indexes arrays.
311pub trait ValueIndex {
312    fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue>;
313}
314
315impl ValueIndex for &str {
316    fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue> {
317        match v {
318            RuntimeValue::Object(o) => o.get(*self),
319            _ => None,
320        }
321    }
322}
323
324impl ValueIndex for usize {
325    fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue> {
326        match v {
327            RuntimeValue::Array(a) => a.get(*self),
328            _ => None,
329        }
330    }
331}
332
333impl ValueIndex for &String {
334    fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue> {
335        self.as_str().get_in(v)
336    }
337}
338
339impl std::fmt::Display for RuntimeValue {
340    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341        match self {
342            RuntimeValue::Null => f.write_str("null"),
343            RuntimeValue::Bool(b) => write!(f, "{b}"),
344            RuntimeValue::Int(i) => write!(f, "{i}"),
345            RuntimeValue::Bytes(b) => write!(f, "0x{}", hex::encode(b)),
346            RuntimeValue::String(s) => write!(f, "{s:?}"),
347            RuntimeValue::Array(a) => {
348                f.write_str("[")?;
349                for (i, v) in a.iter().enumerate() {
350                    if i > 0 {
351                        f.write_str(", ")?;
352                    }
353                    write!(f, "{v}")?;
354                }
355                f.write_str("]")
356            }
357            RuntimeValue::Object(o) => {
358                f.write_str("{")?;
359                for (i, (k, v)) in o.iter().enumerate() {
360                    if i > 0 {
361                        f.write_str(", ")?;
362                    }
363                    write!(f, "{k:?}: {v}")?;
364                }
365                f.write_str("}")
366            }
367        }
368    }
369}
370
371mod byte_buf_serde {
372    //! Serialise `Bytes` so cbor stores raw bytes (efficient) and json
373    //! stores hex (matches upstream IR-on-disk shape from compactc).
374    //! Deserialising is the hand-written `RuntimeValue` visitor's job.
375    use serde::Serializer;
376
377    pub fn serialize<S: Serializer>(v: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> {
378        // Use serde_bytes for binary cbor; falls back to a string
379        // representation when the serializer is human-readable
380        // (json) — hex matches compactc's IR convention.
381        if s.is_human_readable() {
382            s.serialize_str(&hex::encode(v))
383        } else {
384            s.serialize_bytes(v)
385        }
386    }
387}
388
389// ---------------------------------------------------------------------------
390// JSON bridge — migration aid + human-surface projection
391// ---------------------------------------------------------------------------
392
393impl From<RuntimeValue> for JsonValue {
394    fn from(v: RuntimeValue) -> Self {
395        match v {
396            RuntimeValue::Null => JsonValue::Null,
397            RuntimeValue::Bool(b) => JsonValue::Bool(b),
398            RuntimeValue::Int(i) => {
399                if let Ok(u) = u64::try_from(i) {
400                    JsonValue::Number(u.into())
401                } else if let Ok(s) = i64::try_from(i) {
402                    JsonValue::Number(s.into())
403                } else {
404                    JsonValue::String(i.to_string())
405                }
406            }
407            RuntimeValue::Bytes(b) => JsonValue::String(hex::encode(b)),
408            RuntimeValue::String(s) => JsonValue::String(s),
409            RuntimeValue::Array(a) => JsonValue::Array(a.into_iter().map(Into::into).collect()),
410            RuntimeValue::Object(o) => {
411                let mut m = serde_json::Map::with_capacity(o.len());
412                for (k, v) in o {
413                    m.insert(k, v.into());
414                }
415                JsonValue::Object(m)
416            }
417        }
418    }
419}
420
421impl From<JsonValue> for RuntimeValue {
422    fn from(v: JsonValue) -> Self {
423        match v {
424            JsonValue::Null => RuntimeValue::Null,
425            JsonValue::Bool(b) => RuntimeValue::Bool(b),
426            JsonValue::Number(n) => {
427                if let Some(u) = n.as_u64() {
428                    RuntimeValue::Int(i128::from(u))
429                } else if let Some(s) = n.as_i64() {
430                    RuntimeValue::Int(i128::from(s))
431                } else if let Some(f) = n.as_f64() {
432                    // Compact has no float type; this only fires for
433                    // unexpected upstream payloads. Truncate to i128
434                    // rather than silently losing precision.
435                    #[expect(
436                        clippy::cast_possible_truncation,
437                        reason = "truncating a non-integral JSON float to i128 is the intended projection; `as` saturates and maps NaN to 0"
438                    )]
439                    let truncated = f as i128;
440                    RuntimeValue::Int(truncated)
441                } else {
442                    RuntimeValue::Null
443                }
444            }
445            // Strings could be byte buffers (hex) or actual strings —
446            // ambiguous without context. The interpreter / typed
447            // decoders disambiguate at use; default to String here so
448            // round-tripping `Opaque<string>` doesn't corrupt UTF-8.
449            JsonValue::String(s) => RuntimeValue::String(s),
450            JsonValue::Array(a) => RuntimeValue::Array(a.into_iter().map(Into::into).collect()),
451            JsonValue::Object(o) => {
452                let mut m = BTreeMap::new();
453                for (k, v) in o {
454                    m.insert(k, v.into());
455                }
456                RuntimeValue::Object(m)
457            }
458        }
459    }
460}
461
462// ---------------------------------------------------------------------------
463// Primitive From / TryFrom — typed Rust ↔ RuntimeValue
464//
465// Generated code (Rust ledger readers, circuit method args) reaches
466// for these so `(arg).into()` and `rv.try_into()` round-trip a
467// primitive without any descriptor walk on the consumer side.
468// Conventions match `runtime::ir::descriptor`'s `decode_aligned_value`
469// so values from on-chain reads project the same way values pushed
470// at deploy/call time do.
471//
472// `[u8; N]` and `Vec<u8>` are deliberately NOT given blanket impls:
473// the Compact wire convention treats `Bytes<N>` / `Field` /
474// `Opaque<Uint8Array>` as hex-encoded strings, while a `Vector<N,
475// Uint<8>>` would round-trip through `Array(Int)`. Codegen emits the
476// right shape per descriptor.
477// ---------------------------------------------------------------------------
478
479/// Failure projecting a [`RuntimeValue`] back into a typed Rust
480/// scalar. Carried by every `TryFrom<RuntimeValue>` impl so generated
481/// code can wrap with field/argument context.
482#[derive(Debug, Clone, thiserror::Error)]
483#[error("RuntimeValue projection: {0}")]
484pub struct ValueProjectionError(pub String);
485
486impl ValueProjectionError {
487    pub fn new(msg: impl Into<String>) -> Self {
488        Self(msg.into())
489    }
490}
491
492impl From<bool> for RuntimeValue {
493    fn from(b: bool) -> Self {
494        RuntimeValue::Bool(b)
495    }
496}
497
498macro_rules! from_uint {
499    ($($t:ty),*) => {
500        $(
501            impl From<$t> for RuntimeValue {
502                fn from(n: $t) -> Self {
503                    RuntimeValue::Int(i128::from(n))
504                }
505            }
506        )*
507    };
508}
509from_uint!(u8, u16, u32, u64);
510
511macro_rules! from_int {
512    ($($t:ty),*) => {
513        $(
514            impl From<$t> for RuntimeValue {
515                fn from(n: $t) -> Self {
516                    RuntimeValue::Int(i128::from(n))
517                }
518            }
519        )*
520    };
521}
522from_int!(i8, i16, i32, i64);
523
524impl From<i128> for RuntimeValue {
525    fn from(n: i128) -> Self {
526        RuntimeValue::Int(n)
527    }
528}
529
530impl From<u128> for RuntimeValue {
531    fn from(n: u128) -> Self {
532        match i128::try_from(n) {
533            Ok(i) => RuntimeValue::Int(i),
534            Err(_) => RuntimeValue::String(n.to_string()),
535        }
536    }
537}
538
539impl From<String> for RuntimeValue {
540    fn from(s: String) -> Self {
541        RuntimeValue::String(s)
542    }
543}
544
545impl From<&str> for RuntimeValue {
546    fn from(s: &str) -> Self {
547        RuntimeValue::String(s.to_owned())
548    }
549}
550
551// Byte buffers — `Bytes<N>`, `Field`, `Opaque<Uint8Array>` all bridge
552// through these. RuntimeValue::Bytes is the byte-honest canonical
553// representation (no hex round-trip). Generated code uses these
554// blanket impls in both directions.
555impl<const N: usize> From<[u8; N]> for RuntimeValue {
556    fn from(b: [u8; N]) -> Self {
557        RuntimeValue::Bytes(b.to_vec())
558    }
559}
560
561impl From<Vec<u8>> for RuntimeValue {
562    fn from(b: Vec<u8>) -> Self {
563        RuntimeValue::Bytes(b)
564    }
565}
566
567impl<const N: usize> TryFrom<RuntimeValue> for [u8; N] {
568    type Error = ValueProjectionError;
569    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
570        // Pad to declared N (compactc strips trailing zeros on the wire).
571        let bytes: Vec<u8> = match v {
572            RuntimeValue::Bytes(b) => b,
573            other => {
574                return Err(ValueProjectionError::new(format!(
575                    "expected Bytes for [u8; {N}], got {}",
576                    other.type_label()
577                )));
578            }
579        };
580        if bytes.len() > N {
581            return Err(ValueProjectionError::new(format!(
582                "[u8; {N}] expected ≤ {N} bytes, got {}",
583                bytes.len()
584            )));
585        }
586        let mut out = [0u8; N];
587        out[..bytes.len()].copy_from_slice(&bytes);
588        Ok(out)
589    }
590}
591
592impl TryFrom<RuntimeValue> for Vec<u8> {
593    type Error = ValueProjectionError;
594    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
595        match v {
596            RuntimeValue::Bytes(b) => Ok(b),
597            other => Err(ValueProjectionError::new(format!(
598                "expected Bytes for Vec<u8>, got {}",
599                other.type_label()
600            ))),
601        }
602    }
603}
604
605// Tuple From / TryFrom — per-arity (1..=12). Compact's tuple
606// descriptor walks positionally; the runtime convention is
607// `RuntimeValue::Array` with one element per slot.
608//
609// Note: macro positional re-use of generics + an `idx` token (each
610// tuple arity gets a hand-written impl block in the macro expansion)
611// keeps inference straightforward without nightly variadic generics.
612macro_rules! tuple_impls {
613    ( $( ( $arity:literal, $( ($t:ident, $idx:tt) ),+ ) ),+ $(,)? ) => {
614        $(
615            impl< $( $t ),+ > From<( $( $t , )+ )> for RuntimeValue
616            where $( $t: Into<RuntimeValue> ),+
617            {
618                fn from(t: ( $( $t , )+ )) -> Self {
619                    RuntimeValue::Array(::std::vec![ $( t.$idx.into() ),+ ])
620                }
621            }
622
623            impl< $( $t ),+ > TryFrom<RuntimeValue> for ( $( $t , )+ )
624            where $( $t: TryFrom<RuntimeValue, Error = ValueProjectionError> ),+
625            {
626                type Error = ValueProjectionError;
627                fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
628                    let mut arr = match v {
629                        RuntimeValue::Array(a) => a,
630                        other => return Err(ValueProjectionError::new(format!(
631                            "expected Array for tuple of arity {}, got {}",
632                            $arity, other.type_label()
633                        ))),
634                    };
635                    if arr.len() != $arity {
636                        return Err(ValueProjectionError::new(format!(
637                            "tuple expected {} elements, got {}", $arity, arr.len()
638                        )));
639                    }
640                    let mut iter = arr.drain(..);
641                    Ok(( $( {
642                        let _ = $idx;  // referenced for macro symmetry
643                        let elem = iter.next().expect("checked length");
644                        <$t>::try_from(elem)?
645                    } , )+ ))
646                }
647            }
648        )+
649    };
650}
651
652tuple_impls!(
653    (1, (T0, 0)),
654    (2, (T0, 0), (T1, 1)),
655    (3, (T0, 0), (T1, 1), (T2, 2)),
656    (4, (T0, 0), (T1, 1), (T2, 2), (T3, 3)),
657    (5, (T0, 0), (T1, 1), (T2, 2), (T3, 3), (T4, 4)),
658    (6, (T0, 0), (T1, 1), (T2, 2), (T3, 3), (T4, 4), (T5, 5)),
659    (
660        7,
661        (T0, 0),
662        (T1, 1),
663        (T2, 2),
664        (T3, 3),
665        (T4, 4),
666        (T5, 5),
667        (T6, 6)
668    ),
669    (
670        8,
671        (T0, 0),
672        (T1, 1),
673        (T2, 2),
674        (T3, 3),
675        (T4, 4),
676        (T5, 5),
677        (T6, 6),
678        (T7, 7)
679    ),
680    (
681        9,
682        (T0, 0),
683        (T1, 1),
684        (T2, 2),
685        (T3, 3),
686        (T4, 4),
687        (T5, 5),
688        (T6, 6),
689        (T7, 7),
690        (T8, 8)
691    ),
692    (
693        10,
694        (T0, 0),
695        (T1, 1),
696        (T2, 2),
697        (T3, 3),
698        (T4, 4),
699        (T5, 5),
700        (T6, 6),
701        (T7, 7),
702        (T8, 8),
703        (T9, 9)
704    ),
705    (
706        11,
707        (T0, 0),
708        (T1, 1),
709        (T2, 2),
710        (T3, 3),
711        (T4, 4),
712        (T5, 5),
713        (T6, 6),
714        (T7, 7),
715        (T8, 8),
716        (T9, 9),
717        (T10, 10)
718    ),
719    (
720        12,
721        (T0, 0),
722        (T1, 1),
723        (T2, 2),
724        (T3, 3),
725        (T4, 4),
726        (T5, 5),
727        (T6, 6),
728        (T7, 7),
729        (T8, 8),
730        (T9, 9),
731        (T10, 10),
732        (T11, 11)
733    ),
734);
735
736// Empty tuple — `()`.
737impl From<()> for RuntimeValue {
738    fn from((): ()) -> Self {
739        RuntimeValue::Array(::std::vec::Vec::new())
740    }
741}
742
743impl TryFrom<RuntimeValue> for () {
744    type Error = ValueProjectionError;
745    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
746        match v {
747            RuntimeValue::Array(a) if a.is_empty() => Ok(()),
748            RuntimeValue::Null => Ok(()),
749            other => Err(ValueProjectionError::new(format!(
750                "expected empty Array / Null for `()`, got {}",
751                other.type_label()
752            ))),
753        }
754    }
755}
756
757// Reverse: TryFrom<RuntimeValue> for primitives.
758
759impl TryFrom<RuntimeValue> for bool {
760    type Error = ValueProjectionError;
761    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
762        match v {
763            RuntimeValue::Bool(b) => Ok(b),
764            other => Err(ValueProjectionError::new(format!(
765                "expected bool, got {}",
766                other.type_label()
767            ))),
768        }
769    }
770}
771
772macro_rules! try_from_uint {
773    ($($t:ty),*) => {
774        $(
775            impl TryFrom<RuntimeValue> for $t {
776                type Error = ValueProjectionError;
777                fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
778                    let n = match &v {
779                        RuntimeValue::Int(i) if *i >= 0 => u128::try_from(*i).ok(),
780                        RuntimeValue::String(s) => s.parse::<u128>().ok(),
781                        _ => None,
782                    };
783                    let n = n.ok_or_else(|| ValueProjectionError::new(format!(
784                        "expected non-negative integer for {}, got {}",
785                        stringify!($t),
786                        v.type_label()
787                    )))?;
788                    <$t>::try_from(n).map_err(|e| ValueProjectionError::new(format!(
789                        "uint {} doesn't fit {}: {}", n, stringify!($t), e
790                    )))
791                }
792            }
793        )*
794    };
795}
796try_from_uint!(u8, u16, u32, u64, u128);
797
798impl TryFrom<RuntimeValue> for i128 {
799    type Error = ValueProjectionError;
800    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
801        match &v {
802            RuntimeValue::Int(i) => Ok(*i),
803            RuntimeValue::String(s) => s
804                .parse::<i128>()
805                .map_err(|e| ValueProjectionError::new(format!("not an i128 string: `{s}` ({e})"))),
806            _ => Err(ValueProjectionError::new(format!(
807                "expected i128, got {}",
808                v.type_label()
809            ))),
810        }
811    }
812}
813
814impl TryFrom<RuntimeValue> for String {
815    type Error = ValueProjectionError;
816    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
817        match v {
818            RuntimeValue::String(s) => Ok(s),
819            other => Err(ValueProjectionError::new(format!(
820                "expected string, got {}",
821                other.type_label()
822            ))),
823        }
824    }
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830    use serde_json::json;
831
832    #[test]
833    fn round_trip_through_json_preserves_shape() {
834        let rv = RuntimeValue::Object(BTreeMap::from([
835            ("a".into(), RuntimeValue::Bool(true)),
836            ("b".into(), RuntimeValue::Int(42)),
837            (
838                "c".into(),
839                RuntimeValue::Array(vec![RuntimeValue::Null, RuntimeValue::String("hi".into())]),
840            ),
841        ]));
842        let j: JsonValue = rv.clone().into();
843        let back: RuntimeValue = j.into();
844        assert_eq!(rv, back);
845    }
846
847    #[test]
848    fn bytes_serializes_as_hex_in_json() {
849        let rv = RuntimeValue::Bytes(vec![0xaa, 0xbb]);
850        let j: JsonValue = rv.into();
851        assert_eq!(j, json!("aabb"));
852    }
853
854    #[test]
855    fn unit_is_empty_array() {
856        assert_eq!(RuntimeValue::unit(), RuntimeValue::Array(vec![]));
857    }
858
859    #[test]
860    fn type_labels_disambiguate() {
861        assert_eq!(RuntimeValue::Null.type_label(), "null");
862        assert_eq!(RuntimeValue::Bool(true).type_label(), "bool");
863        assert_eq!(RuntimeValue::Int(0).type_label(), "int");
864        assert_eq!(RuntimeValue::Bytes(vec![]).type_label(), "bytes");
865        assert_eq!(RuntimeValue::String(String::new()).type_label(), "string");
866        assert_eq!(RuntimeValue::Array(vec![]).type_label(), "array");
867        assert_eq!(RuntimeValue::Object(BTreeMap::new()).type_label(), "object");
868    }
869
870    #[test]
871    fn cbor_round_trips_bytes_as_raw() {
872        let rv = RuntimeValue::Bytes(vec![1, 2, 3, 4]);
873        let buf = crate::cbor_fast::encode_runtime_value_vec(&rv);
874        // CBOR major type 2 (byte string) header for length 4 = 0x44.
875        assert!(buf.contains(&0x44));
876        let back = crate::cbor_fast::decode_runtime_value_slice(&buf).unwrap();
877        assert_eq!(back, rv);
878    }
879}