Expand description

Encoding and decoding SCALE bytes into a crate::Value.

Exmaple

Given some known metadata type ID, encode and desome some crate::Value to SCALE bytes.

use scale_value::Value;

// Imagine we have a `registry` (of type [`scale_info::PortableRegistry`]) containing this type,
// and a `type_id` (a `u32`) pointing to it in the registry.
#[derive(scale_info::TypeInfo)]
enum Foo {
    A { is_valid: bool, name: String }
}

// Given that, we can encode/decode something with that shape to/from SCALE bytes:
let value = Value::named_variant("A", vec![
    ("is_valid".into(), Value::bool(true)),
    ("name".into(), Value::string("James")),
]);

// Encode the Value to bytes:
let mut bytes = Vec::new();
scale_value::scale::encode_as_type(value.clone(), type_id, &registry, &mut bytes).unwrap();

// Decode the bytes back into a matching Value.
// This value contains contextual information about which type was used
// to decode each part of it, which we can throw away with `.remove_context()`.
let new_value = scale_value::scale::decode_as_type(&mut &*bytes, type_id, &registry).unwrap();

assert_eq!(value, new_value.remove_context());

Structs

A read-only registry containing types in their portable form for serialization.

This represents the ID of a type found in the metadata. A scale info type representation can be converted into this, and we get this back directly when decoding types into Values.

Enums

An error that can occur when we try to encode or decode to a SCALE bit sequence type.

An error decoding SCALE bytes into a Value.

An error encoding a Value into SCALE bytes.

Functions

Attempt to decode some SCALE encoded bytes into a value, by providing a pointer to the bytes (which will be moved forwards as bytes are used in the decoding), a type ID, and a type registry from which we’ll look up the relevant type information.

Attempt to encode some crate::Value<T> into SCALE bytes, by providing a pointer to the type ID that we’d like to encode it as, a type registry from which we’ll look up the relevant type information, and a buffer to encode the bytes to.