use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum RuntimeValue {
Null,
Bool(bool),
Int(i128),
#[serde(serialize_with = "byte_buf_serde::serialize")]
Bytes(Vec<u8>),
String(String),
Array(Vec<RuntimeValue>),
Object(BTreeMap<String, RuntimeValue>),
}
impl<'de> Deserialize<'de> for RuntimeValue {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
use serde::de::{Error, MapAccess, SeqAccess, Visitor};
struct RvVisitor;
impl<'de> Visitor<'de> for RvVisitor {
type Value = RuntimeValue;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(
"any RuntimeValue (null, bool, integer, bytes, string, array, or object)",
)
}
fn visit_unit<E: Error>(self) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::Null)
}
fn visit_none<E: Error>(self) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::Null)
}
fn visit_some<D: serde::Deserializer<'de>>(
self,
d: D,
) -> Result<RuntimeValue, D::Error> {
d.deserialize_any(self)
}
fn visit_bool<E: Error>(self, v: bool) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::Bool(v))
}
fn visit_i64<E: Error>(self, v: i64) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::Int(i128::from(v)))
}
fn visit_u64<E: Error>(self, v: u64) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::Int(i128::from(v)))
}
fn visit_i128<E: Error>(self, v: i128) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::Int(v))
}
fn visit_u128<E: Error>(self, v: u128) -> Result<RuntimeValue, E> {
i128::try_from(v)
.map(RuntimeValue::Int)
.map_err(|_| Error::custom(format!("u128 value {v} exceeds i128 range")))
}
fn visit_f64<E: Error>(self, v: f64) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::String(format!("{v}")))
}
fn visit_str<E: Error>(self, v: &str) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::String(v.to_owned()))
}
fn visit_string<E: Error>(self, v: String) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::String(v))
}
fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::Bytes(v.to_vec()))
}
fn visit_byte_buf<E: Error>(self, v: Vec<u8>) -> Result<RuntimeValue, E> {
Ok(RuntimeValue::Bytes(v))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<RuntimeValue, A::Error> {
let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(elem) = seq.next_element::<RuntimeValue>()? {
out.push(elem);
}
Ok(RuntimeValue::Array(out))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<RuntimeValue, A::Error> {
let mut out = BTreeMap::new();
while let Some((k, v)) = map.next_entry::<String, RuntimeValue>()? {
out.insert(k, v);
}
Ok(RuntimeValue::Object(out))
}
}
d.deserialize_any(RvVisitor)
}
}
impl RuntimeValue {
#[must_use]
pub fn unit() -> Self {
RuntimeValue::Array(Vec::new())
}
#[must_use]
pub fn field(&self, name: &str) -> Option<&RuntimeValue> {
match self {
RuntimeValue::Object(o) => o.get(name),
_ => None,
}
}
#[must_use]
pub fn type_label(&self) -> &'static str {
match self {
RuntimeValue::Null => "null",
RuntimeValue::Bool(_) => "bool",
RuntimeValue::Int(_) => "int",
RuntimeValue::Bytes(_) => "bytes",
RuntimeValue::String(_) => "string",
RuntimeValue::Array(_) => "array",
RuntimeValue::Object(_) => "object",
}
}
#[must_use]
pub fn is_null(&self) -> bool {
matches!(self, RuntimeValue::Null)
}
#[must_use]
pub fn is_number(&self) -> bool {
matches!(self, RuntimeValue::Int(_))
}
#[must_use]
pub fn is_string(&self) -> bool {
matches!(self, RuntimeValue::String(_))
}
#[must_use]
pub fn is_array(&self) -> bool {
matches!(self, RuntimeValue::Array(_))
}
#[must_use]
pub fn is_object(&self) -> bool {
matches!(self, RuntimeValue::Object(_))
}
#[must_use]
pub fn is_bool(&self) -> bool {
matches!(self, RuntimeValue::Bool(_))
}
#[must_use]
pub fn as_bool(&self) -> Option<bool> {
match self {
RuntimeValue::Bool(b) => Some(*b),
_ => None,
}
}
#[must_use]
pub fn as_i128(&self) -> Option<i128> {
match self {
RuntimeValue::Int(i) => Some(*i),
_ => None,
}
}
#[must_use]
pub fn as_u64(&self) -> Option<u64> {
match self {
RuntimeValue::Int(i) if *i >= 0 => u64::try_from(*i).ok(),
_ => None,
}
}
#[must_use]
pub fn as_u128(&self) -> Option<u128> {
match self {
RuntimeValue::Int(i) if *i >= 0 => u128::try_from(*i).ok(),
_ => None,
}
}
#[must_use]
pub fn as_str(&self) -> Option<&str> {
match self {
RuntimeValue::String(s) => Some(s.as_str()),
_ => None,
}
}
#[must_use]
pub fn as_bytes(&self) -> Option<&[u8]> {
match self {
RuntimeValue::Bytes(b) => Some(b.as_slice()),
_ => None,
}
}
#[must_use]
pub fn as_array(&self) -> Option<&Vec<RuntimeValue>> {
match self {
RuntimeValue::Array(a) => Some(a),
_ => None,
}
}
#[must_use]
pub fn as_array_mut(&mut self) -> Option<&mut Vec<RuntimeValue>> {
match self {
RuntimeValue::Array(a) => Some(a),
_ => None,
}
}
#[must_use]
pub fn as_object(&self) -> Option<&BTreeMap<String, RuntimeValue>> {
match self {
RuntimeValue::Object(o) => Some(o),
_ => None,
}
}
#[must_use]
pub fn as_object_mut(&mut self) -> Option<&mut BTreeMap<String, RuntimeValue>> {
match self {
RuntimeValue::Object(o) => Some(o),
_ => None,
}
}
#[must_use]
#[expect(
clippy::needless_pass_by_value,
reason = "mirrors `serde_json::Value::get`: callers pass `\"key\"` or `0` by value through `ValueIndex`"
)]
pub fn get<I: ValueIndex>(&self, idx: I) -> Option<&RuntimeValue> {
idx.get_in(self)
}
}
pub trait ValueIndex {
fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue>;
}
impl ValueIndex for &str {
fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue> {
match v {
RuntimeValue::Object(o) => o.get(*self),
_ => None,
}
}
}
impl ValueIndex for usize {
fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue> {
match v {
RuntimeValue::Array(a) => a.get(*self),
_ => None,
}
}
}
impl ValueIndex for &String {
fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue> {
self.as_str().get_in(v)
}
}
impl std::fmt::Display for RuntimeValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RuntimeValue::Null => f.write_str("null"),
RuntimeValue::Bool(b) => write!(f, "{b}"),
RuntimeValue::Int(i) => write!(f, "{i}"),
RuntimeValue::Bytes(b) => write!(f, "0x{}", hex::encode(b)),
RuntimeValue::String(s) => write!(f, "{s:?}"),
RuntimeValue::Array(a) => {
f.write_str("[")?;
for (i, v) in a.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
write!(f, "{v}")?;
}
f.write_str("]")
}
RuntimeValue::Object(o) => {
f.write_str("{")?;
for (i, (k, v)) in o.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
write!(f, "{k:?}: {v}")?;
}
f.write_str("}")
}
}
}
}
mod byte_buf_serde {
use serde::Serializer;
pub fn serialize<S: Serializer>(v: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
s.serialize_str(&hex::encode(v))
} else {
s.serialize_bytes(v)
}
}
}
impl From<RuntimeValue> for JsonValue {
fn from(v: RuntimeValue) -> Self {
match v {
RuntimeValue::Null => JsonValue::Null,
RuntimeValue::Bool(b) => JsonValue::Bool(b),
RuntimeValue::Int(i) => {
if let Ok(u) = u64::try_from(i) {
JsonValue::Number(u.into())
} else if let Ok(s) = i64::try_from(i) {
JsonValue::Number(s.into())
} else {
JsonValue::String(i.to_string())
}
}
RuntimeValue::Bytes(b) => JsonValue::String(hex::encode(b)),
RuntimeValue::String(s) => JsonValue::String(s),
RuntimeValue::Array(a) => JsonValue::Array(a.into_iter().map(Into::into).collect()),
RuntimeValue::Object(o) => {
let mut m = serde_json::Map::with_capacity(o.len());
for (k, v) in o {
m.insert(k, v.into());
}
JsonValue::Object(m)
}
}
}
}
impl From<JsonValue> for RuntimeValue {
fn from(v: JsonValue) -> Self {
match v {
JsonValue::Null => RuntimeValue::Null,
JsonValue::Bool(b) => RuntimeValue::Bool(b),
JsonValue::Number(n) => {
if let Some(u) = n.as_u64() {
RuntimeValue::Int(i128::from(u))
} else if let Some(s) = n.as_i64() {
RuntimeValue::Int(i128::from(s))
} else if let Some(f) = n.as_f64() {
#[expect(
clippy::cast_possible_truncation,
reason = "truncating a non-integral JSON float to i128 is the intended projection; `as` saturates and maps NaN to 0"
)]
let truncated = f as i128;
RuntimeValue::Int(truncated)
} else {
RuntimeValue::Null
}
}
JsonValue::String(s) => RuntimeValue::String(s),
JsonValue::Array(a) => RuntimeValue::Array(a.into_iter().map(Into::into).collect()),
JsonValue::Object(o) => {
let mut m = BTreeMap::new();
for (k, v) in o {
m.insert(k, v.into());
}
RuntimeValue::Object(m)
}
}
}
}
#[derive(Debug, Clone, thiserror::Error)]
#[error("RuntimeValue projection: {0}")]
pub struct ValueProjectionError(pub String);
impl ValueProjectionError {
pub fn new(msg: impl Into<String>) -> Self {
Self(msg.into())
}
}
impl From<bool> for RuntimeValue {
fn from(b: bool) -> Self {
RuntimeValue::Bool(b)
}
}
macro_rules! from_uint {
($($t:ty),*) => {
$(
impl From<$t> for RuntimeValue {
fn from(n: $t) -> Self {
RuntimeValue::Int(i128::from(n))
}
}
)*
};
}
from_uint!(u8, u16, u32, u64);
macro_rules! from_int {
($($t:ty),*) => {
$(
impl From<$t> for RuntimeValue {
fn from(n: $t) -> Self {
RuntimeValue::Int(i128::from(n))
}
}
)*
};
}
from_int!(i8, i16, i32, i64);
impl From<i128> for RuntimeValue {
fn from(n: i128) -> Self {
RuntimeValue::Int(n)
}
}
impl From<u128> for RuntimeValue {
fn from(n: u128) -> Self {
match i128::try_from(n) {
Ok(i) => RuntimeValue::Int(i),
Err(_) => RuntimeValue::String(n.to_string()),
}
}
}
impl From<String> for RuntimeValue {
fn from(s: String) -> Self {
RuntimeValue::String(s)
}
}
impl From<&str> for RuntimeValue {
fn from(s: &str) -> Self {
RuntimeValue::String(s.to_owned())
}
}
impl<const N: usize> From<[u8; N]> for RuntimeValue {
fn from(b: [u8; N]) -> Self {
RuntimeValue::Bytes(b.to_vec())
}
}
impl From<Vec<u8>> for RuntimeValue {
fn from(b: Vec<u8>) -> Self {
RuntimeValue::Bytes(b)
}
}
impl<const N: usize> TryFrom<RuntimeValue> for [u8; N] {
type Error = ValueProjectionError;
fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
let bytes: Vec<u8> = match v {
RuntimeValue::Bytes(b) => b,
other => {
return Err(ValueProjectionError::new(format!(
"expected Bytes for [u8; {N}], got {}",
other.type_label()
)));
}
};
if bytes.len() > N {
return Err(ValueProjectionError::new(format!(
"[u8; {N}] expected ≤ {N} bytes, got {}",
bytes.len()
)));
}
let mut out = [0u8; N];
out[..bytes.len()].copy_from_slice(&bytes);
Ok(out)
}
}
impl TryFrom<RuntimeValue> for Vec<u8> {
type Error = ValueProjectionError;
fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
match v {
RuntimeValue::Bytes(b) => Ok(b),
other => Err(ValueProjectionError::new(format!(
"expected Bytes for Vec<u8>, got {}",
other.type_label()
))),
}
}
}
macro_rules! tuple_impls {
( $( ( $arity:literal, $( ($t:ident, $idx:tt) ),+ ) ),+ $(,)? ) => {
$(
impl< $( $t ),+ > From<( $( $t , )+ )> for RuntimeValue
where $( $t: Into<RuntimeValue> ),+
{
fn from(t: ( $( $t , )+ )) -> Self {
RuntimeValue::Array(::std::vec![ $( t.$idx.into() ),+ ])
}
}
impl< $( $t ),+ > TryFrom<RuntimeValue> for ( $( $t , )+ )
where $( $t: TryFrom<RuntimeValue, Error = ValueProjectionError> ),+
{
type Error = ValueProjectionError;
fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
let mut arr = match v {
RuntimeValue::Array(a) => a,
other => return Err(ValueProjectionError::new(format!(
"expected Array for tuple of arity {}, got {}",
$arity, other.type_label()
))),
};
if arr.len() != $arity {
return Err(ValueProjectionError::new(format!(
"tuple expected {} elements, got {}", $arity, arr.len()
)));
}
let mut iter = arr.drain(..);
Ok(( $( {
let _ = $idx; let elem = iter.next().expect("checked length");
<$t>::try_from(elem)?
} , )+ ))
}
}
)+
};
}
tuple_impls!(
(1, (T0, 0)),
(2, (T0, 0), (T1, 1)),
(3, (T0, 0), (T1, 1), (T2, 2)),
(4, (T0, 0), (T1, 1), (T2, 2), (T3, 3)),
(5, (T0, 0), (T1, 1), (T2, 2), (T3, 3), (T4, 4)),
(6, (T0, 0), (T1, 1), (T2, 2), (T3, 3), (T4, 4), (T5, 5)),
(
7,
(T0, 0),
(T1, 1),
(T2, 2),
(T3, 3),
(T4, 4),
(T5, 5),
(T6, 6)
),
(
8,
(T0, 0),
(T1, 1),
(T2, 2),
(T3, 3),
(T4, 4),
(T5, 5),
(T6, 6),
(T7, 7)
),
(
9,
(T0, 0),
(T1, 1),
(T2, 2),
(T3, 3),
(T4, 4),
(T5, 5),
(T6, 6),
(T7, 7),
(T8, 8)
),
(
10,
(T0, 0),
(T1, 1),
(T2, 2),
(T3, 3),
(T4, 4),
(T5, 5),
(T6, 6),
(T7, 7),
(T8, 8),
(T9, 9)
),
(
11,
(T0, 0),
(T1, 1),
(T2, 2),
(T3, 3),
(T4, 4),
(T5, 5),
(T6, 6),
(T7, 7),
(T8, 8),
(T9, 9),
(T10, 10)
),
(
12,
(T0, 0),
(T1, 1),
(T2, 2),
(T3, 3),
(T4, 4),
(T5, 5),
(T6, 6),
(T7, 7),
(T8, 8),
(T9, 9),
(T10, 10),
(T11, 11)
),
);
impl From<()> for RuntimeValue {
fn from((): ()) -> Self {
RuntimeValue::Array(::std::vec::Vec::new())
}
}
impl TryFrom<RuntimeValue> for () {
type Error = ValueProjectionError;
fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
match v {
RuntimeValue::Array(a) if a.is_empty() => Ok(()),
RuntimeValue::Null => Ok(()),
other => Err(ValueProjectionError::new(format!(
"expected empty Array / Null for `()`, got {}",
other.type_label()
))),
}
}
}
impl TryFrom<RuntimeValue> for bool {
type Error = ValueProjectionError;
fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
match v {
RuntimeValue::Bool(b) => Ok(b),
other => Err(ValueProjectionError::new(format!(
"expected bool, got {}",
other.type_label()
))),
}
}
}
macro_rules! try_from_uint {
($($t:ty),*) => {
$(
impl TryFrom<RuntimeValue> for $t {
type Error = ValueProjectionError;
fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
let n = match &v {
RuntimeValue::Int(i) if *i >= 0 => u128::try_from(*i).ok(),
RuntimeValue::String(s) => s.parse::<u128>().ok(),
_ => None,
};
let n = n.ok_or_else(|| ValueProjectionError::new(format!(
"expected non-negative integer for {}, got {}",
stringify!($t),
v.type_label()
)))?;
<$t>::try_from(n).map_err(|e| ValueProjectionError::new(format!(
"uint {} doesn't fit {}: {}", n, stringify!($t), e
)))
}
}
)*
};
}
try_from_uint!(u8, u16, u32, u64, u128);
impl TryFrom<RuntimeValue> for i128 {
type Error = ValueProjectionError;
fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
match &v {
RuntimeValue::Int(i) => Ok(*i),
RuntimeValue::String(s) => s
.parse::<i128>()
.map_err(|e| ValueProjectionError::new(format!("not an i128 string: `{s}` ({e})"))),
_ => Err(ValueProjectionError::new(format!(
"expected i128, got {}",
v.type_label()
))),
}
}
}
impl TryFrom<RuntimeValue> for String {
type Error = ValueProjectionError;
fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
match v {
RuntimeValue::String(s) => Ok(s),
other => Err(ValueProjectionError::new(format!(
"expected string, got {}",
other.type_label()
))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn round_trip_through_json_preserves_shape() {
let rv = RuntimeValue::Object(BTreeMap::from([
("a".into(), RuntimeValue::Bool(true)),
("b".into(), RuntimeValue::Int(42)),
(
"c".into(),
RuntimeValue::Array(vec![RuntimeValue::Null, RuntimeValue::String("hi".into())]),
),
]));
let j: JsonValue = rv.clone().into();
let back: RuntimeValue = j.into();
assert_eq!(rv, back);
}
#[test]
fn bytes_serializes_as_hex_in_json() {
let rv = RuntimeValue::Bytes(vec![0xaa, 0xbb]);
let j: JsonValue = rv.into();
assert_eq!(j, json!("aabb"));
}
#[test]
fn unit_is_empty_array() {
assert_eq!(RuntimeValue::unit(), RuntimeValue::Array(vec![]));
}
#[test]
fn type_labels_disambiguate() {
assert_eq!(RuntimeValue::Null.type_label(), "null");
assert_eq!(RuntimeValue::Bool(true).type_label(), "bool");
assert_eq!(RuntimeValue::Int(0).type_label(), "int");
assert_eq!(RuntimeValue::Bytes(vec![]).type_label(), "bytes");
assert_eq!(RuntimeValue::String(String::new()).type_label(), "string");
assert_eq!(RuntimeValue::Array(vec![]).type_label(), "array");
assert_eq!(RuntimeValue::Object(BTreeMap::new()).type_label(), "object");
}
#[test]
fn cbor_round_trips_bytes_as_raw() {
let rv = RuntimeValue::Bytes(vec![1, 2, 3, 4]);
let buf = crate::cbor_fast::encode_runtime_value_vec(&rv);
assert!(buf.contains(&0x44));
let back = crate::cbor_fast::decode_runtime_value_slice(&buf).unwrap();
assert_eq!(back, rv);
}
}