scale_value

Module scale

source
Expand description

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

§Exmaple

Given some known metadata type ID, encode and decode 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", [
    ("is_valid", Value::bool(true)),
    ("name", Value::string("James")),
]);

// Encode the Value to bytes:
let mut bytes = Vec::new();
scale_value::scale::encode_as_type(&value, 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());

Modules§

  • A visitor and function to decode some bytes into a crate::Value while tracing the current decoding state so that a more detailed error can be returned in the event of a failure.

Structs§

  • An error produced while attempting to encode some type.
  • A read-only registry containing types in their portable form for serialization.

Enums§

Traits§

  • This trait can be implemented for any type that is capable of describing how some type (identified by a TypeResolver::TypeId) is represented in terms of SCALE encoded bytes.

Functions§

  • Attempt to decode some SCALE encoded bytes into multiple values, by providing a pointer to the bytes (which will be moved forwards as bytes are used in the decoding), and an iterator of fields, where each field contains a type ID and optionally a field name.
  • 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.

Type Aliases§