1 // Copyright 2025 The ChromiumOS Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 /// A type erased snapshot value. Or, alternatively, you can think of it as a partially 6 /// (de)serialized value that can be nested in other values without incurring double encoding in 7 /// the final output. 8 /// 9 /// There is a performance and code size cost to this type, so only use it if really needed, for 10 /// example, in traits that must be dyn compatible. 11 /// 12 /// If the intermediate representation and the final serialization format don't match, for example, 13 /// if `AnySnapshot` was implemented with `serde_json::Value` but then written to a file as CBOR, 14 /// it will technically work, but the result might not match what you'd get if you directly 15 /// serialized the original value. That should be OK as long as the serialization and 16 /// deserialization paths make symmetric use of `AnySnapshot`. 17 #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 18 pub struct AnySnapshot(serde_json::Value); 19 20 impl AnySnapshot { to_any(x: impl serde::Serialize) -> anyhow::Result<Self>21 pub fn to_any(x: impl serde::Serialize) -> anyhow::Result<Self> { 22 Ok(AnySnapshot(serde_json::to_value(x)?)) 23 } 24 from_any<T: serde::de::DeserializeOwned>(x: Self) -> anyhow::Result<T>25 pub fn from_any<T: serde::de::DeserializeOwned>(x: Self) -> anyhow::Result<T> { 26 Ok(serde_json::from_value(x.0)?) 27 } 28 } 29