From dca2e53ee79223b9bbb5e5414a6f83b678d23c58 Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Mon, 14 Oct 2024 18:15:45 +0100 Subject: [PATCH 01/17] did most of u16 disciminator, failed on deserialize_variant --- Cargo.toml | 2 +- .../src/internals/attributes/item/mod.rs | 17 ++++++++--- borsh-derive/src/internals/attributes/mod.rs | 1 + .../src/internals/deserialize/enums/mod.rs | 21 ++++++++------ .../src/internals/enum_discriminant.rs | 25 +++++++++++------ .../src/internals/serialize/enums/mod.rs | 7 +++-- borsh/src/de/mod.rs | 2 +- .../test_enum_discriminants.rs | 28 +++++++++++++++++++ rust-toolchain.toml | 10 +++++++ 9 files changed, 88 insertions(+), 25 deletions(-) create mode 100644 rust-toolchain.toml diff --git a/Cargo.toml b/Cargo.toml index 2a1e1907c..82020ecb9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,4 +4,4 @@ members = ["borsh", "borsh-derive", "fuzz/fuzz-run", "benchmarks"] [workspace.package] # shared version of all public crates in the workspace version = "1.5.1" -rust-version = "1.67.0" +rust-version = "1.81.0" diff --git a/borsh-derive/src/internals/attributes/item/mod.rs b/borsh-derive/src/internals/attributes/item/mod.rs index ff3551486..9bb3baeb2 100644 --- a/borsh-derive/src/internals/attributes/item/mod.rs +++ b/borsh-derive/src/internals/attributes/item/mod.rs @@ -1,8 +1,8 @@ use crate::internals::attributes::{BORSH, CRATE, INIT, USE_DISCRIMINANT}; use quote::ToTokens; -use syn::{spanned::Spanned, Attribute, DeriveInput, Error, Expr, ItemEnum, Path}; +use syn::{spanned::Spanned, Attribute, DeriveInput, Error, Expr, ItemEnum, Path, TypePath}; -use super::{get_one_attribute, parsing}; +use super::{get_one_attribute, parsing, REPR}; pub fn check_attributes(derive_input: &DeriveInput) -> Result<(), Error> { let borsh = get_one_attribute(&derive_input.attrs)?; @@ -34,10 +34,11 @@ pub fn check_attributes(derive_input: &DeriveInput) -> Result<(), Error> { } pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result { - if input.variants.len() > 256 { + const MAX_VARIANTS: usize = u16::MAX as usize + 1; + if input.variants.len() > MAX_VARIANTS { return Err(syn::Error::new( input.span(), - "up to 256 enum variants are supported", + "up to {MAX_VARIANTS} enum variants are supported", )); } @@ -80,6 +81,14 @@ pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result Option { + input.attrs.iter().find(|x| { + x.path() == REPR + }) + ?.parse_args().ok() +} + pub(crate) fn contains_initialize_with(attrs: &[Attribute]) -> Result, Error> { let mut res = None; let attr = attrs.iter().find(|attr| attr.path() == BORSH); diff --git a/borsh-derive/src/internals/attributes/mod.rs b/borsh-derive/src/internals/attributes/mod.rs index 4c5a69d4d..cc8ea1d4a 100644 --- a/borsh-derive/src/internals/attributes/mod.rs +++ b/borsh-derive/src/internals/attributes/mod.rs @@ -29,6 +29,7 @@ pub const SERIALIZE_WITH: Symbol = Symbol("serialize_with", "serialize_with = .. pub const DESERIALIZE_WITH: Symbol = Symbol("deserialize_with", "deserialize_with = ..."); /// crate - sub-borsh nested meta, item-level only, `BorshSerialize`, `BorshDeserialize`, `BorshSchema` contexts pub const CRATE: Symbol = Symbol("crate", "crate = ..."); +pub const REPR: Symbol = Symbol("repr", "repr(...)"); #[cfg(feature = "schema")] pub mod schema_keys { diff --git a/borsh-derive/src/internals/deserialize/enums/mod.rs b/borsh-derive/src/internals/deserialize/enums/mod.rs index fb405e90d..9d90e75ac 100644 --- a/borsh-derive/src/internals/deserialize/enums/mod.rs +++ b/borsh-derive/src/internals/deserialize/enums/mod.rs @@ -11,7 +11,8 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut where_clause = generics::default_where(where_clause); let mut variant_arms = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; - let discriminants = Discriminants::new(&input.variants); + let maybe_reprc_attribute = item::get_maybe_reprc_attribute(input); + let discriminants: Discriminants = Discriminants::new(&input.variants, maybe_reprc_attribute); let mut generics_output = deserialize::GenericsOutput::new(&generics); for (variant_idx, variant) in input.variants.iter().enumerate() { @@ -20,7 +21,7 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let discriminant_value = discriminants.get(variant_ident, use_discriminant, variant_idx)?; variant_arms.extend(quote! { - if variant_tag == #discriminant_value { #name::#variant_ident #variant_body } else + if variant_tag == #discriminant_value.into() { #name::#variant_ident #variant_body } else }); } let init = if let Some(method_ident) = item::contains_initialize_with(&input.attrs)? { @@ -32,18 +33,21 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { }; generics_output.extend(&mut where_clause, &cratename); - Ok(quote! { + let discriminant_type = discriminants.discriminant_type(); + let x = quote! { impl #impl_generics #cratename::de::BorshDeserialize for #name #ty_generics #where_clause { fn deserialize_reader<__R: #cratename::io::Read>(reader: &mut __R) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let tag = <#discriminant_type as #cratename::de::BorshDeserialize>::deserialize_reader(reader)?; + ::deserialize_variant::<_, #discriminant_type>(reader, tag) } } impl #impl_generics #cratename::de::EnumExt for #name #ty_generics #where_clause { - fn deserialize_variant<__R: #cratename::io::Read>( + fn deserialize_variant<__R: #cratename::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + >( reader: &mut __R, - variant_tag: u8, + variant_tag: u8, //#discriminant_type, ) -> ::core::result::Result { let mut return_value = #variant_arms { @@ -56,7 +60,8 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { Ok(return_value) } } - }) + }; + Ok(x) } fn process_variant( diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index 03b3f5829..71e257722 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -1,15 +1,16 @@ +use core::convert::TryInto; use std::collections::HashMap; use std::convert::TryFrom; use proc_macro2::{Ident, TokenStream}; use quote::quote; -use syn::{punctuated::Punctuated, token::Comma, Variant}; +use syn::{parse::{Parse, ParseBuffer}, punctuated::Punctuated, token::{Comma, Type}, Path, Variant}; -pub struct Discriminants(HashMap); +pub struct Discriminants((HashMap, syn::TypePath)); impl Discriminants { /// Calculates the discriminant that will be assigned by the compiler. /// See: https://doc.rust-lang.org/reference/items/enumerations.html#assigning-discriminant-values - pub fn new(variants: &Punctuated) -> Self { + pub fn new(variants: &Punctuated, maybe_discriminant_type: Option) -> Self { let mut map = HashMap::new(); let mut next_discriminant_if_not_specified = quote! {0}; @@ -18,12 +19,20 @@ impl Discriminants { || quote! { #next_discriminant_if_not_specified }, |(_, e)| quote! { #e }, ); - + next_discriminant_if_not_specified = quote! { #this_discriminant + 1 }; map.insert(variant.ident.clone(), this_discriminant); } + let discriminant_type = //maybe_discriminant_type.unwrap_or( + syn::parse_str("u8").expect("numeric") + //) + ; + + Self((map, discriminant_type)) + } - Self(map) + pub fn discriminant_type(&self) -> &syn::TypePath { + &self.0.1 } pub fn get( @@ -32,14 +41,14 @@ impl Discriminants { use_discriminant: bool, variant_idx: usize, ) -> syn::Result { - let variant_idx = u8::try_from(variant_idx).map_err(|err| { + let variant_idx: u8 = u8::try_from(variant_idx).map_err(|err| { syn::Error::new( variant_ident.span(), - format!("up to 256 enum variants are supported: {}", err), + format!("up to {} enum variants are supported: {}", u8::MAX as usize + 1, err), ) })?; let result = if use_discriminant { - let discriminant_value = self.0.get(variant_ident).unwrap(); + let discriminant_value = self.0.0.get(variant_ident).unwrap(); quote! { #discriminant_value } } else { quote! { #variant_idx } diff --git a/borsh-derive/src/internals/serialize/enums/mod.rs b/borsh-derive/src/internals/serialize/enums/mod.rs index 4e86ca2d4..a62ec324e 100644 --- a/borsh-derive/src/internals/serialize/enums/mod.rs +++ b/borsh-derive/src/internals/serialize/enums/mod.rs @@ -17,7 +17,8 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut all_variants_idx_body = TokenStream2::new(); let mut fields_body = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; - let discriminants = Discriminants::new(&input.variants); + let maybe_discriminant_type = item::get_maybe_reprc_attribute(input); + let discriminants = Discriminants::new(&input.variants, maybe_discriminant_type); let mut has_unit_variant = false; for (variant_idx, variant) in input.variants.iter().enumerate() { @@ -42,11 +43,11 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { } let fields_body = optimize_fields_body(fields_body, has_unit_variant); generics_output.extend(&mut where_clause, &cratename); - + let discriminant_type = discriminants.discriminant_type(); Ok(quote! { impl #impl_generics #cratename::ser::BorshSerialize for #enum_ident #ty_generics #where_clause { fn serialize<__W: #cratename::io::Write>(&self, writer: &mut __W) -> ::core::result::Result<(), #cratename::io::Error> { - let variant_idx: u8 = match self { + let variant_idx: #discriminant_type = match self { #all_variants_idx_body }; writer.write_all(&variant_idx.to_le_bytes())?; diff --git a/borsh/src/de/mod.rs b/borsh/src/de/mod.rs index 0abb36e3e..47bd3f5f9 100644 --- a/borsh/src/de/mod.rs +++ b/borsh/src/de/mod.rs @@ -132,7 +132,7 @@ pub trait EnumExt: BorshDeserialize { /// # #[cfg(feature = "derive")] /// assert!(from_slice::(&data[..]).is_err()); /// ``` - fn deserialize_variant(reader: &mut R, tag: u8) -> Result; + fn deserialize_variant(reader: &mut R, tag: u8) -> Result; } fn unexpected_eof_to_unexpected_length_of_input(e: Error) -> Error { diff --git a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs index ac719fe57..60c62ff91 100644 --- a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs +++ b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs @@ -39,6 +39,34 @@ fn test_discriminant_serde_no_unit_type() { } } +#[test] +pub fn u16_discriminat() { + use borsh::{BorshSerialize, BorshDeserialize}; + #[derive(BorshSerialize, BorshDeserialize, Debug)] + #[borsh(use_discriminant = true)] + #[repr(u16)] + enum ZEnum { + AA = 42, + Z=2, + // A { a: u16, b: u64, d: bool, s: String } = 1u16, + // Z { a: u16, b: u64, d: bool, s: String } = 257u16, + } + let mut ss = vec![]; + ZEnum::AA.serialize(&mut ss).unwrap(); + assert!(ss[0] == 42); + assert!(ss[1] == 0); + // let s = Enum::A { + // a: 13, + // b: 42, + // d: true, + // s: "hello my bonny".to_string(), + // }; + // let mut buf = Vec::new(); + // s.serialize(&mut buf).expect("must serialize"); + // panic!("{:?}", buf); +} + + #[test] fn test_discriminant_serde_no_unit_type_no_use_discriminant() { let values = vec![ diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 000000000..f602afad8 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,10 @@ +[toolchain] +channel = "1.81.0" + +# Default profile includes `rustfmt`, `clippy`, `rust-docs`. +# https://rust-lang.github.io/rustup/concepts/profiles.html +profile = "default" +components = ["rust-analyzer"] + +# For static linking for deployment. +targets = ["x86_64-unknown-linux-musl"] From 24a3be15e3739d013d41f158423c912a5ec5ac8e Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Mon, 14 Oct 2024 19:02:32 +0100 Subject: [PATCH 02/17] generally it works, but code is ugly --- .../src/internals/deserialize/enums/mod.rs | 18 ++- .../borsh_discriminant_false.snap.new | 102 +++++++++++++++++ .../borsh_discriminant_true.snap.new | 102 +++++++++++++++++ .../enums/snapshots/borsh_init_func.snap.new | 103 ++++++++++++++++++ .../borsh_skip_struct_variant_field.snap.new | 63 +++++++++++ .../borsh_skip_tuple_variant_field.snap.new | 63 +++++++++++ .../enums/snapshots/bound_generics.snap.new | 76 +++++++++++++ .../check_deserialize_with_attr.snap.new | 72 ++++++++++++ .../generic_borsh_skip_struct_field.snap.new | 78 +++++++++++++ .../generic_borsh_skip_tuple_field.snap.new | 76 +++++++++++++ .../generic_deserialize_bound.snap.new | 72 ++++++++++++ .../enums/snapshots/recursive_enum.snap.new | 74 +++++++++++++ .../simple_enum_with_custom_crate.snap.new | 69 ++++++++++++ .../enums/snapshots/simple_generics.snap.new | 74 +++++++++++++ .../src/internals/enum_discriminant.rs | 6 +- .../src/internals/serialize/enums/mod.rs | 2 +- borsh/src/de/mod.rs | 2 +- 17 files changed, 1042 insertions(+), 10 deletions(-) create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new create mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new diff --git a/borsh-derive/src/internals/deserialize/enums/mod.rs b/borsh-derive/src/internals/deserialize/enums/mod.rs index 9d90e75ac..f75381dfa 100644 --- a/borsh-derive/src/internals/deserialize/enums/mod.rs +++ b/borsh-derive/src/internals/deserialize/enums/mod.rs @@ -11,17 +11,24 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut where_clause = generics::default_where(where_clause); let mut variant_arms = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; - let maybe_reprc_attribute = item::get_maybe_reprc_attribute(input); + let maybe_reprc_attribute = use_discriminant.then(||item::get_maybe_reprc_attribute(input)).flatten(); let discriminants: Discriminants = Discriminants::new(&input.variants, maybe_reprc_attribute); let mut generics_output = deserialize::GenericsOutput::new(&generics); - + + let discriminant_type = discriminants.discriminant_type(); for (variant_idx, variant) in input.variants.iter().enumerate() { let variant_body = process_variant(variant, &cratename, &mut generics_output)?; let variant_ident = &variant.ident; let discriminant_value = discriminants.get(variant_ident, use_discriminant, variant_idx)?; variant_arms.extend(quote! { - if variant_tag == #discriminant_value.into() { #name::#variant_ident #variant_body } else + if TryInto::<(#discriminant_type)>::try_into(variant_tag).map_err(|_| + return #cratename::io::Error::new( + #cratename::io::ErrorKind::InvalidData, + #cratename::__private::maybestd::format!("Unexpected variant tag: {:?}", variant_tag), + ) + )? + == #discriminant_value { #name::#variant_ident #variant_body } else }); } let init = if let Some(method_ident) = item::contains_initialize_with(&input.attrs)? { @@ -33,7 +40,6 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { }; generics_output.extend(&mut where_clause, &cratename); - let discriminant_type = discriminants.discriminant_type(); let x = quote! { impl #impl_generics #cratename::de::BorshDeserialize for #name #ty_generics #where_clause { fn deserialize_reader<__R: #cratename::io::Read>(reader: &mut __R) -> ::core::result::Result { @@ -45,10 +51,12 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { impl #impl_generics #cratename::de::EnumExt for #name #ty_generics #where_clause { fn deserialize_variant<__R: #cratename::io::Read, Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy >( reader: &mut __R, - variant_tag: u8, //#discriminant_type, + variant_tag: Tag, ) -> ::core::result::Result { + use ::core::convert::TryInto; let mut return_value = #variant_arms { return Err(#cratename::io::Error::new( diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new new file mode 100644 index 000000000..797634a49 --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new @@ -0,0 +1,102 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 307 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for X { + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for X { + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + X::A + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + X::B + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 2u8 + { + X::C + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 3u8 + { + X::D + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 4u8 + { + X::E + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 5u8 + { + X::F + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new new file mode 100644 index 000000000..18c68ca95 --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new @@ -0,0 +1,102 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 325 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for X { + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for X { + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0 + { + X::A + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 20 + { + X::B + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 20 + 1 + { + X::C + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 20 + 1 + 1 + { + X::D + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 10 + { + X::E + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 10 + 1 + { + X::F + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new new file mode 100644 index 000000000..cd5486f4d --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new @@ -0,0 +1,103 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 342 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for A { + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for A { + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + A::A + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + A::B + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 2u8 + { + A::C + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 3u8 + { + A::D + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 4u8 + { + A::E + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 5u8 + { + A::F + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + return_value.initialization_method(); + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new new file mode 100644 index 000000000..a0c55ef0f --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new @@ -0,0 +1,63 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 124 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for AA { + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for AA { + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + AA::B { + c: core::default::Default::default(), + d: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + AA::NegatedVariant { + beta: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new new file mode 100644 index 000000000..b3b159d1d --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new @@ -0,0 +1,63 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 141 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for AAT { + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for AAT { + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + AAT::B( + core::default::Default::default(), + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + AAT::NegatedVariant { + beta: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new new file mode 100644 index 000000000..a74352275 --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new @@ -0,0 +1,76 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 193 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for A +where + V: Value, + K: borsh::de::BorshDeserialize, + V: borsh::de::BorshDeserialize, + U: borsh::de::BorshDeserialize, +{ + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for A +where + V: Value, + K: borsh::de::BorshDeserialize, + V: borsh::de::BorshDeserialize, + U: borsh::de::BorshDeserialize, +{ + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new new file mode 100644 index 000000000..2254a6a18 --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new @@ -0,0 +1,72 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 288 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for C +where + K: borsh::de::BorshDeserialize, + V: borsh::de::BorshDeserialize, +{ + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for C +where + K: borsh::de::BorshDeserialize, + V: borsh::de::BorshDeserialize, +{ + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + C::C3( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + C::C4 { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: third_party_impl::deserialize_third_party(reader)?, + } + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new new file mode 100644 index 000000000..9422546ae --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new @@ -0,0 +1,78 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 229 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for A +where + V: Value, + K: borsh::de::BorshDeserialize, + U: borsh::de::BorshDeserialize, + K: core::default::Default, + V: core::default::Default, +{ + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for A +where + V: Value, + K: borsh::de::BorshDeserialize, + U: borsh::de::BorshDeserialize, + K: core::default::Default, + V: core::default::Default, +{ + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + A::B { + x: core::default::Default::default(), + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new new file mode 100644 index 000000000..69c9096f3 --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new @@ -0,0 +1,76 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 247 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for A +where + V: Value, + K: borsh::de::BorshDeserialize, + V: borsh::de::BorshDeserialize, + U: core::default::Default, +{ + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for A +where + V: Value, + K: borsh::de::BorshDeserialize, + V: borsh::de::BorshDeserialize, + U: core::default::Default, +{ + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + core::default::Default::default(), + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new new file mode 100644 index 000000000..13701ca67 --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new @@ -0,0 +1,72 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 269 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for A +where + T: PartialOrd + Hash + Eq + borsh::de::BorshDeserialize, + U: borsh::de::BorshDeserialize, +{ + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for A +where + T: PartialOrd + Hash + Eq + borsh::de::BorshDeserialize, + U: borsh::de::BorshDeserialize, +{ + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + A::C { + a: borsh::BorshDeserialize::deserialize_reader(reader)?, + b: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + A::D( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new new file mode 100644 index 000000000..7d5d7ff75 --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new @@ -0,0 +1,74 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 211 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for A +where + V: Value, + K: borsh::de::BorshDeserialize, + V: borsh::de::BorshDeserialize, +{ + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for A +where + V: Value, + K: borsh::de::BorshDeserialize, + V: borsh::de::BorshDeserialize, +{ + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new new file mode 100644 index 000000000..c30bf243a --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new @@ -0,0 +1,69 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 159 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl reexporter::borsh::de::BorshDeserialize for A { + fn deserialize_reader<__R: reexporter::borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader( + reader, + )?; + ::deserialize_variant::< + _, + u8, + >(reader, tag) + } +} +impl reexporter::borsh::de::EnumExt for A { + fn deserialize_variant< + __R: reexporter::borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return reexporter::borsh::io::Error::new( + reexporter::borsh::io::ErrorKind::InvalidData, + reexporter::borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + A::B { + x: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + y: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return reexporter::borsh::io::Error::new( + reexporter::borsh::io::ErrorKind::InvalidData, + reexporter::borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + A::C( + reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + reexporter::borsh::io::Error::new( + reexporter::borsh::io::ErrorKind::InvalidData, + reexporter::borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new new file mode 100644 index 000000000..0f4eb9aa2 --- /dev/null +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new @@ -0,0 +1,74 @@ +--- +source: borsh-derive/src/internals/deserialize/enums/mod.rs +assertion_line: 176 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::de::BorshDeserialize for A +where + K: borsh::de::BorshDeserialize, + V: borsh::de::BorshDeserialize, + U: borsh::de::BorshDeserialize, +{ + fn deserialize_reader<__R: borsh::io::Read>( + reader: &mut __R, + ) -> ::core::result::Result { + let tag = ::deserialize_reader(reader)?; + ::deserialize_variant::<_, u8>(reader, tag) + } +} +impl borsh::de::EnumExt for A +where + K: borsh::de::BorshDeserialize, + V: borsh::de::BorshDeserialize, + U: borsh::de::BorshDeserialize, +{ + fn deserialize_variant< + __R: borsh::io::Read, + Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq + + ::core::convert::TryInto + ::core::convert::TryInto + Copy, + >( + reader: &mut __R, + variant_tag: Tag, + ) -> ::core::result::Result { + use ::core::convert::TryInto; + let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 0u8 + { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if TryInto::<(u8)>::try_into(variant_tag) + .map_err(|_| { + return borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ); + })? == 1u8 + { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) + } +} diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index 71e257722..3b80ac32a 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -10,7 +10,7 @@ pub struct Discriminants((HashMap, syn::TypePath)); impl Discriminants { /// Calculates the discriminant that will be assigned by the compiler. /// See: https://doc.rust-lang.org/reference/items/enumerations.html#assigning-discriminant-values - pub fn new(variants: &Punctuated, maybe_discriminant_type: Option) -> Self { + pub fn new(variants: &Punctuated, mut maybe_discriminant_type: Option) -> Self { let mut map = HashMap::new(); let mut next_discriminant_if_not_specified = quote! {0}; @@ -23,9 +23,9 @@ impl Discriminants { next_discriminant_if_not_specified = quote! { #this_discriminant + 1 }; map.insert(variant.ident.clone(), this_discriminant); } - let discriminant_type = //maybe_discriminant_type.unwrap_or( + let discriminant_type = maybe_discriminant_type.unwrap_or( syn::parse_str("u8").expect("numeric") - //) + ) ; Self((map, discriminant_type)) diff --git a/borsh-derive/src/internals/serialize/enums/mod.rs b/borsh-derive/src/internals/serialize/enums/mod.rs index a62ec324e..ed92b1c67 100644 --- a/borsh-derive/src/internals/serialize/enums/mod.rs +++ b/borsh-derive/src/internals/serialize/enums/mod.rs @@ -17,7 +17,7 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut all_variants_idx_body = TokenStream2::new(); let mut fields_body = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; - let maybe_discriminant_type = item::get_maybe_reprc_attribute(input); + let maybe_discriminant_type = use_discriminant.then(||item::get_maybe_reprc_attribute(input)).flatten(); let discriminants = Discriminants::new(&input.variants, maybe_discriminant_type); let mut has_unit_variant = false; diff --git a/borsh/src/de/mod.rs b/borsh/src/de/mod.rs index 47bd3f5f9..0f47b5020 100644 --- a/borsh/src/de/mod.rs +++ b/borsh/src/de/mod.rs @@ -132,7 +132,7 @@ pub trait EnumExt: BorshDeserialize { /// # #[cfg(feature = "derive")] /// assert!(from_slice::(&data[..]).is_err()); /// ``` - fn deserialize_variant(reader: &mut R, tag: u8) -> Result; + fn deserialize_variant + ::core::convert::TryInto + Copy> (reader: &mut R, tag: Tag) -> Result; } fn unexpected_eof_to_unexpected_length_of_input(e: Error) -> Error { From 784755f09b234cdeb8df6c5eef1d4a6e885d39c5 Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Mon, 14 Oct 2024 19:22:58 +0100 Subject: [PATCH 03/17] schema fixed and fmt --- .../src/internals/attributes/item/mod.rs | 12 ++++--- .../src/internals/deserialize/enums/mod.rs | 5 +-- .../borsh_discriminant_false.snap.new | 2 +- .../borsh_discriminant_true.snap.new | 2 +- .../enums/snapshots/borsh_init_func.snap.new | 2 +- .../borsh_skip_struct_variant_field.snap.new | 2 +- .../borsh_skip_tuple_variant_field.snap.new | 2 +- .../enums/snapshots/bound_generics.snap.new | 2 +- .../check_deserialize_with_attr.snap.new | 2 +- .../generic_borsh_skip_struct_field.snap.new | 2 +- .../generic_borsh_skip_tuple_field.snap.new | 2 +- .../generic_deserialize_bound.snap.new | 2 +- .../enums/snapshots/recursive_enum.snap.new | 2 +- .../simple_enum_with_custom_crate.snap.new | 2 +- .../enums/snapshots/simple_generics.snap.new | 2 +- .../src/internals/enum_discriminant.rs | 28 +++++++++------- .../src/internals/schema/enums/mod.rs | 8 +++-- .../src/internals/serialize/enums/mod.rs | 4 ++- borsh/src/de/mod.rs | 13 +++++++- .../test_enum_discriminants.rs | 32 +++++++------------ 20 files changed, 72 insertions(+), 56 deletions(-) diff --git a/borsh-derive/src/internals/attributes/item/mod.rs b/borsh-derive/src/internals/attributes/item/mod.rs index 9bb3baeb2..d596d218b 100644 --- a/borsh-derive/src/internals/attributes/item/mod.rs +++ b/borsh-derive/src/internals/attributes/item/mod.rs @@ -82,11 +82,13 @@ pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result Option { - input.attrs.iter().find(|x| { - x.path() == REPR - }) - ?.parse_args().ok() +pub(crate) fn get_maybe_reprc_attribute(input: &ItemEnum) -> Option { + input + .attrs + .iter() + .find(|x| x.path() == REPR)? + .parse_args() + .ok() } pub(crate) fn contains_initialize_with(attrs: &[Attribute]) -> Result, Error> { diff --git a/borsh-derive/src/internals/deserialize/enums/mod.rs b/borsh-derive/src/internals/deserialize/enums/mod.rs index f75381dfa..7a0f0dde5 100644 --- a/borsh-derive/src/internals/deserialize/enums/mod.rs +++ b/borsh-derive/src/internals/deserialize/enums/mod.rs @@ -11,10 +11,11 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut where_clause = generics::default_where(where_clause); let mut variant_arms = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; - let maybe_reprc_attribute = use_discriminant.then(||item::get_maybe_reprc_attribute(input)).flatten(); + let maybe_reprc_attribute = use_discriminant + .then(|| item::get_maybe_reprc_attribute(input)) + .flatten(); let discriminants: Discriminants = Discriminants::new(&input.variants, maybe_reprc_attribute); let mut generics_output = deserialize::GenericsOutput::new(&generics); - let discriminant_type = discriminants.discriminant_type(); for (variant_idx, variant) in input.variants.iter().enumerate() { let variant_body = process_variant(variant, &cratename, &mut generics_output)?; diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new index 797634a49..5d92449f4 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 307 +assertion_line: 309 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for X { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new index 18c68ca95..f8711144c 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 325 +assertion_line: 327 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for X { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new index cd5486f4d..11e076179 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 342 +assertion_line: 344 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new index a0c55ef0f..25ca5624e 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 124 +assertion_line: 126 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for AA { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new index b3b159d1d..e0ff85b70 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 141 +assertion_line: 143 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for AAT { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new index a74352275..6f2e5df7f 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 193 +assertion_line: 195 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new index 2254a6a18..b9d83efa6 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 288 +assertion_line: 290 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for C diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new index 9422546ae..128a034d5 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 229 +assertion_line: 231 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new index 69c9096f3..111684baf 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 247 +assertion_line: 249 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new index 13701ca67..cc8edaffb 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 269 +assertion_line: 271 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new index 7d5d7ff75..70f2d671b 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 211 +assertion_line: 213 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new index c30bf243a..746154d91 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 159 +assertion_line: 161 expression: pretty_print_syn_str(&actual).unwrap() --- impl reexporter::borsh::de::BorshDeserialize for A { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new index 0f4eb9aa2..6f78895fe 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 176 +assertion_line: 178 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index 3b80ac32a..8ff88f2f2 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -1,16 +1,18 @@ -use core::convert::TryInto; use std::collections::HashMap; use std::convert::TryFrom; use proc_macro2::{Ident, TokenStream}; use quote::quote; -use syn::{parse::{Parse, ParseBuffer}, punctuated::Punctuated, token::{Comma, Type}, Path, Variant}; +use syn::{punctuated::Punctuated, token::Comma, Variant}; pub struct Discriminants((HashMap, syn::TypePath)); impl Discriminants { /// Calculates the discriminant that will be assigned by the compiler. /// See: https://doc.rust-lang.org/reference/items/enumerations.html#assigning-discriminant-values - pub fn new(variants: &Punctuated, mut maybe_discriminant_type: Option) -> Self { + pub fn new( + variants: &Punctuated, + maybe_discriminant_type: Option, + ) -> Self { let mut map = HashMap::new(); let mut next_discriminant_if_not_specified = quote! {0}; @@ -19,20 +21,18 @@ impl Discriminants { || quote! { #next_discriminant_if_not_specified }, |(_, e)| quote! { #e }, ); - + next_discriminant_if_not_specified = quote! { #this_discriminant + 1 }; map.insert(variant.ident.clone(), this_discriminant); } - let discriminant_type = maybe_discriminant_type.unwrap_or( - syn::parse_str("u8").expect("numeric") - ) - ; - + let discriminant_type = + maybe_discriminant_type.unwrap_or(syn::parse_str("u8").expect("numeric")); + Self((map, discriminant_type)) } pub fn discriminant_type(&self) -> &syn::TypePath { - &self.0.1 + &self.0 .1 } pub fn get( @@ -44,11 +44,15 @@ impl Discriminants { let variant_idx: u8 = u8::try_from(variant_idx).map_err(|err| { syn::Error::new( variant_ident.span(), - format!("up to {} enum variants are supported: {}", u8::MAX as usize + 1, err), + format!( + "up to {} enum variants are supported: {}", + u8::MAX as usize + 1, + err + ), ) })?; let result = if use_discriminant { - let discriminant_value = self.0.0.get(variant_ident).unwrap(); + let discriminant_value = self.0 .0.get(variant_ident).unwrap(); quote! { #discriminant_value } } else { quote! { #variant_idx } diff --git a/borsh-derive/src/internals/schema/enums/mod.rs b/borsh-derive/src/internals/schema/enums/mod.rs index 95bbed06b..c2a5fd787 100644 --- a/borsh-derive/src/internals/schema/enums/mod.rs +++ b/borsh-derive/src/internals/schema/enums/mod.rs @@ -36,7 +36,10 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut where_clause = generics::default_where(where_clause); let mut generics_output = schema::GenericsOutput::new(&generics); let use_discriminant = item::contains_use_discriminant(input)?; - let discriminants = Discriminants::new(&input.variants); + let maybe_reprc_attribute = use_discriminant + .then(|| item::get_maybe_reprc_attribute(input)) + .flatten(); + let discriminants = Discriminants::new(&input.variants, maybe_reprc_attribute); // Generate functions that return the schema for variants. let mut variants_defs = vec![]; @@ -128,6 +131,7 @@ fn process_variant( let variant_type = quote! { <#full_variant_ident #inner_struct_ty_generics as #cratename::BorshSchema> }; + let discriminant_type = discriminant_info.discriminants.discriminant_type().clone(); let discriminant_value = process_discriminant(&variant.ident, discriminant_info)?; Ok(VariantOutput { @@ -136,7 +140,7 @@ fn process_variant( #variant_type::add_definitions_recursively(definitions); }, variant_entry: quote! { - (u8::from(#discriminant_value) as i64, + (#discriminant_type::from(#discriminant_value) as i64, #variant_name.into(), #variant_type::declaration()) }, diff --git a/borsh-derive/src/internals/serialize/enums/mod.rs b/borsh-derive/src/internals/serialize/enums/mod.rs index ed92b1c67..528a754ff 100644 --- a/borsh-derive/src/internals/serialize/enums/mod.rs +++ b/borsh-derive/src/internals/serialize/enums/mod.rs @@ -17,7 +17,9 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut all_variants_idx_body = TokenStream2::new(); let mut fields_body = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; - let maybe_discriminant_type = use_discriminant.then(||item::get_maybe_reprc_attribute(input)).flatten(); + let maybe_discriminant_type = use_discriminant + .then(|| item::get_maybe_reprc_attribute(input)) + .flatten(); let discriminants = Discriminants::new(&input.variants, maybe_discriminant_type); let mut has_unit_variant = false; diff --git a/borsh/src/de/mod.rs b/borsh/src/de/mod.rs index 0f47b5020..1e81c5961 100644 --- a/borsh/src/de/mod.rs +++ b/borsh/src/de/mod.rs @@ -132,7 +132,18 @@ pub trait EnumExt: BorshDeserialize { /// # #[cfg(feature = "derive")] /// assert!(from_slice::(&data[..]).is_err()); /// ``` - fn deserialize_variant + ::core::convert::TryInto + Copy> (reader: &mut R, tag: Tag) -> Result; + fn deserialize_variant< + R: Read, + Tag: BorshDeserialize + + ::core::fmt::Debug + + Eq + + ::core::convert::TryInto + + ::core::convert::TryInto + + Copy, + >( + reader: &mut R, + tag: Tag, + ) -> Result; } fn unexpected_eof_to_unexpected_length_of_input(e: Error) -> Error { diff --git a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs index 60c62ff91..b80bb7166 100644 --- a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs +++ b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs @@ -40,30 +40,22 @@ fn test_discriminant_serde_no_unit_type() { } #[test] -pub fn u16_discriminat() { +pub fn u16_discriminant() { use borsh::{BorshSerialize, BorshDeserialize}; - #[derive(BorshSerialize, BorshDeserialize, Debug)] + #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] #[borsh(use_discriminant = true)] #[repr(u16)] - enum ZEnum { - AA = 42, - Z=2, - // A { a: u16, b: u64, d: bool, s: String } = 1u16, - // Z { a: u16, b: u64, d: bool, s: String } = 257u16, + enum U16Discriminant { + U8 { a: u16, } = 42, + U16 { b: u32, } = 666, } - let mut ss = vec![]; - ZEnum::AA.serialize(&mut ss).unwrap(); - assert!(ss[0] == 42); - assert!(ss[1] == 0); - // let s = Enum::A { - // a: 13, - // b: 42, - // d: true, - // s: "hello my bonny".to_string(), - // }; - // let mut buf = Vec::new(); - // s.serialize(&mut buf).expect("must serialize"); - // panic!("{:?}", buf); + let mut buf = vec![]; + let data = U16Discriminant::U16{ b: 1234567 }; + data.serialize(&mut buf).unwrap(); + assert_eq!(buf[0] , 154); + assert_eq!(buf[1] , 2); + let deserialized = U16Discriminant::deserialize(&mut buf.as_slice()).unwrap(); + assert_eq!(deserialized,data); } From 8914f066cc13257a615c4558031f3c5328dd439b Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sat, 26 Oct 2024 22:39:28 +0100 Subject: [PATCH 04/17] basic macro redesign --- .../src/internals/attributes/item/mod.rs | 77 +++++++++++++------ borsh-derive/src/internals/attributes/mod.rs | 4 +- .../src/internals/deserialize/enums/mod.rs | 6 +- .../src/internals/enum_discriminant.rs | 31 ++++++-- .../src/internals/schema/enums/mod.rs | 6 +- .../src/internals/serialize/enums/mod.rs | 4 +- 6 files changed, 88 insertions(+), 40 deletions(-) diff --git a/borsh-derive/src/internals/attributes/item/mod.rs b/borsh-derive/src/internals/attributes/item/mod.rs index d596d218b..c8573f21d 100644 --- a/borsh-derive/src/internals/attributes/item/mod.rs +++ b/borsh-derive/src/internals/attributes/item/mod.rs @@ -1,26 +1,28 @@ use crate::internals::attributes::{BORSH, CRATE, INIT, USE_DISCRIMINANT}; +use proc_macro2::Span; use quote::ToTokens; use syn::{spanned::Spanned, Attribute, DeriveInput, Error, Expr, ItemEnum, Path, TypePath}; -use super::{get_one_attribute, parsing, REPR}; +use super::{get_one_attribute, parsing, TAG_WIDTH}; pub fn check_attributes(derive_input: &DeriveInput) -> Result<(), Error> { let borsh = get_one_attribute(&derive_input.attrs)?; if let Some(attr) = borsh { attr.parse_nested_meta(|meta| { - if meta.path != USE_DISCRIMINANT && meta.path != INIT && meta.path != CRATE { + if meta.path != USE_DISCRIMINANT && meta.path != INIT && meta.path != CRATE && meta.path != TAG_WIDTH { return Err(syn::Error::new( meta.path.span(), - "`crate`, `use_discriminant` or `init` are the only supported attributes for `borsh`", + "`crate`, `use_discriminant`, `tag_width` or `init` are the only supported attributes for `borsh`", )); } - if meta.path == USE_DISCRIMINANT { + if meta.path == USE_DISCRIMINANT || meta.path == TAG_WIDTH { + let msg = if meta.path == USE_DISCRIMINANT { "borsh(use_discriminant=)"} else { "borsh(tag_width=)"}; let _expr: Expr = meta.value()?.parse()?; if let syn::Data::Struct(ref _data) = derive_input.data { return Err(syn::Error::new( derive_input.ident.span(), - "borsh(use_discriminant=) does not support structs", + format!("{msg} does not support structs"), )); } } else if meta.path == INIT || meta.path == CRATE { @@ -33,16 +35,8 @@ pub fn check_attributes(derive_input: &DeriveInput) -> Result<(), Error> { Ok(()) } -pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result { - const MAX_VARIANTS: usize = u16::MAX as usize + 1; - if input.variants.len() > MAX_VARIANTS { - return Err(syn::Error::new( - input.span(), - "up to {MAX_VARIANTS} enum variants are supported", - )); - } - - let attrs = &input.attrs; +pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result { + let attrs: &Vec = &input.attrs; let mut use_discriminant = None; let attr = attrs.iter().find(|attr| attr.path() == BORSH); if let Some(attr) = attr { @@ -81,14 +75,51 @@ pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result Option { - input - .attrs - .iter() - .find(|x| x.path() == REPR)? - .parse_args() - .ok() +// const MAX_VARIANTS: usize = u16::MAX as usize + 1; + // if input.variants.len() > MAX_VARIANTS { + // return Err(syn::Error::new( + // input.span(), + // "up to {MAX_VARIANTS} enum variants are supported", + // )); + // } +// /// Gets type of tag_witdh attribute if it exists +// pub(crate) fn get_maybe_borsh_tag_witdh_attribute(input: &ItemEnum) -> Option { +// input +// .attrs +// .iter() +// .find(|x| x.path() == TAG_WIDTH)? +// .parse_args() +// .ok() +// } + +pub(crate) fn get_maybe_borsh_tag_width(input: &ItemEnum) -> Result, syn::Error> { + let mut maybe_borsh_tag_width = None; + let attr = input.attrs.iter().find(|attr| attr.path() == BORSH); + let Some(attr) = attr else { + return Ok(None); + }; + + attr.parse_nested_meta(|meta| { + if meta.path == TAG_WIDTH { + let value_expr: Expr = meta.value()?.parse()?; + let value = value_expr.to_token_stream().to_string(); + let value = value.parse::().map_err(|_| { + syn::Error::new( + value_expr.span(), + "`tag_width` accepts only u8", + ) + })?; + if value > 8 { + return Err(syn::Error::new( + value_expr.span(), + "`tag_width` accepts only values from 0 to 8", + )); + } + maybe_borsh_tag_width= Some((value, value_expr.span())); + } + Ok(()) + })?; + Ok(maybe_borsh_tag_width) } pub(crate) fn contains_initialize_with(attrs: &[Attribute]) -> Result, Error> { diff --git a/borsh-derive/src/internals/attributes/mod.rs b/borsh-derive/src/internals/attributes/mod.rs index cc8ea1d4a..a79957591 100644 --- a/borsh-derive/src/internals/attributes/mod.rs +++ b/borsh-derive/src/internals/attributes/mod.rs @@ -29,7 +29,9 @@ pub const SERIALIZE_WITH: Symbol = Symbol("serialize_with", "serialize_with = .. pub const DESERIALIZE_WITH: Symbol = Symbol("deserialize_with", "deserialize_with = ..."); /// crate - sub-borsh nested meta, item-level only, `BorshSerialize`, `BorshDeserialize`, `BorshSchema` contexts pub const CRATE: Symbol = Symbol("crate", "crate = ..."); -pub const REPR: Symbol = Symbol("repr", "repr(...)"); + +/// tag_width - sub-borsh nested meta, item-level only attribute in `BorshSerialize`, `BorshDeserialize`, `BorshSchema` contexts +pub const TAG_WIDTH: Symbol = Symbol("tag_width", "tag_width = ..."); #[cfg(feature = "schema")] pub mod schema_keys { diff --git a/borsh-derive/src/internals/deserialize/enums/mod.rs b/borsh-derive/src/internals/deserialize/enums/mod.rs index 7a0f0dde5..2134882ef 100644 --- a/borsh-derive/src/internals/deserialize/enums/mod.rs +++ b/borsh-derive/src/internals/deserialize/enums/mod.rs @@ -11,10 +11,8 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut where_clause = generics::default_where(where_clause); let mut variant_arms = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; - let maybe_reprc_attribute = use_discriminant - .then(|| item::get_maybe_reprc_attribute(input)) - .flatten(); - let discriminants: Discriminants = Discriminants::new(&input.variants, maybe_reprc_attribute); + let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; + let discriminants: Discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width); let mut generics_output = deserialize::GenericsOutput::new(&generics); let discriminant_type = discriminants.discriminant_type(); for (variant_idx, variant) in input.variants.iter().enumerate() { diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index 8ff88f2f2..a9d9ac99b 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -1,8 +1,8 @@ use std::collections::HashMap; use std::convert::TryFrom; -use proc_macro2::{Ident, TokenStream}; -use quote::quote; +use proc_macro2::{Ident, Span, TokenStream}; +use quote::{quote, ToTokens}; use syn::{punctuated::Punctuated, token::Comma, Variant}; pub struct Discriminants((HashMap, syn::TypePath)); @@ -11,12 +11,19 @@ impl Discriminants { /// See: https://doc.rust-lang.org/reference/items/enumerations.html#assigning-discriminant-values pub fn new( variants: &Punctuated, - maybe_discriminant_type: Option, - ) -> Self { + maybe_borsh_tag_width: Option<(u8, Span)>, + ) -> syn::Result { let mut map = HashMap::new(); let mut next_discriminant_if_not_specified = quote! {0}; + let min_tag_width = variants.len().next_power_of_two().trailing_zeros(); + for variant in variants { + if let Some(discriminant) = variant.discriminant { + let value = discriminant.1.to_token_stream().to_string(); + let value = value.parse::().unwrap(); + + } let this_discriminant = variant.discriminant.clone().map_or_else( || quote! { #next_discriminant_if_not_specified }, |(_, e)| quote! { #e }, @@ -25,10 +32,24 @@ impl Discriminants { next_discriminant_if_not_specified = quote! { #this_discriminant + 1 }; map.insert(variant.ident.clone(), this_discriminant); } + + if let Some((borsh_tag_width, span)) = maybe_borsh_tag_width { + if borsh_tag_width < min_tag_width { + return Err(syn::Error::new( + span, + format!( + "borsh_tag_width={} is too small for the number of variants={}", + borsh_tag_width, + variants.len() + ), + )); + } + } + let discriminant_type = maybe_discriminant_type.unwrap_or(syn::parse_str("u8").expect("numeric")); - Self((map, discriminant_type)) + Ok(Self((map, discriminant_type))) } pub fn discriminant_type(&self) -> &syn::TypePath { diff --git a/borsh-derive/src/internals/schema/enums/mod.rs b/borsh-derive/src/internals/schema/enums/mod.rs index c2a5fd787..bfd7f9532 100644 --- a/borsh-derive/src/internals/schema/enums/mod.rs +++ b/borsh-derive/src/internals/schema/enums/mod.rs @@ -36,10 +36,8 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut where_clause = generics::default_where(where_clause); let mut generics_output = schema::GenericsOutput::new(&generics); let use_discriminant = item::contains_use_discriminant(input)?; - let maybe_reprc_attribute = use_discriminant - .then(|| item::get_maybe_reprc_attribute(input)) - .flatten(); - let discriminants = Discriminants::new(&input.variants, maybe_reprc_attribute); + let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; + let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width); // Generate functions that return the schema for variants. let mut variants_defs = vec![]; diff --git a/borsh-derive/src/internals/serialize/enums/mod.rs b/borsh-derive/src/internals/serialize/enums/mod.rs index 528a754ff..e4ecf419f 100644 --- a/borsh-derive/src/internals/serialize/enums/mod.rs +++ b/borsh-derive/src/internals/serialize/enums/mod.rs @@ -17,9 +17,7 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut all_variants_idx_body = TokenStream2::new(); let mut fields_body = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; - let maybe_discriminant_type = use_discriminant - .then(|| item::get_maybe_reprc_attribute(input)) - .flatten(); + let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; let discriminants = Discriminants::new(&input.variants, maybe_discriminant_type); let mut has_unit_variant = false; From 557e240050aca7e6d9d47894d40ac1b1c308b4a3 Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sat, 26 Oct 2024 23:27:25 +0100 Subject: [PATCH 05/17] very weird iterator --- .../src/internals/attributes/item/mod.rs | 25 +++-------- .../src/internals/deserialize/enums/mod.rs | 2 +- .../src/internals/enum_discriminant.rs | 42 ++++++++++++++++--- .../src/internals/serialize/enums/mod.rs | 2 +- .../test_init_in_deserialize.rs | 3 +- .../test_enum_discriminants.rs | 6 +++ 6 files changed, 51 insertions(+), 29 deletions(-) diff --git a/borsh-derive/src/internals/attributes/item/mod.rs b/borsh-derive/src/internals/attributes/item/mod.rs index c8573f21d..2538b2246 100644 --- a/borsh-derive/src/internals/attributes/item/mod.rs +++ b/borsh-derive/src/internals/attributes/item/mod.rs @@ -56,7 +56,7 @@ pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result Result MAX_VARIANTS { - // return Err(syn::Error::new( - // input.span(), - // "up to {MAX_VARIANTS} enum variants are supported", - // )); - // } -// /// Gets type of tag_witdh attribute if it exists -// pub(crate) fn get_maybe_borsh_tag_witdh_attribute(input: &ItemEnum) -> Option { -// input -// .attrs -// .iter() -// .find(|x| x.path() == TAG_WIDTH)? -// .parse_args() -// .ok() -// } - pub(crate) fn get_maybe_borsh_tag_width(input: &ItemEnum) -> Result, syn::Error> { let mut maybe_borsh_tag_width = None; let attr = input.attrs.iter().find(|attr| attr.path() == BORSH); @@ -116,6 +99,8 @@ pub(crate) fn get_maybe_borsh_tag_width(input: &ItemEnum) -> Result Result Result, Error> { if meta.path == CRATE { let value_expr: Path = parsing::parse_lit_into(BORSH, CRATE, &meta)?; res = Some(value_expr); - } else if meta.path == USE_DISCRIMINANT || meta.path == INIT { + } else if meta.path == USE_DISCRIMINANT || meta.path == INIT || meta.path == TAG_WIDTH { let _value_expr: Expr = meta.value()?.parse()?; } diff --git a/borsh-derive/src/internals/deserialize/enums/mod.rs b/borsh-derive/src/internals/deserialize/enums/mod.rs index 2134882ef..54bda9c89 100644 --- a/borsh-derive/src/internals/deserialize/enums/mod.rs +++ b/borsh-derive/src/internals/deserialize/enums/mod.rs @@ -12,7 +12,7 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut variant_arms = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; - let discriminants: Discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width); + let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width)?; let mut generics_output = deserialize::GenericsOutput::new(&generics); let discriminant_type = discriminants.discriminant_type(); for (variant_idx, variant) in input.variants.iter().enumerate() { diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index a9d9ac99b..4ed263021 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -1,3 +1,4 @@ +use core::convert::TryInto; use std::collections::HashMap; use std::convert::TryFrom; @@ -15,15 +16,25 @@ impl Discriminants { ) -> syn::Result { let mut map = HashMap::new(); let mut next_discriminant_if_not_specified = quote! {0}; + + fn bytes_needed(value: usize) -> usize { + let bits_needed = std::mem::size_of::() * 8 - value.leading_zeros() as usize; + (bits_needed + 7) / 8 + } - let min_tag_width = variants.len().next_power_of_two().trailing_zeros(); - + let min_tag_width: u8 = bytes_needed(variants.len()).try_into().expect("variants cannot be bigger u64"); + + let mut min = 0; + let mut max = 0; + for variant in variants { - if let Some(discriminant) = variant.discriminant { + if let Some(discriminant) = &variant.discriminant { let value = discriminant.1.to_token_stream().to_string(); let value = value.parse::().unwrap(); - + min = value.min(min); + max = value.max(max); } + let this_discriminant = variant.discriminant.clone().map_or_else( || quote! { #next_discriminant_if_not_specified }, |(_, e)| quote! { #e }, @@ -33,6 +44,10 @@ impl Discriminants { map.insert(variant.ident.clone(), this_discriminant); } + let min: u64 = min.abs().try_into().expect("variants cannot be bigger u64"); + let max: u64 = max.try_into().expect("variants cannot be bigger u64"); + let min_bytes: u8 = bytes_needed(min as usize).try_into().expect(""); + let max_bytes: u8 = bytes_needed(max as usize).try_into().expect(""); if let Some((borsh_tag_width, span)) = maybe_borsh_tag_width { if borsh_tag_width < min_tag_width { return Err(syn::Error::new( @@ -43,11 +58,26 @@ impl Discriminants { variants.len() ), )); - } + } } + eprintln!("min_bytes: {}, max_bytes: {}, min_tag_width: {}", min_bytes, max_bytes, min_tag_width); + let tag_with = maybe_borsh_tag_width.map(|(tag_width, _ )| tag_width ) + .unwrap_or_else(|| (min_bytes+ max_bytes).max(min_tag_width)); + + let tag_width_type = if tag_with <=1 { + "u8" + } else if tag_with <= 2 { + "u16" + } else if tag_with <= 4 { + "u32" + } else if tag_with <= 8 { + "u64" + } else { + unreachable!("we eliminated such error earlier") + }; let discriminant_type = - maybe_discriminant_type.unwrap_or(syn::parse_str("u8").expect("numeric")); + syn::parse_str(tag_width_type).expect("numeric"); Ok(Self((map, discriminant_type))) } diff --git a/borsh-derive/src/internals/serialize/enums/mod.rs b/borsh-derive/src/internals/serialize/enums/mod.rs index e4ecf419f..27830ebdc 100644 --- a/borsh-derive/src/internals/serialize/enums/mod.rs +++ b/borsh-derive/src/internals/serialize/enums/mod.rs @@ -18,7 +18,7 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut fields_body = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; - let discriminants = Discriminants::new(&input.variants, maybe_discriminant_type); + let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width)?; let mut has_unit_variant = false; for (variant_idx, variant) in input.variants.iter().enumerate() { diff --git a/borsh/tests/init_in_deserialize/test_init_in_deserialize.rs b/borsh/tests/init_in_deserialize/test_init_in_deserialize.rs index 652cfc923..95195dcb8 100644 --- a/borsh/tests/init_in_deserialize/test_init_in_deserialize.rs +++ b/borsh/tests/init_in_deserialize/test_init_in_deserialize.rs @@ -26,8 +26,9 @@ fn test_simple_struct() { assert_eq!(expected_a, decoded_a); } +//ASDF #[derive(BorshSerialize, BorshDeserialize, PartialEq, Debug)] -#[borsh(init=initialization_method)] +#[borsh(init = initialization_method)] enum AEnum { A, B, diff --git a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs index b80bb7166..69fcc26b4 100644 --- a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs +++ b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs @@ -3,6 +3,7 @@ use alloc::vec; use borsh::{from_slice, to_vec, BorshDeserialize, BorshSerialize}; // sequence, no unit enums +//ASDF #[derive(BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone, Copy, Debug)] #[borsh(use_discriminant = true)] #[repr(u16)] @@ -15,6 +16,7 @@ enum XY { F(u64), } +//ASDF #[derive(BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone, Copy, Debug)] #[borsh(use_discriminant = false)] #[repr(u16)] @@ -45,6 +47,7 @@ pub fn u16_discriminant() { #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] #[borsh(use_discriminant = true)] #[repr(u16)] + //ASDF enum U16Discriminant { U8 { a: u16, } = 42, U16 { b: u32, } = 666, @@ -78,6 +81,7 @@ fn test_discriminant_serde_no_unit_type_no_use_discriminant() { } } +//ASDF // minimal #[derive(BorshSerialize)] #[borsh(use_discriminant = true)] @@ -85,6 +89,7 @@ enum MyDiscriminantEnum { A = 20, } +//ASDF #[derive(BorshSerialize)] #[borsh(use_discriminant = false)] enum MyDiscriminantEnumFalse { @@ -111,6 +116,7 @@ fn test_discriminant_minimal_false() { assert_eq!(to_vec(&MyDiscriminantEnumFalse::A).unwrap(), vec![0]); } +//ASDF // sequence #[derive(BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone, Copy, Debug)] #[borsh(use_discriminant = false)] From 4b6cb92b53e4ab59e87edf6e673c599ebc5f29ab Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sat, 26 Oct 2024 23:30:30 +0100 Subject: [PATCH 06/17] in general works --- .../check_attrs_borsh_invalid_on_whole_item.snap.new | 8 ++++++++ .../check_attrs_borsh_skip_on_whole_item.snap.new | 8 ++++++++ .../check_attrs_init_function_wrong_format.snap.new | 8 ++++++++ .../enums/snapshots/borsh_discriminant_false.snap.new | 2 +- .../enums/snapshots/borsh_discriminant_true.snap.new | 2 +- .../deserialize/enums/snapshots/borsh_init_func.snap.new | 2 +- .../snapshots/borsh_skip_struct_variant_field.snap.new | 2 +- .../snapshots/borsh_skip_tuple_variant_field.snap.new | 2 +- .../deserialize/enums/snapshots/bound_generics.snap.new | 2 +- .../enums/snapshots/check_deserialize_with_attr.snap.new | 2 +- .../snapshots/generic_borsh_skip_struct_field.snap.new | 2 +- .../snapshots/generic_borsh_skip_tuple_field.snap.new | 2 +- .../enums/snapshots/generic_deserialize_bound.snap.new | 2 +- .../deserialize/enums/snapshots/recursive_enum.snap.new | 2 +- .../snapshots/simple_enum_with_custom_crate.snap.new | 2 +- .../deserialize/enums/snapshots/simple_generics.snap.new | 2 +- .../tests/init_in_deserialize/test_init_in_deserialize.rs | 1 - .../requires_derive_category/test_enum_discriminants.rs | 5 +---- 18 files changed, 38 insertions(+), 18 deletions(-) create mode 100644 borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new create mode 100644 borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new create mode 100644 borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new new file mode 100644 index 000000000..0f8694bee --- /dev/null +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new @@ -0,0 +1,8 @@ +--- +source: borsh-derive/src/internals/attributes/item/mod.rs +assertion_line: 243 +expression: actual.unwrap_err() +--- +Error( + "`crate`, `use_discriminant`, `tag_width` or `init` are the only supported attributes for `borsh`", +) diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new new file mode 100644 index 000000000..1bdc9a4dc --- /dev/null +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new @@ -0,0 +1,8 @@ +--- +source: borsh-derive/src/internals/attributes/item/mod.rs +assertion_line: 229 +expression: actual.unwrap_err() +--- +Error( + "`crate`, `use_discriminant`, `tag_width` or `init` are the only supported attributes for `borsh`", +) diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new new file mode 100644 index 000000000..680a9c864 --- /dev/null +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new @@ -0,0 +1,8 @@ +--- +source: borsh-derive/src/internals/attributes/item/mod.rs +assertion_line: 328 +expression: actual.unwrap_err() +--- +Error( + "`crate`, `use_discriminant`, `tag_width` or `init` are the only supported attributes for `borsh`", +) diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new index 5d92449f4..48a81d477 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 309 +assertion_line: 306 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for X { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new index f8711144c..95136ffce 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 327 +assertion_line: 324 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for X { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new index 11e076179..483efecff 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 344 +assertion_line: 341 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new index 25ca5624e..b1a3b4b2d 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 126 +assertion_line: 123 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for AA { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new index e0ff85b70..f73a2f220 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 143 +assertion_line: 140 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for AAT { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new index 6f2e5df7f..fc06f63d3 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 195 +assertion_line: 192 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new index b9d83efa6..ca75637d3 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 290 +assertion_line: 287 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for C diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new index 128a034d5..f5ec8bd9b 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 231 +assertion_line: 228 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new index 111684baf..251e9b027 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 249 +assertion_line: 246 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new index cc8edaffb..f85be3e73 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 271 +assertion_line: 268 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new index 70f2d671b..fbc4ed72b 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 213 +assertion_line: 210 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new index 746154d91..b5b16ef79 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 161 +assertion_line: 158 expression: pretty_print_syn_str(&actual).unwrap() --- impl reexporter::borsh::de::BorshDeserialize for A { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new index 6f78895fe..d4a71b159 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 178 +assertion_line: 175 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh/tests/init_in_deserialize/test_init_in_deserialize.rs b/borsh/tests/init_in_deserialize/test_init_in_deserialize.rs index 95195dcb8..1941bc0dc 100644 --- a/borsh/tests/init_in_deserialize/test_init_in_deserialize.rs +++ b/borsh/tests/init_in_deserialize/test_init_in_deserialize.rs @@ -26,7 +26,6 @@ fn test_simple_struct() { assert_eq!(expected_a, decoded_a); } -//ASDF #[derive(BorshSerialize, BorshDeserialize, PartialEq, Debug)] #[borsh(init = initialization_method)] enum AEnum { diff --git a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs index 69fcc26b4..b1b82f937 100644 --- a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs +++ b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs @@ -3,7 +3,6 @@ use alloc::vec; use borsh::{from_slice, to_vec, BorshDeserialize, BorshSerialize}; // sequence, no unit enums -//ASDF #[derive(BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone, Copy, Debug)] #[borsh(use_discriminant = true)] #[repr(u16)] @@ -16,7 +15,6 @@ enum XY { F(u64), } -//ASDF #[derive(BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone, Copy, Debug)] #[borsh(use_discriminant = false)] #[repr(u16)] @@ -46,8 +44,7 @@ pub fn u16_discriminant() { use borsh::{BorshSerialize, BorshDeserialize}; #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] #[borsh(use_discriminant = true)] - #[repr(u16)] - //ASDF + #[repr(u32)] enum U16Discriminant { U8 { a: u16, } = 42, U16 { b: u32, } = 666, From df34e73624c587ce3778398a171e4c82d3ebfece Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 27 Oct 2024 18:12:41 +0000 Subject: [PATCH 07/17] testing --- .../src/internals/attributes/item/mod.rs | 28 ++++++++------- .../src/internals/enum_discriminant.rs | 36 +++++++++++-------- .../test_enum_discriminants.rs | 34 +++++++++++++----- 3 files changed, 63 insertions(+), 35 deletions(-) diff --git a/borsh-derive/src/internals/attributes/item/mod.rs b/borsh-derive/src/internals/attributes/item/mod.rs index 2538b2246..d0f82e846 100644 --- a/borsh-derive/src/internals/attributes/item/mod.rs +++ b/borsh-derive/src/internals/attributes/item/mod.rs @@ -35,7 +35,7 @@ pub fn check_attributes(derive_input: &DeriveInput) -> Result<(), Error> { Ok(()) } -pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result { +pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result { let attrs: &Vec = &input.attrs; let mut use_discriminant = None; let attr = attrs.iter().find(|attr| attr.path() == BORSH); @@ -75,31 +75,34 @@ pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result Result, syn::Error> { +pub(crate) fn get_maybe_borsh_tag_width( + input: &ItemEnum, +) -> Result, syn::Error> { let mut maybe_borsh_tag_width = None; let attr = input.attrs.iter().find(|attr| attr.path() == BORSH); let Some(attr) = attr else { return Ok(None); }; - attr.parse_nested_meta(|meta| { + attr.parse_nested_meta(|meta| { if meta.path == TAG_WIDTH { let value_expr: Expr = meta.value()?.parse()?; let value = value_expr.to_token_stream().to_string(); - let value = value.parse::().map_err(|_| { - syn::Error::new( - value_expr.span(), - "`tag_width` accepts only u8", - ) - })?; + let value = value + .parse::() + .map_err(|_| syn::Error::new(value_expr.span(), "`tag_width` accepts only u8"))?; if value > 8 { return Err(syn::Error::new( value_expr.span(), "`tag_width` accepts only values from 0 to 8", )); } - maybe_borsh_tag_width= Some((value, value_expr.span())); - } else if meta.path == INIT || meta.path == CRATE || meta.path == TAG_WIDTH || meta.path == USE_DISCRIMINANT { + maybe_borsh_tag_width = Some((value, value_expr.span())); + } else if meta.path == INIT + || meta.path == CRATE + || meta.path == TAG_WIDTH + || meta.path == USE_DISCRIMINANT + { let _value_expr: Expr = meta.value()?.parse()?; } Ok(()) @@ -115,7 +118,8 @@ pub(crate) fn contains_initialize_with(attrs: &[Attribute]) -> Result, syn::TypePath)); impl Discriminants { @@ -16,24 +16,26 @@ impl Discriminants { ) -> syn::Result { let mut map = HashMap::new(); let mut next_discriminant_if_not_specified = quote! {0}; - + fn bytes_needed(value: usize) -> usize { let bits_needed = std::mem::size_of::() * 8 - value.leading_zeros() as usize; (bits_needed + 7) / 8 } - let min_tag_width: u8 = bytes_needed(variants.len()).try_into().expect("variants cannot be bigger u64"); - + let min_tag_width: u8 = bytes_needed(variants.len()) + .try_into() + .expect("variants cannot be bigger u64"); + let mut min = 0; let mut max = 0; - + for variant in variants { if let Some(discriminant) = &variant.discriminant { let value = discriminant.1.to_token_stream().to_string(); let value = value.parse::().unwrap(); min = value.min(min); max = value.max(max); - } + } let this_discriminant = variant.discriminant.clone().map_or_else( || quote! { #next_discriminant_if_not_specified }, @@ -46,7 +48,12 @@ impl Discriminants { let min: u64 = min.abs().try_into().expect("variants cannot be bigger u64"); let max: u64 = max.try_into().expect("variants cannot be bigger u64"); - let min_bytes: u8 = bytes_needed(min as usize).try_into().expect(""); + if min > 0 { + return Err(syn::Error::new( + variants.span(), + "negative variants are not supported, please write manual impl", + )); + } let max_bytes: u8 = bytes_needed(max as usize).try_into().expect(""); if let Some((borsh_tag_width, span)) = maybe_borsh_tag_width { if borsh_tag_width < min_tag_width { @@ -58,14 +65,14 @@ impl Discriminants { variants.len() ), )); - } + } } - eprintln!("min_bytes: {}, max_bytes: {}, min_tag_width: {}", min_bytes, max_bytes, min_tag_width); - let tag_with = maybe_borsh_tag_width.map(|(tag_width, _ )| tag_width ) - .unwrap_or_else(|| (min_bytes+ max_bytes).max(min_tag_width)); - - let tag_width_type = if tag_with <=1 { + let tag_with = maybe_borsh_tag_width + .map(|(tag_width, _)| tag_width) + .unwrap_or_else(|| (max_bytes).max(min_tag_width)); + + let tag_width_type = if tag_with <= 1 { "u8" } else if tag_with <= 2 { "u16" @@ -76,8 +83,7 @@ impl Discriminants { } else { unreachable!("we eliminated such error earlier") }; - let discriminant_type = - syn::parse_str(tag_width_type).expect("numeric"); + let discriminant_type = syn::parse_str(tag_width_type).expect("numeric"); Ok(Self((map, discriminant_type))) } diff --git a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs index b1b82f937..eb6bac6ca 100644 --- a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs +++ b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs @@ -40,22 +40,40 @@ fn test_discriminant_serde_no_unit_type() { } #[test] -pub fn u16_discriminant() { - use borsh::{BorshSerialize, BorshDeserialize}; +pub fn u16_discriminant() { + use borsh::{BorshDeserialize, BorshSerialize}; #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] #[borsh(use_discriminant = true)] #[repr(u32)] enum U16Discriminant { - U8 { a: u16, } = 42, - U16 { b: u32, } = 666, + U8 { a: u16 } = 42, + U16 { b: u32 } = 666, } let mut buf = vec![]; - let data = U16Discriminant::U16{ b: 1234567 }; + let data = U16Discriminant::U16 { b: 1234567 }; data.serialize(&mut buf).unwrap(); - assert_eq!(buf[0] , 154); - assert_eq!(buf[1] , 2); + assert_eq!(buf[0], 154); + assert_eq!(buf[1], 2); let deserialized = U16Discriminant::deserialize(&mut buf.as_slice()).unwrap(); - assert_eq!(deserialized,data); + assert_eq!(deserialized, data); +} + +#[test] +pub fn u32_discriminant() { + use borsh::{BorshDeserialize, BorshSerialize}; + #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] + #[borsh(use_discriminant = true)] + enum U32Discriminant { + U8 { a: u16 } = 42, + U32 { b: u32 } = u32::MAX, + } + let mut buf = vec![]; + let data = U16Discriminant::U16 { b: 1234567 }; + data.serialize(&mut buf).unwrap(); + assert_eq!(buf[0], 154); + assert_eq!(buf[1], 2); + let deserialized = U16Discriminant::deserialize(&mut buf.as_slice()).unwrap(); + assert_eq!(deserialized, data); } From 0c2b17eccf665c73a6cc2620091837c966cd1d3e Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 3 Nov 2024 12:57:01 +0000 Subject: [PATCH 08/17] stash --- .../src/internals/attributes/item/mod.rs | 12 +++++- ...attrs_borsh_invalid_on_whole_item.snap.new | 2 +- ...ck_attrs_borsh_skip_on_whole_item.snap.new | 2 +- ..._attrs_init_function_wrong_format.snap.new | 2 +- borsh-derive/src/internals/attributes/mod.rs | 2 + .../src/internals/enum_discriminant.rs | 41 +++++-------------- .../test_enum_discriminants.rs | 8 ++-- 7 files changed, 32 insertions(+), 37 deletions(-) diff --git a/borsh-derive/src/internals/attributes/item/mod.rs b/borsh-derive/src/internals/attributes/item/mod.rs index d0f82e846..b52f04b47 100644 --- a/borsh-derive/src/internals/attributes/item/mod.rs +++ b/borsh-derive/src/internals/attributes/item/mod.rs @@ -3,7 +3,7 @@ use proc_macro2::Span; use quote::ToTokens; use syn::{spanned::Spanned, Attribute, DeriveInput, Error, Expr, ItemEnum, Path, TypePath}; -use super::{get_one_attribute, parsing, TAG_WIDTH}; +use super::{get_one_attribute, parsing, RUST_REPR, TAG_WIDTH}; pub fn check_attributes(derive_input: &DeriveInput) -> Result<(), Error> { let borsh = get_one_attribute(&derive_input.attrs)?; @@ -75,6 +75,16 @@ pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result Result, syn::Error> { + inpute + .attrs + .iter() + .find(|attr| attr.path() == RUST_REPR) + .map(|attr| attr.parse_args::().map(|value| (attr, value))) + .transpose() + .map(|(attr, value)| value.map(|value| (value, attr.unwrap().span()))) +} + pub(crate) fn get_maybe_borsh_tag_width( input: &ItemEnum, ) -> Result, syn::Error> { diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new index 0f8694bee..8fa731ca6 100644 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/attributes/item/mod.rs -assertion_line: 243 +assertion_line: 247 expression: actual.unwrap_err() --- Error( diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new index 1bdc9a4dc..564043c35 100644 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/attributes/item/mod.rs -assertion_line: 229 +assertion_line: 233 expression: actual.unwrap_err() --- Error( diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new index 680a9c864..a55fa171c 100644 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/attributes/item/mod.rs -assertion_line: 328 +assertion_line: 332 expression: actual.unwrap_err() --- Error( diff --git a/borsh-derive/src/internals/attributes/mod.rs b/borsh-derive/src/internals/attributes/mod.rs index a79957591..cf97228cf 100644 --- a/borsh-derive/src/internals/attributes/mod.rs +++ b/borsh-derive/src/internals/attributes/mod.rs @@ -33,6 +33,8 @@ pub const CRATE: Symbol = Symbol("crate", "crate = ..."); /// tag_width - sub-borsh nested meta, item-level only attribute in `BorshSerialize`, `BorshDeserialize`, `BorshSchema` contexts pub const TAG_WIDTH: Symbol = Symbol("tag_width", "tag_width = ..."); +pub const RUST_REPR: Symbol = Symbol("repr", "repr(...)"); + #[cfg(feature = "schema")] pub mod schema_keys { use super::Symbol; diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index 7e1b0e330..e67e81a45 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -1,3 +1,8 @@ +//! +//! Algorithm of finding out tag width: +//! 1. Rust `repr(...)` and `borsh(tag_width = ...) attributes are read +//! 2. If repr is signed, transparent or variable with *size, borsh errors with unsupported +//! 2.1. NOTE: signed to be supported use core::convert::TryInto; use std::collections::HashMap; use std::convert::TryFrom; @@ -17,26 +22,11 @@ impl Discriminants { let mut map = HashMap::new(); let mut next_discriminant_if_not_specified = quote! {0}; - fn bytes_needed(value: usize) -> usize { - let bits_needed = std::mem::size_of::() * 8 - value.leading_zeros() as usize; - (bits_needed + 7) / 8 - } - let min_tag_width: u8 = bytes_needed(variants.len()) .try_into() .expect("variants cannot be bigger u64"); - let mut min = 0; - let mut max = 0; - for variant in variants { - if let Some(discriminant) = &variant.discriminant { - let value = discriminant.1.to_token_stream().to_string(); - let value = value.parse::().unwrap(); - min = value.min(min); - max = value.max(max); - } - let this_discriminant = variant.discriminant.clone().map_or_else( || quote! { #next_discriminant_if_not_specified }, |(_, e)| quote! { #e }, @@ -46,15 +36,6 @@ impl Discriminants { map.insert(variant.ident.clone(), this_discriminant); } - let min: u64 = min.abs().try_into().expect("variants cannot be bigger u64"); - let max: u64 = max.try_into().expect("variants cannot be bigger u64"); - if min > 0 { - return Err(syn::Error::new( - variants.span(), - "negative variants are not supported, please write manual impl", - )); - } - let max_bytes: u8 = bytes_needed(max as usize).try_into().expect(""); if let Some((borsh_tag_width, span)) = maybe_borsh_tag_width { if borsh_tag_width < min_tag_width { return Err(syn::Error::new( @@ -68,17 +49,17 @@ impl Discriminants { } } - let tag_with = maybe_borsh_tag_width + let tag_width = maybe_borsh_tag_width .map(|(tag_width, _)| tag_width) - .unwrap_or_else(|| (max_bytes).max(min_tag_width)); + .unwrap_or_else(|| (1).max(min_tag_width)); - let tag_width_type = if tag_with <= 1 { + let tag_width_type = if tag_width <= 1 { "u8" - } else if tag_with <= 2 { + } else if tag_width <= 2 { "u16" - } else if tag_with <= 4 { + } else if tag_width <= 4 { "u32" - } else if tag_with <= 8 { + } else if tag_width <= 8 { "u64" } else { unreachable!("we eliminated such error earlier") diff --git a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs index eb6bac6ca..9b3065e7f 100644 --- a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs +++ b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs @@ -54,6 +54,7 @@ pub fn u16_discriminant() { data.serialize(&mut buf).unwrap(); assert_eq!(buf[0], 154); assert_eq!(buf[1], 2); + assert!(buf.len(), 2); let deserialized = U16Discriminant::deserialize(&mut buf.as_slice()).unwrap(); assert_eq!(deserialized, data); } @@ -63,16 +64,17 @@ pub fn u32_discriminant() { use borsh::{BorshDeserialize, BorshSerialize}; #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] #[borsh(use_discriminant = true)] + #[repr(u32)] enum U32Discriminant { - U8 { a: u16 } = 42, + U8 { a: u16 } = 42u32, U32 { b: u32 } = u32::MAX, } let mut buf = vec![]; - let data = U16Discriminant::U16 { b: 1234567 }; + let data = U32Discriminant::U32 { b: 1234567 }; data.serialize(&mut buf).unwrap(); assert_eq!(buf[0], 154); assert_eq!(buf[1], 2); - let deserialized = U16Discriminant::deserialize(&mut buf.as_slice()).unwrap(); + let deserialized = U32Discriminant::deserialize(&mut buf.as_slice()).unwrap(); assert_eq!(deserialized, data); } From 58b8b146ada41cb84af14e5b0726c0d5ab391705 Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 3 Nov 2024 14:22:22 +0000 Subject: [PATCH 09/17] flush --- borsh-derive/src/internals/enum_discriminant.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index e67e81a45..b2ca7a656 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -1,8 +1,3 @@ -//! -//! Algorithm of finding out tag width: -//! 1. Rust `repr(...)` and `borsh(tag_width = ...) attributes are read -//! 2. If repr is signed, transparent or variable with *size, borsh errors with unsupported -//! 2.1. NOTE: signed to be supported use core::convert::TryInto; use std::collections::HashMap; use std::convert::TryFrom; From de5f32f1bebf60cc6b2ce1f72eae4ec05fea99e1 Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 3 Nov 2024 21:42:41 +0000 Subject: [PATCH 10/17] so we are backward compatible --- Cargo.toml | 1 + .../src/internals/attributes/item/mod.rs | 15 ++- ...attrs_borsh_invalid_on_whole_item.snap.new | 2 +- ...ck_attrs_borsh_skip_on_whole_item.snap.new | 2 +- ..._attrs_init_function_wrong_format.snap.new | 2 +- .../src/internals/deserialize/enums/mod.rs | 52 ++++---- .../borsh_discriminant_false.snap.new | 105 ++++++---------- .../borsh_discriminant_true.snap.new | 105 ++++++---------- .../enums/snapshots/borsh_init_func.snap.new | 106 ++++++---------- .../borsh_skip_struct_variant_field.snap.new | 58 +++++---- .../borsh_skip_tuple_variant_field.snap.new | 58 +++++---- .../enums/snapshots/bound_generics.snap.new | 59 +++++---- .../check_deserialize_with_attr.snap.new | 59 +++++---- .../generic_borsh_skip_struct_field.snap.new | 59 +++++---- .../generic_borsh_skip_tuple_field.snap.new | 59 +++++---- .../generic_deserialize_bound.snap.new | 59 +++++---- .../enums/snapshots/recursive_enum.snap.new | 59 +++++---- .../simple_enum_with_custom_crate.snap.new | 60 ++++----- .../enums/snapshots/simple_generics.snap.new | 59 +++++---- .../src/internals/enum_discriminant.rs | 118 +++++++++++------- .../src/internals/schema/enums/mod.rs | 5 +- .../src/internals/serialize/enums/mod.rs | 5 +- borsh/src/de/mod.rs | 13 +- .../test_enum_discriminants.rs | 79 ++++++------ 24 files changed, 547 insertions(+), 652 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 82020ecb9..1e86dc9ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,4 +4,5 @@ members = ["borsh", "borsh-derive", "fuzz/fuzz-run", "benchmarks"] [workspace.package] # shared version of all public crates in the workspace version = "1.5.1" +# rust-version = "1.67.0" rust-version = "1.81.0" diff --git a/borsh-derive/src/internals/attributes/item/mod.rs b/borsh-derive/src/internals/attributes/item/mod.rs index b52f04b47..c509a6d85 100644 --- a/borsh-derive/src/internals/attributes/item/mod.rs +++ b/borsh-derive/src/internals/attributes/item/mod.rs @@ -36,6 +36,12 @@ pub fn check_attributes(derive_input: &DeriveInput) -> Result<(), Error> { } pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result { + if input.variants.len() > 256 { + return Err(syn::Error::new( + input.span(), + "up to 256 enum variants are supported", + )); + } let attrs: &Vec = &input.attrs; let mut use_discriminant = None; let attr = attrs.iter().find(|attr| attr.path() == BORSH); @@ -75,14 +81,13 @@ pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result Result, syn::Error> { - inpute +pub(crate) fn get_maybe_rust_repr(input: &ItemEnum) -> Option<(TypePath, Span)> { + input .attrs .iter() .find(|attr| attr.path() == RUST_REPR) - .map(|attr| attr.parse_args::().map(|value| (attr, value))) - .transpose() - .map(|(attr, value)| value.map(|value| (value, attr.unwrap().span()))) + .map(|attr| attr.parse_args::().map(|value| (attr, value)).unwrap()) + .map(|(attr, value)| (value, attr.span())) } pub(crate) fn get_maybe_borsh_tag_width( diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new index 8fa731ca6..2df21661a 100644 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/attributes/item/mod.rs -assertion_line: 247 +assertion_line: 262 expression: actual.unwrap_err() --- Error( diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new index 564043c35..8c6579af7 100644 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/attributes/item/mod.rs -assertion_line: 233 +assertion_line: 248 expression: actual.unwrap_err() --- Error( diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new index a55fa171c..d89523db6 100644 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/attributes/item/mod.rs -assertion_line: 332 +assertion_line: 347 expression: actual.unwrap_err() --- Error( diff --git a/borsh-derive/src/internals/deserialize/enums/mod.rs b/borsh-derive/src/internals/deserialize/enums/mod.rs index 54bda9c89..8a65c26c1 100644 --- a/borsh-derive/src/internals/deserialize/enums/mod.rs +++ b/borsh-derive/src/internals/deserialize/enums/mod.rs @@ -12,22 +12,17 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut variant_arms = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; - let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width)?; + let maybe_rust_repr = item::get_maybe_rust_repr(input); + let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width, maybe_rust_repr, use_discriminant)?; let mut generics_output = deserialize::GenericsOutput::new(&generics); let discriminant_type = discriminants.discriminant_type(); for (variant_idx, variant) in input.variants.iter().enumerate() { let variant_body = process_variant(variant, &cratename, &mut generics_output)?; let variant_ident = &variant.ident; - let discriminant_value = discriminants.get(variant_ident, use_discriminant, variant_idx)?; + let discriminant_value = discriminants.get(variant_ident, variant_idx)?; variant_arms.extend(quote! { - if TryInto::<(#discriminant_type)>::try_into(variant_tag).map_err(|_| - return #cratename::io::Error::new( - #cratename::io::ErrorKind::InvalidData, - #cratename::__private::maybestd::format!("Unexpected variant tag: {:?}", variant_tag), - ) - )? - == #discriminant_value { #name::#variant_ident #variant_body } else + if variant_tag == #discriminant_value { #name::#variant_ident #variant_body } else }); } let init = if let Some(method_ident) = item::contains_initialize_with(&input.attrs)? { @@ -39,36 +34,35 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { }; generics_output.extend(&mut where_clause, &cratename); - let x = quote! { + let deserialize_variant = quote! { + let mut return_value = + #variant_arms { + return Err(#cratename::io::Error::new( + #cratename::io::ErrorKind::InvalidData, + #cratename::__private::maybestd::format!("Unexpected variant tag: {:?}", variant_tag), + )) + }; + #init + Ok(return_value) + }; + + Ok(quote! { impl #impl_generics #cratename::de::BorshDeserialize for #name #ty_generics #where_clause { fn deserialize_reader<__R: #cratename::io::Read>(reader: &mut __R) -> ::core::result::Result { - let tag = <#discriminant_type as #cratename::de::BorshDeserialize>::deserialize_reader(reader)?; - ::deserialize_variant::<_, #discriminant_type>(reader, tag) + let variant_tag = <#discriminant_type as #cratename::de::BorshDeserialize>::deserialize_reader(reader)?; + #deserialize_variant } } impl #impl_generics #cratename::de::EnumExt for #name #ty_generics #where_clause { - fn deserialize_variant<__R: #cratename::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy - >( + fn deserialize_variant<__R: #cratename::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = - #variant_arms { - return Err(#cratename::io::Error::new( - #cratename::io::ErrorKind::InvalidData, - #cratename::__private::maybestd::format!("Unexpected variant tag: {:?}", variant_tag), - )) - }; - #init - Ok(return_value) + #deserialize_variant } } - }; - Ok(x) + }) } fn process_variant( diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new index 48a81d477..563b04198 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new @@ -1,91 +1,56 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 306 +assertion_line: 300 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for X { fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + X::A + } else if variant_tag == 1u8 { + X::B + } else if variant_tag == 2u8 { + X::C + } else if variant_tag == 3u8 { + X::D + } else if variant_tag == 4u8 { + X::E + } else if variant_tag == 5u8 { + X::F + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for X { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { X::A - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { X::B - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 2u8 - { + } else if variant_tag == 2u8 { X::C - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 3u8 - { + } else if variant_tag == 3u8 { X::D - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 4u8 - { + } else if variant_tag == 4u8 { X::E - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 5u8 - { + } else if variant_tag == 5u8 { X::F } else { return Err( diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new index 95136ffce..8d17b1221 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new @@ -1,91 +1,56 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 324 +assertion_line: 318 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for X { fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0 { + X::A + } else if variant_tag == 20 { + X::B + } else if variant_tag == 20 + 1 { + X::C + } else if variant_tag == 20 + 1 + 1 { + X::D + } else if variant_tag == 10 { + X::E + } else if variant_tag == 10 + 1 { + X::F + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for X { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0 - { + let mut return_value = if variant_tag == 0 { X::A - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 20 - { + } else if variant_tag == 20 { X::B - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 20 + 1 - { + } else if variant_tag == 20 + 1 { X::C - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 20 + 1 + 1 - { + } else if variant_tag == 20 + 1 + 1 { X::D - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 10 - { + } else if variant_tag == 10 { X::E - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 10 + 1 - { + } else if variant_tag == 10 + 1 { X::F } else { return Err( diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new index 483efecff..485ec3bc7 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new @@ -1,91 +1,57 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 341 +assertion_line: 335 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A { fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::A + } else if variant_tag == 1u8 { + A::B + } else if variant_tag == 2u8 { + A::C + } else if variant_tag == 3u8 { + A::D + } else if variant_tag == 4u8 { + A::E + } else if variant_tag == 5u8 { + A::F + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + return_value.initialization_method(); + Ok(return_value) } } impl borsh::de::EnumExt for A { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { A::A - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { A::B - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 2u8 - { + } else if variant_tag == 2u8 { A::C - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 3u8 - { + } else if variant_tag == 3u8 { A::D - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 4u8 - { + } else if variant_tag == 4u8 { A::E - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 5u8 - { + } else if variant_tag == 5u8 { A::F } else { return Err( diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new index b1a3b4b2d..55b39b636 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new @@ -1,50 +1,48 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 123 +assertion_line: 117 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for AA { fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + AA::B { + c: core::default::Default::default(), + d: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + AA::NegatedVariant { + beta: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for AA { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { AA::B { c: core::default::Default::default(), d: borsh::BorshDeserialize::deserialize_reader(reader)?, } - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { AA::NegatedVariant { beta: borsh::BorshDeserialize::deserialize_reader(reader)?, } diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new index f73a2f220..e3b91c361 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new @@ -1,50 +1,48 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 140 +assertion_line: 134 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for AAT { fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + AAT::B( + core::default::Default::default(), + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else if variant_tag == 1u8 { + AAT::NegatedVariant { + beta: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for AAT { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { AAT::B( core::default::Default::default(), borsh::BorshDeserialize::deserialize_reader(reader)?, ) - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { AAT::NegatedVariant { beta: borsh::BorshDeserialize::deserialize_reader(reader)?, } diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new index fc06f63d3..74aa01e12 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 192 +assertion_line: 186 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A @@ -13,8 +13,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A @@ -24,39 +46,16 @@ where V: borsh::de::BorshDeserialize, U: borsh::de::BorshDeserialize, { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { A::B { x: borsh::BorshDeserialize::deserialize_reader(reader)?, y: borsh::BorshDeserialize::deserialize_reader(reader)?, } - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { A::C( borsh::BorshDeserialize::deserialize_reader(reader)?, borsh::BorshDeserialize::deserialize_reader(reader)?, diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new index ca75637d3..d3436e453 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 287 +assertion_line: 281 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for C @@ -11,8 +11,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + C::C3( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else if variant_tag == 1u8 { + C::C4 { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: third_party_impl::deserialize_third_party(reader)?, + } + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for C @@ -20,39 +42,16 @@ where K: borsh::de::BorshDeserialize, V: borsh::de::BorshDeserialize, { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { C::C3( borsh::BorshDeserialize::deserialize_reader(reader)?, borsh::BorshDeserialize::deserialize_reader(reader)?, ) - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { C::C4 { x: borsh::BorshDeserialize::deserialize_reader(reader)?, y: third_party_impl::deserialize_third_party(reader)?, diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new index f5ec8bd9b..86068606b 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 228 +assertion_line: 222 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A @@ -14,8 +14,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::B { + x: core::default::Default::default(), + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A @@ -26,39 +48,16 @@ where K: core::default::Default, V: core::default::Default, { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { A::B { x: core::default::Default::default(), y: borsh::BorshDeserialize::deserialize_reader(reader)?, } - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { A::C( borsh::BorshDeserialize::deserialize_reader(reader)?, borsh::BorshDeserialize::deserialize_reader(reader)?, diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new index 251e9b027..49399f5bd 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 246 +assertion_line: 240 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A @@ -13,8 +13,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + core::default::Default::default(), + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A @@ -24,39 +46,16 @@ where V: borsh::de::BorshDeserialize, U: core::default::Default, { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { A::B { x: borsh::BorshDeserialize::deserialize_reader(reader)?, y: borsh::BorshDeserialize::deserialize_reader(reader)?, } - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { A::C( borsh::BorshDeserialize::deserialize_reader(reader)?, core::default::Default::default(), diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new index f85be3e73..fe5ca6bd6 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 268 +assertion_line: 262 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A @@ -11,8 +11,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::C { + a: borsh::BorshDeserialize::deserialize_reader(reader)?, + b: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::D( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A @@ -20,39 +42,16 @@ where T: PartialOrd + Hash + Eq + borsh::de::BorshDeserialize, U: borsh::de::BorshDeserialize, { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { A::C { a: borsh::BorshDeserialize::deserialize_reader(reader)?, b: borsh::BorshDeserialize::deserialize_reader(reader)?, } - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { A::D( borsh::BorshDeserialize::deserialize_reader(reader)?, borsh::BorshDeserialize::deserialize_reader(reader)?, diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new index fbc4ed72b..b306b012f 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 210 +assertion_line: 204 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A @@ -12,8 +12,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A @@ -22,39 +44,16 @@ where K: borsh::de::BorshDeserialize, V: borsh::de::BorshDeserialize, { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { A::B { x: borsh::BorshDeserialize::deserialize_reader(reader)?, y: borsh::BorshDeserialize::deserialize_reader(reader)?, } - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { A::C( borsh::BorshDeserialize::deserialize_reader(reader)?, borsh::BorshDeserialize::deserialize_reader(reader)?, diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new index b5b16ef79..ec4091df5 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new @@ -1,55 +1,49 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 158 +assertion_line: 152 expression: pretty_print_syn_str(&actual).unwrap() --- impl reexporter::borsh::de::BorshDeserialize for A { fn deserialize_reader<__R: reexporter::borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader( + let variant_tag = ::deserialize_reader( reader, )?; - ::deserialize_variant::< - _, - u8, - >(reader, tag) + let mut return_value = if variant_tag == 0u8 { + A::B { + x: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + y: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + reexporter::borsh::io::Error::new( + reexporter::borsh::io::ErrorKind::InvalidData, + reexporter::borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl reexporter::borsh::de::EnumExt for A { - fn deserialize_variant< - __R: reexporter::borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: reexporter::borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return reexporter::borsh::io::Error::new( - reexporter::borsh::io::ErrorKind::InvalidData, - reexporter::borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { A::B { x: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, y: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, } - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return reexporter::borsh::io::Error::new( - reexporter::borsh::io::ErrorKind::InvalidData, - reexporter::borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { A::C( reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new index d4a71b159..ee4281d66 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 175 +assertion_line: 169 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A @@ -12,8 +12,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant::<_, u8>(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A @@ -22,39 +44,16 @@ where V: borsh::de::BorshDeserialize, U: borsh::de::BorshDeserialize, { - fn deserialize_variant< - __R: borsh::io::Read, - Tag: borsh::BorshDeserialize + ::core::fmt::Debug + Eq - + ::core::convert::TryInto + ::core::convert::TryInto + Copy, - >( + fn deserialize_variant<__R: borsh::io::Read>( reader: &mut __R, - variant_tag: Tag, + variant_tag: u8, ) -> ::core::result::Result { - use ::core::convert::TryInto; - let mut return_value = if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 0u8 - { + let mut return_value = if variant_tag == 0u8 { A::B { x: borsh::BorshDeserialize::deserialize_reader(reader)?, y: borsh::BorshDeserialize::deserialize_reader(reader)?, } - } else if TryInto::<(u8)>::try_into(variant_tag) - .map_err(|_| { - return borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ); - })? == 1u8 - { + } else if variant_tag == 1u8 { A::C( borsh::BorshDeserialize::deserialize_reader(reader)?, borsh::BorshDeserialize::deserialize_reader(reader)?, diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index b2ca7a656..5602bba8c 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -6,21 +6,24 @@ use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, ToTokens}; use syn::{punctuated::Punctuated, spanned::Spanned, token::Comma, Variant}; -pub struct Discriminants((HashMap, syn::TypePath)); +pub struct Discriminants{ + variants: HashMap, + discriminant_type : syn::TypePath, + use_discriminant: bool, +} + impl Discriminants { /// Calculates the discriminant that will be assigned by the compiler. /// See: https://doc.rust-lang.org/reference/items/enumerations.html#assigning-discriminant-values pub fn new( variants: &Punctuated, maybe_borsh_tag_width: Option<(u8, Span)>, + maybe_rust_repr: Option<(syn::TypePath,Span)>, + use_discriminant: bool, ) -> syn::Result { let mut map = HashMap::new(); let mut next_discriminant_if_not_specified = quote! {0}; - let min_tag_width: u8 = bytes_needed(variants.len()) - .try_into() - .expect("variants cannot be bigger u64"); - for variant in variants { let this_discriminant = variant.discriminant.clone().map_or_else( || quote! { #next_discriminant_if_not_specified }, @@ -29,65 +32,90 @@ impl Discriminants { next_discriminant_if_not_specified = quote! { #this_discriminant + 1 }; map.insert(variant.ident.clone(), this_discriminant); - } + } - if let Some((borsh_tag_width, span)) = maybe_borsh_tag_width { - if borsh_tag_width < min_tag_width { + let mut discriminant_type = syn::parse_str("u8").unwrap(); + + if let Some((tag_width, span)) = maybe_borsh_tag_width { + if !use_discriminant { return Err(syn::Error::new( span, - format!( - "borsh_tag_width={} is too small for the number of variants={}", - borsh_tag_width, - variants.len() - ), + "`tag_width` specifier is only allowed when `use_discriminant` is set to true", )); } - } - - let tag_width = maybe_borsh_tag_width - .map(|(tag_width, _)| tag_width) - .unwrap_or_else(|| (1).max(min_tag_width)); + let Some((rust_repr, span)) = maybe_rust_repr else { + return Err(syn::Error::new( + span, + "`tag_width` specifier is only allowed when `repr` is set", + )); + }; + match rust_repr.path.get_ident() { + Some(repr_type) => { + let repr_size= match repr_type.to_string().as_str() { + "u8" => { + discriminant_type = syn::parse_str("u8").unwrap(); + 1 + }, + "u16" => { + discriminant_type = syn::parse_str("u16").unwrap(); + 2 + }, + "u32" => { + discriminant_type = syn::parse_str("u32").unwrap(); + 4 + }, + _ => return Err(syn::Error::new( + span, + "`tag_width` specifier is only allowed when `repr` is set to a u8, u16, or u32", + )), + }; - let tag_width_type = if tag_width <= 1 { - "u8" - } else if tag_width <= 2 { - "u16" - } else if tag_width <= 4 { - "u32" - } else if tag_width <= 8 { - "u64" - } else { - unreachable!("we eliminated such error earlier") - }; - let discriminant_type = syn::parse_str(tag_width_type).expect("numeric"); + if repr_size != tag_width { + return Err(syn::Error::new( + span, + "`tag_width` specifier must match the size of the `repr` type", + )); + } + } + None => { + return Err(syn::Error::new( + span, + "`tag_width` specifier is only allowed when `repr` is set to a specific numeric type", + )); + } + } + } - Ok(Self((map, discriminant_type))) + Ok(Self { + variants : map, + discriminant_type, + use_discriminant + }) } pub fn discriminant_type(&self) -> &syn::TypePath { - &self.0 .1 + &self.discriminant_type } pub fn get( &self, variant_ident: &Ident, - use_discriminant: bool, variant_idx: usize, ) -> syn::Result { - let variant_idx: u8 = u8::try_from(variant_idx).map_err(|err| { - syn::Error::new( - variant_ident.span(), - format!( - "up to {} enum variants are supported: {}", - u8::MAX as usize + 1, - err - ), - ) - })?; - let result = if use_discriminant { - let discriminant_value = self.0 .0.get(variant_ident).unwrap(); + let result = if self.use_discriminant { + let discriminant_value = self.variants.get(variant_ident).unwrap(); quote! { #discriminant_value } } else { + let variant_idx = u8::try_from(variant_idx).map_err(|err| { + syn::Error::new( + variant_ident.span(), + format!( + "up to {} enum variants are supported: {}", + u8::MAX as usize + 1, + err + ), + ) + })?; quote! { #variant_idx } }; Ok(result) diff --git a/borsh-derive/src/internals/schema/enums/mod.rs b/borsh-derive/src/internals/schema/enums/mod.rs index bfd7f9532..aef12c19c 100644 --- a/borsh-derive/src/internals/schema/enums/mod.rs +++ b/borsh-derive/src/internals/schema/enums/mod.rs @@ -37,7 +37,8 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut generics_output = schema::GenericsOutput::new(&generics); let use_discriminant = item::contains_use_discriminant(input)?; let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; - let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width); + let maybe_rust_repr = item::get_maybe_rust_repr(input); + let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width, maybe_rust_repr, use_discriminant)?; // Generate functions that return the schema for variants. let mut variants_defs = vec![]; @@ -106,7 +107,7 @@ fn process_discriminant( info: DiscriminantInfo<'_>, ) -> syn::Result { info.discriminants - .get(variant_ident, info.use_discriminant, info.variant_idx) + .get(variant_ident, info.variant_idx) } fn process_variant( diff --git a/borsh-derive/src/internals/serialize/enums/mod.rs b/borsh-derive/src/internals/serialize/enums/mod.rs index 27830ebdc..e9e284040 100644 --- a/borsh-derive/src/internals/serialize/enums/mod.rs +++ b/borsh-derive/src/internals/serialize/enums/mod.rs @@ -18,12 +18,13 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let mut fields_body = TokenStream2::new(); let use_discriminant = item::contains_use_discriminant(input)?; let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; - let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width)?; + let maybe_rust_repr = item::get_maybe_rust_repr(input); + let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width, maybe_rust_repr, use_discriminant)?; let mut has_unit_variant = false; for (variant_idx, variant) in input.variants.iter().enumerate() { let variant_ident = &variant.ident; - let discriminant_value = discriminants.get(variant_ident, use_discriminant, variant_idx)?; + let discriminant_value = discriminants.get(variant_ident, variant_idx)?; let variant_output = process_variant( variant, enum_ident, diff --git a/borsh/src/de/mod.rs b/borsh/src/de/mod.rs index 1e81c5961..0abb36e3e 100644 --- a/borsh/src/de/mod.rs +++ b/borsh/src/de/mod.rs @@ -132,18 +132,7 @@ pub trait EnumExt: BorshDeserialize { /// # #[cfg(feature = "derive")] /// assert!(from_slice::(&data[..]).is_err()); /// ``` - fn deserialize_variant< - R: Read, - Tag: BorshDeserialize - + ::core::fmt::Debug - + Eq - + ::core::convert::TryInto - + ::core::convert::TryInto - + Copy, - >( - reader: &mut R, - tag: Tag, - ) -> Result; + fn deserialize_variant(reader: &mut R, tag: u8) -> Result; } fn unexpected_eof_to_unexpected_length_of_input(e: Error) -> Error { diff --git a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs index 9b3065e7f..617a68b29 100644 --- a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs +++ b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs @@ -39,44 +39,44 @@ fn test_discriminant_serde_no_unit_type() { } } -#[test] -pub fn u16_discriminant() { - use borsh::{BorshDeserialize, BorshSerialize}; - #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] - #[borsh(use_discriminant = true)] - #[repr(u32)] - enum U16Discriminant { - U8 { a: u16 } = 42, - U16 { b: u32 } = 666, - } - let mut buf = vec![]; - let data = U16Discriminant::U16 { b: 1234567 }; - data.serialize(&mut buf).unwrap(); - assert_eq!(buf[0], 154); - assert_eq!(buf[1], 2); - assert!(buf.len(), 2); - let deserialized = U16Discriminant::deserialize(&mut buf.as_slice()).unwrap(); - assert_eq!(deserialized, data); -} - -#[test] -pub fn u32_discriminant() { - use borsh::{BorshDeserialize, BorshSerialize}; - #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] - #[borsh(use_discriminant = true)] - #[repr(u32)] - enum U32Discriminant { - U8 { a: u16 } = 42u32, - U32 { b: u32 } = u32::MAX, - } - let mut buf = vec![]; - let data = U32Discriminant::U32 { b: 1234567 }; - data.serialize(&mut buf).unwrap(); - assert_eq!(buf[0], 154); - assert_eq!(buf[1], 2); - let deserialized = U32Discriminant::deserialize(&mut buf.as_slice()).unwrap(); - assert_eq!(deserialized, data); -} +// #[test] +// pub fn u16_discriminant() { +// use borsh::{BorshDeserialize, BorshSerialize}; +// #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] +// #[borsh(use_discriminant = true)] +// #[repr(u32)] +// enum U16Discriminant { +// U8 { a: u16 } = 42, +// U16 { b: u32 } = 666, +// } +// let mut buf = vec![]; +// let data = U16Discriminant::U16 { b: 1234567 }; +// data.serialize(&mut buf).unwrap(); +// assert_eq!(buf[0], 154); +// assert_eq!(buf[1], 2); +// assert!(buf.len(), 2); +// let deserialized = U16Discriminant::deserialize(&mut buf.as_slice()).unwrap(); +// assert_eq!(deserialized, data); +// } + +// #[test] +// pub fn u32_discriminant() { +// use borsh::{BorshDeserialize, BorshSerialize}; +// #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] +// #[borsh(use_discriminant = true)] +// #[repr(u32)] +// enum U32Discriminant { +// U8 { a: u16 } = 42u32, +// U32 { b: u32 } = u32::MAX, +// } +// let mut buf = vec![]; +// let data = U32Discriminant::U32 { b: 1234567 }; +// data.serialize(&mut buf).unwrap(); +// assert_eq!(buf[0], 154); +// assert_eq!(buf[1], 2); +// let deserialized = U32Discriminant::deserialize(&mut buf.as_slice()).unwrap(); +// assert_eq!(deserialized, data); +// } #[test] @@ -98,7 +98,6 @@ fn test_discriminant_serde_no_unit_type_no_use_discriminant() { } } -//ASDF // minimal #[derive(BorshSerialize)] #[borsh(use_discriminant = true)] @@ -106,7 +105,6 @@ enum MyDiscriminantEnum { A = 20, } -//ASDF #[derive(BorshSerialize)] #[borsh(use_discriminant = false)] enum MyDiscriminantEnumFalse { @@ -133,7 +131,6 @@ fn test_discriminant_minimal_false() { assert_eq!(to_vec(&MyDiscriminantEnumFalse::A).unwrap(), vec![0]); } -//ASDF // sequence #[derive(BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone, Copy, Debug)] #[borsh(use_discriminant = false)] From 3da00cee06969de9f702102aa1ad9b0840062456 Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 3 Nov 2024 22:09:07 +0000 Subject: [PATCH 11/17] semantic tests path --- .../src/internals/deserialize/enums/mod.rs | 30 +++++-- .../borsh_discriminant_false.snap.new | 2 +- .../borsh_discriminant_true.snap.new | 2 +- .../enums/snapshots/borsh_init_func.snap.new | 2 +- .../borsh_skip_struct_variant_field.snap.new | 2 +- .../borsh_skip_tuple_variant_field.snap.new | 2 +- .../enums/snapshots/bound_generics.snap.new | 2 +- .../check_deserialize_with_attr.snap.new | 2 +- .../generic_borsh_skip_struct_field.snap.new | 2 +- .../generic_borsh_skip_tuple_field.snap.new | 2 +- .../generic_deserialize_bound.snap.new | 2 +- .../enums/snapshots/recursive_enum.snap.new | 2 +- .../simple_enum_with_custom_crate.snap.new | 2 +- .../enums/snapshots/simple_generics.snap.new | 2 +- .../src/internals/enum_discriminant.rs | 10 +-- .../test_enum_discriminants.rs | 84 ++++++++++--------- 16 files changed, 85 insertions(+), 65 deletions(-) diff --git a/borsh-derive/src/internals/deserialize/enums/mod.rs b/borsh-derive/src/internals/deserialize/enums/mod.rs index 8a65c26c1..e4634c675 100644 --- a/borsh-derive/src/internals/deserialize/enums/mod.rs +++ b/borsh-derive/src/internals/deserialize/enums/mod.rs @@ -1,6 +1,6 @@ use proc_macro2::TokenStream as TokenStream2; use quote::quote; -use syn::{Fields, ItemEnum, Path, Variant}; +use syn::{Fields, ItemEnum, Path, TypePath, Variant}; use crate::internals::{attributes::item, deserialize, enum_discriminant::Discriminants, generics}; @@ -46,22 +46,34 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { Ok(return_value) }; - Ok(quote! { + let deserialize = quote! { impl #impl_generics #cratename::de::BorshDeserialize for #name #ty_generics #where_clause { fn deserialize_reader<__R: #cratename::io::Read>(reader: &mut __R) -> ::core::result::Result { let variant_tag = <#discriminant_type as #cratename::de::BorshDeserialize>::deserialize_reader(reader)?; #deserialize_variant } } + }; - impl #impl_generics #cratename::de::EnumExt for #name #ty_generics #where_clause { - fn deserialize_variant<__R: #cratename::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - #deserialize_variant - } + let impl_trait = if discriminant_type.path.get_ident() == (syn::parse_str::("u8").unwrap().path.get_ident()) { + quote! { + impl #impl_generics #cratename::de::EnumExt for #name #ty_generics #where_clause { + fn deserialize_variant<__R: #cratename::io::Read>( + reader: &mut __R, + variant_tag: u8, + ) -> ::core::result::Result { + #deserialize_variant + } + } } + } else { + quote! {} + }; + + Ok(quote! { + #deserialize + + #impl_trait }) } diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new index 563b04198..1e07dcb26 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 300 +assertion_line: 312 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for X { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new index 8d17b1221..7c0bbde13 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 318 +assertion_line: 330 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for X { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new index 485ec3bc7..0ee509e42 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 335 +assertion_line: 347 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new index 55b39b636..a227471c4 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 117 +assertion_line: 129 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for AA { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new index e3b91c361..0401a15fc 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 134 +assertion_line: 146 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for AAT { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new index 74aa01e12..6f11d1533 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 186 +assertion_line: 198 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new index d3436e453..4a728b2f0 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 281 +assertion_line: 293 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for C diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new index 86068606b..63be0833a 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 222 +assertion_line: 234 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new index 49399f5bd..f9df777ba 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 240 +assertion_line: 252 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new index fe5ca6bd6..e1de7a21b 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 262 +assertion_line: 274 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new index b306b012f..c15758aec 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 204 +assertion_line: 216 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new index ec4091df5..2d1961394 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 152 +assertion_line: 164 expression: pretty_print_syn_str(&actual).unwrap() --- impl reexporter::borsh::de::BorshDeserialize for A { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new index ee4281d66..a8138af2f 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new @@ -1,6 +1,6 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 169 +assertion_line: 181 expression: pretty_print_syn_str(&actual).unwrap() --- impl borsh::de::BorshDeserialize for A diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index 5602bba8c..448209ad9 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -4,7 +4,7 @@ use std::convert::TryFrom; use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, ToTokens}; -use syn::{punctuated::Punctuated, spanned::Spanned, token::Comma, Variant}; +use syn::{punctuated::Punctuated, spanned::Spanned, token::Comma, TypePath, Variant}; pub struct Discriminants{ variants: HashMap, @@ -34,7 +34,7 @@ impl Discriminants { map.insert(variant.ident.clone(), this_discriminant); } - let mut discriminant_type = syn::parse_str("u8").unwrap(); + let mut discriminant_type: TypePath = syn::parse_str("u8").unwrap(); if let Some((tag_width, span)) = maybe_borsh_tag_width { if !use_discriminant { @@ -53,15 +53,12 @@ impl Discriminants { Some(repr_type) => { let repr_size= match repr_type.to_string().as_str() { "u8" => { - discriminant_type = syn::parse_str("u8").unwrap(); 1 }, "u16" => { - discriminant_type = syn::parse_str("u16").unwrap(); 2 }, "u32" => { - discriminant_type = syn::parse_str("u32").unwrap(); 4 }, _ => return Err(syn::Error::new( @@ -69,6 +66,8 @@ impl Discriminants { "`tag_width` specifier is only allowed when `repr` is set to a u8, u16, or u32", )), }; + discriminant_type = rust_repr.clone(); + println!("repr_type: {:?}, repr_size: {:?} tag_width:{:?} ", repr_type, repr_size, tag_width); if repr_size != tag_width { return Err(syn::Error::new( @@ -84,6 +83,7 @@ impl Discriminants { )); } } + println!("discriminant_type: {:?}", discriminant_type.path.get_ident()); } Ok(Self { diff --git a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs index 617a68b29..88dcd372c 100644 --- a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs +++ b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs @@ -39,44 +39,52 @@ fn test_discriminant_serde_no_unit_type() { } } -// #[test] -// pub fn u16_discriminant() { -// use borsh::{BorshDeserialize, BorshSerialize}; -// #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] -// #[borsh(use_discriminant = true)] -// #[repr(u32)] -// enum U16Discriminant { -// U8 { a: u16 } = 42, -// U16 { b: u32 } = 666, -// } -// let mut buf = vec![]; -// let data = U16Discriminant::U16 { b: 1234567 }; -// data.serialize(&mut buf).unwrap(); -// assert_eq!(buf[0], 154); -// assert_eq!(buf[1], 2); -// assert!(buf.len(), 2); -// let deserialized = U16Discriminant::deserialize(&mut buf.as_slice()).unwrap(); -// assert_eq!(deserialized, data); -// } - -// #[test] -// pub fn u32_discriminant() { -// use borsh::{BorshDeserialize, BorshSerialize}; -// #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] -// #[borsh(use_discriminant = true)] -// #[repr(u32)] -// enum U32Discriminant { -// U8 { a: u16 } = 42u32, -// U32 { b: u32 } = u32::MAX, -// } -// let mut buf = vec![]; -// let data = U32Discriminant::U32 { b: 1234567 }; -// data.serialize(&mut buf).unwrap(); -// assert_eq!(buf[0], 154); -// assert_eq!(buf[1], 2); -// let deserialized = U32Discriminant::deserialize(&mut buf.as_slice()).unwrap(); -// assert_eq!(deserialized, data); -// } +#[test] +pub fn u16_discriminant() { + use borsh::{BorshDeserialize, BorshSerialize}; + #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] + #[borsh(use_discriminant = true, tag_width = 2)] + #[repr(u16)] + enum U16Discriminant { + U8 = 42, + U16 = 666, + } + let mut buf = vec![]; + let data = U16Discriminant::U16; + data.serialize(&mut buf).unwrap(); + assert_eq!(buf[0], 154); + assert_eq!(buf[1], 2); + + assert_eq!(buf.len(), 2, "Serialized data should be 2 bytes long"); + + let deserialized = U16Discriminant::deserialize(&mut buf.as_slice()).unwrap(); + assert_eq!(deserialized, data); +} + +#[test] +pub fn u32_discriminant() { + use borsh::{BorshDeserialize, BorshSerialize}; + #[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)] + #[borsh(use_discriminant = true, tag_width = 4)] + #[repr(u32)] + enum U32Discriminant { + U8 = 42u32, + U32 = u32::MAX, + } + let mut buf = vec![]; + let data = U32Discriminant::U32; + data.serialize(&mut buf).unwrap(); + assert_eq!(buf.len(), 4, "Serialized data should be 4 bytes long"); + + assert_eq!(buf[0], 255); + assert_eq!(buf[1], 255); + assert_eq!(buf[2], 255); + assert_eq!(buf[3], 255); + + + let deserialized = U32Discriminant::deserialize(&mut buf.as_slice()).unwrap(); + assert_eq!(deserialized, data); +} #[test] From 4acaec256e45ebec06fd22cbc7168c4bb78f397b Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 3 Nov 2024 22:55:34 +0000 Subject: [PATCH 12/17] schema changes --- .../src/internals/enum_discriminant.rs | 14 +++-- .../src/internals/schema/enums/mod.rs | 4 +- .../enums/snapshots/recursive_enum.snap.new | 56 +++++++++++++++++++ borsh/src/schema.rs | 6 ++ borsh/src/schema/container_ext/max_size.rs | 2 + borsh/src/schema/container_ext/validate.rs | 2 + .../container_extension/test_max_size.rs | 1 + borsh/tests/schema/test_enum_discriminants.rs | 54 +++++++++++++++++- borsh/tests/schema/test_generic_enums.rs | 6 ++ borsh/tests/schema/test_option.rs | 3 + borsh/tests/schema/test_recursive_enums.rs | 1 + .../schema/test_schema_with_third_party.rs | 1 + borsh/tests/schema/test_simple_enums.rs | 3 + 13 files changed, 147 insertions(+), 6 deletions(-) create mode 100644 borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap.new diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index 448209ad9..4bf44185f 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -10,6 +10,7 @@ pub struct Discriminants{ variants: HashMap, discriminant_type : syn::TypePath, use_discriminant: bool, + tag_width: u8, } impl Discriminants { @@ -35,8 +36,10 @@ impl Discriminants { } let mut discriminant_type: TypePath = syn::parse_str("u8").unwrap(); + let mut tag_width = 1; - if let Some((tag_width, span)) = maybe_borsh_tag_width { + if let Some((defined_tag_width, span)) = maybe_borsh_tag_width { + tag_width = defined_tag_width; if !use_discriminant { return Err(syn::Error::new( span, @@ -67,7 +70,6 @@ impl Discriminants { )), }; discriminant_type = rust_repr.clone(); - println!("repr_type: {:?}, repr_size: {:?} tag_width:{:?} ", repr_type, repr_size, tag_width); if repr_size != tag_width { return Err(syn::Error::new( @@ -83,13 +85,13 @@ impl Discriminants { )); } } - println!("discriminant_type: {:?}", discriminant_type.path.get_ident()); } Ok(Self { variants : map, discriminant_type, - use_discriminant + use_discriminant, + tag_width, }) } @@ -97,6 +99,10 @@ impl Discriminants { &self.discriminant_type } + pub fn tag_width(&self) -> u8 { + self.tag_width + } + pub fn get( &self, variant_ident: &Ident, diff --git a/borsh-derive/src/internals/schema/enums/mod.rs b/borsh-derive/src/internals/schema/enums/mod.rs index aef12c19c..273a155c9 100644 --- a/borsh-derive/src/internals/schema/enums/mod.rs +++ b/borsh-derive/src/internals/schema/enums/mod.rs @@ -63,13 +63,15 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { variants_defs.push(variant_output.variant_entry); } + let tag_width = discriminants.tag_width(); let type_definitions = quote! { fn add_definitions_recursively(definitions: &mut #cratename::__private::maybestd::collections::BTreeMap<#cratename::schema::Declaration, #cratename::schema::Definition>) { #inner_defs #add_recursive_defs let definition = #cratename::schema::Definition::Enum { - tag_width: 1, + tag_width: #tag_width, variants: #cratename::__private::maybestd::vec![#(#variants_defs),*], + tag_signed: false, }; #cratename::schema::add_definition(::declaration(), definition, definitions); } diff --git a/borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap.new b/borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap.new new file mode 100644 index 000000000..65800467e --- /dev/null +++ b/borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap.new @@ -0,0 +1,56 @@ +--- +source: borsh-derive/src/internals/schema/enums/mod.rs +assertion_line: 403 +expression: pretty_print_syn_str(&actual).unwrap() +--- +impl borsh::BorshSchema for A +where + V: Value, + K: borsh::BorshSchema, + V: borsh::BorshSchema, +{ + fn declaration() -> borsh::schema::Declaration { + let params = borsh::__private::maybestd::vec![ + < K as borsh::BorshSchema > ::declaration(), < V as borsh::BorshSchema > + ::declaration() + ]; + format!(r#"{}<{}>"#, "A", params.join(", ")) + } + fn add_definitions_recursively( + definitions: &mut borsh::__private::maybestd::collections::BTreeMap< + borsh::schema::Declaration, + borsh::schema::Definition, + >, + ) { + #[allow(dead_code)] + #[derive(borsh::BorshSchema)] + #[borsh(crate = "borsh")] + struct AB + where + V: Value, + { + x: HashMap, + y: String, + } + #[allow(dead_code)] + #[derive(borsh::BorshSchema)] + #[borsh(crate = "borsh")] + struct AC(K, Vec); + as borsh::BorshSchema>::add_definitions_recursively(definitions); + as borsh::BorshSchema>::add_definitions_recursively(definitions); + let definition = borsh::schema::Definition::Enum { + tag_width: 1u8, + variants: borsh::__private::maybestd::vec![ + (u8::from(0u8) as i64, "B".into(), < AB < K, V > as borsh::BorshSchema > + ::declaration()), (u8::from(1u8) as i64, "C".into(), < AC < K > as + borsh::BorshSchema > ::declaration()) + ], + tag_signed: false, + }; + borsh::schema::add_definition( + ::declaration(), + definition, + definitions, + ); + } +} diff --git a/borsh/src/schema.rs b/borsh/src/schema.rs index 65b5bb1c9..810c8cfa5 100644 --- a/borsh/src/schema.rs +++ b/borsh/src/schema.rs @@ -112,6 +112,10 @@ pub enum Definition { /// invalid if the value is greater than eight. tag_width: u8, + /// If true, than tag is signed value. + /// If false, unsigned value. + tag_signed: bool, + /// Possible variants of the enumeration. /// `VariantName` is metadata, not present in a type's serialized representation. variants: Vec<(DiscriminantValue, VariantName, Declaration)>, @@ -601,6 +605,7 @@ where (0u8 as i64, "None".to_string(), <()>::declaration()), (1u8 as i64, "Some".to_string(), T::declaration()), ], + tag_signed: false, }; add_definition(Self::declaration(), definition, definitions); T::add_definitions_recursively(definitions); @@ -624,6 +629,7 @@ where (1u8 as i64, "Ok".to_string(), T::declaration()), (0u8 as i64, "Err".to_string(), E::declaration()), ], + tag_signed: false, }; add_definition(Self::declaration(), definition, definitions); T::add_definitions_recursively(definitions); diff --git a/borsh/src/schema/container_ext/max_size.rs b/borsh/src/schema/container_ext/max_size.rs index 193f3be1e..a7e71e54c 100644 --- a/borsh/src/schema/container_ext/max_size.rs +++ b/borsh/src/schema/container_ext/max_size.rs @@ -126,6 +126,7 @@ fn max_serialized_size_impl<'a>( Ok(Definition::Enum { tag_width, variants, + tag_signed: _, }) => { let mut max = 0; for (_, _, variant) in variants { @@ -232,6 +233,7 @@ fn is_zero_size_impl<'a>( Ok(Definition::Enum { tag_width: 0, variants, + tag_signed: _, }) => all( variants.iter(), |(_variant_discrim, _variant_name, declaration)| declaration, diff --git a/borsh/src/schema/container_ext/validate.rs b/borsh/src/schema/container_ext/validate.rs index 6bd2738fb..524fe344f 100644 --- a/borsh/src/schema/container_ext/validate.rs +++ b/borsh/src/schema/container_ext/validate.rs @@ -106,10 +106,12 @@ fn validate_impl<'a>( Definition::Enum { tag_width, variants, + tag_signed: _, } => { if *tag_width > U64_LEN { return Err(Error::TagTooWide(declaration.to_string())); } + for (_, _, variant) in variants { validate_impl(variant, schema, stack)?; } diff --git a/borsh/tests/schema/container_extension/test_max_size.rs b/borsh/tests/schema/container_extension/test_max_size.rs index d179b0e83..7369d6502 100644 --- a/borsh/tests/schema/container_extension/test_max_size.rs +++ b/borsh/tests/schema/container_extension/test_max_size.rs @@ -133,6 +133,7 @@ fn max_serialized_size_custom_enum() { } fn add_definitions_recursively(definitions: &mut BTreeMap) { let definition = Definition::Enum { + tag_signed: false, tag_width: N, variants: vec![ (0, "Just".into(), T::declaration()), diff --git a/borsh/tests/schema/test_enum_discriminants.rs b/borsh/tests/schema/test_enum_discriminants.rs index eb502ab12..5004f2f8c 100644 --- a/borsh/tests/schema/test_enum_discriminants.rs +++ b/borsh/tests/schema/test_enum_discriminants.rs @@ -21,6 +21,7 @@ fn test_schema_discriminant_no_unit_type() { assert_eq!( schema_map! { "XY" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "A".to_string(), "XYA".to_string()), @@ -29,7 +30,7 @@ fn test_schema_discriminant_no_unit_type() { (22, "D".to_string(), "XYD".to_string()), (10, "E".to_string(), "XYE".to_string()), (11, "F".to_string(), "XYF".to_string()) - ] + ], }, "XYA" => Definition::Struct{ fields: Fields::Empty }, "XYB" => Definition::Struct{ fields: Fields::Empty }, @@ -73,6 +74,7 @@ fn test_schema_discriminant_no_unit_type_no_use_discriminant() { assert_eq!( schema_map! { "XYNoDiscriminant" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "A".to_string(), "XYNoDiscriminantA".to_string()), @@ -100,3 +102,53 @@ fn test_schema_discriminant_no_unit_type_no_use_discriminant() { defs ); } + + +#[test] +fn tag_widths() { + #[derive(BorshSchema)] + #[borsh(use_discriminant=true, tag_width = 2)] + #[repr(u16)] + enum U16Discriminant { + A = 42u16, + } + + let mut defs = Default::default(); + U16Discriminant::add_definitions_recursively(&mut defs); + assert_eq!( + schema_map! { + "U16Discriminant" => Definition::Enum { + tag_signed: false, + tag_width: 2, + variants: vec![ + (42, "A".to_string(), "U16DiscriminantA".to_string()), + ], + }, + "U16DiscriminantA" => Definition::Struct{ fields: Fields::Empty } + }, + defs + ); + + #[derive(BorshSchema)] + #[borsh(use_discriminant = true, tag_width = 4)] + #[repr(u32)] + enum U32Discriminant { + A = 42u32, + } + + let mut defs = Default::default(); + U32Discriminant::add_definitions_recursively(&mut defs); + assert_eq!( + schema_map! { + "U32Discriminant" => Definition::Enum { + tag_signed: false, + tag_width: 4, + variants: vec![ + (42, "A".to_string(), "U32DiscriminantA".to_string()), + ], + }, + "U32DiscriminantA" => Definition::Struct{ fields: Fields::Empty } + }, + defs + ); +} \ No newline at end of file diff --git a/borsh/tests/schema/test_generic_enums.rs b/borsh/tests/schema/test_generic_enums.rs index 61965bbb8..72d1c7c1b 100644 --- a/borsh/tests/schema/test_generic_enums.rs +++ b/borsh/tests/schema/test_generic_enums.rs @@ -40,6 +40,7 @@ pub fn complex_enum_generics() { "ABacon" => Definition::Struct {fields: Fields::Empty}, "Oil" => Definition::Struct {fields: Fields::Empty}, "A" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "Bacon".to_string(), "ABacon".to_string()), @@ -102,6 +103,7 @@ pub fn complex_enum_generics2() { assert_eq!( schema_map! { "A>" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "Bacon".to_string(), "ABacon".to_string()), @@ -111,6 +113,7 @@ pub fn complex_enum_generics2() { ] }, "A" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "Bacon".to_string(), "ABacon".to_string()), @@ -134,6 +137,7 @@ pub fn complex_enum_generics2() { }, "Oil" => Definition::Struct { fields: Fields::NamedFields(vec![("seeds".to_string(), "HashMap".to_string()), ("liquid".to_string(), "Option".to_string())])}, "Option" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "None".to_string(), "()".to_string()), @@ -141,6 +145,7 @@ pub fn complex_enum_generics2() { ] }, "Option" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "None".to_string(), "()".to_string()), @@ -166,6 +171,7 @@ pub fn complex_enum_generics2() { fn common_map_associated() -> BTreeMap { schema_map! { "EnumParametrized" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "B".to_string(), "EnumParametrizedB".to_string()), diff --git a/borsh/tests/schema/test_option.rs b/borsh/tests/schema/test_option.rs index f04c1f906..e9baa9e2b 100644 --- a/borsh/tests/schema/test_option.rs +++ b/borsh/tests/schema/test_option.rs @@ -9,6 +9,7 @@ fn simple_option() { assert_eq!( schema_map! { "Option" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "None".to_string(), "()".to_string()), @@ -31,6 +32,7 @@ fn nested_option() { assert_eq!( schema_map! { "Option" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "None".to_string(), "()".to_string()), @@ -38,6 +40,7 @@ fn nested_option() { ] }, "Option>" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "None".to_string(), "()".to_string()), diff --git a/borsh/tests/schema/test_recursive_enums.rs b/borsh/tests/schema/test_recursive_enums.rs index f5bc64e49..dca9195dc 100644 --- a/borsh/tests/schema/test_recursive_enums.rs +++ b/borsh/tests/schema/test_recursive_enums.rs @@ -14,6 +14,7 @@ pub fn recursive_enum_schema() { assert_eq!( schema_map! { "ERecD" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "B".to_string(), "ERecDB".to_string()), diff --git a/borsh/tests/schema/test_schema_with_third_party.rs b/borsh/tests/schema/test_schema_with_third_party.rs index 30562f89a..b8b104a9d 100644 --- a/borsh/tests/schema/test_schema_with_third_party.rs +++ b/borsh/tests/schema/test_schema_with_third_party.rs @@ -100,6 +100,7 @@ pub fn enum_overriden() { assert_eq!( schema_map! { "C" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "C3".to_string(), "CC3".to_string()), diff --git a/borsh/tests/schema/test_simple_enums.rs b/borsh/tests/schema/test_simple_enums.rs index 27e94804e..0bb647b95 100644 --- a/borsh/tests/schema/test_simple_enums.rs +++ b/borsh/tests/schema/test_simple_enums.rs @@ -25,6 +25,7 @@ pub fn simple_enum() { "ABacon" => Definition::Struct{ fields: Fields::Empty }, "AEggs" => Definition::Struct{ fields: Fields::Empty }, "A" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![(0, "Bacon".to_string(), "ABacon".to_string()), (1, "Eggs".to_string(), "AEggs".to_string())] } @@ -47,6 +48,7 @@ pub fn single_field_enum() { schema_map! { "ABacon" => Definition::Struct {fields: Fields::Empty}, "A" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![(0, "Bacon".to_string(), "ABacon".to_string())] } @@ -131,6 +133,7 @@ pub fn complex_enum_with_schema() { "ABacon" => Definition::Struct {fields: Fields::Empty}, "Oil" => Definition::Struct {fields: Fields::Empty}, "A" => Definition::Enum { + tag_signed: false, tag_width: 1, variants: vec![ (0, "Bacon".to_string(), "ABacon".to_string()), From affadf461f0e7a1f0af08aa8903fb9ac42148924 Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 3 Nov 2024 23:20:59 +0000 Subject: [PATCH 13/17] sign in schema --- ...eck_attrs_borsh_invalid_on_whole_item.snap | 3 +- ...attrs_borsh_invalid_on_whole_item.snap.new | 8 -- .../check_attrs_borsh_skip_on_whole_item.snap | 3 +- ...ck_attrs_borsh_skip_on_whole_item.snap.new | 8 -- ...heck_attrs_init_function_wrong_format.snap | 3 +- ..._attrs_init_function_wrong_format.snap.new | 8 -- .../snapshots/borsh_discriminant_false.snap | 29 ++++++- .../borsh_discriminant_false.snap.new | 67 ---------------- .../snapshots/borsh_discriminant_true.snap | 29 ++++++- .../borsh_discriminant_true.snap.new | 67 ---------------- .../enums/snapshots/borsh_init_func.snap | 30 +++++++- .../enums/snapshots/borsh_init_func.snap.new | 69 ----------------- .../borsh_skip_struct_variant_field.snap | 26 ++++++- .../borsh_skip_struct_variant_field.snap.new | 61 --------------- .../borsh_skip_tuple_variant_field.snap | 26 ++++++- .../borsh_skip_tuple_variant_field.snap.new | 61 --------------- .../enums/snapshots/bound_generics.snap | 27 ++++++- .../enums/snapshots/bound_generics.snap.new | 75 ------------------ .../check_deserialize_with_attr.snap | 27 ++++++- .../check_deserialize_with_attr.snap.new | 71 ----------------- .../generic_borsh_skip_struct_field.snap | 27 ++++++- .../generic_borsh_skip_struct_field.snap.new | 77 ------------------- .../generic_borsh_skip_tuple_field.snap | 27 ++++++- .../generic_borsh_skip_tuple_field.snap.new | 75 ------------------ .../snapshots/generic_deserialize_bound.snap | 27 ++++++- .../generic_deserialize_bound.snap.new | 71 ----------------- .../enums/snapshots/recursive_enum.snap | 27 ++++++- .../enums/snapshots/recursive_enum.snap.new | 73 ------------------ .../simple_enum_with_custom_crate.snap | 25 +++++- .../simple_enum_with_custom_crate.snap.new | 63 --------------- .../enums/snapshots/simple_generics.snap | 27 ++++++- .../enums/snapshots/simple_generics.snap.new | 73 ------------------ .../enums/snapshots/recursive_enum.snap | 5 +- .../enums/snapshots/recursive_enum.snap.new | 56 -------------- ..._schema__test_ip_addr__ip_addr_schema.snap | 2 + ...imple_enums__complex_enum_with_schema.snap | 2 + 36 files changed, 341 insertions(+), 1014 deletions(-) delete mode 100644 borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new delete mode 100644 borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new delete mode 100644 borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new delete mode 100644 borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new delete mode 100644 borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap.new diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap index f2a856a52..f6d28ffa8 100644 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap @@ -1,7 +1,8 @@ --- source: borsh-derive/src/internals/attributes/item/mod.rs expression: actual.unwrap_err() +snapshot_kind: text --- Error( - "`crate`, `use_discriminant` or `init` are the only supported attributes for `borsh`", + "`crate`, `use_discriminant`, `tag_width` or `init` are the only supported attributes for `borsh`", ) diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new deleted file mode 100644 index 2df21661a..000000000 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_invalid_on_whole_item.snap.new +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: borsh-derive/src/internals/attributes/item/mod.rs -assertion_line: 262 -expression: actual.unwrap_err() ---- -Error( - "`crate`, `use_discriminant`, `tag_width` or `init` are the only supported attributes for `borsh`", -) diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap index f2a856a52..f6d28ffa8 100644 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap @@ -1,7 +1,8 @@ --- source: borsh-derive/src/internals/attributes/item/mod.rs expression: actual.unwrap_err() +snapshot_kind: text --- Error( - "`crate`, `use_discriminant` or `init` are the only supported attributes for `borsh`", + "`crate`, `use_discriminant`, `tag_width` or `init` are the only supported attributes for `borsh`", ) diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new deleted file mode 100644 index 8c6579af7..000000000 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_borsh_skip_on_whole_item.snap.new +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: borsh-derive/src/internals/attributes/item/mod.rs -assertion_line: 248 -expression: actual.unwrap_err() ---- -Error( - "`crate`, `use_discriminant`, `tag_width` or `init` are the only supported attributes for `borsh`", -) diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap index f2a856a52..f6d28ffa8 100644 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap +++ b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap @@ -1,7 +1,8 @@ --- source: borsh-derive/src/internals/attributes/item/mod.rs expression: actual.unwrap_err() +snapshot_kind: text --- Error( - "`crate`, `use_discriminant` or `init` are the only supported attributes for `borsh`", + "`crate`, `use_discriminant`, `tag_width` or `init` are the only supported attributes for `borsh`", ) diff --git a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new b/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new deleted file mode 100644 index d89523db6..000000000 --- a/borsh-derive/src/internals/attributes/item/snapshots/check_attrs_init_function_wrong_format.snap.new +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: borsh-derive/src/internals/attributes/item/mod.rs -assertion_line: 347 -expression: actual.unwrap_err() ---- -Error( - "`crate`, `use_discriminant`, `tag_width` or `init` are the only supported attributes for `borsh`", -) diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap index 1e0446681..824f55a0b 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap @@ -1,13 +1,38 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for X { fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + X::A + } else if variant_tag == 1u8 { + X::B + } else if variant_tag == 2u8 { + X::C + } else if variant_tag == 3u8 { + X::D + } else if variant_tag == 4u8 { + X::E + } else if variant_tag == 5u8 { + X::F + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for X { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new deleted file mode 100644 index 1e07dcb26..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_false.snap.new +++ /dev/null @@ -1,67 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 312 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for X { - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - X::A - } else if variant_tag == 1u8 { - X::B - } else if variant_tag == 2u8 { - X::C - } else if variant_tag == 3u8 { - X::D - } else if variant_tag == 4u8 { - X::E - } else if variant_tag == 5u8 { - X::F - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for X { - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - X::A - } else if variant_tag == 1u8 { - X::B - } else if variant_tag == 2u8 { - X::C - } else if variant_tag == 3u8 { - X::D - } else if variant_tag == 4u8 { - X::E - } else if variant_tag == 5u8 { - X::F - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap index add0f62ed..aa8337a8f 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap @@ -1,13 +1,38 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for X { fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0 { + X::A + } else if variant_tag == 20 { + X::B + } else if variant_tag == 20 + 1 { + X::C + } else if variant_tag == 20 + 1 + 1 { + X::D + } else if variant_tag == 10 { + X::E + } else if variant_tag == 10 + 1 { + X::F + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for X { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new deleted file mode 100644 index 7c0bbde13..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_discriminant_true.snap.new +++ /dev/null @@ -1,67 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 330 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for X { - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0 { - X::A - } else if variant_tag == 20 { - X::B - } else if variant_tag == 20 + 1 { - X::C - } else if variant_tag == 20 + 1 + 1 { - X::D - } else if variant_tag == 10 { - X::E - } else if variant_tag == 10 + 1 { - X::F - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for X { - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0 { - X::A - } else if variant_tag == 20 { - X::B - } else if variant_tag == 20 + 1 { - X::C - } else if variant_tag == 20 + 1 + 1 { - X::D - } else if variant_tag == 10 { - X::E - } else if variant_tag == 10 + 1 { - X::F - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap index 28dd7dbce..51f383cd5 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap @@ -1,13 +1,39 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for A { fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::A + } else if variant_tag == 1u8 { + A::B + } else if variant_tag == 2u8 { + A::C + } else if variant_tag == 3u8 { + A::D + } else if variant_tag == 4u8 { + A::E + } else if variant_tag == 5u8 { + A::F + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + return_value.initialization_method(); + Ok(return_value) } } impl borsh::de::EnumExt for A { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new deleted file mode 100644 index 0ee509e42..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_init_func.snap.new +++ /dev/null @@ -1,69 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 347 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for A { - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - A::A - } else if variant_tag == 1u8 { - A::B - } else if variant_tag == 2u8 { - A::C - } else if variant_tag == 3u8 { - A::D - } else if variant_tag == 4u8 { - A::E - } else if variant_tag == 5u8 { - A::F - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - return_value.initialization_method(); - Ok(return_value) - } -} -impl borsh::de::EnumExt for A { - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - A::A - } else if variant_tag == 1u8 { - A::B - } else if variant_tag == 2u8 { - A::C - } else if variant_tag == 3u8 { - A::D - } else if variant_tag == 4u8 { - A::E - } else if variant_tag == 5u8 { - A::F - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - return_value.initialization_method(); - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap index a8a2d9e1a..edbc475c0 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap @@ -1,13 +1,35 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for AA { fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + AA::B { + c: core::default::Default::default(), + d: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + AA::NegatedVariant { + beta: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for AA { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new deleted file mode 100644 index a227471c4..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_struct_variant_field.snap.new +++ /dev/null @@ -1,61 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 129 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for AA { - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - AA::B { - c: core::default::Default::default(), - d: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - AA::NegatedVariant { - beta: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for AA { - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - AA::B { - c: core::default::Default::default(), - d: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - AA::NegatedVariant { - beta: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap index 60149fc60..9c406ba31 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap @@ -1,13 +1,35 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for AAT { fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + AAT::B( + core::default::Default::default(), + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else if variant_tag == 1u8 { + AAT::NegatedVariant { + beta: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for AAT { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new deleted file mode 100644 index 0401a15fc..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/borsh_skip_tuple_variant_field.snap.new +++ /dev/null @@ -1,61 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 146 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for AAT { - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - AAT::B( - core::default::Default::default(), - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else if variant_tag == 1u8 { - AAT::NegatedVariant { - beta: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for AAT { - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - AAT::B( - core::default::Default::default(), - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else if variant_tag == 1u8 { - AAT::NegatedVariant { - beta: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap index 6b31f4bc6..66ea7cf79 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for A where @@ -12,8 +13,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new deleted file mode 100644 index 6f11d1533..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/bound_generics.snap.new +++ /dev/null @@ -1,75 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 198 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for A -where - V: Value, - K: borsh::de::BorshDeserialize, - V: borsh::de::BorshDeserialize, - U: borsh::de::BorshDeserialize, -{ - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - A::B { - x: borsh::BorshDeserialize::deserialize_reader(reader)?, - y: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for A -where - V: Value, - K: borsh::de::BorshDeserialize, - V: borsh::de::BorshDeserialize, - U: borsh::de::BorshDeserialize, -{ - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - A::B { - x: borsh::BorshDeserialize::deserialize_reader(reader)?, - y: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap index 968e0c3b5..12c008cc5 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for C where @@ -10,8 +11,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + C::C3( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else if variant_tag == 1u8 { + C::C4 { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: third_party_impl::deserialize_third_party(reader)?, + } + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for C diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new deleted file mode 100644 index 4a728b2f0..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/check_deserialize_with_attr.snap.new +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 293 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for C -where - K: borsh::de::BorshDeserialize, - V: borsh::de::BorshDeserialize, -{ - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - C::C3( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else if variant_tag == 1u8 { - C::C4 { - x: borsh::BorshDeserialize::deserialize_reader(reader)?, - y: third_party_impl::deserialize_third_party(reader)?, - } - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for C -where - K: borsh::de::BorshDeserialize, - V: borsh::de::BorshDeserialize, -{ - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - C::C3( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else if variant_tag == 1u8 { - C::C4 { - x: borsh::BorshDeserialize::deserialize_reader(reader)?, - y: third_party_impl::deserialize_third_party(reader)?, - } - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap index cde62e488..20af08a4e 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for A where @@ -13,8 +14,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::B { + x: core::default::Default::default(), + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new deleted file mode 100644 index 63be0833a..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_struct_field.snap.new +++ /dev/null @@ -1,77 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 234 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for A -where - V: Value, - K: borsh::de::BorshDeserialize, - U: borsh::de::BorshDeserialize, - K: core::default::Default, - V: core::default::Default, -{ - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - A::B { - x: core::default::Default::default(), - y: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for A -where - V: Value, - K: borsh::de::BorshDeserialize, - U: borsh::de::BorshDeserialize, - K: core::default::Default, - V: core::default::Default, -{ - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - A::B { - x: core::default::Default::default(), - y: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap index 0cc108681..58ea76ad7 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for A where @@ -12,8 +13,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + core::default::Default::default(), + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new deleted file mode 100644 index f9df777ba..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_borsh_skip_tuple_field.snap.new +++ /dev/null @@ -1,75 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 252 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for A -where - V: Value, - K: borsh::de::BorshDeserialize, - V: borsh::de::BorshDeserialize, - U: core::default::Default, -{ - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - A::B { - x: borsh::BorshDeserialize::deserialize_reader(reader)?, - y: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - borsh::BorshDeserialize::deserialize_reader(reader)?, - core::default::Default::default(), - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for A -where - V: Value, - K: borsh::de::BorshDeserialize, - V: borsh::de::BorshDeserialize, - U: core::default::Default, -{ - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - A::B { - x: borsh::BorshDeserialize::deserialize_reader(reader)?, - y: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - borsh::BorshDeserialize::deserialize_reader(reader)?, - core::default::Default::default(), - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap index adf641118..ee110fa17 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for A where @@ -10,8 +11,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::C { + a: borsh::BorshDeserialize::deserialize_reader(reader)?, + b: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::D( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new deleted file mode 100644 index e1de7a21b..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/generic_deserialize_bound.snap.new +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 274 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for A -where - T: PartialOrd + Hash + Eq + borsh::de::BorshDeserialize, - U: borsh::de::BorshDeserialize, -{ - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - A::C { - a: borsh::BorshDeserialize::deserialize_reader(reader)?, - b: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::D( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for A -where - T: PartialOrd + Hash + Eq + borsh::de::BorshDeserialize, - U: borsh::de::BorshDeserialize, -{ - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - A::C { - a: borsh::BorshDeserialize::deserialize_reader(reader)?, - b: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::D( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap index b3c8f7790..441e789ce 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for A where @@ -11,8 +12,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new deleted file mode 100644 index c15758aec..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/recursive_enum.snap.new +++ /dev/null @@ -1,73 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 216 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for A -where - V: Value, - K: borsh::de::BorshDeserialize, - V: borsh::de::BorshDeserialize, -{ - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - A::B { - x: borsh::BorshDeserialize::deserialize_reader(reader)?, - y: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for A -where - V: Value, - K: borsh::de::BorshDeserialize, - V: borsh::de::BorshDeserialize, -{ - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - A::B { - x: borsh::BorshDeserialize::deserialize_reader(reader)?, - y: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap index 88457ee99..cafb0cc08 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap @@ -1,15 +1,36 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl reexporter::borsh::de::BorshDeserialize for A { fn deserialize_reader<__R: reexporter::borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader( + let variant_tag = ::deserialize_reader( reader, )?; - ::deserialize_variant(reader, tag) + let mut return_value = if variant_tag == 0u8 { + A::B { + x: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + y: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + reexporter::borsh::io::Error::new( + reexporter::borsh::io::ErrorKind::InvalidData, + reexporter::borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl reexporter::borsh::de::EnumExt for A { diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new deleted file mode 100644 index 2d1961394..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_enum_with_custom_crate.snap.new +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 164 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl reexporter::borsh::de::BorshDeserialize for A { - fn deserialize_reader<__R: reexporter::borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - A::B { - x: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, - y: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, - reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - reexporter::borsh::io::Error::new( - reexporter::borsh::io::ErrorKind::InvalidData, - reexporter::borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl reexporter::borsh::de::EnumExt for A { - fn deserialize_variant<__R: reexporter::borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - A::B { - x: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, - y: reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, - reexporter::borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - reexporter::borsh::io::Error::new( - reexporter::borsh::io::ErrorKind::InvalidData, - reexporter::borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap index d8b85259c..f16009dd7 100644 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap +++ b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/deserialize/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::de::BorshDeserialize for A where @@ -11,8 +12,30 @@ where fn deserialize_reader<__R: borsh::io::Read>( reader: &mut __R, ) -> ::core::result::Result { - let tag = ::deserialize_reader(reader)?; - ::deserialize_variant(reader, tag) + let variant_tag = ::deserialize_reader( + reader, + )?; + let mut return_value = if variant_tag == 0u8 { + A::B { + x: borsh::BorshDeserialize::deserialize_reader(reader)?, + y: borsh::BorshDeserialize::deserialize_reader(reader)?, + } + } else if variant_tag == 1u8 { + A::C( + borsh::BorshDeserialize::deserialize_reader(reader)?, + borsh::BorshDeserialize::deserialize_reader(reader)?, + ) + } else { + return Err( + borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + borsh::__private::maybestd::format!( + "Unexpected variant tag: {:?}", variant_tag + ), + ), + ) + }; + Ok(return_value) } } impl borsh::de::EnumExt for A diff --git a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new b/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new deleted file mode 100644 index a8138af2f..000000000 --- a/borsh-derive/src/internals/deserialize/enums/snapshots/simple_generics.snap.new +++ /dev/null @@ -1,73 +0,0 @@ ---- -source: borsh-derive/src/internals/deserialize/enums/mod.rs -assertion_line: 181 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::de::BorshDeserialize for A -where - K: borsh::de::BorshDeserialize, - V: borsh::de::BorshDeserialize, - U: borsh::de::BorshDeserialize, -{ - fn deserialize_reader<__R: borsh::io::Read>( - reader: &mut __R, - ) -> ::core::result::Result { - let variant_tag = ::deserialize_reader( - reader, - )?; - let mut return_value = if variant_tag == 0u8 { - A::B { - x: borsh::BorshDeserialize::deserialize_reader(reader)?, - y: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} -impl borsh::de::EnumExt for A -where - K: borsh::de::BorshDeserialize, - V: borsh::de::BorshDeserialize, - U: borsh::de::BorshDeserialize, -{ - fn deserialize_variant<__R: borsh::io::Read>( - reader: &mut __R, - variant_tag: u8, - ) -> ::core::result::Result { - let mut return_value = if variant_tag == 0u8 { - A::B { - x: borsh::BorshDeserialize::deserialize_reader(reader)?, - y: borsh::BorshDeserialize::deserialize_reader(reader)?, - } - } else if variant_tag == 1u8 { - A::C( - borsh::BorshDeserialize::deserialize_reader(reader)?, - borsh::BorshDeserialize::deserialize_reader(reader)?, - ) - } else { - return Err( - borsh::io::Error::new( - borsh::io::ErrorKind::InvalidData, - borsh::__private::maybestd::format!( - "Unexpected variant tag: {:?}", variant_tag - ), - ), - ) - }; - Ok(return_value) - } -} diff --git a/borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap b/borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap index 856f9f630..df9e24cb6 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for A where @@ -38,12 +39,13 @@ where as borsh::BorshSchema>::add_definitions_recursively(definitions); as borsh::BorshSchema>::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "B".into(), < AB < K, V > as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "C".into(), < AC < K > as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -52,4 +54,3 @@ where ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap.new b/borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap.new deleted file mode 100644 index 65800467e..000000000 --- a/borsh-derive/src/internals/schema/enums/snapshots/recursive_enum.snap.new +++ /dev/null @@ -1,56 +0,0 @@ ---- -source: borsh-derive/src/internals/schema/enums/mod.rs -assertion_line: 403 -expression: pretty_print_syn_str(&actual).unwrap() ---- -impl borsh::BorshSchema for A -where - V: Value, - K: borsh::BorshSchema, - V: borsh::BorshSchema, -{ - fn declaration() -> borsh::schema::Declaration { - let params = borsh::__private::maybestd::vec![ - < K as borsh::BorshSchema > ::declaration(), < V as borsh::BorshSchema > - ::declaration() - ]; - format!(r#"{}<{}>"#, "A", params.join(", ")) - } - fn add_definitions_recursively( - definitions: &mut borsh::__private::maybestd::collections::BTreeMap< - borsh::schema::Declaration, - borsh::schema::Definition, - >, - ) { - #[allow(dead_code)] - #[derive(borsh::BorshSchema)] - #[borsh(crate = "borsh")] - struct AB - where - V: Value, - { - x: HashMap, - y: String, - } - #[allow(dead_code)] - #[derive(borsh::BorshSchema)] - #[borsh(crate = "borsh")] - struct AC(K, Vec); - as borsh::BorshSchema>::add_definitions_recursively(definitions); - as borsh::BorshSchema>::add_definitions_recursively(definitions); - let definition = borsh::schema::Definition::Enum { - tag_width: 1u8, - variants: borsh::__private::maybestd::vec![ - (u8::from(0u8) as i64, "B".into(), < AB < K, V > as borsh::BorshSchema > - ::declaration()), (u8::from(1u8) as i64, "C".into(), < AC < K > as - borsh::BorshSchema > ::declaration()) - ], - tag_signed: false, - }; - borsh::schema::add_definition( - ::declaration(), - definition, - definitions, - ); - } -} diff --git a/borsh/tests/schema/snapshots/tests__schema__test_ip_addr__ip_addr_schema.snap b/borsh/tests/schema/snapshots/tests__schema__test_ip_addr__ip_addr_schema.snap index 68f0c7109..8037a8da9 100644 --- a/borsh/tests/schema/snapshots/tests__schema__test_ip_addr__ip_addr_schema.snap +++ b/borsh/tests/schema/snapshots/tests__schema__test_ip_addr__ip_addr_schema.snap @@ -1,10 +1,12 @@ --- source: borsh/tests/schema/test_ip_addr.rs expression: "format!(\"{:#?}\", defs)" +snapshot_kind: text --- { "IpAddr": Enum { tag_width: 1, + tag_signed: false, variants: [ ( 0, diff --git a/borsh/tests/schema/snapshots/tests__schema__test_simple_enums__complex_enum_with_schema.snap b/borsh/tests/schema/snapshots/tests__schema__test_simple_enums__complex_enum_with_schema.snap index 1cdf94d5f..674c08f43 100644 --- a/borsh/tests/schema/snapshots/tests__schema__test_simple_enums__complex_enum_with_schema.snap +++ b/borsh/tests/schema/snapshots/tests__schema__test_simple_enums__complex_enum_with_schema.snap @@ -1,6 +1,7 @@ --- source: borsh/tests/schema/test_simple_enums.rs expression: data +snapshot_kind: text --- [ 1, @@ -19,6 +20,7 @@ expression: data 65, 3, 1, + 0, 4, 0, 0, From aef4b2e1e9cbdf33a195e454870fb9dd1ffbe29e Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 3 Nov 2024 23:21:44 +0000 Subject: [PATCH 14/17] fmt --- .../src/internals/attributes/item/mod.rs | 8 +++++-- .../src/internals/deserialize/enums/mod.rs | 13 ++++++++--- .../src/internals/enum_discriminant.rs | 22 ++++++++----------- .../src/internals/schema/enums/mod.rs | 10 ++++++--- .../src/internals/serialize/enums/mod.rs | 7 +++++- borsh/src/schema/container_ext/max_size.rs | 2 +- 6 files changed, 39 insertions(+), 23 deletions(-) diff --git a/borsh-derive/src/internals/attributes/item/mod.rs b/borsh-derive/src/internals/attributes/item/mod.rs index c509a6d85..b4452aace 100644 --- a/borsh-derive/src/internals/attributes/item/mod.rs +++ b/borsh-derive/src/internals/attributes/item/mod.rs @@ -41,7 +41,7 @@ pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result = &input.attrs; let mut use_discriminant = None; let attr = attrs.iter().find(|attr| attr.path() == BORSH); @@ -86,7 +86,11 @@ pub(crate) fn get_maybe_rust_repr(input: &ItemEnum) -> Option<(TypePath, Span)> .attrs .iter() .find(|attr| attr.path() == RUST_REPR) - .map(|attr| attr.parse_args::().map(|value| (attr, value)).unwrap()) + .map(|attr| { + attr.parse_args::() + .map(|value| (attr, value)) + .unwrap() + }) .map(|(attr, value)| (value, attr.span())) } diff --git a/borsh-derive/src/internals/deserialize/enums/mod.rs b/borsh-derive/src/internals/deserialize/enums/mod.rs index e4634c675..c9e7eb7d1 100644 --- a/borsh-derive/src/internals/deserialize/enums/mod.rs +++ b/borsh-derive/src/internals/deserialize/enums/mod.rs @@ -13,7 +13,12 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let use_discriminant = item::contains_use_discriminant(input)?; let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; let maybe_rust_repr = item::get_maybe_rust_repr(input); - let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width, maybe_rust_repr, use_discriminant)?; + let discriminants = Discriminants::new( + &input.variants, + maybe_borsh_tag_width, + maybe_rust_repr, + use_discriminant, + )?; let mut generics_output = deserialize::GenericsOutput::new(&generics); let discriminant_type = discriminants.discriminant_type(); for (variant_idx, variant) in input.variants.iter().enumerate() { @@ -55,7 +60,9 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { } }; - let impl_trait = if discriminant_type.path.get_ident() == (syn::parse_str::("u8").unwrap().path.get_ident()) { + let impl_trait = if discriminant_type.path.get_ident() + == (syn::parse_str::("u8").unwrap().path.get_ident()) + { quote! { impl #impl_generics #cratename::de::EnumExt for #name #ty_generics #where_clause { fn deserialize_variant<__R: #cratename::io::Read>( @@ -64,7 +71,7 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { ) -> ::core::result::Result { #deserialize_variant } - } + } } } else { quote! {} diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index 4bf44185f..02b623c56 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -6,9 +6,9 @@ use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, ToTokens}; use syn::{punctuated::Punctuated, spanned::Spanned, token::Comma, TypePath, Variant}; -pub struct Discriminants{ - variants: HashMap, - discriminant_type : syn::TypePath, +pub struct Discriminants { + variants: HashMap, + discriminant_type: syn::TypePath, use_discriminant: bool, tag_width: u8, } @@ -19,7 +19,7 @@ impl Discriminants { pub fn new( variants: &Punctuated, maybe_borsh_tag_width: Option<(u8, Span)>, - maybe_rust_repr: Option<(syn::TypePath,Span)>, + maybe_rust_repr: Option<(syn::TypePath, Span)>, use_discriminant: bool, ) -> syn::Result { let mut map = HashMap::new(); @@ -33,7 +33,7 @@ impl Discriminants { next_discriminant_if_not_specified = quote! { #this_discriminant + 1 }; map.insert(variant.ident.clone(), this_discriminant); - } + } let mut discriminant_type: TypePath = syn::parse_str("u8").unwrap(); let mut tag_width = 1; @@ -53,7 +53,7 @@ impl Discriminants { )); }; match rust_repr.path.get_ident() { - Some(repr_type) => { + Some(repr_type) => { let repr_size= match repr_type.to_string().as_str() { "u8" => { 1 @@ -88,7 +88,7 @@ impl Discriminants { } Ok(Self { - variants : map, + variants: map, discriminant_type, use_discriminant, tag_width, @@ -103,11 +103,7 @@ impl Discriminants { self.tag_width } - pub fn get( - &self, - variant_ident: &Ident, - variant_idx: usize, - ) -> syn::Result { + pub fn get(&self, variant_ident: &Ident, variant_idx: usize) -> syn::Result { let result = if self.use_discriminant { let discriminant_value = self.variants.get(variant_ident).unwrap(); quote! { #discriminant_value } @@ -121,7 +117,7 @@ impl Discriminants { err ), ) - })?; + })?; quote! { #variant_idx } }; Ok(result) diff --git a/borsh-derive/src/internals/schema/enums/mod.rs b/borsh-derive/src/internals/schema/enums/mod.rs index 273a155c9..15c46ffb2 100644 --- a/borsh-derive/src/internals/schema/enums/mod.rs +++ b/borsh-derive/src/internals/schema/enums/mod.rs @@ -38,7 +38,12 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let use_discriminant = item::contains_use_discriminant(input)?; let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; let maybe_rust_repr = item::get_maybe_rust_repr(input); - let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width, maybe_rust_repr, use_discriminant)?; + let discriminants = Discriminants::new( + &input.variants, + maybe_borsh_tag_width, + maybe_rust_repr, + use_discriminant, + )?; // Generate functions that return the schema for variants. let mut variants_defs = vec![]; @@ -108,8 +113,7 @@ fn process_discriminant( variant_ident: &Ident, info: DiscriminantInfo<'_>, ) -> syn::Result { - info.discriminants - .get(variant_ident, info.variant_idx) + info.discriminants.get(variant_ident, info.variant_idx) } fn process_variant( diff --git a/borsh-derive/src/internals/serialize/enums/mod.rs b/borsh-derive/src/internals/serialize/enums/mod.rs index e9e284040..9c85c09e2 100644 --- a/borsh-derive/src/internals/serialize/enums/mod.rs +++ b/borsh-derive/src/internals/serialize/enums/mod.rs @@ -19,7 +19,12 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let use_discriminant = item::contains_use_discriminant(input)?; let maybe_borsh_tag_width = item::get_maybe_borsh_tag_width(input)?; let maybe_rust_repr = item::get_maybe_rust_repr(input); - let discriminants = Discriminants::new(&input.variants, maybe_borsh_tag_width, maybe_rust_repr, use_discriminant)?; + let discriminants = Discriminants::new( + &input.variants, + maybe_borsh_tag_width, + maybe_rust_repr, + use_discriminant, + )?; let mut has_unit_variant = false; for (variant_idx, variant) in input.variants.iter().enumerate() { diff --git a/borsh/src/schema/container_ext/max_size.rs b/borsh/src/schema/container_ext/max_size.rs index a7e71e54c..f963b9e77 100644 --- a/borsh/src/schema/container_ext/max_size.rs +++ b/borsh/src/schema/container_ext/max_size.rs @@ -126,7 +126,7 @@ fn max_serialized_size_impl<'a>( Ok(Definition::Enum { tag_width, variants, - tag_signed: _, + tag_signed: _, }) => { let mut max = 0; for (_, _, variant) in variants { From 538976796350973a80416c41805c2f0ed5a92801 Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 3 Nov 2024 23:30:07 +0000 Subject: [PATCH 15/17] clean up --- Cargo.toml | 3 +-- .../src/internals/attributes/item/mod.rs | 4 ++-- borsh-derive/src/internals/enum_discriminant.rs | 6 +++--- borsh-derive/src/internals/schema/enums/mod.rs | 2 -- borsh/examples/serde_json_value.rs | 8 ++++---- .../test_enum_discriminants.rs | 16 ++++++---------- borsh/tests/schema/test_enum_discriminants.rs | 2 ++ .../tests/schema/test_schema_with_third_party.rs | 2 +- rust-toolchain.toml | 10 ---------- 9 files changed, 19 insertions(+), 34 deletions(-) delete mode 100644 rust-toolchain.toml diff --git a/Cargo.toml b/Cargo.toml index 1e86dc9ee..2a1e1907c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,5 +4,4 @@ members = ["borsh", "borsh-derive", "fuzz/fuzz-run", "benchmarks"] [workspace.package] # shared version of all public crates in the workspace version = "1.5.1" -# rust-version = "1.67.0" -rust-version = "1.81.0" +rust-version = "1.67.0" diff --git a/borsh-derive/src/internals/attributes/item/mod.rs b/borsh-derive/src/internals/attributes/item/mod.rs index b4452aace..f85ec5ace 100644 --- a/borsh-derive/src/internals/attributes/item/mod.rs +++ b/borsh-derive/src/internals/attributes/item/mod.rs @@ -36,10 +36,10 @@ pub fn check_attributes(derive_input: &DeriveInput) -> Result<(), Error> { } pub(crate) fn contains_use_discriminant(input: &ItemEnum) -> Result { - if input.variants.len() > 256 { + if input.variants.len() > u8::MAX as usize + 1 { return Err(syn::Error::new( input.span(), - "up to 256 enum variants are supported", + format!("up to {} enum variants are supported", u8::MAX as usize + 1), )); } let attrs: &Vec = &input.attrs; diff --git a/borsh-derive/src/internals/enum_discriminant.rs b/borsh-derive/src/internals/enum_discriminant.rs index 02b623c56..232d0ba3b 100644 --- a/borsh-derive/src/internals/enum_discriminant.rs +++ b/borsh-derive/src/internals/enum_discriminant.rs @@ -1,10 +1,9 @@ -use core::convert::TryInto; use std::collections::HashMap; use std::convert::TryFrom; use proc_macro2::{Ident, Span, TokenStream}; -use quote::{quote, ToTokens}; -use syn::{punctuated::Punctuated, spanned::Spanned, token::Comma, TypePath, Variant}; +use quote::quote; +use syn::{punctuated::Punctuated, token::Comma, TypePath, Variant}; pub struct Discriminants { variants: HashMap, @@ -99,6 +98,7 @@ impl Discriminants { &self.discriminant_type } + #[allow(dead_code)] pub fn tag_width(&self) -> u8 { self.tag_width } diff --git a/borsh-derive/src/internals/schema/enums/mod.rs b/borsh-derive/src/internals/schema/enums/mod.rs index 15c46ffb2..452ccb225 100644 --- a/borsh-derive/src/internals/schema/enums/mod.rs +++ b/borsh-derive/src/internals/schema/enums/mod.rs @@ -53,7 +53,6 @@ pub fn process(input: &ItemEnum, cratename: Path) -> syn::Result { let discriminant_info = DiscriminantInfo { variant_idx, discriminants: &discriminants, - use_discriminant, }; let variant_output = process_variant( variant, @@ -106,7 +105,6 @@ struct VariantOutput { struct DiscriminantInfo<'a> { variant_idx: usize, discriminants: &'a Discriminants, - use_discriminant: bool, } fn process_discriminant( diff --git a/borsh/examples/serde_json_value.rs b/borsh/examples/serde_json_value.rs index 21cadf758..a4d11b7bf 100644 --- a/borsh/examples/serde_json_value.rs +++ b/borsh/examples/serde_json_value.rs @@ -75,7 +75,7 @@ mod serde_json_value { &(u32::try_from(array.len()).map_err(|_| ErrorKind::InvalidData)?).to_le_bytes(), )?; for item in array { - serialize_value(&item, writer)?; + serialize_value(item, writer)?; } Ok(()) } @@ -92,7 +92,7 @@ mod serde_json_value { for (key, value) in map { key.serialize(writer)?; - serialize_value(&value, writer)?; + serialize_value(value, writer)?; } Ok(()) @@ -260,8 +260,8 @@ fn main() { "negative_integer": -88888, "positive_float": 123.45, "negative_float": -888.88, - "positive_max": 1.7976931348623157e+308, - "negative_max": -1.7976931348623157e+308, + "positive_max": 1.797_693_134_862_315_7e308, + "negative_max": -1.797_693_134_862_315_7e308, "string": "Larry", "array_of_nulls": [null, null, null], "array_of_numbers": [0, -1, 1, 1.1, -1.1, 34798324], diff --git a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs index 88dcd372c..237674bbb 100644 --- a/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs +++ b/borsh/tests/roundtrip/requires_derive_category/test_enum_discriminants.rs @@ -29,7 +29,7 @@ enum XYNoDiscriminant { #[test] fn test_discriminant_serde_no_unit_type() { - let values = vec![XY::A, XY::B, XY::C, XY::E, XY::D(12, 14), XY::F(35325423)]; + let values = [XY::A, XY::B, XY::C, XY::E, XY::D(12, 14), XY::F(35325423)]; let expected_discriminants = [0u8, 20, 21, 10, 22, 11]; for (ind, value) in values.iter().enumerate() { @@ -89,14 +89,12 @@ pub fn u32_discriminant() { #[test] fn test_discriminant_serde_no_unit_type_no_use_discriminant() { - let values = vec![ - XYNoDiscriminant::A, + let values = [XYNoDiscriminant::A, XYNoDiscriminant::B, XYNoDiscriminant::C, XYNoDiscriminant::D(12, 14), XYNoDiscriminant::E, - XYNoDiscriminant::F(35325423), - ]; + XYNoDiscriminant::F(35325423)]; let expected_discriminants = [0u8, 1, 2, 3, 4, 5]; for (ind, value) in values.iter().enumerate() { @@ -153,14 +151,12 @@ enum XNoDiscriminant { #[test] fn test_discriminant_serde_no_use_discriminant() { - let values = vec![ - XNoDiscriminant::A, + let values = [XNoDiscriminant::A, XNoDiscriminant::B, XNoDiscriminant::C, XNoDiscriminant::D, XNoDiscriminant::E, - XNoDiscriminant::F, - ]; + XNoDiscriminant::F]; let expected_discriminants = [0u8, 1, 2, 3, 4, 5]; for (index, value) in values.iter().enumerate() { let data = to_vec(value).unwrap(); @@ -217,7 +213,7 @@ fn test_deserialize_invalid_discriminant() { #[test] fn test_discriminant_serde() { - let values = vec![X::A, X::B, X::C, X::D, X::E, X::F]; + let values = [X::A, X::B, X::C, X::D, X::E, X::F]; let expected_discriminants = [0u8, 20, 21, 22, 10, 11]; for (index, value) in values.iter().enumerate() { let data = to_vec(value).unwrap(); diff --git a/borsh/tests/schema/test_enum_discriminants.rs b/borsh/tests/schema/test_enum_discriminants.rs index 5004f2f8c..770855715 100644 --- a/borsh/tests/schema/test_enum_discriminants.rs +++ b/borsh/tests/schema/test_enum_discriminants.rs @@ -109,6 +109,7 @@ fn tag_widths() { #[derive(BorshSchema)] #[borsh(use_discriminant=true, tag_width = 2)] #[repr(u16)] + #[allow(dead_code)] enum U16Discriminant { A = 42u16, } @@ -132,6 +133,7 @@ fn tag_widths() { #[derive(BorshSchema)] #[borsh(use_discriminant = true, tag_width = 4)] #[repr(u32)] + #[allow(dead_code)] enum U32Discriminant { A = 42u32, } diff --git a/borsh/tests/schema/test_schema_with_third_party.rs b/borsh/tests/schema/test_schema_with_third_party.rs index b8b104a9d..c246c6d05 100644 --- a/borsh/tests/schema/test_schema_with_third_party.rs +++ b/borsh/tests/schema/test_schema_with_third_party.rs @@ -10,7 +10,7 @@ mod third_party_impl { pub(super) fn declaration( ) -> borsh::schema::Declaration { - let params = vec![::declaration(), ::declaration()]; + let params = [::declaration(), ::declaration()]; format!(r#"{}<{}>"#, "ThirdParty", params.join(", ")) } diff --git a/rust-toolchain.toml b/rust-toolchain.toml deleted file mode 100644 index f602afad8..000000000 --- a/rust-toolchain.toml +++ /dev/null @@ -1,10 +0,0 @@ -[toolchain] -channel = "1.81.0" - -# Default profile includes `rustfmt`, `clippy`, `rust-docs`. -# https://rust-lang.github.io/rustup/concepts/profiles.html -profile = "default" -components = ["rust-analyzer"] - -# For static linking for deployment. -targets = ["x86_64-unknown-linux-musl"] From bb457c769e67679eda2ba567f4125aac5f29f88c Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 3 Nov 2024 23:35:34 +0000 Subject: [PATCH 16/17] fixed CI --- .../schema/enums/snapshots/trailing_comma_generics.snap | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/borsh-derive/src/internals/schema/enums/snapshots/trailing_comma_generics.snap b/borsh-derive/src/internals/schema/enums/snapshots/trailing_comma_generics.snap index d6dfffc9a..1dc700234 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/trailing_comma_generics.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/trailing_comma_generics.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for Side where @@ -41,12 +42,13 @@ where as borsh::BorshSchema>::add_definitions_recursively(definitions); as borsh::BorshSchema>::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "Left".into(), < SideLeft < A > as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "Right" .into(), < SideRight < B > as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -55,4 +57,3 @@ where ); } } - From 8e1a8b29f88d5c8e7eaec5df73d476afe103e8a5 Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Sun, 3 Nov 2024 23:38:55 +0000 Subject: [PATCH 17/17] oh more CI --- .../schema/enums/snapshots/borsh_discriminant_false.snap | 5 +++-- .../schema/enums/snapshots/borsh_discriminant_true.snap | 5 +++-- .../src/internals/schema/enums/snapshots/complex_enum.snap | 5 +++-- .../schema/enums/snapshots/complex_enum_generics.snap | 5 +++-- .../complex_enum_generics_borsh_skip_named_field.snap | 5 +++-- .../complex_enum_generics_borsh_skip_tuple_field.snap | 5 +++-- .../schema/enums/snapshots/filter_foreign_attrs.snap | 5 +++-- .../schema/enums/snapshots/generic_associated_type.snap | 5 +++-- .../snapshots/generic_associated_type_param_override.snap | 5 +++-- .../src/internals/schema/enums/snapshots/simple_enum.snap | 5 +++-- .../enums/snapshots/simple_enum_with_custom_crate.snap | 5 +++-- .../internals/schema/enums/snapshots/single_field_enum.snap | 5 +++-- .../internals/schema/enums/snapshots/with_funcs_attr.snap | 5 +++-- 13 files changed, 39 insertions(+), 26 deletions(-) diff --git a/borsh-derive/src/internals/schema/enums/snapshots/borsh_discriminant_false.snap b/borsh-derive/src/internals/schema/enums/snapshots/borsh_discriminant_false.snap index 4fa592109..e8009a830 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/borsh_discriminant_false.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/borsh_discriminant_false.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for X { fn declaration() -> borsh::schema::Declaration { @@ -43,7 +44,7 @@ impl borsh::BorshSchema for X { ::add_definitions_recursively(definitions); ::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "A".into(), < XA as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "B".into(), < XB as @@ -54,6 +55,7 @@ impl borsh::BorshSchema for X { (u8::from(5u8) as i64, "F".into(), < XF as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -62,4 +64,3 @@ impl borsh::BorshSchema for X { ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/borsh_discriminant_true.snap b/borsh-derive/src/internals/schema/enums/snapshots/borsh_discriminant_true.snap index 1b234f1df..2a600241c 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/borsh_discriminant_true.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/borsh_discriminant_true.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for X { fn declaration() -> borsh::schema::Declaration { @@ -43,7 +44,7 @@ impl borsh::BorshSchema for X { ::add_definitions_recursively(definitions); ::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0) as i64, "A".into(), < XA as borsh::BorshSchema > ::declaration()), (u8::from(20) as i64, "B".into(), < XB as @@ -54,6 +55,7 @@ impl borsh::BorshSchema for X { ::declaration()), (u8::from(10 + 1) as i64, "F".into(), < XF as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -62,4 +64,3 @@ impl borsh::BorshSchema for X { ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/complex_enum.snap b/borsh-derive/src/internals/schema/enums/snapshots/complex_enum.snap index 60006941b..0d5a5b543 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/complex_enum.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/complex_enum.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for A { fn declaration() -> borsh::schema::Declaration { @@ -36,7 +37,7 @@ impl borsh::BorshSchema for A { ::add_definitions_recursively(definitions); ::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "Bacon".into(), < ABacon as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "Eggs".into(), < AEggs as @@ -45,6 +46,7 @@ impl borsh::BorshSchema for A { (u8::from(3u8) as i64, "Sausage".into(), < ASausage as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -53,4 +55,3 @@ impl borsh::BorshSchema for A { ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics.snap b/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics.snap index 46c0ca102..5a7c2bcea 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for A where @@ -44,7 +45,7 @@ where as borsh::BorshSchema>::add_definitions_recursively(definitions); as borsh::BorshSchema>::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "Bacon".into(), < ABacon as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "Eggs".into(), < AEggs as @@ -53,6 +54,7 @@ where (u8::from(3u8) as i64, "Sausage".into(), < ASausage < W > as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -61,4 +63,3 @@ where ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics_borsh_skip_named_field.snap b/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics_borsh_skip_named_field.snap index c73bb784d..b3fa481a5 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics_borsh_skip_named_field.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics_borsh_skip_named_field.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for A where @@ -46,7 +47,7 @@ where as borsh::BorshSchema>::add_definitions_recursively(definitions); as borsh::BorshSchema>::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "Bacon".into(), < ABacon as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "Eggs".into(), < AEggs as @@ -55,6 +56,7 @@ where (u8::from(3u8) as i64, "Sausage".into(), < ASausage < W, U > as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -63,4 +65,3 @@ where ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics_borsh_skip_tuple_field.snap b/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics_borsh_skip_tuple_field.snap index a531044c8..5d90a6aaa 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics_borsh_skip_tuple_field.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/complex_enum_generics_borsh_skip_tuple_field.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for A where @@ -46,7 +47,7 @@ where as borsh::BorshSchema>::add_definitions_recursively(definitions); as borsh::BorshSchema>::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "Bacon".into(), < ABacon as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "Eggs".into(), < AEggs as @@ -55,6 +56,7 @@ where (u8::from(3u8) as i64, "Sausage".into(), < ASausage < W > as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -63,4 +65,3 @@ where ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/filter_foreign_attrs.snap b/borsh-derive/src/internals/schema/enums/snapshots/filter_foreign_attrs.snap index 3eaab191e..e166faa44 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/filter_foreign_attrs.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/filter_foreign_attrs.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for A { fn declaration() -> borsh::schema::Declaration { @@ -30,12 +31,13 @@ impl borsh::BorshSchema for A { ::add_definitions_recursively(definitions); ::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "B".into(), < AB as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "Negative".into(), < ANegative as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -44,4 +46,3 @@ impl borsh::BorshSchema for A { ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/generic_associated_type.snap b/borsh-derive/src/internals/schema/enums/snapshots/generic_associated_type.snap index c87de892b..d573051b7 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/generic_associated_type.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/generic_associated_type.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for EnumParametrized where @@ -57,12 +58,13 @@ where T, > as borsh::BorshSchema>::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "B".into(), < EnumParametrizedB < K, V > as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "C".into(), < EnumParametrizedC < T > as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -71,4 +73,3 @@ where ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/generic_associated_type_param_override.snap b/borsh-derive/src/internals/schema/enums/snapshots/generic_associated_type_param_override.snap index 9389a848d..4f6bb9f3a 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/generic_associated_type_param_override.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/generic_associated_type_param_override.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for EnumParametrized where @@ -58,12 +59,13 @@ where T, > as borsh::BorshSchema>::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "B".into(), < EnumParametrizedB < K, V > as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "C".into(), < EnumParametrizedC < T > as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -72,4 +74,3 @@ where ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/simple_enum.snap b/borsh-derive/src/internals/schema/enums/snapshots/simple_enum.snap index cbadbaf7f..65671829c 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/simple_enum.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/simple_enum.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for A { fn declaration() -> borsh::schema::Declaration { @@ -23,12 +24,13 @@ impl borsh::BorshSchema for A { ::add_definitions_recursively(definitions); ::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "Bacon".into(), < ABacon as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "Eggs".into(), < AEggs as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -37,4 +39,3 @@ impl borsh::BorshSchema for A { ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/simple_enum_with_custom_crate.snap b/borsh-derive/src/internals/schema/enums/snapshots/simple_enum_with_custom_crate.snap index 368a39d92..ff25f7db9 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/simple_enum_with_custom_crate.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/simple_enum_with_custom_crate.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl reexporter::borsh::BorshSchema for A { fn declaration() -> reexporter::borsh::schema::Declaration { @@ -27,13 +28,14 @@ impl reexporter::borsh::BorshSchema for A { definitions, ); let definition = reexporter::borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: reexporter::borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "Bacon".into(), < ABacon as reexporter::borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "Eggs".into(), < AEggs as reexporter::borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; reexporter::borsh::schema::add_definition( ::declaration(), @@ -42,4 +44,3 @@ impl reexporter::borsh::BorshSchema for A { ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/single_field_enum.snap b/borsh-derive/src/internals/schema/enums/snapshots/single_field_enum.snap index f3a886f9b..3ed379674 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/single_field_enum.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/single_field_enum.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for A { fn declaration() -> borsh::schema::Declaration { @@ -18,11 +19,12 @@ impl borsh::BorshSchema for A { struct ABacon; ::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "Bacon".into(), < ABacon as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -31,4 +33,3 @@ impl borsh::BorshSchema for A { ); } } - diff --git a/borsh-derive/src/internals/schema/enums/snapshots/with_funcs_attr.snap b/borsh-derive/src/internals/schema/enums/snapshots/with_funcs_attr.snap index 17f16077c..d3085df8e 100644 --- a/borsh-derive/src/internals/schema/enums/snapshots/with_funcs_attr.snap +++ b/borsh-derive/src/internals/schema/enums/snapshots/with_funcs_attr.snap @@ -1,6 +1,7 @@ --- source: borsh-derive/src/internals/schema/enums/mod.rs expression: pretty_print_syn_str(&actual).unwrap() +snapshot_kind: text --- impl borsh::BorshSchema for C where @@ -42,12 +43,13 @@ where ::add_definitions_recursively(definitions); as borsh::BorshSchema>::add_definitions_recursively(definitions); let definition = borsh::schema::Definition::Enum { - tag_width: 1, + tag_width: 1u8, variants: borsh::__private::maybestd::vec![ (u8::from(0u8) as i64, "C3".into(), < CC3 as borsh::BorshSchema > ::declaration()), (u8::from(1u8) as i64, "C4".into(), < CC4 < K, V > as borsh::BorshSchema > ::declaration()) ], + tag_signed: false, }; borsh::schema::add_definition( ::declaration(), @@ -56,4 +58,3 @@ where ); } } -