Files
prometeu-runtime/crates/console/prometeu-hal/src/value_snapshot.rs
T

63 lines
2.0 KiB
Rust

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<Value>,
#[serde(skip)]
owners: [Option<Arc<dyn Send + Sync>>; 2],
}
impl ValueSnapshot {
pub fn with_owners(values: Vec<Value>, owners: [Option<Arc<dyn Send + Sync>>; 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<Vec<Value>> for ValueSnapshot {
fn eq(&self, other: &Vec<Value>) -> bool {
self.values == *other
}
}
impl From<Vec<Value>> for ValueSnapshot {
/// External/native values have no provenance and are copied on guest import.
fn from(values: Vec<Value>) -> 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<dyn Send + Sync> = 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);
}
}