Expand description
Value inspection.
The Visit
trait provides a simple visitor API that can be used to inspect
the structure of primitives stored in a ValueBag
.
More complex datatypes can then be handled using std::fmt
, sval
, or serde
.
use value_bag::{ValueBag, Error, visit::Visit};
// Implement some simple custom serialization
struct MyVisit(Vec<u8>);
impl<'v> Visit<'v> for MyVisit {
fn visit_any(&mut self, v: ValueBag) -> Result<(), Error> {
// Fallback to `Debug` if we didn't visit the value specially
write!(&mut self.0, "{:?}", v).map_err(|_| Error::msg("failed to write value"))
}
fn visit_u64(&mut self, v: u64) -> Result<(), Error> {
self.0.extend_from_slice(itoa_fmt(v).as_slice());
Ok(())
}
fn visit_i64(&mut self, v: i64) -> Result<(), Error> {
self.0.extend_from_slice(itoa_fmt(v).as_slice());
Ok(())
}
fn visit_f64(&mut self, v: f64) -> Result<(), Error> {
self.0.extend_from_slice(ryu_fmt(v).as_slice());
Ok(())
}
fn visit_str(&mut self, v: &str) -> Result<(), Error> {
self.0.push(b'\"');
self.0.extend_from_slice(escape(v.as_bytes()));
self.0.push(b'\"');
Ok(())
}
fn visit_bool(&mut self, v: bool) -> Result<(), Error> {
self.0.extend_from_slice(if v { b"true" } else { b"false" });
Ok(())
}
}
let value = ValueBag::from(42i64);
let mut visitor = MyVisit(vec![]);
value.visit(&mut visitor)?;
Traits
A visitor for a
ValueBag
.