value-bag
What is a value bag?
A ValueBag
is an anonymous structured value that supports casting, downcasting, formatting, and serializing. The producer of a ValueBag
and its eventual consumer don't need to agree on a serialization contract. Any translation is handled internally by ValueBag
.
Say we capture an i32
using its Display
implementation as a ValueBag
:
let bag = capture_display;
That value can then be cast to a concrete integer type, like u64
:
let num = bag.as_u64.unwrap;
assert_eq!;
It could also be serialized as a number using serde
:
let num = to_value.unwrap;
assert!;
It works for more complex types too. Say we derive sval::Value
on a type and capture it as a ValueBag
:
let work = Work
let bag = capture_sval2;
We could still serialize that value using serde
without losing structure:
let obj = to_value.unwrap;
assert!;
It could also be formatted using Display
:
assert_eq!;
The tradeoff in all this is that ValueBag
needs to depend on the serialization frameworks (sval
, serde
, and std::fmt
) that it supports, instead of just providing an API of its own for others to plug into. Doing this lets ValueBag
guarantee everything will always line up, and keep its own public API narrow.
Getting started
Add the value-bag
crate to your Cargo.toml
:
= "1.10.0"
version
You'll probably also want to add a feature for either sval
(if you're in a no-std environment) or serde
(if you need to integrate with other code that uses serde
):
= "1.10.0"
features =
version
= "1.10.0"
features =
version
Then you're ready to capture anonymous values!
// Capture a value that implements `serde::Serialize`
let bag = capture_serde1;
// Print the contents of the value bag
println!;
Cargo features
The value-bag
crate is no-std by default, and offers the following Cargo features:
std
: Enable support for the standard library. This allows more types to be captured in aValueBag
.error
: Enable support for capturingstd::error::Error
s. Impliesstd
.sval
: Enable support for using thesval
serialization framework for inspectingValueBag
s by implementingsval::value::Value
. Impliessval2
.sval2
: Enable support for the stable2.x.x
version ofsval
.
serde
: Enable support for using theserde
serialization framework for inspectingValueBag
s by implementingserde::Serialize
. Impliesstd
andserde1
.serde1
: Enable support for the stable1.x.x
version ofserde
.
owned
: Add support for bufferingValueBag
s into an ownedSend + Sync
variant.seq
: Add support for working with sequences without needing to go through a full serialization framework.test
: Add test helpers for inspecting the shape of the value inside aValueBag
.