use prometeu_bytecode::Value; use serde::{Deserialize, Serialize}; use std::sync::Arc; /// Native/debug ownership only. Wire data is the ordinary list of values; /// opaque accounting domains stay alive for every retained string allocation. #[derive(Clone, Default, Serialize, Deserialize)] #[serde(transparent)] pub struct ValueSnapshot { values: Vec, #[serde(skip)] owners: [Option>; 2], } impl ValueSnapshot { pub fn with_owners(values: Vec, owners: [Option>; 2]) -> Self { Self { values, owners } } pub fn retained_domains(&self) -> usize { self.owners.iter().filter(|owner| owner.is_some()).count() } } impl std::ops::Deref for ValueSnapshot { type Target = [Value]; fn deref(&self) -> &[Value] { &self.values } } impl std::fmt::Debug for ValueSnapshot { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.values.fmt(f) } } impl PartialEq> for ValueSnapshot { fn eq(&self, other: &Vec) -> bool { self.values == *other } } impl From> for ValueSnapshot { /// External/native values have no provenance and are copied on guest import. fn from(values: Vec) -> Self { Self::with_owners(values, [None, None]) } } #[cfg(test)] mod tests { use super::*; #[test] fn serialization_contains_values_and_never_exports_native_domain_metadata() { let owner: Arc = Arc::new(17u32); let snapshot = ValueSnapshot::with_owners( vec![Value::string("shared"), Value::Null], [Some(owner), None], ); assert_eq!(snapshot.retained_domains(), 1); let bytes = serde_json::to_string(&snapshot).unwrap(); assert_eq!(bytes, "[\"shared\",null]"); let imported: ValueSnapshot = serde_json::from_str(&bytes).unwrap(); assert_eq!(imported.retained_domains(), 0); assert_eq!(&*imported, &*snapshot); } }