to_writer_custom

Function to_writer_custom 

Source
pub fn to_writer_custom<T, W: Write>() -> ToWriterBuilder<T, W>
Expand description

Format a crate::Value to a string. Several options can be configured in the process, such as the indentation, custom formatters, printing of context, and style (compact or spaced).

ยงExample

use scale_value::{Value, ValueDef, Primitive, value};
use scale_value::stringify::custom_formatters::format_hex;
use core::fmt::Write;

let value = value!({
    foo: true,
    bar: (1u8,2u8,3u8,4u8)
});

let mut s = String::new();

fn capitalise_bools<T, W: Write>(v: &Value<T>, w: &mut W) -> Option<core::fmt::Result> {
    if let ValueDef::Primitive(Primitive::Bool(b)) = &v.value {
        match b {
            true => Some(write!(w, "TRUE")),
            false => Some(write!(w, "FALSE"))
        }
    } else {
        None
    }
}

scale_value::stringify::to_writer_custom()
    .compact()
    .add_custom_formatter(|v, w| format_hex(v, w))
    .add_custom_formatter(|v, w| capitalise_bools(v, w))
    .write(&value, &mut s);

assert_eq!(s, r#"{foo:TRUE,bar:0x01020304}"#)