From faac8ccd595f2c05eb29c79995dc02beeb19422d Mon Sep 17 00:00:00 2001 From: Alexander Kalankhodzhaev Date: Tue, 30 Apr 2024 20:07:56 +0700 Subject: [PATCH] Source code formatting (#583) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * style: apply formatting * ci: add cargo fmt check * Update derive/src/decode.rs --------- Co-authored-by: Bastian Köcher --- .github/workflows/ci.yml | 14 ++ benches/benches.rs | 160 +++++++------ derive/src/decode.rs | 77 +++--- derive/src/encode.rs | 10 +- derive/src/lib.rs | 20 +- derive/src/max_encoded_len.rs | 2 +- derive/src/trait_bounds.rs | 6 +- derive/src/utils.rs | 16 +- fuzzer/src/main.rs | 55 +++-- src/bit_vec.rs | 29 ++- src/codec.rs | 328 ++++++++++++++------------ src/compact.rs | 241 +++++++++++++------ src/const_encoded_len.rs | 24 +- src/decode_all.rs | 4 +- src/encode_append.rs | 56 +++-- src/encode_like.rs | 15 +- src/generic_array.rs | 6 +- src/joiner.rs | 5 +- src/keyedvec.rs | 3 +- src/lib.rs | 64 +++-- src/max_encoded_len.rs | 46 +++- tests/chain-error.rs | 21 +- tests/max_encoded_len.rs | 6 +- tests/mod.rs | 10 +- tests/single_field_struct_encoding.rs | 10 +- tests/skip.rs | 24 +- tests/type_inference.rs | 7 +- tests/variant_number.rs | 2 +- 28 files changed, 709 insertions(+), 552 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 573ce99f..da548f02 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,20 @@ jobs: run: echo "IMAGE=${{ env.IMAGE }}" >> $GITHUB_OUTPUT # Checks + fmt: + runs-on: ubuntu-latest + needs: [set-image] + container: ${{ needs.set-image.outputs.IMAGE }} + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Show Cargo version + run: cargo +nightly -vV + + - name: Cargo fmt + run: cargo +nightly fmt --all -- --check + clippy: runs-on: ubuntu-latest needs: [set-image] diff --git a/benches/benches.rs b/benches/benches.rs index 902be9e0..16d225fa 100644 --- a/benches/benches.rs +++ b/benches/benches.rs @@ -12,21 +12,23 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::{time::Duration, any::type_name, convert::{TryFrom, TryInto}}; +use std::{ + any::type_name, + convert::{TryFrom, TryInto}, + time::Duration, +}; #[cfg(feature = "bit-vec")] -use bitvec::{vec::BitVec, order::Lsb0}; -use criterion::{Criterion, black_box, Bencher, criterion_group, criterion_main}; +use bitvec::{order::Lsb0, vec::BitVec}; +use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion}; use parity_scale_codec::*; -use parity_scale_codec_derive::{Encode, Decode}; +use parity_scale_codec_derive::{Decode, Encode}; fn array_vec_write_u128(b: &mut Bencher) { b.iter(|| { for b in 0..black_box(1_000_000) { let a = 0xffff_ffff_ffff_ffff_ffff_u128; - Compact(a ^ b).using_encoded(|x| { - black_box(x).len() - }); + Compact(a ^ b).using_encoded(|x| black_box(x).len()); } }); } @@ -84,8 +86,7 @@ fn vec_append_with_decode_and_encode(b: &mut Bencher) { b.iter(|| { let mut encoded_events_vec = Vec::new(); for _ in 0..1000 { - let mut events = Vec::::decode(&mut &encoded_events_vec[..]) - .unwrap_or_default(); + let mut events = Vec::::decode(&mut &encoded_events_vec[..]).unwrap_or_default(); events.push(Event::ComplexEvent(data.to_vec(), 4, 5, 6, 9)); @@ -107,62 +108,69 @@ fn vec_append_with_encode_append(b: &mut Bencher) { encoded_events_vec = as EncodeAppend>::append_or_new( encoded_events_vec, &[Event::ComplexEvent(data.to_vec(), 4, 5, 6, 9)], - ).unwrap(); + ) + .unwrap(); } }); } -fn encode_decode_vec + Codec>(c: &mut Criterion) where T::Error: std::fmt::Debug { +fn encode_decode_vec + Codec>(c: &mut Criterion) +where + T::Error: std::fmt::Debug, +{ let mut g = c.benchmark_group("vec_encode"); for vec_size in [1, 2, 5, 32, 1024, 2048, 16384] { - g.bench_with_input(&format!("{}/{}", type_name::(), vec_size), &vec_size, |b, &vec_size| { - let vec: Vec = (0..=127u8) - .cycle() - .take(vec_size) - .map(|v| v.try_into().unwrap()) - .collect(); - - let vec = black_box(vec); - b.iter(|| vec.encode()) - }); + g.bench_with_input( + &format!("{}/{}", type_name::(), vec_size), + &vec_size, + |b, &vec_size| { + let vec: Vec = + (0..=127u8).cycle().take(vec_size).map(|v| v.try_into().unwrap()).collect(); + + let vec = black_box(vec); + b.iter(|| vec.encode()) + }, + ); } drop(g); let mut g = c.benchmark_group("vec_decode"); for vec_size in [1, 2, 5, 32, 1024, 2048, 16384] { - g.bench_with_input(&format!("{}/{}", type_name::(), vec_size), &vec_size, |b, &vec_size| { - let vec: Vec = (0..=127u8) - .cycle() - .take(vec_size) - .map(|v| v.try_into().unwrap()) - .collect(); - - let vec = vec.encode(); - - let vec = black_box(vec); - b.iter(|| { - let _: Vec = Decode::decode(&mut &vec[..]).unwrap(); - }) - }); + g.bench_with_input( + &format!("{}/{}", type_name::(), vec_size), + &vec_size, + |b, &vec_size| { + let vec: Vec = + (0..=127u8).cycle().take(vec_size).map(|v| v.try_into().unwrap()).collect(); + + let vec = vec.encode(); + + let vec = black_box(vec); + b.iter(|| { + let _: Vec = Decode::decode(&mut &vec[..]).unwrap(); + }) + }, + ); } drop(g); let mut g = c.benchmark_group("vec_decode_no_limit"); for vec_size in [16384, 131072] { - g.bench_with_input(&format!("vec_decode_no_limit_{}/{}", type_name::(), vec_size), &vec_size, |b, &vec_size| { - let vec: Vec = (0..=127u8) - .cycle() - .take(vec_size) - .map(|v| v.try_into().unwrap()) - .collect(); - - let vec = vec.encode(); - - let vec = black_box(vec); - b.iter(|| { - let _: Vec = Decode::decode(&mut NoLimitInput(&vec[..])).unwrap(); - }) - }); + g.bench_with_input( + &format!("vec_decode_no_limit_{}/{}", type_name::(), vec_size), + &vec_size, + |b, &vec_size| { + let vec: Vec = + (0..=127u8).cycle().take(vec_size).map(|v| v.try_into().unwrap()).collect(); + + let vec = vec.encode(); + + let vec = black_box(vec); + b.iter(|| { + let _: Vec = Decode::decode(&mut NoLimitInput(&vec[..])).unwrap(); + }) + }, + ); } } @@ -183,28 +191,38 @@ fn encode_decode_complex_type(c: &mut Criterion) { let mut g = c.benchmark_group("vec_encode_complex_type"); for vec_size in [1, 2, 5, 32, 1024, 2048, 16384] { let complex_types = complex_types.clone(); - g.bench_with_input(format!("vec_encode_complex_type/{}", vec_size), &vec_size, move |b, &vec_size| { - let vec: Vec = complex_types.clone().into_iter().cycle().take(vec_size).collect(); + g.bench_with_input( + format!("vec_encode_complex_type/{}", vec_size), + &vec_size, + move |b, &vec_size| { + let vec: Vec = + complex_types.clone().into_iter().cycle().take(vec_size).collect(); - let vec = black_box(vec); - b.iter(|| vec.encode()) - }); + let vec = black_box(vec); + b.iter(|| vec.encode()) + }, + ); } drop(g); let mut g = c.benchmark_group("vec_decode_complex_type"); for vec_size in [1, 2, 5, 32, 1024, 2048, 16384] { let complex_types = complex_types.clone(); - g.bench_with_input(format!("vec_decode_complex_type/{}", vec_size), &vec_size, move |b, &vec_size| { - let vec: Vec = complex_types.clone().into_iter().cycle().take(vec_size).collect(); + g.bench_with_input( + format!("vec_decode_complex_type/{}", vec_size), + &vec_size, + move |b, &vec_size| { + let vec: Vec = + complex_types.clone().into_iter().cycle().take(vec_size).collect(); - let vec = vec.encode(); + let vec = vec.encode(); - let vec = black_box(vec); - b.iter(|| { - let _: Vec = Decode::decode(&mut &vec[..]).unwrap(); - }) - }); + let vec = black_box(vec); + b.iter(|| { + let _: Vec = Decode::decode(&mut &vec[..]).unwrap(); + }) + }, + ); } } @@ -225,12 +243,8 @@ fn encode_decode_bitvec_u8(c: &mut Criterion) { let mut g = c.benchmark_group("bitvec_u8_encode"); for size in [1, 2, 5, 32, 1024] { g.bench_with_input(size.to_string(), &size, |b, &size| { - let vec: BitVec = [true, false] - .iter() - .cloned() - .cycle() - .take(size) - .collect(); + let vec: BitVec = + [true, false].iter().cloned().cycle().take(size).collect(); let vec = black_box(vec); b.iter(|| vec.encode()) @@ -243,12 +257,8 @@ fn encode_decode_bitvec_u8(c: &mut Criterion) { let mut g = c.benchmark_group("bitvec_u8_decode"); for size in [1, 2, 5, 32, 1024] { g.bench_with_input(size.to_string(), &size, |b, &size| { - let vec: BitVec = [true, false] - .iter() - .cloned() - .cycle() - .take(size) - .collect(); + let vec: BitVec = + [true, false].iter().cloned().cycle().take(size).collect(); let vec = vec.encode(); @@ -261,7 +271,7 @@ fn encode_decode_bitvec_u8(c: &mut Criterion) { } } -criterion_group!{ +criterion_group! { name = benches; config = Criterion::default().warm_up_time(Duration::from_millis(500)).without_plots(); targets = encode_decode_vec::, encode_decode_vec::, encode_decode_vec::, encode_decode_vec::, diff --git a/derive/src/decode.rs b/derive/src/decode.rs index 38d5565a..7f2d08b2 100644 --- a/derive/src/decode.rs +++ b/derive/src/decode.rs @@ -12,11 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -use proc_macro2::{Span, TokenStream, Ident}; -use syn::{ - spanned::Spanned, - Data, Fields, Field, Error, -}; +use proc_macro2::{Ident, Span, TokenStream}; +use syn::{spanned::Spanned, Data, Error, Field, Fields}; use crate::utils; @@ -49,13 +46,15 @@ pub fn quote( }, }, Data::Enum(ref data) => { - let data_variants = || data.variants.iter().filter(|variant| !utils::should_skip(&variant.attrs)); + let data_variants = + || data.variants.iter().filter(|variant| !utils::should_skip(&variant.attrs)); if data_variants().count() > 256 { return Error::new( data.variants.span(), - "Currently only enums with at most 256 variants are encodable." - ).to_compile_error(); + "Currently only enums with at most 256 variants are encodable.", + ) + .to_compile_error(); } let recurse = data_variants().enumerate().map(|(i, v)| { @@ -84,14 +83,10 @@ pub fn quote( } }); - let read_byte_err_msg = format!( - "Could not decode `{}`, failed to read variant byte", - type_name, - ); - let invalid_variant_err_msg = format!( - "Could not decode `{}`, variant doesn't exist", - type_name, - ); + let read_byte_err_msg = + format!("Could not decode `{type_name}`, failed to read variant byte"); + let invalid_variant_err_msg = + format!("Could not decode `{type_name}`, variant doesn't exist"); quote! { match #input.read_byte() .map_err(|e| e.chain(#read_byte_err_msg))? @@ -107,9 +102,9 @@ pub fn quote( }, } } - }, - Data::Union(_) => Error::new(Span::call_site(), "Union types are not supported.").to_compile_error(), + Data::Union(_) => + Error::new(Span::call_site(), "Union types are not supported.").to_compile_error(), } } @@ -117,7 +112,7 @@ pub fn quote_decode_into( data: &Data, crate_path: &syn::Path, input: &TokenStream, - attrs: &[syn::Attribute] + attrs: &[syn::Attribute], ) -> Option { // Make sure the type is `#[repr(transparent)]`, as this guarantees that // there can be only one field that is not zero-sized. @@ -126,16 +121,13 @@ pub fn quote_decode_into( } let fields = match data { - Data::Struct( - syn::DataStruct { - fields: Fields::Named(syn::FieldsNamed { named: fields, .. }) | - Fields::Unnamed(syn::FieldsUnnamed { unnamed: fields, .. }), - .. - } - ) => { - fields - }, - _ => return None + Data::Struct(syn::DataStruct { + fields: + Fields::Named(syn::FieldsNamed { named: fields, .. }) | + Fields::Unnamed(syn::FieldsUnnamed { unnamed: fields, .. }), + .. + }) => fields, + _ => return None, }; if fields.is_empty() { @@ -143,11 +135,11 @@ pub fn quote_decode_into( } // Bail if there are any extra attributes which could influence how the type is decoded. - if fields.iter().any(|field| + if fields.iter().any(|field| { utils::get_encoded_as_type(field).is_some() || - utils::is_compact(field) || - utils::should_skip(&field.attrs) - ) { + utils::is_compact(field) || + utils::should_skip(&field.attrs) + }) { return None; } @@ -183,10 +175,11 @@ pub fn quote_decode_into( if !non_zst_field_count.is_empty() { non_zst_field_count.push(quote! { + }); } - non_zst_field_count.push(quote! { if ::core::mem::size_of::<#field_type>() > 0 { 1 } else { 0 } }); + non_zst_field_count + .push(quote! { if ::core::mem::size_of::<#field_type>() > 0 { 1 } else { 0 } }); } - Some(quote!{ + Some(quote! { // Just a sanity check. These should always be true and will be optimized-out. ::core::assert_eq!(#(#sizes)*, ::core::mem::size_of::()); ::core::assert!(#(#non_zst_field_count)* <= 1); @@ -198,7 +191,12 @@ pub fn quote_decode_into( }) } -fn create_decode_expr(field: &Field, name: &str, input: &TokenStream, crate_path: &syn::Path) -> TokenStream { +fn create_decode_expr( + field: &Field, + name: &str, + input: &TokenStream, + crate_path: &syn::Path, +) -> TokenStream { let encoded_as = utils::get_encoded_as_type(field); let compact = utils::is_compact(field); let skip = utils::should_skip(&field.attrs); @@ -208,8 +206,9 @@ fn create_decode_expr(field: &Field, name: &str, input: &TokenStream, crate_path if encoded_as.is_some() as u8 + compact as u8 + skip as u8 > 1 { return Error::new( field.span(), - "`encoded_as`, `compact` and `skip` can only be used one at a time!" - ).to_compile_error(); + "`encoded_as`, `compact` and `skip` can only be used one at a time!", + ) + .to_compile_error(); } let err_msg = format!("Could not decode `{}`", name); @@ -282,7 +281,7 @@ fn create_instance( } }, Fields::Unnamed(ref fields) => { - let recurse = fields.unnamed.iter().enumerate().map(|(i, f) | { + let recurse = fields.unnamed.iter().enumerate().map(|(i, f)| { let field_name = format!("{}.{}", name_str, i); create_decode_expr(f, &field_name, input, crate_path) diff --git a/derive/src/encode.rs b/derive/src/encode.rs index e1ec680c..a29eec78 100644 --- a/derive/src/encode.rs +++ b/derive/src/encode.rs @@ -35,7 +35,7 @@ fn encode_single_field( Span::call_site(), "Internal error: cannot encode single field optimisation if skipped", ) - .to_compile_error() + .to_compile_error(); } if encoded_as.is_some() && compact { @@ -43,7 +43,7 @@ fn encode_single_field( Span::call_site(), "`encoded_as` and `compact` can not be used at the same time!", ) - .to_compile_error() + .to_compile_error(); } let final_field_variable = if compact { @@ -128,7 +128,7 @@ where f.span(), "`encoded_as`, `compact` and `skip` can only be used one at a time!", ) - .to_compile_error() + .to_compile_error(); } // Based on the seen attribute, we call a handler that generates code for a specific @@ -306,12 +306,12 @@ fn impl_encode(data: &Data, type_name: &Ident, crate_path: &syn::Path) -> TokenS data.variants.span(), "Currently only enums with at most 256 variants are encodable.", ) - .to_compile_error() + .to_compile_error(); } // If the enum has no variants, we don't need to encode anything. if data_variants().count() == 0 { - return quote!() + return quote!(); } let recurse = data_variants().enumerate().map(|(i, f)| { diff --git a/derive/src/lib.rs b/derive/src/lib.rs index 3c868e27..47c26dc4 100644 --- a/derive/src/lib.rs +++ b/derive/src/lib.rs @@ -129,7 +129,7 @@ pub fn encode_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream }; if let Err(e) = utils::check_attributes(&input) { - return e.to_compile_error().into() + return e.to_compile_error().into(); } let crate_path = match codec_crate_path(&input.attrs) { @@ -147,7 +147,7 @@ pub fn encode_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream utils::has_dumb_trait_bound(&input.attrs), &crate_path, ) { - return e.to_compile_error().into() + return e.to_compile_error().into(); } let name = &input.ident; @@ -179,7 +179,7 @@ pub fn decode_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream }; if let Err(e) = utils::check_attributes(&input) { - return e.to_compile_error().into() + return e.to_compile_error().into(); } let crate_path = match codec_crate_path(&input.attrs) { @@ -197,7 +197,7 @@ pub fn decode_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream utils::has_dumb_trait_bound(&input.attrs), &crate_path, ) { - return e.to_compile_error().into() + return e.to_compile_error().into(); } let name = &input.ident; @@ -208,12 +208,8 @@ pub fn decode_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream let decoding = decode::quote(&input.data, name, "e!(#ty_gen_turbofish), &input_, &crate_path); - let decode_into_body = decode::quote_decode_into( - &input.data, - &crate_path, - &input_, - &input.attrs - ); + let decode_into_body = + decode::quote_decode_into(&input.data, &crate_path, &input_, &input.attrs); let impl_decode_into = if let Some(body) = decode_into_body { quote! { @@ -266,7 +262,7 @@ pub fn compact_as_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStr }; if let Err(e) = utils::check_attributes(&input) { - return e.to_compile_error().into() + return e.to_compile_error().into(); } let crate_path = match codec_crate_path(&input.attrs) { @@ -284,7 +280,7 @@ pub fn compact_as_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStr utils::has_dumb_trait_bound(&input.attrs), &crate_path, ) { - return e.to_compile_error().into() + return e.to_compile_error().into(); } let name = &input.ident; diff --git a/derive/src/max_encoded_len.rs b/derive/src/max_encoded_len.rs index 763e8ceb..008ffd28 100644 --- a/derive/src/max_encoded_len.rs +++ b/derive/src/max_encoded_len.rs @@ -45,7 +45,7 @@ pub fn derive_max_encoded_len(input: proc_macro::TokenStream) -> proc_macro::Tok has_dumb_trait_bound(&input.attrs), &crate_path, ) { - return e.to_compile_error().into() + return e.to_compile_error().into(); } let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); diff --git a/derive/src/trait_bounds.rs b/derive/src/trait_bounds.rs index f803990d..209e1bf6 100644 --- a/derive/src/trait_bounds.rs +++ b/derive/src/trait_bounds.rs @@ -55,7 +55,7 @@ impl<'a, 'ast> Visit<'ast> for TypePathStartsWithIdent<'a> { if let Some(segment) = i.path.segments.first() { if &segment.ident == self.ident { self.result = true; - return + return; } } @@ -119,7 +119,7 @@ pub fn add( let skip_type_params = match custom_trait_bound { Some(CustomTraitBound::SpecifiedBounds { bounds, .. }) => { generics.make_where_clause().predicates.extend(bounds); - return Ok(()) + return Ok(()); }, Some(CustomTraitBound::SkipTypeParams { type_names, .. }) => type_names.into_iter().collect::>(), @@ -132,7 +132,7 @@ pub fn add( .map(|tp| tp.ident.clone()) .collect::>(); if ty_params.is_empty() { - return Ok(()) + return Ok(()); } let codec_types = diff --git a/derive/src/utils.rs b/derive/src/utils.rs index 5a2fa45d..091a45ee 100644 --- a/derive/src/utils.rs +++ b/derive/src/utils.rs @@ -20,7 +20,7 @@ use std::str::FromStr; use proc_macro2::TokenStream; -use quote::{ToTokens, quote}; +use quote::{quote, ToTokens}; use syn::{ parse::Parse, punctuated::Punctuated, spanned::Spanned, token, Attribute, Data, DeriveInput, Field, Fields, FieldsNamed, FieldsUnnamed, Lit, Meta, MetaNameValue, NestedMeta, Path, Variant, @@ -48,7 +48,7 @@ pub fn variant_index(v: &Variant, i: usize) -> TokenStream { let byte = v .base10_parse::() .expect("Internal error, index attribute must have been checked"); - return Some(byte) + return Some(byte); } } } @@ -75,7 +75,7 @@ pub fn get_encoded_as_type(field: &Field) -> Option { return Some( TokenStream::from_str(&s.value()) .expect("Internal error, encoded_as attribute must have been checked"), - ) + ); } } } @@ -89,7 +89,7 @@ pub fn is_compact(field: &Field) -> bool { find_meta_item(field.attrs.iter(), |meta| { if let NestedMeta::Meta(Meta::Path(ref path)) = meta { if path.is_ident("compact") { - return Some(()) + return Some(()); } } @@ -103,7 +103,7 @@ pub fn should_skip(attrs: &[Attribute]) -> bool { find_meta_item(attrs.iter(), |meta| { if let NestedMeta::Meta(Meta::Path(ref path)) = meta { if path.is_ident("skip") { - return Some(path.span()) + return Some(path.span()); } } @@ -117,7 +117,7 @@ pub fn has_dumb_trait_bound(attrs: &[Attribute]) -> bool { find_meta_item(attrs.iter(), |meta| { if let NestedMeta::Meta(Meta::Path(ref path)) = meta { if path.is_ident("dumb_trait_bound") { - return Some(()) + return Some(()); } } @@ -262,9 +262,7 @@ pub fn filter_skip_named(fields: &syn::FieldsNamed) -> impl Iterator impl Iterator { +pub fn filter_skip_unnamed(fields: &syn::FieldsUnnamed) -> impl Iterator { fields.unnamed.iter().enumerate().filter(|(_, f)| !should_skip(&f.attrs)) } diff --git a/fuzzer/src/main.rs b/fuzzer/src/main.rs index 8463d74e..fba804c9 100644 --- a/fuzzer/src/main.rs +++ b/fuzzer/src/main.rs @@ -1,28 +1,37 @@ -use std::collections::{BTreeMap, BTreeSet, VecDeque, LinkedList, BinaryHeap}; -use std::time::Duration; +use std::{ + collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}, + time::Duration, +}; -use bitvec::{vec::BitVec, order::Msb0, order::BitOrder, store::BitStore}; -use honggfuzz::fuzz; -use parity_scale_codec::{Encode, Decode, Compact}; -use honggfuzz::arbitrary::{Arbitrary, Unstructured, Result as ArbResult}; +use bitvec::{ + order::{BitOrder, Msb0}, + store::BitStore, + vec::BitVec, +}; +use honggfuzz::{ + arbitrary::{Arbitrary, Result as ArbResult, Unstructured}, + fuzz, +}; +use parity_scale_codec::{Compact, Decode, Encode}; #[derive(Encode, Decode, Clone, PartialEq, Debug, Arbitrary)] -pub struct MockStruct{ - vec_u: Vec +pub struct MockStruct { + vec_u: Vec, } /// Used for implementing the Arbitrary trait for a BitVec. #[derive(Encode, Decode, Clone, PartialEq, Debug)] pub struct BitVecWrapper(BitVec); -impl<'a, O: 'static + BitOrder, T: 'static + BitStore + Arbitrary<'a>> Arbitrary<'a> for BitVecWrapper { +impl<'a, O: 'static + BitOrder, T: 'static + BitStore + Arbitrary<'a>> Arbitrary<'a> + for BitVecWrapper +{ fn arbitrary(u: &mut Unstructured<'a>) -> ArbResult { let v = Vec::::arbitrary(u)?; Ok(BitVecWrapper(BitVec::::from_vec(v))) } } - /// Used for implementing the PartialEq trait for a BinaryHeap. #[derive(Encode, Decode, Debug, Clone, Arbitrary)] struct BinaryHeapWrapper(BinaryHeap); @@ -38,19 +47,16 @@ pub enum MockEnum { Empty, Unit(u32), UnitVec(Vec), - Complex { - data: Vec, - bitvec: BitVecWrapper, - string: String, - }, + Complex { data: Vec, bitvec: BitVecWrapper, string: String }, Mock(MockStruct), NestedVec(Vec>>>>>>>>), } /// `fuzz_flow` parameter can either be `round_trip` or `only_decode`. -/// `round_trip` will decode -> encode and compare the obtained encoded bytes with the original data. -/// `only_decode` will only decode, without trying to encode the decoded object. -/// `round_trip_sort` will decode -> encode and compare the obtained encoded SORTED bytes with the original SORTED data. +/// `round_trip` will decode -> encode and compare the obtained encoded bytes with the original +/// data. `only_decode` will only decode, without trying to encode the decoded object. +/// `round_trip_sort` will decode -> encode and compare the obtained encoded SORTED bytes with the +/// original SORTED data. macro_rules! fuzz_decoder { ( $fuzz_flow:ident; @@ -253,23 +259,22 @@ macro_rules! fuzz_encoder { }; } -fn fuzz_encode (data: T) { +fn fuzz_encode(data: T) { let original = data.clone(); let mut obj: &[u8] = &data.encode(); let decoded = ::decode(&mut obj); match decoded { - Ok(object) => { + Ok(object) => if object != original { println!("original object: {:?}", original); println!("decoded object: {:?}", object); panic!("Original object differs from decoded object") - } - } + }, Err(e) => { println!("original object: {:?}", original); println!("decoding error: {:?}", e); panic!("Failed to decode the encoded object"); - } + }, } } @@ -308,7 +313,9 @@ macro_rules! fuzz_encoding { fn main() { loop { - fuzz!(|data: &[u8]| { fuzz_decode(data); }); + fuzz!(|data: &[u8]| { + fuzz_decode(data); + }); fuzz_encoding!(); } } diff --git a/src/bit_vec.rs b/src/bit_vec.rs index 4f0f84b5..c4a00669 100644 --- a/src/bit_vec.rs +++ b/src/bit_vec.rs @@ -14,11 +14,11 @@ //! `BitVec` specific serialization. -use bitvec::{ - vec::BitVec, store::BitStore, order::BitOrder, slice::BitSlice, boxed::BitBox, view::BitView, -}; use crate::{ - EncodeLike, Encode, Decode, Input, Output, Error, Compact, codec::decode_vec_with_len, + codec::decode_vec_with_len, Compact, Decode, Encode, EncodeLike, Error, Input, Output, +}; +use bitvec::{ + boxed::BitBox, order::BitOrder, slice::BitSlice, store::BitStore, vec::BitVec, view::BitView, }; impl Encode for BitSlice { @@ -59,12 +59,13 @@ impl Decode for BitVec { } let vec = decode_vec_with_len(input, bitvec::mem::elts::(bits as usize))?; - let mut result = Self::try_from_vec(vec) - .map_err(|_| { - Error::from("UNEXPECTED ERROR: `bits` is less or equal to + let mut result = Self::try_from_vec(vec).map_err(|_| { + Error::from( + "UNEXPECTED ERROR: `bits` is less or equal to `ARCH32BIT_BITSLICE_MAX_BITS`; So BitVec must be able to handle the number of - segment needed for `bits` to be represented; qed") - })?; + segment needed for `bits` to be represented; qed", + ) + })?; assert!(bits as usize <= result.len()); result.truncate(bits as usize); @@ -90,8 +91,11 @@ impl Decode for BitBox { #[cfg(test)] mod tests { use super::*; - use bitvec::{bitvec, order::{Msb0, Lsb0}}; use crate::{codec::MAX_PREALLOCATION, CompactLen}; + use bitvec::{ + bitvec, + order::{Lsb0, Msb0}, + }; macro_rules! test_data { ($inner_type:ident) => ( @@ -202,7 +206,10 @@ mod tests { (bitvec![u8, Lsb0; 1, 1, 1, 1].encode(), (Compact(4u32), 0b00001111u8).encode()), (bitvec![u8, Lsb0; 1, 1, 1, 1, 1].encode(), (Compact(5u32), 0b00011111u8).encode()), (bitvec![u8, Lsb0; 1, 1, 1, 1, 1, 0].encode(), (Compact(6u32), 0b00011111u8).encode()), - (bitvec![u8, Lsb0; 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1].encode(), (Compact(12u32), 0b00011111u8, 0b00001011u8).encode()), + ( + bitvec![u8, Lsb0; 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1].encode(), + (Compact(12u32), 0b00011111u8, 0b00001011u8).encode(), + ), ]; for (idx, (actual, expected)) in cases.into_iter().enumerate() { diff --git a/src/codec.rs b/src/codec.rs index 08f4640b..6beebad2 100644 --- a/src/codec.rs +++ b/src/codec.rs @@ -14,49 +14,38 @@ //! Serialization. -use core::fmt; use core::{ convert::TryFrom, + fmt, iter::FromIterator, marker::PhantomData, mem, - mem::{ - MaybeUninit, + mem::MaybeUninit, + num::{ + NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroU128, NonZeroU16, + NonZeroU32, NonZeroU64, NonZeroU8, }, ops::{Deref, Range, RangeInclusive}, time::Duration, }; -use core::num::{ - NonZeroI8, - NonZeroI16, - NonZeroI32, - NonZeroI64, - NonZeroI128, - NonZeroU8, - NonZeroU16, - NonZeroU32, - NonZeroU64, - NonZeroU128, -}; use byte_slice_cast::{AsByteSlice, AsMutByteSlice, ToMutByteSlice}; #[cfg(target_has_atomic = "ptr")] use crate::alloc::sync::Arc; -use crate::alloc::{ - boxed::Box, - borrow::{Cow, ToOwned}, - collections::{ - BTreeMap, BTreeSet, VecDeque, LinkedList, BinaryHeap +use crate::{ + alloc::{ + borrow::{Cow, ToOwned}, + boxed::Box, + collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}, + rc::Rc, + string::String, + vec::Vec, }, - rc::Rc, - string::String, - vec::Vec, + compact::Compact, + encode_like::EncodeLike, + DecodeFinished, Error, }; -use crate::compact::Compact; -use crate::DecodeFinished; -use crate::encode_like::EncodeLike; -use crate::Error; pub(crate) const MAX_PREALLOCATION: usize = 4 * 1024; const A_BILLION: u32 = 1_000_000_000; @@ -101,7 +90,10 @@ pub trait Input { /// Decodes a `bytes::Bytes`. #[cfg(feature = "bytes")] #[doc(hidden)] - fn scale_internal_decode_bytes(&mut self) -> Result where Self: Sized { + fn scale_internal_decode_bytes(&mut self) -> Result + where + Self: Sized, + { Vec::::decode(self).map(bytes::Bytes::from) } } @@ -186,18 +178,20 @@ impl Output for Vec { #[cfg(feature = "std")] impl Output for W { fn write(&mut self, bytes: &[u8]) { - (self as &mut dyn std::io::Write).write_all(bytes).expect("Codec outputs are infallible"); + (self as &mut dyn std::io::Write) + .write_all(bytes) + .expect("Codec outputs are infallible"); } } - /// !INTERNAL USE ONLY! /// /// This enum provides type information to optimize encoding/decoding by doing fake specialization. #[doc(hidden)] #[non_exhaustive] pub enum TypeInfo { - /// Default value of [`Encode::TYPE_INFO`] to not require implementors to set this value in the trait. + /// Default value of [`Encode::TYPE_INFO`] to not require implementors to set this value in the + /// trait. Unknown, U8, I8, @@ -215,8 +209,8 @@ pub enum TypeInfo { /// Trait that allows zero-copy write of value-references to slices in LE format. /// -/// Implementations should override `using_encoded` for value types and `encode_to` and `size_hint` for allocating types. -/// Wrapper types should override all methods. +/// Implementations should override `using_encoded` for value types and `encode_to` and `size_hint` +/// for allocating types. Wrapper types should override all methods. pub trait Encode { // !INTERNAL USE ONLY! // This const helps SCALE to optimize the encoding/decoding by doing fake specialization. @@ -254,8 +248,9 @@ pub trait Encode { /// /// # Note /// - /// This works by using a special [`Output`] that only tracks the size. So, there are no allocations inside the - /// output. However, this can not prevent allocations that some types are doing inside their own encoding. + /// This works by using a special [`Output`] that only tracks the size. So, there are no + /// allocations inside the output. However, this can not prevent allocations that some types are + /// doing inside their own encoding. fn encoded_size(&self) -> usize { let mut size_tracker = SizeTracker { written: 0 }; self.encode_to(&mut size_tracker); @@ -304,8 +299,12 @@ pub trait Decode: Sized { /// If this function returns `Ok` then `dst` **must** be properly initialized. /// /// This is enforced by requiring the implementation to return a [`DecodeFinished`] - /// which can only be created by calling [`DecodeFinished::assert_decoding_finished`] which is `unsafe`. - fn decode_into(input: &mut I, dst: &mut MaybeUninit) -> Result { + /// which can only be created by calling [`DecodeFinished::assert_decoding_finished`] which is + /// `unsafe`. + fn decode_into( + input: &mut I, + dst: &mut MaybeUninit, + ) -> Result { let value = Self::decode(input)?; dst.write(value); @@ -388,7 +387,7 @@ impl EncodeLike<&str> for String {} impl EncodeLike for &str {} #[cfg(target_has_atomic = "ptr")] -mod atomic_ptr_targets { +mod atomic_ptr_targets { use super::*; impl WrapperTypeEncode for Arc {} impl EncodeLike for Arc {} @@ -412,7 +411,7 @@ mod feature_wrapper_bytes { #[cfg(feature = "bytes")] struct BytesCursor { bytes: bytes::Bytes, - position: usize + position: usize, } #[cfg(feature = "bytes")] @@ -423,7 +422,7 @@ impl Input for BytesCursor { fn read(&mut self, into: &mut [u8]) -> Result<(), Error> { if into.len() > self.bytes.len() - self.position { - return Err("Not enough data to fill buffer".into()) + return Err("Not enough data to fill buffer".into()); } into.copy_from_slice(&self.bytes[self.position..self.position + into.len()]); @@ -447,7 +446,10 @@ impl Input for BytesCursor { /// Decodes a given `T` from `Bytes`. #[cfg(feature = "bytes")] -pub fn decode_from_bytes(bytes: bytes::Bytes) -> Result where T: Decode { +pub fn decode_from_bytes(bytes: bytes::Bytes) -> Result +where + T: Decode, +{ // We could just use implement `Input` for `Bytes` and use `Bytes::split_to` // to move the cursor, however doing it this way allows us to prevent an // unnecessary allocation when the `T` which is being deserialized doesn't @@ -464,10 +466,7 @@ pub fn decode_from_bytes(bytes: bytes::Bytes) -> Result where T: De // However, if `T` doesn't contain any `Bytes` then this extra allocation is // technically unnecessary, and we can avoid it by tracking the position ourselves // and treating the underlying `Bytes` as a fancy `&[u8]`. - let mut input = BytesCursor { - bytes, - position: 0 - }; + let mut input = BytesCursor { bytes, position: 0 }; T::decode(&mut input) } @@ -478,7 +477,8 @@ impl Decode for bytes::Bytes { } } -impl Encode for X where +impl Encode for X +where T: Encode + ?Sized, X: WrapperTypeEncode, { @@ -510,7 +510,10 @@ pub trait WrapperTypeDecode: Sized { // This is a used to specialize `decode` for the wrapped type. #[doc(hidden)] #[inline] - fn decode_wrapped(input: &mut I) -> Result where Self::Wrapped: Decode { + fn decode_wrapped(input: &mut I) -> Result + where + Self::Wrapped: Decode, + { input.descend_ref()?; let result = Ok(Self::Wrapped::decode(input)?.into()); input.ascend_ref(); @@ -521,7 +524,10 @@ pub trait WrapperTypeDecode: Sized { impl WrapperTypeDecode for Box { type Wrapped = T; - fn decode_wrapped(input: &mut I) -> Result where Self::Wrapped: Decode { + fn decode_wrapped(input: &mut I) -> Result + where + Self::Wrapped: Decode, + { input.descend_ref()?; // Placement new is not yet stable, but we can just manually allocate a chunk of memory @@ -535,11 +541,8 @@ impl WrapperTypeDecode for Box { let ptr: *mut MaybeUninit = if layout.size() == 0 { core::ptr::NonNull::dangling().as_ptr() } else { - // SAFETY: Layout has a non-zero size so calling this is safe. - let ptr: *mut u8 = unsafe { - crate::alloc::alloc::alloc(layout) - }; + let ptr: *mut u8 = unsafe { crate::alloc::alloc::alloc(layout) }; if ptr.is_null() { crate::alloc::alloc::handle_alloc_error(layout); @@ -576,7 +579,10 @@ impl WrapperTypeDecode for Box { impl WrapperTypeDecode for Rc { type Wrapped = T; - fn decode_wrapped(input: &mut I) -> Result where Self::Wrapped: Decode { + fn decode_wrapped(input: &mut I) -> Result + where + Self::Wrapped: Decode, + { // TODO: This is inefficient; use `Rc::new_uninit` once that's stable. Box::::decode(input).map(|output| output.into()) } @@ -586,15 +592,19 @@ impl WrapperTypeDecode for Rc { impl WrapperTypeDecode for Arc { type Wrapped = T; - fn decode_wrapped(input: &mut I) -> Result where Self::Wrapped: Decode { + fn decode_wrapped(input: &mut I) -> Result + where + Self::Wrapped: Decode, + { // TODO: This is inefficient; use `Arc::new_uninit` once that's stable. Box::::decode(input).map(|output| output.into()) } } -impl Decode for X where +impl Decode for X +where T: Decode + Into, - X: WrapperTypeDecode, + X: WrapperTypeDecode, { #[inline] fn decode(input: &mut I) -> Result { @@ -604,8 +614,8 @@ impl Decode for X where /// A macro that matches on a [`TypeInfo`] and expands a given macro per variant. /// -/// The first parameter to the given macro will be the type of variant (e.g. `u8`, `u32`, etc.) and other parameters -/// given to this macro. +/// The first parameter to the given macro will be the type of variant (e.g. `u8`, `u32`, etc.) and +/// other parameters given to this macro. /// /// The last parameter is the code that should be executed for the `Unknown` type info. macro_rules! with_type_info { @@ -647,11 +657,11 @@ impl Encode for Result { Ok(ref t) => { dest.push_byte(0); t.encode_to(dest); - } + }, Err(ref e) => { dest.push_byte(1); e.encode_to(dest); - } + }, } } } @@ -662,19 +672,19 @@ where LikeT: Encode, E: EncodeLike, LikeE: Encode, -{} +{ +} impl Decode for Result { fn decode(input: &mut I) -> Result { - match input.read_byte() + match input + .read_byte() .map_err(|e| e.chain("Could not result variant byte for `Result`"))? { - 0 => Ok( - Ok(T::decode(input).map_err(|e| e.chain("Could not Decode `Result::Ok(T)`"))?) - ), - 1 => Ok( - Err(E::decode(input).map_err(|e| e.chain("Could not decode `Result::Error(E)`"))?) - ), + 0 => Ok(Ok(T::decode(input).map_err(|e| e.chain("Could not Decode `Result::Ok(T)`"))?)), + 1 => Ok(Err( + E::decode(input).map_err(|e| e.chain("Could not decode `Result::Error(E)`"))? + )), _ => Err("unexpected first byte decoding Result".into()), } } @@ -732,7 +742,7 @@ impl Encode for Option { Some(ref t) => { dest.push_byte(1); t.encode_to(dest); - } + }, None => dest.push_byte(0), } } @@ -740,13 +750,14 @@ impl Encode for Option { impl Decode for Option { fn decode(input: &mut I) -> Result { - match input.read_byte() + match input + .read_byte() .map_err(|e| e.chain("Could not decode variant byte for `Option`"))? { 0 => Ok(None), - 1 => Ok( - Some(T::decode(input).map_err(|e| e.chain("Could not decode `Option::Some(T)`"))?) - ), + 1 => Ok(Some( + T::decode(input).map_err(|e| e.chain("Could not decode `Option::Some(T)`"))?, + )), _ => Err("unexpected first byte decoding Option".into()), } } @@ -835,7 +846,8 @@ pub fn decode_vec_with_len( input: &mut I, items_len: usize, ) -> Result, Error> { - let input_capacity = input.remaining_len()? + let input_capacity = input + .remaining_len()? .unwrap_or(MAX_PREALLOCATION) .checked_div(mem::size_of::()) .unwrap_or(0); @@ -910,28 +922,26 @@ impl Decode for [T; N] { Self::decode_into(input, &mut array)?; // SAFETY: `decode_into` succeeded, so the array is initialized. - unsafe { - Ok(array.assume_init()) - } + unsafe { Ok(array.assume_init()) } } - fn decode_into(input: &mut I, dst: &mut MaybeUninit) -> Result { + fn decode_into( + input: &mut I, + dst: &mut MaybeUninit, + ) -> Result { let is_primitive = match ::TYPE_INFO { - | TypeInfo::U8 - | TypeInfo::I8 - => true, - | TypeInfo::U16 - | TypeInfo::I16 - | TypeInfo::U32 - | TypeInfo::I32 - | TypeInfo::U64 - | TypeInfo::I64 - | TypeInfo::U128 - | TypeInfo::I128 - | TypeInfo::F32 - | TypeInfo::F64 - => cfg!(target_endian = "little"), - TypeInfo::Unknown => false + | TypeInfo::U8 | TypeInfo::I8 => true, + | TypeInfo::U16 | + TypeInfo::I16 | + TypeInfo::U32 | + TypeInfo::I32 | + TypeInfo::U64 | + TypeInfo::I64 | + TypeInfo::U128 | + TypeInfo::I128 | + TypeInfo::F32 | + TypeInfo::F64 => cfg!(target_endian = "little"), + TypeInfo::Unknown => false, }; if is_primitive { @@ -952,9 +962,7 @@ impl Decode for [T; N] { } // SAFETY: We've zero-initialized everything so creating a slice here is safe. - let slice: &mut [u8] = unsafe { - core::slice::from_raw_parts_mut(ptr, bytesize) - }; + let slice: &mut [u8] = unsafe { core::slice::from_raw_parts_mut(ptr, bytesize) }; input.read(slice)?; @@ -975,7 +983,7 @@ impl Decode for [T; N] { /// dropped in case an error occurs or the underlying `decode` implementation panics. struct State<'a, T, const N: usize> { count: usize, - slice: &'a mut [MaybeUninit; N] + slice: &'a mut [MaybeUninit; N], } impl<'a, T, const N: usize> Drop for State<'a, T, N> { @@ -1002,10 +1010,7 @@ impl Decode for [T; N] { } } - let mut state = State { - count: 0, - slice - }; + let mut state = State { count: 0, slice }; while state.count < state.slice.len() { T::decode_into(input, &mut state.slice[state.count])?; @@ -1016,9 +1021,7 @@ impl Decode for [T; N] { mem::forget(state); // SAFETY: We've initialized the whole slice so calling this is safe. - unsafe { - Ok(DecodeFinished::assert_decoding_finished()) - } + unsafe { Ok(DecodeFinished::assert_decoding_finished()) } } fn skip(input: &mut I) -> Result<(), Error> { @@ -1028,7 +1031,7 @@ impl Decode for [T; N] { T::skip(input)?; } } else { - Self::decode(input)?; + Self::decode(input)?; } Ok(()) } @@ -1059,7 +1062,8 @@ impl Encode for str { } impl<'a, T: ToOwned + ?Sized> Decode for Cow<'a, T> - where ::Owned: Decode, +where + ::Owned: Decode, { fn decode(input: &mut I) -> Result { Ok(Cow::Owned(Decode::decode(input)?)) @@ -1085,7 +1089,10 @@ impl Decode for String { } /// Writes the compact encoding of `len` do `dest`. -pub(crate) fn compact_encode_len_to(dest: &mut W, len: usize) -> Result<(), Error> { +pub(crate) fn compact_encode_len_to( + dest: &mut W, + len: usize, +) -> Result<(), Error> { if len > u32::MAX as usize { return Err("Attempted to serialize a collection with too many elements.".into()); } @@ -1117,14 +1124,15 @@ where { debug_assert!(MAX_PREALLOCATION >= mem::size_of::(), "Invalid precondition"); - let byte_len = items_len.checked_mul(mem::size_of::()) + let byte_len = items_len + .checked_mul(mem::size_of::()) .ok_or("Item is too big and cannot be allocated")?; let input_len = input.remaining_len()?; // If there is input len and it cannot be pre-allocated then return directly. if input_len.map(|l| l < byte_len).unwrap_or(false) { - return Err("Not enough data to decode vector".into()) + return Err("Not enough data to decode vector".into()); } // In both these branches we're going to be creating and resizing a Vec, @@ -1179,9 +1187,8 @@ impl, U: Encode> EncodeLike> for &[T] {} impl Decode for Vec { fn decode(input: &mut I) -> Result { - >::decode(input).and_then(move |Compact(len)| { - decode_vec_with_len(input, len as usize) - }) + >::decode(input) + .and_then(move |Compact(len)| decode_vec_with_len(input, len as usize)) } } @@ -1257,9 +1264,8 @@ impl Encode for VecDeque { ( $ty:ty, $self:ident, $dest:ident ) => {{ if cfg!(target_endian = "little") || mem::size_of::() == 1 { let slices = $self.as_slices(); - let typed = unsafe { - core::mem::transmute::<(&[T], &[T]), (&[$ty], &[$ty])>(slices) - }; + let typed = + unsafe { core::mem::transmute::<(&[T], &[T]), (&[$ty], &[$ty])>(slices) }; $dest.write(<[$ty] as AsByteSlice<$ty>>::as_byte_slice(typed.0)); $dest.write(<[$ty] as AsByteSlice<$ty>>::as_byte_slice(typed.1)); @@ -1292,8 +1298,7 @@ impl Decode for VecDeque { impl EncodeLike for () {} impl Encode for () { - fn encode_to(&self, _dest: &mut W) { - } + fn encode_to(&self, _dest: &mut W) {} fn using_encoded R>(&self, f: F) -> R { f(&[]) @@ -1419,8 +1424,24 @@ mod inner_tuple_impl { use super::*; tuple_impl!( - (A0, A1), (B0, B1), (C0, C1), (D0, D1), (E0, E1), (F0, F1), (G0, G1), (H0, H1), (I0, I1), - (J0, J1), (K0, K1), (L0, L1), (M0, M1), (N0, N1), (O0, O1), (P0, P1), (Q0, Q1), (R0, R1), + (A0, A1), + (B0, B1), + (C0, C1), + (D0, D1), + (E0, E1), + (F0, F1), + (G0, G1), + (H0, H1), + (I0, I1), + (J0, J1), + (K0, K1), + (L0, L1), + (M0, M1), + (N0, N1), + (O0, O1), + (P0, P1), + (Q0, Q1), + (R0, R1), ); } @@ -1505,7 +1526,7 @@ impl Decode for bool { match byte { 0 => Ok(false), 1 => Ok(true), - _ => Err("Invalid boolean representation".into()) + _ => Err("Invalid boolean representation".into()), } } @@ -1542,7 +1563,7 @@ impl EncodeLike for Duration {} impl Encode for Range where - T: Encode + T: Encode, { fn size_hint(&self) -> usize { 2 * mem::size_of::() @@ -1555,18 +1576,18 @@ where impl Decode for Range where - T: Decode + T: Decode, { fn decode(input: &mut I) -> Result { - let (start, end) = <(T, T)>::decode(input) - .map_err(|e| e.chain("Could not decode `Range`"))?; + let (start, end) = + <(T, T)>::decode(input).map_err(|e| e.chain("Could not decode `Range`"))?; Ok(Range { start, end }) } } impl Encode for RangeInclusive where - T: Encode + T: Encode, { fn size_hint(&self) -> usize { 2 * mem::size_of::() @@ -1579,16 +1600,15 @@ where impl Decode for RangeInclusive where - T: Decode + T: Decode, { fn decode(input: &mut I) -> Result { - let (start, end) = <(T, T)>::decode(input) - .map_err(|e| e.chain("Could not decode `RangeInclusive`"))?; + let (start, end) = + <(T, T)>::decode(input).map_err(|e| e.chain("Could not decode `RangeInclusive`"))?; Ok(RangeInclusive::new(start, end)) } } - #[cfg(test)] mod tests { use super::*; @@ -1597,9 +1617,7 @@ mod tests { #[test] fn vec_is_sliceable() { let v = b"Hello world".to_vec(); - v.using_encoded(|ref slice| - assert_eq!(slice, &b"\x2cHello world") - ); + v.using_encoded(|ref slice| assert_eq!(slice, &b"\x2cHello world")); } #[test] @@ -1633,7 +1651,11 @@ mod tests { } fn hexify(bytes: &[u8]) -> String { - bytes.iter().map(|ref b| format!("{:02x}", b)).collect::>().join(" ") + bytes + .iter() + .map(|ref b| format!("{:02x}", b)) + .collect::>() + .join(" ") } #[test] @@ -1684,10 +1706,7 @@ mod tests { let encoded_vec = input.to_vec().encode(); assert_eq!(encoded, encoded_vec); - assert_eq!( - &b"hello"[..], - bytes::Bytes::decode(&mut &encoded[..]).unwrap(), - ); + assert_eq!(&b"hello"[..], bytes::Bytes::decode(&mut &encoded[..]).unwrap(),); } #[cfg(feature = "bytes")] @@ -1754,13 +1773,16 @@ mod tests { "Hamlet".to_owned(), "Война и мир".to_owned(), "三国演义".to_owned(), - "أَلْف لَيْلَة وَلَيْلَة‎".to_owned() + "أَلْف لَيْلَة وَلَيْلَة‎".to_owned(), ]; let encoded = value.encode(); - assert_eq!(hexify(&encoded), "10 18 48 61 6d 6c 65 74 50 d0 92 d0 be d0 b9 d0 bd d0 b0 20 d0 \ + assert_eq!( + hexify(&encoded), + "10 18 48 61 6d 6c 65 74 50 d0 92 d0 be d0 b9 d0 bd d0 b0 20 d0 \ b8 20 d0 bc d0 b8 d1 80 30 e4 b8 89 e5 9b bd e6 bc 94 e4 b9 89 bc d8 a3 d9 8e d9 84 d9 92 \ d9 81 20 d9 84 d9 8e d9 8a d9 92 d9 84 d9 8e d8 a9 20 d9 88 d9 8e d9 84 d9 8e d9 8a d9 92 \ - d9 84 d9 8e d8 a9 e2 80 8e"); + d9 84 d9 8e d8 a9 e2 80 8e" + ); assert_eq!(>::decode(&mut &encoded[..]).unwrap(), value); } @@ -1768,12 +1790,16 @@ mod tests { struct MyWrapper(Compact); impl Deref for MyWrapper { type Target = Compact; - fn deref(&self) -> &Self::Target { &self.0 } + fn deref(&self) -> &Self::Target { + &self.0 + } } impl WrapperTypeEncode for MyWrapper {} impl From> for MyWrapper { - fn from(c: Compact) -> Self { MyWrapper(c) } + fn from(c: Compact) -> Self { + MyWrapper(c) + } } impl WrapperTypeDecode for MyWrapper { type Wrapped = Compact; @@ -1810,18 +1836,15 @@ mod tests { let t1: BTreeSet = FromIterator::from_iter((0..10).flat_map(|i| 0..i)); let t2: LinkedList = FromIterator::from_iter((0..10).flat_map(|i| 0..i)); let t3: BinaryHeap = FromIterator::from_iter((0..10).flat_map(|i| 0..i)); - let t4: BTreeMap = FromIterator::from_iter( - (0..10) - .flat_map(|i| 0..i) - .map(|i| (i as u16, i + 10)) - ); + let t4: BTreeMap = + FromIterator::from_iter((0..10).flat_map(|i| 0..i).map(|i| (i as u16, i + 10))); let t5: BTreeSet> = FromIterator::from_iter((0..10).map(|i| Vec::from_iter(0..i))); - let t6: LinkedList> = FromIterator::from_iter((0..10).map(|i| Vec::from_iter(0..i))); - let t7: BinaryHeap> = FromIterator::from_iter((0..10).map(|i| Vec::from_iter(0..i))); + let t6: LinkedList> = + FromIterator::from_iter((0..10).map(|i| Vec::from_iter(0..i))); + let t7: BinaryHeap> = + FromIterator::from_iter((0..10).map(|i| Vec::from_iter(0..i))); let t8: BTreeMap, u32> = FromIterator::from_iter( - (0..10) - .map(|i| Vec::from_iter(0..i)) - .map(|i| (i.clone(), i.len() as u32)) + (0..10).map(|i| Vec::from_iter(0..i)).map(|i| (i.clone(), i.len() as u32)), ); assert_eq!(Decode::decode(&mut &t1.encode()[..]), Ok(t1)); @@ -2013,7 +2036,6 @@ mod tests { <[u32; 0]>::decode(&mut &encoded[..]).unwrap(); } - macro_rules! test_array_encode_and_decode { ( $( $name:ty ),* $(,)? ) => { $( diff --git a/src/compact.rs b/src/compact.rs index 91e632e5..9299db6b 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -16,12 +16,14 @@ use arrayvec::ArrayVec; -use crate::alloc::vec::Vec; -use crate::codec::{Encode, Decode, Input, Output, EncodeAsRef}; -use crate::encode_like::EncodeLike; -use crate::Error; #[cfg(feature = "max-encoded-len")] use crate::MaxEncodedLen; +use crate::{ + alloc::vec::Vec, + codec::{Decode, Encode, EncodeAsRef, Input, Output}, + encode_like::EncodeLike, + Error, +}; #[cfg(feature = "fuzz")] use arbitrary::Arbitrary; @@ -66,8 +68,8 @@ impl<'a, T: 'a + Input> Input for PrefixInput<'a, T> { Some(v) if !buffer.is_empty() => { buffer[0] = v; self.input.read(&mut buffer[1..]) - } - _ => self.input.read(buffer) + }, + _ => self.input.read(buffer), } } } @@ -84,11 +86,15 @@ pub trait CompactLen { pub struct Compact(pub T); impl From for Compact { - fn from(x: T) -> Compact { Compact(x) } + fn from(x: T) -> Compact { + Compact(x) + } } impl<'a, T: Copy> From<&'a T> for Compact { - fn from(x: &'a T) -> Compact { Compact(*x) } + fn from(x: &'a T) -> Compact { + Compact(*x) + } } /// Allow foreign structs to be wrap in Compact @@ -103,10 +109,7 @@ pub trait CompactAs: From> { fn decode_from(_: Self::As) -> Result; } -impl EncodeLike for Compact -where - for<'a> CompactRef<'a, T>: Encode, -{} +impl EncodeLike for Compact where for<'a> CompactRef<'a, T>: Encode {} impl Encode for Compact where @@ -133,7 +136,8 @@ impl<'a, T> EncodeLike for CompactRef<'a, T> where T: CompactAs, for<'b> CompactRef<'b, T::As>: Encode, -{} +{ +} impl<'a, T> Encode for CompactRef<'a, T> where @@ -185,25 +189,42 @@ impl_from_compact! { (), u8, u16, u32, u64, u128 } pub struct CompactRef<'a, T>(pub &'a T); impl<'a, T> From<&'a T> for CompactRef<'a, T> { - fn from(x: &'a T) -> Self { CompactRef(x) } + fn from(x: &'a T) -> Self { + CompactRef(x) + } } -impl core::fmt::Debug for Compact where T: core::fmt::Debug { +impl core::fmt::Debug for Compact +where + T: core::fmt::Debug, +{ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.0.fmt(f) } } #[cfg(feature = "serde")] -impl serde::Serialize for Compact where T: serde::Serialize { - fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { +impl serde::Serialize for Compact +where + T: serde::Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { T::serialize(&self.0, serializer) } } #[cfg(feature = "serde")] -impl<'de, T> serde::Deserialize<'de> for Compact where T: serde::Deserialize<'de> { - fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { +impl<'de, T> serde::Deserialize<'de> for Compact +where + T: serde::Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { T::deserialize(deserializer).map(Compact) } } @@ -228,26 +249,34 @@ pub trait HasCompact: Sized { type Type: for<'a> EncodeAsRef<'a, Self> + Decode + From + Into + MaybeMaxEncodedLen; } -impl<'a, T: 'a> EncodeAsRef<'a, T> for Compact where CompactRef<'a, T>: Encode + From<&'a T> { +impl<'a, T: 'a> EncodeAsRef<'a, T> for Compact +where + CompactRef<'a, T>: Encode + From<&'a T>, +{ type RefType = CompactRef<'a, T>; } #[cfg(feature = "max-encoded-len")] -impl MaxEncodedLen for Compact where T: CompactAs, Compact: MaxEncodedLen, Compact: Encode { +impl MaxEncodedLen for Compact +where + T: CompactAs, + Compact: MaxEncodedLen, + Compact: Encode, +{ fn max_encoded_len() -> usize { Compact::::max_encoded_len() } } -impl HasCompact for T where - Compact: for<'a> EncodeAsRef<'a, T> + Decode + From + Into + MaybeMaxEncodedLen +impl HasCompact for T +where + Compact: for<'a> EncodeAsRef<'a, T> + Decode + From + Into + MaybeMaxEncodedLen, { type Type = Compact; } impl<'a> Encode for CompactRef<'a, ()> { - fn encode_to(&self, _dest: &mut W) { - } + fn encode_to(&self, _dest: &mut W) {} fn using_encoded R>(&self, f: F) -> R { f(&[]) @@ -325,11 +354,12 @@ impl<'a> Encode for CompactRef<'a, u32> { match self.0 { 0..=0b0011_1111 => dest.push_byte((*self.0 as u8) << 2), 0..=0b0011_1111_1111_1111 => (((*self.0 as u16) << 2) | 0b01).encode_to(dest), - 0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => ((*self.0 << 2) | 0b10).encode_to(dest), + 0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => + ((*self.0 << 2) | 0b10).encode_to(dest), _ => { dest.push_byte(0b11); self.0.encode_to(dest); - } + }, } } @@ -360,10 +390,14 @@ impl<'a> Encode for CompactRef<'a, u64> { match self.0 { 0..=0b0011_1111 => dest.push_byte((*self.0 as u8) << 2), 0..=0b0011_1111_1111_1111 => (((*self.0 as u16) << 2) | 0b01).encode_to(dest), - 0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => (((*self.0 as u32) << 2) | 0b10).encode_to(dest), + 0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => + (((*self.0 as u32) << 2) | 0b10).encode_to(dest), _ => { let bytes_needed = 8 - self.0.leading_zeros() / 8; - assert!(bytes_needed >= 4, "Previous match arm matches anyting less than 2^30; qed"); + assert!( + bytes_needed >= 4, + "Previous match arm matches anyting less than 2^30; qed" + ); dest.push_byte(0b11 + ((bytes_needed - 4) << 2) as u8); let mut v = *self.0; for _ in 0..bytes_needed { @@ -371,7 +405,7 @@ impl<'a> Encode for CompactRef<'a, u64> { v >>= 8; } assert_eq!(v, 0, "shifted sufficient bits right to lead only leading zeros; qed") - } + }, } } @@ -388,9 +422,7 @@ impl CompactLen for Compact { 0..=0b0011_1111 => 1, 0..=0b0011_1111_1111_1111 => 2, 0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => 4, - _ => { - (8 - val.leading_zeros() / 8) as usize + 1 - }, + _ => (8 - val.leading_zeros() / 8) as usize + 1, } } } @@ -404,10 +436,14 @@ impl<'a> Encode for CompactRef<'a, u128> { match self.0 { 0..=0b0011_1111 => dest.push_byte((*self.0 as u8) << 2), 0..=0b0011_1111_1111_1111 => (((*self.0 as u16) << 2) | 0b01).encode_to(dest), - 0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => (((*self.0 as u32) << 2) | 0b10).encode_to(dest), + 0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => + (((*self.0 as u32) << 2) | 0b10).encode_to(dest), _ => { let bytes_needed = 16 - self.0.leading_zeros() / 8; - assert!(bytes_needed >= 4, "Previous match arm matches anyting less than 2^30; qed"); + assert!( + bytes_needed >= 4, + "Previous match arm matches anyting less than 2^30; qed" + ); dest.push_byte(0b11 + ((bytes_needed - 4) << 2) as u8); let mut v = *self.0; for _ in 0..bytes_needed { @@ -415,7 +451,7 @@ impl<'a> Encode for CompactRef<'a, u128> { v >>= 8; } assert_eq!(v, 0, "shifted sufficient bits right to lead only leading zeros; qed") - } + }, } } @@ -432,9 +468,7 @@ impl CompactLen for Compact { 0..=0b0011_1111 => 1, 0..=0b0011_1111_1111_1111 => 2, 0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => 4, - _ => { - (16 - val.leading_zeros() / 8) as usize + 1 - }, + _ => (16 - val.leading_zeros() / 8) as usize + 1, } } } @@ -457,7 +491,7 @@ impl Decode for Compact { Ok(Compact(match prefix % 4 { 0 => prefix >> 2, 1 => { - let x = u16::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2; + let x = u16::decode(&mut PrefixInput { prefix: Some(prefix), input })? >> 2; if x > 0b0011_1111 && x <= 255 { x as u8 } else { @@ -475,7 +509,7 @@ impl Decode for Compact { Ok(Compact(match prefix % 4 { 0 => u16::from(prefix) >> 2, 1 => { - let x = u16::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2; + let x = u16::decode(&mut PrefixInput { prefix: Some(prefix), input })? >> 2; if x > 0b0011_1111 && x <= 0b0011_1111_1111_1111 { x } else { @@ -483,7 +517,7 @@ impl Decode for Compact { } }, 2 => { - let x = u32::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2; + let x = u32::decode(&mut PrefixInput { prefix: Some(prefix), input })? >> 2; if x > 0b0011_1111_1111_1111 && x < 65536 { x as u16 } else { @@ -501,7 +535,7 @@ impl Decode for Compact { Ok(Compact(match prefix % 4 { 0 => u32::from(prefix) >> 2, 1 => { - let x = u16::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2; + let x = u16::decode(&mut PrefixInput { prefix: Some(prefix), input })? >> 2; if x > 0b0011_1111 && x <= 0b0011_1111_1111_1111 { u32::from(x) } else { @@ -509,7 +543,7 @@ impl Decode for Compact { } }, 2 => { - let x = u32::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2; + let x = u32::decode(&mut PrefixInput { prefix: Some(prefix), input })? >> 2; if x > 0b0011_1111_1111_1111 && x <= u32::MAX >> 2 { x } else { @@ -541,7 +575,7 @@ impl Decode for Compact { Ok(Compact(match prefix % 4 { 0 => u64::from(prefix) >> 2, 1 => { - let x = u16::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2; + let x = u16::decode(&mut PrefixInput { prefix: Some(prefix), input })? >> 2; if x > 0b0011_1111 && x <= 0b0011_1111_1111_1111 { u64::from(x) } else { @@ -549,7 +583,7 @@ impl Decode for Compact { } }, 2 => { - let x = u32::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2; + let x = u32::decode(&mut PrefixInput { prefix: Some(prefix), input })? >> 2; if x > 0b0011_1111_1111_1111 && x <= u32::MAX >> 2 { u64::from(x) } else { @@ -597,7 +631,7 @@ impl Decode for Compact { Ok(Compact(match prefix % 4 { 0 => u128::from(prefix) >> 2, 1 => { - let x = u16::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2; + let x = u16::decode(&mut PrefixInput { prefix: Some(prefix), input })? >> 2; if x > 0b0011_1111 && x <= 0b0011_1111_1111_1111 { u128::from(x) } else { @@ -605,7 +639,7 @@ impl Decode for Compact { } }, 2 => { - let x = u32::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2; + let x = u32::decode(&mut PrefixInput { prefix: Some(prefix), input })? >> 2; if x > 0b0011_1111_1111_1111 && x <= u32::MAX >> 2 { u128::from(x) } else { @@ -662,12 +696,30 @@ mod tests { #[test] fn compact_128_encoding_works() { let tests = [ - (0u128, 1usize), (63, 1), (64, 2), (16383, 2), - (16384, 4), (1073741823, 4), - (1073741824, 5), ((1 << 32) - 1, 5), - (1 << 32, 6), (1 << 40, 7), (1 << 48, 8), ((1 << 56) - 1, 8), (1 << 56, 9), ((1 << 64) - 1, 9), - (1 << 64, 10), (1 << 72, 11), (1 << 80, 12), (1 << 88, 13), (1 << 96, 14), (1 << 104, 15), - (1 << 112, 16), ((1 << 120) - 1, 16), (1 << 120, 17), (u128::MAX, 17) + (0u128, 1usize), + (63, 1), + (64, 2), + (16383, 2), + (16384, 4), + (1073741823, 4), + (1073741824, 5), + ((1 << 32) - 1, 5), + (1 << 32, 6), + (1 << 40, 7), + (1 << 48, 8), + ((1 << 56) - 1, 8), + (1 << 56, 9), + ((1 << 64) - 1, 9), + (1 << 64, 10), + (1 << 72, 11), + (1 << 80, 12), + (1 << 88, 13), + (1 << 96, 14), + (1 << 104, 15), + (1 << 112, 16), + ((1 << 120) - 1, 16), + (1 << 120, 17), + (u128::MAX, 17), ]; for &(n, l) in &tests { let encoded = Compact(n as u128).encode(); @@ -680,10 +732,20 @@ mod tests { #[test] fn compact_64_encoding_works() { let tests = [ - (0u64, 1usize), (63, 1), (64, 2), (16383, 2), - (16384, 4), (1073741823, 4), - (1073741824, 5), ((1 << 32) - 1, 5), - (1 << 32, 6), (1 << 40, 7), (1 << 48, 8), ((1 << 56) - 1, 8), (1 << 56, 9), (u64::MAX, 9) + (0u64, 1usize), + (63, 1), + (64, 2), + (16383, 2), + (16384, 4), + (1073741823, 4), + (1073741824, 5), + ((1 << 32) - 1, 5), + (1 << 32, 6), + (1 << 40, 7), + (1 << 48, 8), + ((1 << 56) - 1, 8), + (1 << 56, 9), + (u64::MAX, 9), ]; for &(n, l) in &tests { let encoded = Compact(n as u64).encode(); @@ -695,7 +757,16 @@ mod tests { #[test] fn compact_32_encoding_works() { - let tests = [(0u32, 1usize), (63, 1), (64, 2), (16383, 2), (16384, 4), (1073741823, 4), (1073741824, 5), (u32::MAX, 5)]; + let tests = [ + (0u32, 1usize), + (63, 1), + (64, 2), + (16383, 2), + (16384, 4), + (1073741823, 4), + (1073741824, 5), + (u32::MAX, 5), + ]; for &(n, l) in &tests { let encoded = Compact(n as u32).encode(); assert_eq!(encoded.len(), l); @@ -729,7 +800,11 @@ mod tests { } fn hexify(bytes: &[u8]) -> String { - bytes.iter().map(|ref b| format!("{:02x}", b)).collect::>().join(" ") + bytes + .iter() + .map(|ref b| format!("{:02x}", b)) + .collect::>() + .join(" ") } #[test] @@ -748,7 +823,7 @@ mod tests { (1 << 48, "0f 00 00 00 00 00 00 01"), ((1 << 56) - 1, "0f ff ff ff ff ff ff ff"), (1 << 56, "13 00 00 00 00 00 00 00 01"), - (u64::MAX, "13 ff ff ff ff ff ff ff ff") + (u64::MAX, "13 ff ff ff ff ff ff ff ff"), ]; for &(n, s) in &tests { // Verify u64 encoding @@ -806,7 +881,7 @@ mod tests { let encoded = compact.encode(); assert_eq!(encoded.len(), l); assert_eq!(Compact::compact_len(&n), l); - let decoded = >::decode(&mut & encoded[..]).unwrap(); + let decoded = >::decode(&mut &encoded[..]).unwrap(); let wrapper: Wrapper = decoded.into(); assert_eq!(wrapper, Wrapper(n)); } @@ -899,7 +974,9 @@ mod tests { (u64::MAX << 8) - 1, u64::MAX << 16, (u64::MAX << 16) - 1, - ].iter() { + ] + .iter() + { let e = Compact::::encode(&Compact(*a)); let d = Compact::::decode(&mut &e[..]).unwrap().0; assert_eq!(*a, d); @@ -908,12 +985,7 @@ mod tests { #[test] fn compact_u128_test() { - for a in [ - u64::MAX as u128, - (u64::MAX - 10) as u128, - u128::MAX, - u128::MAX - 10, - ].iter() { + for a in [u64::MAX as u128, (u64::MAX - 10) as u128, u128::MAX, u128::MAX - 10].iter() { let e = Compact::::encode(&Compact(*a)); let d = Compact::::decode(&mut &e[..]).unwrap().0; assert_eq!(*a, d); @@ -923,16 +995,33 @@ mod tests { #[test] fn should_avoid_overlapping_definition() { check_bound!( - 0b01, u8, u16, [ (u8, U8_OUT_OF_RANGE), (u16, U16_OUT_OF_RANGE), - (u32, U32_OUT_OF_RANGE), (u64, U64_OUT_OF_RANGE), (u128, U128_OUT_OF_RANGE)] + 0b01, + u8, + u16, + [ + (u8, U8_OUT_OF_RANGE), + (u16, U16_OUT_OF_RANGE), + (u32, U32_OUT_OF_RANGE), + (u64, U64_OUT_OF_RANGE), + (u128, U128_OUT_OF_RANGE) + ] ); check_bound!( - 0b10, u16, u32, [ (u16, U16_OUT_OF_RANGE), - (u32, U32_OUT_OF_RANGE), (u64, U64_OUT_OF_RANGE), (u128, U128_OUT_OF_RANGE)] - ); - check_bound_u32!( - [(u32, U32_OUT_OF_RANGE), (u64, U64_OUT_OF_RANGE), (u128, U128_OUT_OF_RANGE)] + 0b10, + u16, + u32, + [ + (u16, U16_OUT_OF_RANGE), + (u32, U32_OUT_OF_RANGE), + (u64, U64_OUT_OF_RANGE), + (u128, U128_OUT_OF_RANGE) + ] ); + check_bound_u32!([ + (u32, U32_OUT_OF_RANGE), + (u64, U64_OUT_OF_RANGE), + (u128, U128_OUT_OF_RANGE) + ]); for i in 5..=8 { check_bound_high!(i, [(u64, U64_OUT_OF_RANGE), (u128, U128_OUT_OF_RANGE)]); } diff --git a/src/const_encoded_len.rs b/src/const_encoded_len.rs index 6a0ee33c..8b5625f5 100644 --- a/src/const_encoded_len.rs +++ b/src/const_encoded_len.rs @@ -13,16 +13,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Contains the [`ConstEncodedLen`] trait. +//! Contains the [`ConstEncodedLen`] trait. -use crate::MaxEncodedLen; +use crate::{alloc::boxed::Box, MaxEncodedLen}; use core::{ marker::PhantomData, num::*, ops::{Range, RangeInclusive}, time::Duration, }; -use crate::alloc::boxed::Box; use impl_trait_for_tuples::impl_for_tuples; /// Types that have a constant encoded length. This implies [`MaxEncodedLen`]. @@ -31,9 +30,9 @@ use impl_trait_for_tuples::impl_for_tuples; pub trait ConstEncodedLen: MaxEncodedLen {} #[impl_for_tuples(18)] -impl ConstEncodedLen for Tuple { } +impl ConstEncodedLen for Tuple {} -impl ConstEncodedLen for [T; N] { } +impl ConstEncodedLen for [T; N] {} /// Mark `T` or `T` as `CEL`. macro_rules! mark_cel { @@ -50,7 +49,18 @@ macro_rules! mark_cel { } mark_cel!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, bool); -mark_cel!(NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128); +mark_cel!( + NonZeroU8, + NonZeroU16, + NonZeroU32, + NonZeroU64, + NonZeroU128, + NonZeroI8, + NonZeroI16, + NonZeroI32, + NonZeroI64, + NonZeroI128 +); mark_cel!(Duration); mark_cel!(PhantomData); @@ -85,7 +95,7 @@ mod tests { test_cel_compliance!(Void); test_cel_compliance!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, bool); - + type TupleArithmetic = (u8, u16, u32, u64, u128, i8, i16, i32, i64, i128); test_cel_compliance!(TupleArithmetic); diff --git a/src/decode_all.rs b/src/decode_all.rs index 448afbd5..62836190 100644 --- a/src/decode_all.rs +++ b/src/decode_all.rs @@ -17,8 +17,8 @@ use crate::{Decode, Error}; /// The error message returned when `decode_all` fails. pub(crate) const DECODE_ALL_ERR_MSG: &str = "Input buffer has still data left after decoding!"; -/// Extension trait to [`Decode`] that ensures that the given input data is consumed completely while -/// decoding. +/// Extension trait to [`Decode`] that ensures that the given input data is consumed completely +/// while decoding. pub trait DecodeAll: Sized { /// Decode `Self` and consume all of the given input data. /// diff --git a/src/encode_append.rs b/src/encode_append.rs index 6f60f6aa..82cf4f81 100644 --- a/src/encode_append.rs +++ b/src/encode_append.rs @@ -14,10 +14,12 @@ use core::iter::ExactSizeIterator; -use crate::alloc::vec::Vec; -use crate::{Encode, Decode, Error}; -use crate::compact::{Compact, CompactLen}; -use crate::encode_like::EncodeLike; +use crate::{ + alloc::vec::Vec, + compact::{Compact, CompactLen}, + encode_like::EncodeLike, + Decode, Encode, Error, +}; /// Trait that allows to append items to an encoded representation without /// decoding all previous added items. @@ -31,7 +33,7 @@ pub trait EncodeAppend { /// # Example /// /// ``` - ///# use parity_scale_codec::EncodeAppend; + /// # use parity_scale_codec::EncodeAppend; /// /// // Some encoded data /// let data = Vec::new(); @@ -42,10 +44,7 @@ pub trait EncodeAppend { /// // Add multiple element /// as EncodeAppend>::append_or_new(encoded, &[700u32, 800u32, 10u32]).expect("Adds new elements"); /// ``` - fn append_or_new( - self_encoded: Vec, - iter: I, - ) -> Result, Error> + fn append_or_new(self_encoded: Vec, iter: I) -> Result, Error> where I: IntoIterator, EncodeLikeItem: EncodeLike, @@ -55,10 +54,7 @@ pub trait EncodeAppend { impl EncodeAppend for Vec { type Item = T; - fn append_or_new( - self_encoded: Vec, - iter: I, - ) -> Result, Error> + fn append_or_new(self_encoded: Vec, iter: I) -> Result, Error> where I: IntoIterator, EncodeLikeItem: EncodeLike, @@ -71,10 +67,7 @@ impl EncodeAppend for Vec { impl EncodeAppend for crate::alloc::collections::VecDeque { type Item = T; - fn append_or_new( - self_encoded: Vec, - iter: I, - ) -> Result, Error> + fn append_or_new(self_encoded: Vec, iter: I) -> Result, Error> where I: IntoIterator, EncodeLikeItem: EncodeLike, @@ -87,10 +80,7 @@ impl EncodeAppend for crate::alloc::collections::VecDeque { /// Extends a SCALE-encoded vector with elements from the given `iter`. /// /// `vec` must either be empty, or contain a valid SCALE-encoded `Vec` payload. -fn append_or_new_impl( - mut vec: Vec, - iter: I, -) -> Result, Error> +fn append_or_new_impl(mut vec: Vec, iter: I) -> Result, Error> where Item: Encode, I: IntoIterator, @@ -113,9 +103,9 @@ where if old_item_count_encoded_bytesize == new_item_count_encoded_bytesize { // The size of the length as encoded by SCALE didn't change, so we can just // keep the old buffer as-is. We just need to update the length prefix. - Compact(new_item_count).using_encoded(|length_encoded| + Compact(new_item_count).using_encoded(|length_encoded| { vec[..old_item_count_encoded_bytesize].copy_from_slice(length_encoded) - ); + }); } else { // We can't update the length as the new length prefix will take up more // space when encoded, so we need to move our data to make space for it. @@ -143,14 +133,18 @@ where #[cfg(test)] mod tests { use super::*; - use crate::{Input, Encode, EncodeLike}; + use crate::{Encode, EncodeLike, Input}; use std::collections::VecDeque; const TEST_VALUE: u32 = { #[cfg(not(miri))] - { 1_000_000 } + { + 1_000_000 + } #[cfg(miri)] - { 1_000 } + { + 1_000 + } }; #[test] @@ -204,7 +198,9 @@ mod tests { #[test] fn append_non_copyable() { #[derive(Eq, PartialEq, Debug)] - struct NoCopy { data: u32 } + struct NoCopy { + data: u32, + } impl EncodeLike for NoCopy {} @@ -222,7 +218,8 @@ mod tests { let append = NoCopy { data: 100 }; let data = Vec::new(); - let encoded = as EncodeAppend>::append_or_new(data, std::iter::once(&append)).unwrap(); + let encoded = + as EncodeAppend>::append_or_new(data, std::iter::once(&append)).unwrap(); let decoded = >::decode(&mut &encoded[..]).unwrap(); assert_eq!(vec![append], decoded); @@ -231,7 +228,8 @@ mod tests { #[test] fn vec_encode_like_append_works() { let encoded = (0..TEST_VALUE).fold(Vec::new(), |encoded, v| { - as EncodeAppend>::append_or_new(encoded, std::iter::once(Box::new(v as u32))).unwrap() + as EncodeAppend>::append_or_new(encoded, std::iter::once(Box::new(v as u32))) + .unwrap() }); let decoded = Vec::::decode(&mut &encoded[..]).unwrap(); diff --git a/src/encode_like.rs b/src/encode_like.rs index 36023dd9..80fc2947 100644 --- a/src/encode_like.rs +++ b/src/encode_like.rs @@ -22,7 +22,7 @@ use crate::codec::Encode; /// # Example /// /// ``` -///# use parity_scale_codec::{EncodeLike, Encode}; +/// # use parity_scale_codec::{EncodeLike, Encode}; /// fn encode_like>(data: &R) { /// data.encode(); // Valid `T` encoded value. /// } @@ -51,7 +51,7 @@ use crate::codec::Encode; /// combination or use [`Ref`](./struct.Ref.html) reference wrapper or define your own wrapper /// and implement `EncodeLike` on it as such: /// ``` -///# use parity_scale_codec::{EncodeLike, Encode, WrapperTypeEncode}; +/// # use parity_scale_codec::{EncodeLike, Encode, WrapperTypeEncode}; /// fn encode_like>(data: &R) { /// data.encode(); // Valid `T` encoded value. /// } @@ -88,8 +88,10 @@ pub trait EncodeLike: Sized + Encode {} /// ``` pub struct Ref<'a, T: EncodeLike, U: Encode>(&'a T, core::marker::PhantomData); impl<'a, T: EncodeLike, U: Encode> core::ops::Deref for Ref<'a, T, U> { - type Target = T; - fn deref(&self) -> &Self::Target { self.0 } + type Target = T; + fn deref(&self) -> &Self::Target { + self.0 + } } impl<'a, T: EncodeLike, U: Encode> From<&'a T> for Ref<'a, T, U> { @@ -109,7 +111,10 @@ mod tests { struct ComplexStuff(T); impl ComplexStuff { - fn complex_method(value: &R) -> Vec where T: EncodeLike { + fn complex_method(value: &R) -> Vec + where + T: EncodeLike, + { value.encode() } } diff --git a/src/generic_array.rs b/src/generic_array.rs index a346b355..18dffceb 100644 --- a/src/generic_array.rs +++ b/src/generic_array.rs @@ -12,9 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::alloc::vec::Vec; -use crate::{Encode, Decode, Input, Output, Error}; -use crate::encode_like::EncodeLike; +use crate::{alloc::vec::Vec, encode_like::EncodeLike, Decode, Encode, Error, Input, Output}; impl> Encode for generic_array::GenericArray { fn encode_to(&self, dest: &mut W) { @@ -44,7 +42,7 @@ impl> Decode for generic_array::Gene #[cfg(test)] mod tests { use super::*; - use generic_array::{typenum, GenericArray, arr}; + use generic_array::{arr, typenum, GenericArray}; #[test] fn generic_array() { diff --git a/src/joiner.rs b/src/joiner.rs index 6dd44589..1baa026d 100644 --- a/src/joiner.rs +++ b/src/joiner.rs @@ -25,7 +25,10 @@ pub trait Joiner { fn and(self, value: &V) -> Self; } -impl Joiner for T where T: for<'a> Extend<&'a u8> { +impl Joiner for T +where + T: for<'a> Extend<&'a u8>, +{ fn and(mut self, value: &V) -> Self { value.using_encoded(|s| self.extend(s)); self diff --git a/src/keyedvec.rs b/src/keyedvec.rs index 20e76e71..78f00673 100644 --- a/src/keyedvec.rs +++ b/src/keyedvec.rs @@ -16,8 +16,7 @@ use core::iter::Extend; -use crate::alloc::vec::Vec; -use crate::codec::Codec; +use crate::{alloc::vec::Vec, codec::Codec}; /// Trait to allow itself to be serialised and prepended by a given slice. pub trait KeyedVec { diff --git a/src/lib.rs b/src/lib.rs index fb247601..9f95cf69 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,54 +36,49 @@ pub use parity_scale_codec_derive::*; #[cfg(feature = "std")] #[doc(hidden)] pub mod alloc { - pub use std::boxed; - pub use std::vec; - pub use std::string; - pub use std::borrow; - pub use std::collections; - pub use std::sync; - pub use std::rc; - pub use std::alloc; + pub use std::{alloc, borrow, boxed, collections, rc, string, sync, vec}; } -mod codec; -mod compact; -mod joiner; -mod keyedvec; #[cfg(feature = "bit-vec")] mod bit_vec; -#[cfg(feature = "generic-array")] -mod generic_array; +mod codec; +mod compact; +#[cfg(feature = "max-encoded-len")] +mod const_encoded_len; mod decode_all; mod decode_finished; mod depth_limit; mod encode_append; mod encode_like; mod error; +#[cfg(feature = "generic-array")] +mod generic_array; +mod joiner; +mod keyedvec; #[cfg(feature = "max-encoded-len")] mod max_encoded_len; -#[cfg(feature = "max-encoded-len")] -mod const_encoded_len; -pub use self::error::Error; -pub use self::codec::{ - Input, Output, Decode, Encode, Codec, EncodeAsRef, WrapperTypeEncode, WrapperTypeDecode, - OptionBool, DecodeLength, FullCodec, FullEncode, decode_vec_with_len, -}; #[cfg(feature = "std")] pub use self::codec::IoReader; -pub use self::compact::{Compact, HasCompact, CompactAs, CompactLen, CompactRef}; -pub use self::joiner::Joiner; -pub use self::keyedvec::KeyedVec; -pub use self::decode_all::DecodeAll; -pub use self::decode_finished::DecodeFinished; -pub use self::depth_limit::DecodeLimit; -pub use self::encode_append::EncodeAppend; -pub use self::encode_like::{EncodeLike, Ref}; -#[cfg(feature = "max-encoded-len")] -pub use max_encoded_len::MaxEncodedLen; +pub use self::{ + codec::{ + decode_vec_with_len, Codec, Decode, DecodeLength, Encode, EncodeAsRef, FullCodec, + FullEncode, Input, OptionBool, Output, WrapperTypeDecode, WrapperTypeEncode, + }, + compact::{Compact, CompactAs, CompactLen, CompactRef, HasCompact}, + decode_all::DecodeAll, + decode_finished::DecodeFinished, + depth_limit::DecodeLimit, + encode_append::EncodeAppend, + encode_like::{EncodeLike, Ref}, + error::Error, + joiner::Joiner, + keyedvec::KeyedVec, +}; #[cfg(feature = "max-encoded-len")] pub use const_encoded_len::ConstEncodedLen; +#[cfg(feature = "max-encoded-len")] +pub use max_encoded_len::MaxEncodedLen; /// Derive macro for [`MaxEncodedLen`][max_encoded_len::MaxEncodedLen]. /// @@ -117,9 +112,10 @@ pub use const_encoded_len::ConstEncodedLen; /// /// # Within other macros /// -/// Sometimes the `MaxEncodedLen` trait and macro are used within another macro, and it can't be -/// guaranteed that the `parity_scale_codec` module is available at the call site. In that case, the -/// macro should reexport the `parity_scale_codec` module and specify the path to the reexport: +/// Sometimes the `MaxEncodedLen` trait and macro are used within another macro, and it can't +/// be guaranteed that the `parity_scale_codec` module is available at the call site. In that +/// case, the macro should reexport the `parity_scale_codec` module and specify the path to the +/// reexport: /// /// ```ignore /// pub use parity_scale_codec as codec; diff --git a/src/max_encoded_len.rs b/src/max_encoded_len.rs index 1e857595..2c08dc81 100644 --- a/src/max_encoded_len.rs +++ b/src/max_encoded_len.rs @@ -15,10 +15,15 @@ //! `trait MaxEncodedLen` bounds the maximum encoded length of items. -use crate::{Compact, Encode}; +use crate::{alloc::boxed::Box, Compact, Encode}; +use core::{ + marker::PhantomData, + mem, + num::*, + ops::{Range, RangeInclusive}, + time::Duration, +}; use impl_trait_for_tuples::impl_for_tuples; -use core::{mem, marker::PhantomData, num::*, ops::{Range, RangeInclusive}, time::Duration}; -use crate::alloc::boxed::Box; #[cfg(target_has_atomic = "ptr")] use crate::alloc::sync::Arc; @@ -47,9 +52,27 @@ macro_rules! impl_primitives { } impl_primitives!( - u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, bool, - NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroI8, NonZeroI16, NonZeroI32, - NonZeroI64, NonZeroI128 + u8, + i8, + u16, + i16, + u32, + i32, + u64, + i64, + u128, + i128, + bool, + NonZeroU8, + NonZeroU16, + NonZeroU32, + NonZeroU64, + NonZeroU128, + NonZeroI8, + NonZeroI16, + NonZeroI32, + NonZeroI64, + NonZeroI128 ); macro_rules! impl_compact { @@ -78,7 +101,8 @@ impl_compact!( u128 => 17; ); -// impl_for_tuples for values 19 and higher fails because that's where the WrapperTypeEncode impl stops. +// impl_for_tuples for values 19 and higher fails because that's where the WrapperTypeEncode impl +// stops. #[impl_for_tuples(18)] impl MaxEncodedLen for Tuple { fn max_encoded_len() -> usize { @@ -96,7 +120,7 @@ impl MaxEncodedLen for [T; N] { impl MaxEncodedLen for Box { fn max_encoded_len() -> usize { - T::max_encoded_len() + T::max_encoded_len() } } @@ -131,19 +155,19 @@ impl MaxEncodedLen for PhantomData { impl MaxEncodedLen for Duration { fn max_encoded_len() -> usize { - u64::max_encoded_len() + u32::max_encoded_len() + u64::max_encoded_len() + u32::max_encoded_len() } } impl MaxEncodedLen for Range { fn max_encoded_len() -> usize { - T::max_encoded_len().saturating_mul(2) + T::max_encoded_len().saturating_mul(2) } } impl MaxEncodedLen for RangeInclusive { fn max_encoded_len() -> usize { - T::max_encoded_len().saturating_mul(2) + T::max_encoded_len().saturating_mul(2) } } diff --git a/tests/chain-error.rs b/tests/chain-error.rs index b8c764be..9503bd9b 100644 --- a/tests/chain-error.rs +++ b/tests/chain-error.rs @@ -12,15 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -use parity_scale_codec_derive::Decode as DeriveDecode; use parity_scale_codec::Decode; +use parity_scale_codec_derive::Decode as DeriveDecode; #[derive(DeriveDecode, Debug)] struct Wrapper(T); #[derive(DeriveDecode, Debug)] struct StructNamed { - _foo: u16 + _foo: u16, } #[derive(DeriveDecode, Debug)] @@ -28,7 +28,7 @@ struct StructUnnamed(u16); #[derive(DeriveDecode, Debug)] enum E { - VariantNamed { _foo: u16, }, + VariantNamed { _foo: u16 }, VariantUnnamed(u16), } @@ -65,10 +65,7 @@ fn full_error_enum_unknown_variant() { let encoded = vec![2]; let err = r#"Could not decode `E`, variant doesn't exist"#; - assert_eq!( - E::decode(&mut &encoded[..]).unwrap_err().to_string(), - String::from(err), - ); + assert_eq!(E::decode(&mut &encoded[..]).unwrap_err().to_string(), String::from(err),); } #[test] @@ -78,10 +75,7 @@ fn full_error_enum_named_field() { Not enough data to fill buffer "#; - assert_eq!( - E::decode(&mut &encoded[..]).unwrap_err().to_string(), - String::from(err), - ); + assert_eq!(E::decode(&mut &encoded[..]).unwrap_err().to_string(), String::from(err),); } #[test] @@ -91,8 +85,5 @@ fn full_error_enum_unnamed_field() { Not enough data to fill buffer "#; - assert_eq!( - E::decode(&mut &encoded[..]).unwrap_err().to_string(), - String::from(err), - ); + assert_eq!(E::decode(&mut &encoded[..]).unwrap_err().to_string(), String::from(err),); } diff --git a/tests/max_encoded_len.rs b/tests/max_encoded_len.rs index 6924aa37..6a15e95b 100644 --- a/tests/max_encoded_len.rs +++ b/tests/max_encoded_len.rs @@ -80,7 +80,6 @@ fn compact_field_max_length() { ); } - #[derive(Encode, MaxEncodedLen)] struct CompactFieldGenerics { #[codec(compact)] @@ -90,10 +89,7 @@ struct CompactFieldGenerics { #[test] fn compact_field_generics_max_length() { - assert_eq!( - CompactFieldGenerics::::max_encoded_len(), - CompactField::max_encoded_len() - ); + assert_eq!(CompactFieldGenerics::::max_encoded_len(), CompactField::max_encoded_len()); } #[derive(Encode, MaxEncodedLen)] diff --git a/tests/mod.rs b/tests/mod.rs index 93d2595b..952d6f2a 100644 --- a/tests/mod.rs +++ b/tests/mod.rs @@ -679,15 +679,17 @@ fn decoding_a_huge_boxed_newtype_array_does_not_overflow_the_stack() { fn decoding_two_indirectly_boxed_arrays_works() { // This test will fail if the check for `#[repr(transparent)]` in the derive crate // doesn't work when implementing `Decode::decode_into`. - #[derive(DeriveDecode)] - #[derive(PartialEq, Eq, Debug)] + #[derive(DeriveDecode, PartialEq, Eq, Debug)] struct SmallArrays([u8; 2], [u8; 2]); #[derive(DeriveDecode)] struct SmallArraysBox(Box); let data = &[1, 2, 3, 4]; - assert_eq!(*SmallArraysBox::decode(&mut data.as_slice()).unwrap().0, SmallArrays([1, 2], [3, 4])); + assert_eq!( + *SmallArraysBox::decode(&mut data.as_slice()).unwrap().0, + SmallArrays([1, 2], [3, 4]) + ); } #[test] @@ -708,7 +710,7 @@ fn zero_sized_types_are_properly_decoded_in_a_transparent_boxed_struct() { _zst_2: ZstTransparent, _zst_3: ZstNonTransparent, field: [u8; 1], - _zst_4: ConsumeByte + _zst_4: ConsumeByte, } #[derive(DeriveDecode)] diff --git a/tests/single_field_struct_encoding.rs b/tests/single_field_struct_encoding.rs index cbf5cf66..565a7d72 100644 --- a/tests/single_field_struct_encoding.rs +++ b/tests/single_field_struct_encoding.rs @@ -1,6 +1,8 @@ -use parity_scale_codec_derive::{Encode as DeriveEncode, Decode as DeriveDecode, CompactAs as DeriveCompactAs}; use parity_scale_codec::{Compact, Decode, Encode, HasCompact}; -use serde_derive::{Serialize, Deserialize}; +use parity_scale_codec_derive::{ + CompactAs as DeriveCompactAs, Decode as DeriveDecode, Encode as DeriveEncode, +}; +use serde_derive::{Deserialize, Serialize}; #[derive(Debug, PartialEq, DeriveEncode, DeriveDecode)] struct S { @@ -35,7 +37,9 @@ struct U(u32); #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[derive(Debug, PartialEq, Eq, Clone, Copy, DeriveEncode, DeriveDecode, DeriveCompactAs)] -struct U2 { a: u64 } +struct U2 { + a: u64, +} #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[derive(Debug, PartialEq, Eq, Clone, Copy, DeriveEncode, DeriveDecode, DeriveCompactAs)] diff --git a/tests/skip.rs b/tests/skip.rs index 0c9439cf..20f37311 100644 --- a/tests/skip.rs +++ b/tests/skip.rs @@ -1,5 +1,5 @@ -use parity_scale_codec_derive::{Encode as DeriveEncode, Decode as DeriveDecode}; -use parity_scale_codec::{Encode, Decode}; +use parity_scale_codec::{Decode, Encode}; +use parity_scale_codec_derive::{Decode as DeriveDecode, Encode as DeriveEncode}; #[test] fn enum_struct_test() { @@ -9,9 +9,9 @@ fn enum_struct_test() { #[derive(PartialEq, Debug)] struct UncodecUndefaultType; -use parity_scale_codec_derive::{Encode as DeriveEncode, Decode as DeriveDecode}; + use parity_scale_codec_derive::{Decode as DeriveDecode, Encode as DeriveEncode}; #[derive(PartialEq, Debug, DeriveEncode, DeriveDecode)] - enum Enum { + enum Enum { #[codec(skip)] A(S), B { @@ -19,26 +19,18 @@ use parity_scale_codec_derive::{Encode as DeriveEncode, Decode as DeriveDecode}; _b1: T, b2: u32, }, - C( - #[codec(skip)] - T, - u32, - ), + C(#[codec(skip)] T, u32), } #[derive(PartialEq, Debug, DeriveEncode, DeriveDecode)] - struct StructNamed { + struct StructNamed { #[codec(skip)] a: T, b: u32, } #[derive(PartialEq, Debug, DeriveEncode, DeriveDecode)] - struct StructUnnamed( - #[codec(skip)] - T, - u32, - ); + struct StructUnnamed(#[codec(skip)] T, u32); let ea: Enum = Enum::A(UncodecUndefaultType); let eb: Enum = Enum::B { _b1: UncodecType, b2: 1 }; @@ -70,7 +62,7 @@ fn skip_enum_struct_inner_variant() { some_named: u32, #[codec(skip)] ignore: Option, - } + }, } let encoded = Enum::Data { some_named: 1, ignore: Some(1) }.encode(); diff --git a/tests/type_inference.rs b/tests/type_inference.rs index 97967632..613e7aa5 100644 --- a/tests/type_inference.rs +++ b/tests/type_inference.rs @@ -14,8 +14,8 @@ //! Test for type inference issue in decode. -use parity_scale_codec_derive::Decode as DeriveDecode; use parity_scale_codec::Decode; +use parity_scale_codec_derive::Decode as DeriveDecode; pub trait Trait { type Value; @@ -24,10 +24,7 @@ pub trait Trait { #[derive(DeriveDecode)] pub enum A { - _C( - (T::AccountId, T::AccountId), - Vec<(T::Value, T::Value)>, - ), + _C((T::AccountId, T::AccountId), Vec<(T::Value, T::Value)>), } #[derive(DeriveDecode)] diff --git a/tests/variant_number.rs b/tests/variant_number.rs index 54a900d3..9bdaba0a 100644 --- a/tests/variant_number.rs +++ b/tests/variant_number.rs @@ -1,5 +1,5 @@ -use parity_scale_codec_derive::Encode as DeriveEncode; use parity_scale_codec::Encode; +use parity_scale_codec_derive::Encode as DeriveEncode; #[test] fn discriminant_variant_counted_in_default_index() {