Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move MaxEncodedLen from Substrate #268

Merged
merged 16 commits into from
Jun 23, 2021
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ All notable changes to this crate are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this crate adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

## [2.2.0-rc.1] - 2021-06-22

### Added
- `MaxEncodedLen` trait for items that have a statically known maximum encoded size. ([#268](https://github.com/paritytech/parity-scale-codec/pull/268))

## [2.1.3] - 2021-06-14

### Changed
Expand Down
53 changes: 49 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "parity-scale-codec"
description = "SCALE - Simple Concatenating Aggregated Little Endians"
version = "2.1.3"
version = "2.2.0-rc.1"
authors = ["Parity Technologies <admin@parity.io>"]
license = "Apache-2.0"
repository = "https://github.com/paritytech/parity-scale-codec"
Expand All @@ -11,17 +11,19 @@ edition = "2018"
[dependencies]
arrayvec = { version = "0.7", default-features = false }
serde = { version = "1.0.102", optional = true }
parity-scale-codec-derive = { path = "derive", version = "2.1.3", default-features = false, optional = true }
parity-scale-codec-derive = { path = "derive", version = "2.2.0-rc.1", default-features = false, optional = true }
bitvec = { version = "0.20.1", default-features = false, features = ["alloc"], optional = true }
byte-slice-cast = { version = "1.0.0", default-features = false }
generic-array = { version = "0.14.4", optional = true }
arbitrary = { version = "1.0.1", features = ["derive"], optional = true }
impl-trait-for-tuples = "0.2.1"

[dev-dependencies]
criterion = "0.3.0"
serde_derive = { version = "1.0" }
parity-scale-codec-derive = { path = "derive", version = "2.1.3", default-features = false }
parity-scale-codec-derive = { path = "derive", version = "2.2.0-rc.1", default-features = false }
quickcheck = "1.0"
trybuild = "1.0.42"

[[bench]]
name = "benches"
Expand Down
4 changes: 2 additions & 2 deletions derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "parity-scale-codec-derive"
description = "Serialization and deserialization derive macro for Parity SCALE Codec"
version = "2.1.3"
version = "2.2.0-rc.1"
authors = ["Parity Technologies <admin@parity.io>"]
license = "Apache-2.0"
edition = "2018"
Expand All @@ -16,4 +16,4 @@ proc-macro2 = "1.0.6"
proc-macro-crate = "1.0.0"

[dev-dependencies]
parity-scale-codec = { path = "..", version = "2.0.1" }
parity-scale-codec = { path = "..", version = "2.2.0-rc.1" }
9 changes: 8 additions & 1 deletion derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2017-2018 Parity Technologies
// Copyright 2017-2021 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -32,6 +32,7 @@ use crate::utils::is_lint_attribute;

mod decode;
mod encode;
mod max_encoded_len;
mod utils;
mod trait_bounds;

Expand Down Expand Up @@ -333,3 +334,9 @@ pub fn compact_as_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStr

wrap_with_dummy_const(input, impl_block)
}

/// Derive `MaxEncodedLen`.
#[proc_macro_derive(MaxEncodedLen, attributes(max_encoded_len_mod))]
pub fn derive_max_encoded_len(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
max_encoded_len::derive_max_encoded_len(input)
}
131 changes: 131 additions & 0 deletions derive/src/max_encoded_len.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Copyright (C) 2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::utils::codec_crate_path;
use quote::{quote, quote_spanned};
use syn::{
Data, DeriveInput, Fields, GenericParam, Generics, TraitBound, Type, TypeParamBound,
parse_quote, spanned::Spanned,
};

/// impl for `#[derive(MaxEncodedLen)]`
pub fn derive_max_encoded_len(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input: DeriveInput = match syn::parse(input) {
Ok(input) => input,
Err(e) => return e.to_compile_error().into(),
};

let mel_trait = match max_encoded_len_trait(&input) {
Ok(mel_trait) => mel_trait,
Err(e) => return e.to_compile_error().into(),
};

let name = &input.ident;
let generics = add_trait_bounds(input.generics, mel_trait.clone());
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

let data_expr = data_length_expr(&input.data);

quote::quote!(
const _: () = {
impl #impl_generics #mel_trait for #name #ty_generics #where_clause {
fn max_encoded_len() -> usize {
#data_expr
}
}
};
)
.into()
}

fn max_encoded_len_trait(input: &DeriveInput) -> syn::Result<TraitBound> {
coriolinus marked this conversation as resolved.
Show resolved Hide resolved
let mel = codec_crate_path(&input.attrs)?;
Ok(parse_quote!(#mel::MaxEncodedLen))
}

// Add a bound `T: MaxEncodedLen` to every type parameter T.
fn add_trait_bounds(mut generics: Generics, mel_trait: TraitBound) -> Generics {
for param in &mut generics.params {
if let GenericParam::Type(ref mut type_param) = *param {
type_param.bounds.push(TypeParamBound::Trait(mel_trait.clone()));
}
}
generics
}

/// generate an expression to sum up the max encoded length from several fields
fn fields_length_expr(fields: &Fields) -> proc_macro2::TokenStream {
let type_iter: Box<dyn Iterator<Item = &Type>> = match fields {
Fields::Named(ref fields) => Box::new(fields.named.iter().map(|field| &field.ty)),
Fields::Unnamed(ref fields) => Box::new(fields.unnamed.iter().map(|field| &field.ty)),
Fields::Unit => Box::new(std::iter::empty()),
};
// expands to an expression like
//
// 0
// .saturating_add(<type of first field>::max_encoded_len())
// .saturating_add(<type of second field>::max_encoded_len())
//
// We match the span of each field to the span of the corresponding
// `max_encoded_len` call. This way, if one field's type doesn't implement
// `MaxEncodedLen`, the compiler's error message will underline which field
// caused the issue.
let expansion = type_iter.map(|ty| {
quote_spanned! {
ty.span() => .saturating_add(<#ty>::max_encoded_len())
}
});
quote! {
0_usize #( #expansion )*
}
}

// generate an expression to sum up the max encoded length of each field
fn data_length_expr(data: &Data) -> proc_macro2::TokenStream {
match *data {
Data::Struct(ref data) => fields_length_expr(&data.fields),
Data::Enum(ref data) => {
// We need an expression expanded for each variant like
//
// 0
// .max(<variant expression>)
// .max(<variant expression>)
// .saturating_add(1)
//
// The 1 derives from the discriminant; see
// https://github.com/paritytech/parity-scale-codec/
// blob/f0341dabb01aa9ff0548558abb6dcc5c31c669a1/derive/src/encode.rs#L211-L216
//
// Each variant expression's sum is computed the way an equivalent struct's would be.

let expansion = data.variants.iter().map(|variant| {
let variant_expression = fields_length_expr(&variant.fields);
quote! {
.max(#variant_expression)
}
});

quote! {
0_usize #( #expansion )* .saturating_add(1)
}
}
Data::Union(ref data) => {
// https://github.com/paritytech/parity-scale-codec/
// blob/f0341dabb01aa9ff0548558abb6dcc5c31c669a1/derive/src/encode.rs#L290-L293
syn::Error::new(data.union_token.span(), "Union types are not supported")
.to_compile_error()
}
}
}
Loading