Module scale_info::build
source · Expand description
Builders for defining metadata for variant types (enums), and composite types (structs). They are designed to allow only construction of valid definitions.
In most cases we recommend using the scale-info-derive
crate to auto generate the builder
constructions.
Examples
Generic struct
struct Foo<T> {
bar: T,
data: u64,
}
impl<T> TypeInfo for Foo<T>
where
T: TypeInfo + 'static,
{
type Identity = Self;
fn type_info() -> Type {
Type::builder()
.path(Path::new("Foo", module_path!()))
.type_params(type_params!(T))
.composite(Fields::named()
.field(|f| f.ty::<T>().name("bar").type_name("T"))
.field(|f| f.ty::<u64>().name("data").type_name("u64"))
)
}
}
Tuple struct
struct Foo(u32, bool);
impl TypeInfo for Foo {
type Identity = Self;
fn type_info() -> Type {
Type::builder()
.path(Path::new("Foo", module_path!()))
.composite(Fields::unnamed()
.field(|f| f.ty::<u32>().type_name("u32"))
.field(|f| f.ty::<bool>().type_name("bool"))
)
}
}
Enum with fields
enum Foo<T>{
A(T),
B { f: u32 },
C,
}
impl<T> TypeInfo for Foo<T>
where
T: TypeInfo + 'static,
{
type Identity = Self;
fn type_info() -> Type {
Type::builder()
.path(Path::new("Foo", module_path!()))
.type_params(type_params!(T))
.variant(
Variants::new()
.variant("A", |v| v
.index(0)
.fields(Fields::unnamed().field(|f| f.ty::<T>().type_name("T")))
)
.variant("B", |v| v
.index(1)
.fields(Fields::named().field(|f| f.ty::<u32>().name("f").type_name("u32")))
)
.variant_unit("A", 2)
)
}
}
Enum without fields, aka C-style enums.
enum Foo {
A,
B,
C = 33,
}
impl TypeInfo for Foo {
type Identity = Self;
fn type_info() -> Type {
Type::builder()
.path(Path::new("Foo", module_path!()))
.variant(
Variants::new()
.variant("A", |v| v.index(1))
.variant("B", |v| v.index(2))
.variant("C", |v| v.index(33))
)
}
}
Modules
- Type states for building a field.
- State types for type builders which require a Path.
- State types for the
VariantBuilder
which requires an index.
Structs
- Construct a valid
Field
. - Provides FieldsBuilder constructors
- Build a set of either all named (e.g. for a struct) or all unnamed (e.g. for a tuple struct)
- Builds a
Type
- Build a
Variant
. - Builds a definition of a variant type i.e an
enum
Enums
- A fields builder only allows named fields (e.g. a struct)
- A fields builder has no fields (e.g. a unit struct)
- A fields builder only allows unnamed fields (e.g. a tuple)