git.delta.rocks / unique-network / refs/commits / f78f490e83cf

difftreelog

source

crates/struct-versioning/README.md1.9 KiBsourcehistory
1# struct-versioning23The crate contains procedural macros for versioning data structures.4Macros [`versioned`] generate versioned variants of a struct.56Example:7```8# use struct_versioning::versioned;9#[versioned(version = 5, first_version = 2)]10struct Example {}1112// versioned macro will generate suffixed versions of example struct,13// starting from `Version{first_version or 1}` to `Version{version}` inclusive14let _ver2 = ExampleVersion2 {};15let _ver3 = ExampleVersion3 {};16let _ver4 = ExampleVersion4 {};17let _ver5 = ExampleVersion5 {};1819// last version will also be aliased with original struct name20let _orig: Example = ExampleVersion5 {};2122#[versioned(version = 2, upper)]23#[derive(PartialEq, Debug)]24struct Upper {25    #[version(..2)]26    removed: u32,27    #[version(2.., upper(10))]28    added: u32,2930    #[version(..2)]31    retyped: u32,32    #[version(2.., upper(retyped as u64))]33    retyped: u64,34}3536// #[version] attribute on field allows to specify, in which versions of structs this field should present37// versions here works as standard rust ranges, start is inclusive, end is exclusive38let _up1 = UpperVersion1 {removed: 1, retyped: 0};39let _up2 = UpperVersion2 {added: 1, retyped: 0};4041// and upper() allows to specify, which value should be assigned to this field in `From<OldVersion>` impl42assert_eq!(43    UpperVersion2::from(UpperVersion1 {removed: 0, retyped: 6}),44    UpperVersion2 {added: 10, retyped: 6},45);46```4748In this case, the upgrade is described in `on_runtime_upgrade` using the `translate_values` substrate feature4950```ignore51#[pallet::hooks]52impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {53    fn on_runtime_upgrade() -> Weight {54        if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {55            <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {56                Some(<ItemDataVersion2>::from(v))57            })58        }59        060    }61}62```