snapshot/any_snapshot.rs
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, serde::Serialize, serde::Deserialize)]
18pub struct AnySnapshot(ciborium::Value);
19
20impl AnySnapshot {
21 pub fn to_any(x: impl serde::Serialize) -> anyhow::Result<Self> {
22 Ok(AnySnapshot(ciborium::Value::serialized(&x)?))
23 }
24
25 pub fn from_any<T: serde::de::DeserializeOwned>(x: Self) -> anyhow::Result<T> {
26 Ok(x.0.deserialized()?)
27 }
28}