Skip to main content

scale_serialization/
registry.rs

1use alloc::string::String;
2use alloc::vec::Vec;
3use serde::{Deserialize, Serialize};
4
5/// Index into a [`Registry`].
6pub type TypeId = u32;
7
8/// A minimal type registry storing only what is needed for SCALE serialization.
9/// No docs, no full paths, no type params.
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Registry(Vec<TypeDef>);
12
13impl Registry {
14    /// Create a registry from a list of type definitions.
15    pub fn new(types: Vec<TypeDef>) -> Self {
16        Self(types)
17    }
18
19    /// Look up a type by its ID.
20    #[inline]
21    #[must_use]
22    pub fn resolve(&self, id: TypeId) -> Option<&TypeDef> {
23        self.0.get(id as usize)
24    }
25}
26
27/// Type definitions that map directly to serde's data model.
28#[rustfmt::skip]
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub enum TypeDef {
31    Bool,
32    U8, U16, U32, U64, U128,
33    I8, I16, I32, I64, I128,
34    Char,
35    Str,
36    /// `Vec<u8>` serialized as raw bytes
37    Bytes,
38    /// Homogeneous sequence with compact-length prefix
39    Sequence(TypeId),
40    /// `BTreeMap<K, V>`
41    Map(TypeId, TypeId),
42    /// Fixed-length array `[T; N]`
43    Array(TypeId, u32),
44    /// Heterogeneous tuple `(T1, T2, ...)`
45    Tuple(Vec<TypeId>),
46    /// Unit struct (zero fields)
47    StructUnit,
48    /// Newtype struct `Foo(T)`
49    StructNewType(TypeId),
50    /// Tuple struct `Foo(T1, T2, ...)`
51    StructTuple(Vec<TypeId>),
52    /// Named-field struct
53    Struct(Vec<Field>),
54    /// Enum type
55    Variant(VariantDef),
56    /// Compact-encoded integer
57    Compact(TypeId),
58    /// Bit sequence (store, order type IDs)
59    BitSequence(TypeId, TypeId),
60}
61
62/// A named field within a struct or variant.
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct Field {
65    pub name: String,
66    pub ty: TypeId,
67}
68
69/// Definition of an enum type with its variants.
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct VariantDef {
72    /// Short name (e.g. "Option") used for special-case detection.
73    pub name: String,
74    pub variants: Vec<Variant>,
75}
76
77impl VariantDef {
78    /// Find a variant by its SCALE index byte.
79    pub fn variant(&self, index: u8) -> Result<&Variant, crate::Error> {
80        self.variants
81            .iter()
82            .find(|v| v.index == index)
83            .ok_or(crate::Error::InvalidVariant(index))
84    }
85}
86
87/// A single variant of an enum.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct Variant {
90    pub index: u8,
91    pub name: String,
92    pub fields: Fields,
93}
94
95/// Pre-classified variant payload shapes matching serde's enum model
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub enum Fields {
98    Unit,
99    NewType(TypeId),
100    Tuple(Vec<TypeId>),
101    Struct(Vec<Field>),
102}