from_str

Function from_str 

Source
pub fn from_str(s: &str) -> (Result<Value<()>, ParseError>, &str)
Expand description

Attempt to parse a string into a crate::Value<()>, returning a tuple consisting of a result (either the value or a ParseError containing location and error information) and the remainder of the string that wasn’t parsed.

§Examples

use scale_value::Value;

fn to_value(str: &str) -> Value {
    scale_value::stringify::from_str(str).0.unwrap()
}

// Primitive values:
assert_eq!(to_value("1"), Value::u128(1));
assert_eq!(to_value("-1"), Value::i128(-1));
assert_eq!(to_value("true"), Value::bool(true));
assert_eq!(to_value("'a'"), Value::char('a'));
assert_eq!(to_value("\"hi\""), Value::string("hi"));

// Named composite values look a bit like rust structs:
let value = to_value("{ a: true, b: \"hello\" }");
assert_eq!(
    value,
    Value::named_composite(vec![
        ("a", Value::bool(true)),
        ("b", Value::string("hello"))
    ])
);

// Unnamed composite values look a bit like rust tuples:
let value = to_value("(true, \"hello\")");
assert_eq!(
    value,
    Value::unnamed_composite(vec![
        Value::bool(true),
        Value::string("hello")
    ])
);

// Variant values (named or unnamed) are just the above with a variant name
// prefixed:
let value = to_value("MyVariant { a: true, b: \"hello\" }");
assert_eq!(
    value,
    Value::named_variant(
        "MyVariant",
        vec![
            ("a", Value::bool(true)),
            ("b", Value::string("hello"))
        ]
    )
);

// Bit sequences can be encoded from unnamed composites, but we have a
// compact syntax for them too:
assert_eq!(
    to_value("<0101>"),
    Value::bit_sequence(scale_bits::Bits::from_iter([false, true, false, true]))
);