Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Make constraints explicitly constant and evaluated in compile time & move some computation there (OER/PER) #318

Merged
merged 22 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,10 @@ snafu = { version = "0.8.5", default-features = false, features = [
serde_json = { version = "1", default-features = false, features = ["alloc"] }

[dev-dependencies]
criterion = { version = "0.5.1", default-features = false, features = ["plotters", "cargo_bench_support"] }
criterion = { version = "0.5.1", default-features = false, features = [
"plotters",
"cargo_bench_support",
] }
iai-callgrind = "0.14.0"
once_cell = "1.20.2"
pretty_assertions.workspace = true
Expand Down
206 changes: 142 additions & 64 deletions macros/macros_impl/src/config.rs

Large diffs are not rendered by default.

32 changes: 29 additions & 3 deletions macros/macros_impl/src/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,22 @@ pub fn derive_struct_impl(
decoder.decode_explicit_prefix::<#ty>(tag).map(Self)
}
} else {
let constraints = config
.constraints
.const_expr(crate_root)
.unwrap_or_else(|| quote!(#crate_root::types::Constraints::default()));
let constraint_name = format_ident!("DELEGATE_DECODE_CONSTRAINT");
let constraint_def = if generics.params.is_empty() {
quote! {
let #constraint_name: #crate_root::types::Constraints = const {<#ty as #crate_root::AsnType>::CONSTRAINTS.intersect(#constraints)}.intersect(constraints);
}
} else {
quote! {
let #constraint_name: #crate_root::types::Constraints = <#ty as #crate_root::AsnType>::CONSTRAINTS.intersect(constraints).intersect(const {#constraints });
}
};
quote! {
#constraint_def
match tag {
#crate_root::types::Tag::EOC => {
Ok(Self(<#ty>::decode(decoder)?))
Expand All @@ -36,7 +51,7 @@ pub fn derive_struct_impl(
<#ty as #crate_root::Decode>::decode_with_tag_and_constraints(
decoder,
tag,
<#ty as #crate_root::AsnType>::CONSTRAINTS.override_constraints(constraints),
#constraint_name
).map(Self)
}
}
Expand Down Expand Up @@ -186,7 +201,18 @@ pub fn derive_struct_impl(
count_root_fields += 1;
}

list.push(field_config.decode_field_def(&name, i));
let type_params: Vec<_> = generics
.params
.iter()
.filter_map(|param| {
if let syn::GenericParam::Type(type_param) = param {
Some(type_param.ident.clone())
} else {
None
}
})
.collect();
list.push(field_config.decode_field_def(&name, i, &type_params));
}

let fields = match container.fields {
Expand Down Expand Up @@ -254,7 +280,7 @@ pub fn derive_struct_impl(

quote! {
impl #impl_generics #crate_root::Decode for #name #ty_generics #where_clause {
fn decode_with_tag_and_constraints<'constraints, D: #crate_root::Decoder>(decoder: &mut D, tag: #crate_root::types::Tag, constraints: #crate_root::types::Constraints<'constraints>) -> core::result::Result<Self, D::Error> {
fn decode_with_tag_and_constraints<D: #crate_root::Decoder>(decoder: &mut D, tag: #crate_root::types::Tag, constraints: #crate_root::types::Constraints) -> core::result::Result<Self, D::Error> {
#decode_impl
}
}
Expand Down
28 changes: 25 additions & 3 deletions macros/macros_impl/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,22 @@ pub fn derive_struct_impl(
let mut field_encodings = Vec::with_capacity(container.fields.len());
let mut number_root_fields: usize = 0;
let mut number_extended_fields: usize = 0;
let type_params: Vec<_> = generics
.params
.iter()
.filter_map(|param| {
if let syn::GenericParam::Type(type_param) = param {
Some(type_param.ident.clone())
} else {
None
}
})
.collect();

// Count the number of root and extended fields so that encoder can know the number of fields in advance
for (i, field) in container.fields.iter().enumerate() {
let field_config = FieldConfig::new(field, config);
let field_encoding = field_config.encode(i, true);
let field_encoding = field_config.encode(i, true, &type_params);

if field_config.is_extension() {
number_extended_fields += 1;
Expand All @@ -39,7 +50,18 @@ pub fn derive_struct_impl(
// Note: encoder must be aware if the field is optional and present, so we should not do the presence check on this level
quote!(encoder.encode_explicit_prefix(#tag, &self.0).map(drop))
} else {
let constraint_name = quote::format_ident!("effective_constraint");
let constraint_def = if generics.params.is_empty() {
quote! {
let #constraint_name: #crate_root::types::Constraints = const {<#ty as #crate_root::AsnType>::CONSTRAINTS}.intersect(constraints);
}
} else {
quote! {
let #constraint_name: #crate_root::types::Constraints = <#ty as #crate_root::AsnType>::CONSTRAINTS.intersect(constraints);
}
};
quote!(
#constraint_def
match tag {
#crate_root::types::Tag::EOC => {
self.0.encode(encoder)
Expand All @@ -49,7 +71,7 @@ pub fn derive_struct_impl(
&self.0,
encoder,
tag,
<#ty as #crate_root::AsnType>::CONSTRAINTS.override_constraints(constraints)
#constraint_name
)
}
}
Expand Down Expand Up @@ -87,7 +109,7 @@ pub fn derive_struct_impl(
quote! {
#[allow(clippy::mutable_key_type)]
impl #impl_generics #crate_root::Encode for #name #ty_generics #where_clause {
fn encode_with_tag_and_constraints<'constraints, EN: #crate_root::Encoder>(&self, encoder: &mut EN, tag: #crate_root::types::Tag, constraints: #crate_root::types::Constraints<'constraints>) -> core::result::Result<(), EN::Error> {
fn encode_with_tag_and_constraints<EN: #crate_root::Encoder>(&self, encoder: &mut EN, tag: #crate_root::types::Tag, constraints: #crate_root::types::Constraints) -> core::result::Result<(), EN::Error> {
#(#vars)*

#encode_impl
Expand Down
21 changes: 15 additions & 6 deletions macros/macros_impl/src/enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ impl Enum {
let extended_const_variants = extensible
.then(|| quote!(Some(&[#(#extended_variants),*])))
.unwrap_or(quote!(None));

// Check count of the root components in the choice
// https://github.com/XAMPPRocky/rasn/issues/168
// Choice index starts from zero, so we need to reduce variance by one
Expand All @@ -115,7 +116,7 @@ impl Enum {
const VARIANTS: &'static [#crate_root::types::TagTree] = &[
#(#base_variants),*
];
const VARIANCE_CONSTRAINT: #crate_root::types::Constraints<'static> = #variance_constraint;
const VARIANCE_CONSTRAINT: #crate_root::types::Constraints = #variance_constraint;
const EXTENDED_VARIANTS: Option<&'static [#crate_root::types::TagTree]> = #extended_const_variants;
const IDENTIFIERS: &'static [&'static str] = &[
#(#identifiers),*
Expand Down Expand Up @@ -308,7 +309,7 @@ impl Enum {

#[automatically_derived]
impl #impl_generics #crate_root::Decode for #name #ty_generics #where_clause {
fn decode_with_tag_and_constraints<'constraints, D: #crate_root::Decoder>(decoder: &mut D, tag: #crate_root::types::Tag, constraints: #crate_root::types::Constraints<'constraints>) -> core::result::Result<Self, D::Error> {
fn decode_with_tag_and_constraints<D: #crate_root::Decoder>(decoder: &mut D, tag: #crate_root::types::Tag, constraints: #crate_root::types::Constraints) -> core::result::Result<Self, D::Error> {
#decode_with_tag
}

Expand All @@ -330,7 +331,7 @@ impl Enum {
};

quote! {
fn encode_with_tag_and_constraints<'constraints, EN: #crate_root::Encoder>(&self, encoder: &mut EN, tag: #crate_root::types::Tag, constraints: #crate_root::types::Constraints<'constraints>) -> core::result::Result<(), EN::Error> {
fn encode_with_tag_and_constraints<EN: #crate_root::Encoder>(&self, encoder: &mut EN, tag: #crate_root::types::Tag, constraints: #crate_root::types::Constraints) -> core::result::Result<(), EN::Error> {
#operation
}
}
Expand Down Expand Up @@ -361,7 +362,7 @@ impl Enum {
syn::Fields::Unit => quote!(#name::#ident => #tag_tokens),
}
});

let mut variant_constraints: Vec<proc_macro2::TokenStream> = vec![];
let variants = self.variants.iter().enumerate().map(|(i, v)| {
let ident = &v.ident;
let name = &self.name;
Expand Down Expand Up @@ -397,17 +398,24 @@ impl Enum {
let constraints = variant_config
.constraints
.const_expr(&self.config.crate_root);
let constraint_name = format_ident!("VARIANT_CONSTRAINT_{}", i);
let variant_tag = variant_tag.to_tokens(crate_root);
let encode_operation = if variant_config.has_explicit_tag() {
quote!(encoder.encode_explicit_prefix(#variant_tag, value))
} else if variant_config.tag.is_some() || self.config.automatic_tags {
if let Some(constraints) = constraints {
quote!(#crate_root::Encode::encode_with_tag_and_constraints(value, encoder, #variant_tag, #constraints))
variant_constraints.push(quote! {
const #constraint_name: #crate_root::types::constraints::Constraints = #constraints;
});
quote!(#crate_root::Encode::encode_with_tag_and_constraints(value, encoder, #variant_tag, #constraint_name))
} else {
quote!(#crate_root::Encode::encode_with_tag(value, encoder, #variant_tag))
}
} else if let Some(constraints) = constraints {
quote!(#crate_root::Encode::encode_with_constraints(value, encoder, #constraints))
variant_constraints.push(quote! {
const #constraint_name: #crate_root::types::constraints::Constraints = #constraints;
});
quote!(#crate_root::Encode::encode_with_constraints(value, encoder, #constraint_name))
} else {
quote!(#crate_root::Encode::encode(value, encoder))
};
Expand Down Expand Up @@ -510,6 +518,7 @@ impl Enum {

quote! {
fn encode<E: #crate_root::Encoder>(&self, encoder: &mut E) -> core::result::Result<(), E::Error> {
#(#variant_constraints)*
#encode_impl.map(drop)
}
}
Expand Down
6 changes: 5 additions & 1 deletion src/jer/enc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,11 @@ impl crate::Encoder for Encoder {
type Error = EncodeError;
type AnyEncoder<const R: usize, const E: usize> = Encoder;

fn encode_any(&mut self, t: Tag, value: &crate::types::Any) -> Result<Self::Ok, Self::Error> {
fn encode_any(
&mut self,
t: crate::types::Tag,
value: &crate::types::Any,
) -> Result<Self::Ok, Self::Error> {
self.encode_octet_string(t, Constraints::default(), &value.contents)
}

Expand Down
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pub mod prelude {
pub use crate::{
de::{Decode, Decoder},
enc::{Encode, Encoder},
macros,
types::*,
};
}
Expand Down Expand Up @@ -140,8 +141,8 @@ mod tests {

impl crate::AsnType for CustomInt {
const TAG: Tag = Tag::INTEGER;
const CONSTRAINTS: Constraints<'static> =
crate::macros::constraints!(crate::macros::value_constraint!(start: 127));
const CONSTRAINTS: Constraints =
macros::constraints!(macros::value_constraint!(start: 127));
}

impl crate::Encode for CustomInt {
Expand Down
2 changes: 0 additions & 2 deletions src/oer.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
//! Codec for Octet Encoding Rules (OER).
//! Encodes in canonical format (COER), and decodes in more versatile format (OER).

mod ranges;

pub mod de;
pub mod enc;

Expand Down
46 changes: 24 additions & 22 deletions src/oer/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use alloc::{
};

use crate::{
oer::{ranges, EncodingRules},
oer::EncodingRules,
types::{
self,
fields::{Field, Fields},
Expand Down Expand Up @@ -270,27 +270,31 @@ impl<'input, const RFC: usize, const EFC: usize> Decoder<'input, RFC, EFC> {
) -> Result<I, DecodeError> {
// Only 'value' constraint is OER visible for integer
if let Some(value) = constraints.value() {
ranges::determine_integer_size_and_sign(value, self.input, |_, sign, octets| {
let integer = self.decode_integer_from_bytes::<I>(sign, octets.map(usize::from))?;
// if the value is too large for a i128, the constraint isn't satisfied
if let Some(constraint_integer) = integer.to_i128() {
if value.constraint.contains(&constraint_integer) {
Ok(integer)
} else {
Err(DecodeError::value_constraint_not_satisfied(
integer.to_bigint().unwrap_or_default(),
value.constraint.0,
self.codec(),
))
}
let (signed, octets) = if value.extensible.is_some() {
(true, None)
} else {
(value.constraint.get_sign(), value.constraint.get_range())
};
let integer = self.decode_integer_from_bytes::<I>(signed, octets.map(usize::from))?;
// if the value is too large for a i128, the constraint isn't satisfied
if let Some(constraint_integer) = integer.to_i128() {
if value.constraint.contains(&constraint_integer) {
Ok(integer)
} else {
Err(DecodeError::value_constraint_not_satisfied(
integer.to_bigint().unwrap_or_default(),
value.constraint.0,
value.constraint.value,
self.codec(),
))
}
})
} else {
Err(DecodeError::value_constraint_not_satisfied(
integer.to_bigint().unwrap_or_default(),
value.constraint.value,
self.codec(),
))
}
// })
} else {
// No constraints
self.decode_integer_from_bytes::<I>(true, None)
Expand Down Expand Up @@ -352,23 +356,21 @@ impl<'input, const RFC: usize, const EFC: usize> Decoder<'input, RFC, EFC> {
fn parse_known_multiplier_string<
T: crate::types::strings::StaticPermittedAlphabet
+ crate::types::AsnType
+ TryFrom<Vec<u8>, Error = crate::error::strings::PermittedAlphabetError>,
+ for<'a> TryFrom<&'a [u8], Error = crate::error::strings::PermittedAlphabetError>,
>(
&mut self,
constraints: &Constraints,
) -> Result<T, DecodeError> {
if let Some(size) = constraints.size() {
// Fixed size, only data is included
if size.constraint.is_fixed() && size.extensible.is_none() {
let data = self
.extract_data_by_length(*size.constraint.as_start().unwrap())
.map(|data| data.as_bytes().to_vec())?;
return T::try_from(data)
let data = self.extract_data_by_length(*size.constraint.as_start().unwrap())?;
return T::try_from(data.as_bytes())
.map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()));
}
}
let length = self.decode_length()?;
T::try_from(self.extract_data_by_length(length)?.as_bytes().to_vec())
T::try_from(self.extract_data_by_length(length)?.as_bytes())
.map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()))
}

Expand Down
Loading
Loading