twenty_first/math/
bfield_codec.rs

1use std::cmp::Ordering;
2use std::error::Error;
3use std::fmt::Debug;
4use std::fmt::Display;
5use std::marker::PhantomData;
6use std::slice::Iter;
7
8// Re-export the derive macro so that it can be used in other crates without having to add
9// an explicit dependency on `bfieldcodec_derive` to their Cargo.toml.
10pub use bfieldcodec_derive::BFieldCodec;
11use num_traits::ConstOne;
12use num_traits::ConstZero;
13use thiserror::Error;
14
15use super::b_field_element::BFieldElement;
16use super::polynomial::Polynomial;
17use super::traits::FiniteField;
18use crate::bfe;
19use crate::bfe_vec;
20
21/// This trait provides functions for encoding to and decoding from a Vec of
22/// [BFieldElement]s. This encoding does not record the size of objects nor
23/// their type information; this is the responsibility of the decoder.
24///
25/// ### Dyn-Compatibility
26///
27/// This trait is _not_ [dyn-compatible] (previously known as “object safe”).
28///
29/// [dyn-compatible]: https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility
30pub trait BFieldCodec {
31    type Error: Into<Box<dyn Error + Send + Sync>> + Debug + Display;
32
33    fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error>;
34    fn encode(&self) -> Vec<BFieldElement>;
35
36    /// Returns the length in number of [BFieldElement]s if it is known at compile-time.
37    /// Otherwise, None.
38    fn static_length() -> Option<usize>;
39}
40
41#[derive(Debug, Error)]
42#[non_exhaustive]
43pub enum BFieldCodecError {
44    #[error("empty sequence")]
45    EmptySequence,
46
47    #[error("sequence too short")]
48    SequenceTooShort,
49
50    #[error("sequence too long")]
51    SequenceTooLong,
52
53    #[error("element out of range")]
54    ElementOutOfRange,
55
56    #[error("missing length indicator")]
57    MissingLengthIndicator,
58
59    #[error("invalid length indicator")]
60    InvalidLengthIndicator,
61
62    #[error(transparent)]
63    TryFromIntError(#[from] std::num::TryFromIntError),
64
65    #[error("inner decoding error: {0}")]
66    InnerDecodingFailure(#[from] Box<dyn Error + Send + Sync>),
67}
68
69// The type underlying BFieldElement is u64. A single u64 does not fit in one BFieldElement.
70// Therefore, deriving the BFieldCodec for BFieldElement using the derive macro will result in a
71// BFieldCodec implementation that encodes a single BFieldElement as two BFieldElements.
72// This is not desired. Hence, BFieldCodec is implemented manually for BFieldElement.
73impl BFieldCodec for BFieldElement {
74    type Error = BFieldCodecError;
75
76    fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
77        if sequence.is_empty() {
78            return Err(Self::Error::EmptySequence);
79        }
80        if sequence.len() > 1 {
81            return Err(Self::Error::SequenceTooLong);
82        }
83        Ok(Box::new(sequence[0]))
84    }
85
86    fn encode(&self) -> Vec<BFieldElement> {
87        [*self].to_vec()
88    }
89
90    fn static_length() -> Option<usize> {
91        Some(1)
92    }
93}
94
95macro_rules! impl_bfield_codec_for_big_primitive_uint {
96    ($ty:ty, $size:literal) => {
97        impl BFieldCodec for $ty {
98            type Error = BFieldCodecError;
99
100            fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
101                if sequence.is_empty() {
102                    return Err(Self::Error::EmptySequence);
103                }
104                if sequence.len() < $size {
105                    return Err(Self::Error::SequenceTooShort);
106                }
107                if sequence.len() > $size {
108                    return Err(Self::Error::SequenceTooLong);
109                }
110                if sequence.iter().any(|s| s.value() > u32::MAX.into()) {
111                    return Err(Self::Error::ElementOutOfRange);
112                }
113
114                let element = sequence
115                    .iter()
116                    .enumerate()
117                    .map(|(i, s)| Self::from(s) << (i * 32))
118                    .sum();
119                Ok(Box::new(element))
120            }
121
122            fn encode(&self) -> Vec<BFieldElement> {
123                const LOW_BIT_MASK: $ty = u32::MAX as $ty;
124
125                (0..$size)
126                    .map(|i| bfe!((*self >> (i * 32)) & LOW_BIT_MASK))
127                    .collect()
128            }
129
130            fn static_length() -> Option<usize> {
131                Some($size)
132            }
133        }
134    };
135}
136
137impl_bfield_codec_for_big_primitive_uint!(u64, 2);
138impl_bfield_codec_for_big_primitive_uint!(u128, 4);
139
140macro_rules! impl_bfield_codec_for_signed_int {
141    ($iint:ty, using $uint:ty) => {
142        impl BFieldCodec for $iint {
143            type Error = <$uint as BFieldCodec>::Error;
144
145            fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
146                <$uint>::decode(sequence).map(|v| Box::new(*v as Self))
147            }
148
149            fn encode(&self) -> Vec<BFieldElement> {
150                (*self as $uint).encode()
151            }
152
153            fn static_length() -> Option<usize> {
154                <$uint>::static_length()
155            }
156        }
157    };
158}
159
160impl_bfield_codec_for_signed_int!(i8, using u8);
161impl_bfield_codec_for_signed_int!(i16, using u16);
162impl_bfield_codec_for_signed_int!(i32, using u32);
163impl_bfield_codec_for_signed_int!(i64, using u64);
164impl_bfield_codec_for_signed_int!(i128, using u128);
165
166impl BFieldCodec for bool {
167    type Error = BFieldCodecError;
168
169    fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
170        if sequence.is_empty() {
171            return Err(Self::Error::EmptySequence);
172        }
173        if sequence.len() > 1 {
174            return Err(Self::Error::SequenceTooLong);
175        }
176
177        let element = match sequence[0].value() {
178            0 => false,
179            1 => true,
180            _ => return Err(Self::Error::ElementOutOfRange),
181        };
182        Ok(Box::new(element))
183    }
184
185    fn encode(&self) -> Vec<BFieldElement> {
186        vec![BFieldElement::new(*self as u64)]
187    }
188
189    fn static_length() -> Option<usize> {
190        Some(1)
191    }
192}
193
194macro_rules! impl_bfield_codec_for_small_primitive_uint {
195    ($($t:ident),+ $(,)?) => {$(
196        impl BFieldCodec for $t {
197            type Error = BFieldCodecError;
198
199            fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
200                if sequence.is_empty() {
201                    return Err(Self::Error::EmptySequence);
202                }
203                let [first] = sequence[..] else {
204                    return Err(Self::Error::SequenceTooLong);
205                };
206                let element = $t::try_from(first.value())
207                    .map_err(|_| Self::Error::ElementOutOfRange)?;
208
209                Ok(Box::new(element))
210            }
211
212            fn encode(&self) -> Vec<BFieldElement> {
213                bfe_vec![*self]
214            }
215
216            fn static_length() -> Option<usize> {
217                Some(1)
218            }
219        }
220    )+};
221}
222
223impl_bfield_codec_for_small_primitive_uint!(u8, u16, u32);
224
225impl<T: BFieldCodec> BFieldCodec for Box<T> {
226    type Error = T::Error;
227
228    fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
229        T::decode(sequence).map(Box::new)
230    }
231
232    fn encode(&self) -> Vec<BFieldElement> {
233        self.as_ref().encode()
234    }
235
236    fn static_length() -> Option<usize> {
237        T::static_length()
238    }
239}
240
241macro_rules! impl_bfield_codec_for_tuple {
242    // entrypoint: introduce marker tokens to start reversing token sequence
243    ($($forward:ident),+) => {
244        impl_bfield_codec_for_tuple!(@>@ $($forward)+ @rev@);
245    };
246
247    // general case: reversing in progress, move marker token `@>@`
248    ($($a:ident)* @>@ $b:ident $($c:ident)* @rev@ $($reverse:ident)*) => {
249        impl_bfield_codec_for_tuple!($($a)* $b @>@ $($c)* @rev@ $b $($reverse)*);
250    };
251
252    // base case: reversing is done
253    //
254    // Use token sequence in “forward” mode to
255    //  - declare the tuple type,
256    //  - construct the tuple after successful decoding, and
257    //  - pattern-match-deconstruct `self` to prepare encoding.
258    // Use token sequence in “reverse” mode to en/decode in reverse order from type
259    // declaration.
260    //
261    // Because it is impossible to construct tuple accessors (like the 0 in
262    // `my_tuple.0`) in a declarative macro, pattern matching is used to
263    // deconstruct `self`. This requires identifiers. The current design uses the
264    // type identifiers for this purpose. While these identifiers don't follow the
265    // guidelines for variable identifiers, this is deemed acceptable in macro code.
266    ($($f:ident)+ @>@ @rev@ $($r:ident)+) => {
267        impl <$($f),+> BFieldCodec for ($($f),+ ,)
268        where $($f: BFieldCodec),+
269        {
270            type Error = BFieldCodecError;
271
272            fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
273                $(
274                if $r::static_length().is_none() && sequence.first().is_none() {
275                    return Err(Self::Error::MissingLengthIndicator);
276                }
277                let (length, sequence) = $r::static_length()
278                    .map(|length| (Ok(length), sequence))
279                    .unwrap_or_else(|| (sequence[0].try_into(), &sequence[1..]));
280                let length = length?;
281                if sequence.len() < length {
282                    return Err(Self::Error::SequenceTooShort);
283                }
284                let (sequence_for_ty, sequence) = sequence.split_at(length);
285                #[allow(non_snake_case)]
286                let $r = *$r::decode(sequence_for_ty).map_err(|err| err.into())?;
287                )+
288
289                if !sequence.is_empty() {
290                    return Err(Self::Error::SequenceTooLong);
291                }
292                Ok(Box::new(($($f),+ ,)))
293            }
294
295            fn encode(&self) -> Vec<BFieldElement> {
296                #[allow(non_snake_case)]
297                let ($($f),+ ,) = self;
298                let mut sequence = vec![];
299
300                $(
301                let encoding = $r.encode();
302                if $r::static_length().is_none() {
303                    sequence.push(encoding.len().into());
304                }
305                sequence.extend(encoding);
306                )+
307
308                sequence
309            }
310
311            fn static_length() -> Option<usize> {
312                // Token `+` cannot be used as macro repetition separator. As a workaround, use
313                // it inside macro repetition, and make last emitted `+` syntactic by adding 0.
314                Some($($f::static_length()? +)+ 0)
315            }
316        }
317    };
318}
319
320impl_bfield_codec_for_tuple!(A);
321impl_bfield_codec_for_tuple!(A, B);
322impl_bfield_codec_for_tuple!(A, B, C);
323impl_bfield_codec_for_tuple!(A, B, C, D);
324impl_bfield_codec_for_tuple!(A, B, C, D, E);
325impl_bfield_codec_for_tuple!(A, B, C, D, E, F);
326impl_bfield_codec_for_tuple!(A, B, C, D, E, F, G);
327impl_bfield_codec_for_tuple!(A, B, C, D, E, F, G, H);
328impl_bfield_codec_for_tuple!(A, B, C, D, E, F, G, H, I);
329impl_bfield_codec_for_tuple!(A, B, C, D, E, F, G, H, I, J);
330impl_bfield_codec_for_tuple!(A, B, C, D, E, F, G, H, I, J, K);
331impl_bfield_codec_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
332
333impl<T: BFieldCodec> BFieldCodec for Option<T> {
334    type Error = BFieldCodecError;
335
336    fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
337        if sequence.is_empty() {
338            return Err(Self::Error::EmptySequence);
339        }
340        let is_some = *bool::decode(&sequence[0..1])?;
341        let sequence = &sequence[1..];
342        let maybe_result = is_some.then(|| T::decode(sequence).map_err(|e| e.into()));
343        let element = maybe_result.transpose()?.map(|boxed_self| *boxed_self);
344
345        if !is_some && !sequence.is_empty() {
346            return Err(Self::Error::SequenceTooLong);
347        }
348        Ok(Box::new(element))
349    }
350
351    fn encode(&self) -> Vec<BFieldElement> {
352        match self {
353            None => vec![BFieldElement::ZERO],
354            Some(t) => [vec![BFieldElement::ONE], t.encode()].concat(),
355        }
356    }
357
358    fn static_length() -> Option<usize> {
359        None
360    }
361}
362
363impl<T: BFieldCodec, const N: usize> BFieldCodec for [T; N] {
364    type Error = BFieldCodecError;
365
366    fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
367        if N > 0 && sequence.is_empty() {
368            return Err(Self::Error::EmptySequence);
369        }
370
371        let vec_t = bfield_codec_decode_list(N, sequence)?;
372        let array = vec_t.try_into().map_err(|_| {
373            Self::Error::InnerDecodingFailure(format!("cannot convert Vec<T> into [T; {N}]").into())
374        })?;
375        Ok(Box::new(array))
376    }
377
378    fn encode(&self) -> Vec<BFieldElement> {
379        bfield_codec_encode_list(self.iter())
380    }
381
382    fn static_length() -> Option<usize> {
383        T::static_length().map(|len| len * N)
384    }
385}
386
387impl<T: BFieldCodec> BFieldCodec for Vec<T> {
388    type Error = BFieldCodecError;
389
390    fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
391        if sequence.is_empty() {
392            return Err(Self::Error::EmptySequence);
393        }
394
395        let vec_length = sequence[0].try_into()?;
396        let vec = bfield_codec_decode_list(vec_length, &sequence[1..])?;
397        Ok(Box::new(vec))
398    }
399
400    fn encode(&self) -> Vec<BFieldElement> {
401        let mut encoding = bfe_vec![self.len()];
402        encoding.extend(bfield_codec_encode_list(self.iter()));
403        encoding
404    }
405
406    fn static_length() -> Option<usize> {
407        None
408    }
409}
410
411#[derive(Debug, Error)]
412pub enum PolynomialBFieldCodecError {
413    /// A polynomial with leading zero-coefficients, corresponding to an encoding
414    /// with trailing zeros, is a waste of space. More importantly, it allows for
415    /// non-canonical encodings of the same underlying polynomial, which is
416    /// confusing and can lead to errors.
417    ///
418    /// A note on “leading” vs “trailing”:
419    /// The polynomial 0·x³ + 2x² + 42 has a spuriuous _leading_ zero, which
420    /// translates into a spurious _trailing_ zero in its encoding.
421    #[error("trailing zeros in polynomial-encoding")]
422    TrailingZerosInPolynomialEncoding,
423
424    #[error(transparent)]
425    Other(#[from] BFieldCodecError),
426}
427
428impl<T> BFieldCodec for Polynomial<'_, T>
429where
430    T: BFieldCodec + FiniteField + 'static,
431{
432    type Error = PolynomialBFieldCodecError;
433
434    fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
435        if sequence.is_empty() {
436            return Err(Self::Error::Other(BFieldCodecError::EmptySequence));
437        }
438
439        let coefficients_field_length_indicator: Result<usize, _> = sequence[0].value().try_into();
440        let Ok(coefficients_field_length_indicator) = coefficients_field_length_indicator else {
441            return Err(Self::Error::Other(BFieldCodecError::InvalidLengthIndicator));
442        };
443
444        // Indicated sequence length is 1 + field size, as the size indicator takes up 1 word.
445        let indicated_sequence_length = coefficients_field_length_indicator + 1;
446        let decoded_vec = match sequence.len().cmp(&indicated_sequence_length) {
447            Ordering::Equal => Vec::<T>::decode(&sequence[1..]),
448            Ordering::Less => Err(BFieldCodecError::SequenceTooShort),
449            Ordering::Greater => Err(BFieldCodecError::SequenceTooLong),
450        }?;
451
452        let encoding_contains_trailing_zeros = decoded_vec
453            .last()
454            .is_some_and(|last_coeff| last_coeff.is_zero());
455        if encoding_contains_trailing_zeros {
456            return Err(PolynomialBFieldCodecError::TrailingZerosInPolynomialEncoding);
457        }
458
459        Ok(Box::new(Polynomial::new(*decoded_vec)))
460    }
461
462    fn encode(&self) -> Vec<BFieldElement> {
463        // The length of the coefficients field is prepended to the encoding to make the
464        // encoding consistent with a hypothetical derived implementation.
465        let coefficients_encoded = self.coefficients().to_owned().encode();
466        [bfe_vec!(coefficients_encoded.len()), coefficients_encoded].concat()
467    }
468
469    fn static_length() -> Option<usize> {
470        None
471    }
472}
473
474/// The core of the [`BFieldCodec`] decoding logic for `Vec<T>` and `[T; N]`.
475/// Decoding the length-prepending must be handled by the caller (if necessary).
476fn bfield_codec_decode_list<T: BFieldCodec>(
477    indicated_num_items: usize,
478    sequence: &[BFieldElement],
479) -> Result<Vec<T>, BFieldCodecError> {
480    let vec = if T::static_length().is_some() {
481        bfield_codec_decode_list_with_statically_sized_items(indicated_num_items, sequence)?
482    } else {
483        bfield_codec_decode_list_with_dynamically_sized_items(indicated_num_items, sequence)?
484    };
485    Ok(vec)
486}
487
488fn bfield_codec_decode_list_with_statically_sized_items<T: BFieldCodec>(
489    num_items: usize,
490    sequence: &[BFieldElement],
491) -> Result<Vec<T>, BFieldCodecError> {
492    // Initializing the vector with the indicated capacity potentially allows a DOS.
493    let mut vec = vec![];
494
495    let item_length = T::static_length().unwrap();
496    let maybe_vector_size = num_items.checked_mul(item_length);
497    let Some(vector_size) = maybe_vector_size else {
498        return Err(BFieldCodecError::InvalidLengthIndicator);
499    };
500    if sequence.len() < vector_size {
501        return Err(BFieldCodecError::SequenceTooShort);
502    }
503    if sequence.len() > vector_size {
504        return Err(BFieldCodecError::SequenceTooLong);
505    }
506
507    for raw_item in sequence.chunks_exact(item_length) {
508        let item = *T::decode(raw_item).map_err(|e| e.into())?;
509        vec.push(item);
510    }
511    Ok(vec)
512}
513
514fn bfield_codec_decode_list_with_dynamically_sized_items<T: BFieldCodec>(
515    num_items: usize,
516    sequence: &[BFieldElement],
517) -> Result<Vec<T>, BFieldCodecError> {
518    // Initializing the vector with the indicated capacity potentially allows a DOS.
519    let mut vec = vec![];
520    let mut sequence_index = 0;
521    for _ in 0..num_items {
522        let item_length = sequence
523            .get(sequence_index)
524            .ok_or(BFieldCodecError::MissingLengthIndicator)?;
525        let item_length = usize::try_from(item_length)?;
526        sequence_index += 1;
527        if sequence.len() < sequence_index + item_length {
528            return Err(BFieldCodecError::SequenceTooShort);
529        }
530        let item = *T::decode(&sequence[sequence_index..sequence_index + item_length])
531            .map_err(|e| e.into())?;
532        sequence_index += item_length;
533        vec.push(item);
534    }
535    if sequence.len() != sequence_index {
536        return Err(BFieldCodecError::SequenceTooLong);
537    }
538    Ok(vec)
539}
540
541/// The core of the [`BFieldCodec`] encoding logic for `Vec<T>` and `[T; N]`.
542/// Encoding the length-prepending must be handled by the caller (if necessary).
543fn bfield_codec_encode_list<T: BFieldCodec>(elements: Iter<T>) -> Vec<BFieldElement> {
544    if T::static_length().is_some() {
545        return elements.flat_map(|elem| elem.encode()).collect();
546    }
547
548    let mut encoding = vec![];
549    for element in elements {
550        let element_encoded = element.encode();
551        encoding.push(element_encoded.len().into());
552        encoding.extend(element_encoded);
553    }
554    encoding
555}
556
557impl BFieldCodec for () {
558    type Error = BFieldCodecError;
559
560    fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
561        sequence
562            .is_empty()
563            .then(|| Box::new(()))
564            .ok_or_else(|| BFieldCodecError::SequenceTooLong)
565    }
566
567    fn encode(&self) -> Vec<BFieldElement> {
568        Vec::new()
569    }
570
571    fn static_length() -> Option<usize> {
572        Some(0)
573    }
574}
575
576impl<T> BFieldCodec for PhantomData<T> {
577    type Error = BFieldCodecError;
578
579    fn decode(sequence: &[BFieldElement]) -> Result<Box<Self>, Self::Error> {
580        sequence
581            .is_empty()
582            .then(|| Box::new(PhantomData))
583            .ok_or_else(|| BFieldCodecError::SequenceTooLong)
584    }
585
586    fn encode(&self) -> Vec<BFieldElement> {
587        Vec::new()
588    }
589
590    fn static_length() -> Option<usize> {
591        Some(0)
592    }
593}
594
595#[cfg(test)]
596#[cfg_attr(coverage_nightly, coverage(off))]
597mod tests {
598    use num_traits::ConstZero;
599    use num_traits::Zero;
600    use proptest::collection::size_range;
601    use proptest::collection::vec;
602    use proptest::prelude::*;
603    use proptest::test_runner::TestCaseResult;
604    use proptest_arbitrary_interop::arb;
605    use test_strategy::proptest;
606
607    use super::*;
608    use crate::prelude::*;
609
610    #[derive(Debug, PartialEq, Eq, test_strategy::Arbitrary)]
611    struct BFieldCodecPropertyTestData<T>
612    where
613        T: 'static + BFieldCodec + Eq + Debug + Clone + for<'a> arbitrary::Arbitrary<'a>,
614    {
615        #[strategy(arb())]
616        value: T,
617
618        #[strategy(Just(#value.encode()))]
619        encoding: Vec<BFieldElement>,
620
621        #[strategy(vec(arb(), #encoding.len()))]
622        #[filter(#encoding.iter().zip(#random_encoding.iter()).all(|(a, b)| a != b))]
623        random_encoding: Vec<BFieldElement>,
624
625        #[any(size_range(1..128).lift())]
626        encoding_lengthener: Vec<BFieldElement>,
627
628        #[strategy(0..=#encoding.len())]
629        length_of_too_short_sequence: usize,
630    }
631
632    impl<T> BFieldCodecPropertyTestData<T>
633    where
634        T: 'static + BFieldCodec + Eq + Debug + Clone + for<'a> arbitrary::Arbitrary<'a>,
635    {
636        fn assert_bfield_codec_properties(&self) -> TestCaseResult {
637            self.assert_static_length_is_equal_to_encoded_length()?;
638            self.assert_decoded_encoding_is_self()?;
639            self.assert_decoding_too_long_encoding_fails()?;
640            self.assert_decoding_too_short_encoding_fails()?;
641            self.modify_each_element_and_assert_decoding_failure()?;
642            self.assert_decoding_random_too_short_encoding_fails_gracefully()?;
643            Ok(())
644        }
645
646        fn assert_static_length_is_equal_to_encoded_length(&self) -> TestCaseResult {
647            if let Some(static_len) = T::static_length() {
648                prop_assert_eq!(static_len, self.encoding.len());
649            }
650            Ok(())
651        }
652
653        fn assert_decoded_encoding_is_self(&self) -> TestCaseResult {
654            let Ok(decoding) = T::decode(&self.encoding) else {
655                let err = TestCaseError::Fail("decoding canonical encoding must not fail".into());
656                return Err(err);
657            };
658            prop_assert_eq!(&self.value, &*decoding);
659            Ok(())
660        }
661
662        fn assert_decoding_too_long_encoding_fails(&self) -> TestCaseResult {
663            let mut too_long_encoding = self.encoding.to_owned();
664            too_long_encoding.extend(self.encoding_lengthener.to_owned());
665            prop_assert!(T::decode(&too_long_encoding).is_err());
666            Ok(())
667        }
668
669        fn assert_decoding_too_short_encoding_fails(&self) -> TestCaseResult {
670            if self.failure_assertions_for_decoding_too_short_sequence_is_not_meaningful() {
671                return Ok(());
672            }
673            let mut encoded = self.encoding.to_owned();
674            encoded.pop();
675            prop_assert!(T::decode(&encoded).is_err());
676            Ok(())
677        }
678
679        fn modify_each_element_and_assert_decoding_failure(&self) -> TestCaseResult {
680            let mut encoding = self.encoding.to_owned();
681            for i in 0..encoding.len() {
682                let original_value = encoding[i];
683                encoding[i] = self.random_encoding[i];
684                let decoding = T::decode(&encoding);
685                if decoding.is_ok_and(|d| *d == self.value) {
686                    return Err(TestCaseError::Fail(format!("failing index: {i}").into()));
687                }
688                encoding[i] = original_value;
689            }
690            Ok(())
691        }
692
693        fn assert_decoding_random_too_short_encoding_fails_gracefully(&self) -> TestCaseResult {
694            if self.failure_assertions_for_decoding_too_short_sequence_is_not_meaningful() {
695                return Ok(());
696            }
697
698            let random_encoding =
699                self.random_encoding[..self.length_of_too_short_sequence].to_vec();
700            let decoding_result = T::decode(&random_encoding);
701            if decoding_result.is_ok_and(|d| *d == self.value) {
702                return Err(TestCaseError::Fail("randomness mustn't be `self`".into()));
703            }
704            Ok(())
705        }
706
707        fn failure_assertions_for_decoding_too_short_sequence_is_not_meaningful(&self) -> bool {
708            self.encoding.is_empty()
709        }
710    }
711
712    macro_rules! test_case {
713        (fn $fn_name:ident for $t:ty: $static_len:expr) => {
714            #[proptest]
715            fn $fn_name(test_data: BFieldCodecPropertyTestData<$t>) {
716                prop_assert_eq!($static_len, <$t as BFieldCodec>::static_length());
717                test_data.assert_bfield_codec_properties()?;
718            }
719        };
720    }
721
722    macro_rules! neg_test_case {
723        (fn $fn_name:ident for $t:ty) => {
724            #[proptest]
725            fn $fn_name(random_encoding: Vec<BFieldElement>) {
726                let decoding = <$t as BFieldCodec>::decode(&random_encoding);
727                prop_assert!(decoding.is_err());
728            }
729        };
730    }
731
732    test_case! { fn test_u8 for u8: Some(1) }
733    test_case! { fn test_i8 for i8: Some(1) }
734    test_case! { fn test_u16 for u16: Some(1) }
735    test_case! { fn test_i16 for i16: Some(1) }
736    test_case! { fn test_u32 for u32: Some(1) }
737    test_case! { fn test_i32 for i32: Some(1) }
738    test_case! { fn test_u64 for u64: Some(2) }
739    test_case! { fn test_i64 for i64: Some(2) }
740    test_case! { fn test_u128 for u128: Some(4) }
741    test_case! { fn test_i128 for i128: Some(4) }
742    test_case! { fn bfieldelement for BFieldElement: Some(1) }
743    test_case! { fn xfieldelement for XFieldElement: Some(3) }
744    test_case! { fn digest for Digest: Some(5) }
745    test_case! { fn vec_of_bfieldelement for Vec<BFieldElement>: None }
746    test_case! { fn vec_of_xfieldelement for Vec<XFieldElement>: None }
747    test_case! { fn vec_of_digest for Vec<Digest>: None }
748    test_case! { fn vec_of_vec_of_bfieldelement for Vec<Vec<BFieldElement>>: None }
749    test_case! { fn vec_of_vec_of_xfieldelement for Vec<Vec<XFieldElement>>: None }
750    test_case! { fn vec_of_vec_of_digest for Vec<Vec<Digest>>: None }
751    test_case! { fn poly_bfe for Polynomial<'static, BFieldElement>: None }
752    test_case! { fn poly_xfe for Polynomial<'static, XFieldElement>: None }
753    test_case! { fn tuples_static_static_size_0 for (Digest, u128): Some(9) }
754    test_case! { fn tuples_static_static_size_1 for (Digest, u64): Some(7) }
755    test_case! { fn tuples_static_static_size_2 for (BFieldElement, BFieldElement): Some(2) }
756    test_case! { fn tuples_static_static_size_3 for (BFieldElement, XFieldElement): Some(4) }
757    test_case! { fn tuples_static_static_size_4 for (XFieldElement, BFieldElement): Some(4) }
758    test_case! { fn tuples_static_static_size_5 for (XFieldElement, Digest): Some(8) }
759    test_case! { fn tuples_static_static_size_6 for (u8, u16, u32, u64): Some(5) }
760    test_case! { fn tuples_static_static_size_7 for (u8,): Some(1) }
761    test_case! { fn tuples_static_dynamic_size_0 for (u32, Vec<u32>): None }
762    test_case! { fn tuples_static_dynamic_size_1 for (u32, Vec<u64>): None }
763    test_case! { fn tuples_static_dynamic_size_2 for (Digest, Vec<BFieldElement>): None }
764    test_case! { fn tuples_static_dynamic_size_3 for (Vec<BFieldElement>,): None }
765    test_case! { fn tuples_dynamic_static_size for (Vec<XFieldElement>, Digest): None }
766    test_case! { fn tuples_dynamic_dynamic_size for (Vec<XFieldElement>, Vec<Digest>): None }
767    test_case! { fn unit for (): Some(0) }
768    test_case! { fn phantom_data for PhantomData<Tip5>: Some(0) }
769    test_case! { fn boxed_u32s for Box<u32>: Some(1) }
770    test_case! { fn tuple_with_boxed_bfe for (u64, Box<BFieldElement>): Some(3) }
771    test_case! { fn tuple_with_boxed_digest for (u128, Box<Digest>): Some(9) }
772    test_case! { fn vec_of_boxed_tuple_of_u128_and_bfe for Vec<(u128, Box<BFieldElement>)>: None }
773    test_case! { fn vec_option_xfieldelement for Vec<Option<XFieldElement>>: None }
774    test_case! { fn array_with_static_element_size for [u64; 14]: Some(28) }
775    test_case! { fn array_with_dynamic_element_size for [Vec<Digest>; 19]: None }
776
777    neg_test_case! { fn vec_of_bfield_element_neg for Vec<BFieldElement> }
778    neg_test_case! { fn vec_of_xfield_elements_neg for Vec<XFieldElement> }
779    neg_test_case! { fn vec_of_digests_neg for Vec<Digest> }
780    neg_test_case! { fn vec_of_vec_of_bfield_elements_neg for Vec<Vec<BFieldElement>> }
781    neg_test_case! { fn vec_of_vec_of_xfield_elements_neg for Vec<Vec<XFieldElement>> }
782    neg_test_case! { fn poly_of_bfe_neg for Polynomial<BFieldElement> }
783    neg_test_case! { fn poly_of_xfe_neg for Polynomial<XFieldElement> }
784
785    #[test]
786    fn encoding_tuple_puts_fields_in_expected_order() {
787        let encoding = (1_u8, 2_u16, 3_u32, 4_u64, true).encode();
788        let expected = bfe_vec![1, 4, 0, 3, 2, 1];
789        assert_eq!(expected, encoding);
790    }
791
792    #[test]
793    fn leading_zero_coefficient_have_no_effect_on_encoding_empty_poly_bfe() {
794        let empty_poly = Polynomial::<BFieldElement>::new(vec![]);
795        assert_eq!(empty_poly.encode(), Polynomial::new(bfe_vec![0]).encode());
796    }
797
798    #[test]
799    fn leading_zero_coefficients_have_no_effect_on_encoding_empty_poly_xfe() {
800        let empty_poly = Polynomial::<XFieldElement>::new(vec![]);
801        assert_eq!(empty_poly.encode(), Polynomial::new(xfe_vec![0]).encode());
802    }
803
804    #[proptest]
805    fn leading_zero_coefficients_have_no_effect_on_encoding_poly_bfe_pbt(
806        polynomial: Polynomial<'static, BFieldElement>,
807        #[strategy(0usize..30)] num_leading_zeros: usize,
808    ) {
809        let encoded = polynomial.encode();
810
811        let mut coefficients = polynomial.into_coefficients();
812        coefficients.extend(vec![BFieldElement::ZERO; num_leading_zeros]);
813        let poly_w_leading_zeros = Polynomial::new(coefficients);
814
815        prop_assert_eq!(encoded, poly_w_leading_zeros.encode());
816    }
817
818    #[proptest]
819    fn leading_zero_coefficients_have_no_effect_on_encoding_poly_xfe_pbt(
820        polynomial: Polynomial<'static, XFieldElement>,
821        #[strategy(0usize..30)] num_leading_zeros: usize,
822    ) {
823        let encoded = polynomial.encode();
824
825        let mut coefficients = polynomial.into_coefficients();
826        coefficients.extend(vec![XFieldElement::ZERO; num_leading_zeros]);
827        let poly_w_leading_zeros = Polynomial::new(coefficients);
828
829        prop_assert_eq!(encoded, poly_w_leading_zeros.encode());
830    }
831
832    fn disallow_trailing_zeros_in_poly_encoding_prop<FF>(
833        polynomial: Polynomial<FF>,
834        leading_coefficient: FF,
835        num_leading_zeros: usize,
836    ) -> TestCaseResult
837    where
838        FF: FiniteField + BFieldCodec + 'static,
839    {
840        let mut polynomial_coefficients = polynomial.into_coefficients();
841        polynomial_coefficients.push(leading_coefficient);
842        let actual_polynomial = Polynomial::new(polynomial_coefficients.clone());
843        let vec_encoding = actual_polynomial.coefficients().to_vec().encode();
844        let poly_encoding = actual_polynomial.encode();
845        prop_assert_eq!(
846            [bfe_vec!(vec_encoding.len()), vec_encoding].concat(),
847            poly_encoding,
848            "This test expects similarity of Vec and Polynomial encoding"
849        );
850
851        polynomial_coefficients.extend(vec![FF::ZERO; num_leading_zeros]);
852        let coefficient_encoding = polynomial_coefficients.encode();
853        let poly_encoding_with_leading_zeros =
854            [bfe_vec!(coefficient_encoding.len()), coefficient_encoding].concat();
855        let decoding_result = Polynomial::<FF>::decode(&poly_encoding_with_leading_zeros);
856        prop_assert!(matches!(
857            decoding_result.unwrap_err(),
858            PolynomialBFieldCodecError::TrailingZerosInPolynomialEncoding
859        ));
860
861        Ok(())
862    }
863
864    #[proptest]
865    fn disallow_trailing_zeros_in_poly_encoding_bfe(
866        polynomial: Polynomial<'static, BFieldElement>,
867        #[filter(!#leading_coefficient.is_zero())] leading_coefficient: BFieldElement,
868        #[strategy(1usize..30)] num_leading_zeros: usize,
869    ) {
870        disallow_trailing_zeros_in_poly_encoding_prop(
871            polynomial,
872            leading_coefficient,
873            num_leading_zeros,
874        )?
875    }
876
877    #[proptest]
878    fn disallow_trailing_zeros_in_poly_encoding_xfe(
879        polynomial: Polynomial<'static, XFieldElement>,
880        #[filter(!#leading_coefficient.is_zero())] leading_coefficient: XFieldElement,
881        #[strategy(1usize..30)] num_leading_zeros: usize,
882    ) {
883        disallow_trailing_zeros_in_poly_encoding_prop(
884            polynomial,
885            leading_coefficient,
886            num_leading_zeros,
887        )?
888    }
889
890    /// Depending on the test helper [`BFieldCodecPropertyTestData`] in the bfieldcodec_derive crate
891    /// would introduce an almost-cyclic dependency.[^1] This would make publishing to crates.io
892    /// quite difficult. Hence, integration tests in the bfieldcodec_derive crate are also off the
893    /// table. Consequently, we test the derive macro here.
894    ///
895    /// See also: https://github.com/rust-lang/cargo/issues/8379#issuecomment-1261970561
896    ///
897    /// [^1]: almost-cyclic because the dependency would be a dev-dependency
898    pub mod derive {
899        use arbitrary::Arbitrary;
900        use num_traits::Zero;
901
902        use super::*;
903        use crate::math::x_field_element::XFieldElement;
904        use crate::tip5::Digest;
905        use crate::tip5::Tip5;
906        use crate::util_types::mmr::mmr_accumulator::MmrAccumulator;
907        use crate::util_types::mmr::mmr_membership_proof::MmrMembershipProof;
908
909        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
910        struct UnitStruct;
911
912        test_case! { fn unit_struct for UnitStruct: Some(0) }
913
914        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
915        struct StructWithUnitStruct {
916            a: UnitStruct,
917        }
918
919        test_case! { fn struct_with_unit_struct for StructWithUnitStruct: Some(0) }
920
921        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
922        enum EnumWithUnitStruct {
923            A(UnitStruct),
924            B,
925        }
926
927        test_case! { fn enum_with_unit_struct for EnumWithUnitStruct: Some(1) }
928
929        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
930        struct DeriveTestStructA {
931            field_a: u64,
932            field_b: u64,
933            field_c: u64,
934        }
935
936        test_case! { fn struct_a for DeriveTestStructA: Some(6) }
937
938        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
939        struct DeriveTestStructB(u128);
940
941        test_case! { fn struct_b for DeriveTestStructB: Some(4) }
942
943        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
944        struct DeriveTestStructC(u128, u64, u32);
945
946        test_case! { fn struct_c for DeriveTestStructC: Some(7) }
947
948        // Struct containing Vec<T> where T is BFieldCodec
949        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
950        struct DeriveTestStructD(Vec<u128>);
951
952        test_case! { fn struct_d for DeriveTestStructD: None }
953
954        // Structs containing Polynomial<T> where T is BFieldCodec
955        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
956        struct DeriveTestStructWithBfePolynomialField(Polynomial<'static, BFieldElement>);
957
958        test_case! {
959            fn struct_with_bfe_poly_field for DeriveTestStructWithBfePolynomialField: None
960        }
961
962        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
963        struct DeriveTestStructWithXfePolynomialField(Polynomial<'static, XFieldElement>);
964
965        test_case! {
966            fn struct_with_xfe_poly_field for DeriveTestStructWithXfePolynomialField: None
967        }
968
969        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
970        enum EnumWithVariantWithPolyField {
971            Bee,
972            BooBoo(Polynomial<'static, BFieldElement>),
973            Bop(Polynomial<'static, XFieldElement>),
974        }
975
976        test_case! { fn enum_with_variant_with_poly_field for EnumWithVariantWithPolyField: None }
977        neg_test_case! { fn enum_with_variant_with_poly_field_neg for EnumWithVariantWithPolyField }
978
979        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
980        struct DeriveTestStructE(Vec<u128>, u128, u64, Vec<bool>, u32, Vec<u128>);
981
982        test_case! { fn struct_e for DeriveTestStructE: None }
983
984        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
985        struct DeriveTestStructF {
986            field_a: Vec<u64>,
987            field_b: bool,
988            field_c: u32,
989            field_d: Vec<bool>,
990            field_e: Vec<BFieldElement>,
991            field_f: Vec<BFieldElement>,
992        }
993
994        test_case! { fn struct_f for DeriveTestStructF: None }
995
996        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
997        struct WithPhantomData<FF: FiniteField> {
998            a_field: u128,
999            #[bfield_codec(ignore)]
1000            _phantom_data: PhantomData<FF>,
1001            another_field: Vec<u64>,
1002        }
1003
1004        test_case! { fn with_phantom_data for WithPhantomData<BFieldElement>: None }
1005
1006        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1007        struct WithNestedPhantomData<FF: FiniteField> {
1008            a_field: u128,
1009            #[bfield_codec(ignore)]
1010            _phantom_data: PhantomData<FF>,
1011            another_field: Vec<u64>,
1012            a_third_field: Vec<WithPhantomData<FF>>,
1013            a_fourth_field: WithPhantomData<BFieldElement>,
1014        }
1015
1016        test_case! { fn with_nested_phantom_data for WithNestedPhantomData<XFieldElement>: None }
1017
1018        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1019        struct WithNestedVec {
1020            a_field: Vec<Vec<u64>>,
1021        }
1022
1023        test_case! { fn with_nested_vec for WithNestedVec: None }
1024
1025        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1026        struct EmptyStruct {}
1027
1028        test_case! { fn empty_struct for EmptyStruct: Some(0) }
1029
1030        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1031        struct StructWithEmptyStruct {
1032            a: EmptyStruct,
1033        }
1034
1035        test_case! { fn struct_with_empty_struct for StructWithEmptyStruct: Some(0) }
1036
1037        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1038        struct StructWithTwoEmptyStructs {
1039            a: EmptyStruct,
1040            b: EmptyStruct,
1041        }
1042
1043        test_case! { fn struct_with_two_empty_structs for StructWithTwoEmptyStructs: Some(0) }
1044
1045        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1046        struct BigStructWithEmptyStructs {
1047            a: EmptyStruct,
1048            b: EmptyStruct,
1049            c: StructWithTwoEmptyStructs,
1050            d: StructWithEmptyStruct,
1051            e: EmptyStruct,
1052        }
1053
1054        test_case! { fn big_struct_with_empty_structs for BigStructWithEmptyStructs: Some(0) }
1055
1056        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1057        enum EnumWithEmptyStruct {
1058            A(EmptyStruct),
1059            B,
1060            C(EmptyStruct),
1061        }
1062
1063        test_case! { fn enum_with_empty_struct for EnumWithEmptyStruct: Some(1) }
1064
1065        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1066        struct MuchNesting {
1067            a: Vec<Vec<Vec<Vec<BFieldElement>>>>,
1068            #[bfield_codec(ignore)]
1069            b: PhantomData<Tip5>,
1070            #[bfield_codec(ignore)]
1071            c: PhantomData<Tip5>,
1072        }
1073
1074        test_case! { fn much_nesting for MuchNesting: None }
1075
1076        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1077        struct SmallArrayStructUnnamedFields([u128; 1]);
1078
1079        test_case! {
1080            fn small_array_struct_unnamed_fields for SmallArrayStructUnnamedFields: Some(4)
1081        }
1082
1083        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1084        struct SmallArrayStructNamedFields {
1085            a: [u128; 1],
1086        }
1087
1088        test_case! { fn small_array_struct_named_fields for SmallArrayStructNamedFields: Some(4) }
1089
1090        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1091        struct BigArrayStructUnnamedFields([u128; 150]);
1092
1093        test_case! {
1094            fn big_array_struct_unnamed_fields for BigArrayStructUnnamedFields: Some(4 * 150)
1095        }
1096
1097        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1098        struct BigArrayStructNamedFields {
1099            a: [XFieldElement; 150],
1100            b: XFieldElement,
1101            c: u64,
1102        }
1103
1104        test_case! {
1105            fn big_array_struct_named_fields for BigArrayStructNamedFields: Some(3 * 150 + 3 + 2)
1106        }
1107
1108        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1109        struct ArrayStructDynamicallySizedElementsUnnamedFields([Vec<u128>; 7]);
1110
1111        test_case! {
1112            fn array_struct_dyn_sized_elements_unnamed_fields
1113            for ArrayStructDynamicallySizedElementsUnnamedFields: None
1114        }
1115
1116        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1117        struct ArrayStructDynamicallySizedElementsNamedFields {
1118            a: [Vec<u128>; 7],
1119        }
1120
1121        test_case! {
1122            fn array_struct_dyn_sized_elements_named_fields
1123            for ArrayStructDynamicallySizedElementsNamedFields: None
1124        }
1125
1126        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1127        struct StructWithTupleField {
1128            a: (Digest, Vec<Digest>),
1129        }
1130
1131        test_case! { fn struct_with_tuple_field for StructWithTupleField: None }
1132
1133        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1134        struct StructWithTupleFieldTwoElements {
1135            a: ([Digest; 2], XFieldElement),
1136        }
1137
1138        test_case! {
1139            fn struct_with_tuple_field_two_elements for StructWithTupleFieldTwoElements: Some(13)
1140        }
1141
1142        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1143        struct StructWithNestedTupleField {
1144            a: (([Digest; 2], Vec<XFieldElement>), (XFieldElement, u64)),
1145        }
1146
1147        test_case! { fn struct_with_nested_tuple_field for StructWithNestedTupleField: None }
1148
1149        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1150        struct MsMembershipProof {
1151            sender_randomness: Digest,
1152            receiver_preimage: Digest,
1153            auth_path_aocl: MmrMembershipProof,
1154        }
1155
1156        test_case! { fn ms_membership_proof for MsMembershipProof: None }
1157        test_case! { fn mmr_accumulator for MmrAccumulator: None }
1158
1159        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1160        struct UnsupportedFields {
1161            a: u64,
1162            #[bfield_codec(ignore)]
1163            b: usize,
1164        }
1165
1166        #[proptest]
1167        fn unsupported_fields_can_be_ignored_test(#[strategy(arb())] my_struct: UnsupportedFields) {
1168            let encoded = my_struct.encode();
1169            let decoded = UnsupportedFields::decode(&encoded).unwrap();
1170            prop_assert_eq!(my_struct.a, decoded.a);
1171            prop_assert_eq!(usize::default(), decoded.b);
1172        }
1173
1174        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1175        struct OneFixedLenField {
1176            some_digest: Digest,
1177        }
1178
1179        test_case! { fn one_fixed_len_field for OneFixedLenField: Some(5) }
1180
1181        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1182        pub struct TwoFixedLenFields {
1183            pub some_digest: Digest,
1184            pub some_u64: u64,
1185        }
1186
1187        test_case! { fn two_fixed_len_fields for TwoFixedLenFields: Some(7) }
1188
1189        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1190        pub struct TwoFixedLenUnnamedFields(Digest, u64);
1191
1192        test_case! { fn two_fixed_len_unnamed_fields for TwoFixedLenUnnamedFields: Some(7) }
1193
1194        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1195        pub struct FixAndVarLenFields {
1196            pub some_digest: Digest,
1197            pub some_vec: Vec<u64>,
1198        }
1199
1200        test_case! { fn fix_and_var_len_fields for FixAndVarLenFields: None }
1201
1202        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1203        struct FixAndVarLenUnnamedFields(Digest, Vec<u64>);
1204
1205        test_case! { fn fix_and_var_len_unnamed_fields for FixAndVarLenUnnamedFields: None }
1206
1207        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1208        struct QuiteAFewFixAndVarLenFields {
1209            some_digest: Digest,
1210            some_vec: Vec<u64>,
1211            some_u64: u64,
1212            other_vec: Vec<u32>,
1213            other_digest: Digest,
1214            yet_another_vec: Vec<u32>,
1215            and_another_vec: Vec<u64>,
1216            more_fixed_len: u64,
1217            even_more_fixed_len: u64,
1218        }
1219
1220        test_case! { fn quite_a_few_fix_and_var_len_fields for QuiteAFewFixAndVarLenFields: None }
1221
1222        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1223        struct SimpleStructA {
1224            a: BFieldElement,
1225            b: XFieldElement,
1226        }
1227
1228        test_case! { fn simple_struct_a for SimpleStructA: Some(4) }
1229
1230        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1231        struct SimpleStructB(u32, u64);
1232
1233        test_case! { fn simple_struct_b for SimpleStructB: Some(3) }
1234
1235        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1236        struct StructWithBox {
1237            a: Box<u64>,
1238        }
1239
1240        test_case! { fn struct_with_box for StructWithBox: Some(2) }
1241
1242        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1243        struct TupleStructWithBox(Box<u64>);
1244
1245        test_case! { fn tuple_struct_with_box for TupleStructWithBox: Some(2) }
1246
1247        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1248        struct StructWithBoxContainingStructWithBox {
1249            a: Box<StructWithBox>,
1250            b: Box<TupleStructWithBox>,
1251        }
1252
1253        test_case! {
1254            fn struct_with_box_containing_struct_with_box
1255            for StructWithBoxContainingStructWithBox: Some(4)
1256        }
1257
1258        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1259        enum SimpleEnum {
1260            A,
1261            B(u32),
1262            C(BFieldElement, u32, u32),
1263        }
1264
1265        test_case! { fn simple_enum for SimpleEnum: None }
1266
1267        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1268        enum ComplexEnum {
1269            A,
1270            B(u32),
1271            C(BFieldElement, XFieldElement, u32),
1272            D(Vec<BFieldElement>, Digest),
1273            E(Option<bool>),
1274        }
1275
1276        test_case! { fn complex_enum for ComplexEnum: None }
1277
1278        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1279        enum EnumWithUniformDataSize {
1280            A(Digest),
1281            B(Digest),
1282            C(Digest),
1283        }
1284
1285        test_case! { fn enum_with_uniform_data_size for EnumWithUniformDataSize: Some(6) }
1286
1287        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1288        enum EnumWithIrregularDataSize {
1289            A(u32),
1290            B,
1291            C(Digest),
1292            D(Vec<XFieldElement>),
1293        }
1294
1295        test_case! { fn enum_with_irregular_data_size for EnumWithIrregularDataSize: None }
1296
1297        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1298        enum EnumWithGenerics<I: Into<u64>> {
1299            A(I),
1300            B(I, I),
1301        }
1302
1303        test_case! { fn enum_with_generics for EnumWithGenerics<u32>: None }
1304
1305        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1306        enum EnumWithGenericsAndWhereClause<I: Into<u64>>
1307        where
1308            I: Debug + Copy + Eq,
1309        {
1310            A,
1311            B(I),
1312            C(I, I),
1313        }
1314
1315        test_case! {
1316            fn enum_with_generics_and_where_clause for EnumWithGenericsAndWhereClause<u32>: None
1317        }
1318
1319        #[test]
1320        fn enums_bfield_codec_discriminant_can_be_accessed() {
1321            let a = EnumWithGenericsAndWhereClause::<u32>::A;
1322            let b = EnumWithGenericsAndWhereClause::<u32>::B(1);
1323            let c = EnumWithGenericsAndWhereClause::<u32>::C(1, 2);
1324            assert_eq!(0, a.bfield_codec_discriminant());
1325            assert_eq!(1, b.bfield_codec_discriminant());
1326            assert_eq!(2, c.bfield_codec_discriminant());
1327        }
1328
1329        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1330        enum EnumWithBoxedVariant {
1331            A(Box<u64>),
1332            B(Box<u64>, Box<u64>),
1333        }
1334
1335        test_case! { fn enum_with_boxed_variant for EnumWithBoxedVariant: None }
1336
1337        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1338        enum EnumWithBoxedVariantAndBoxedStruct {
1339            A(Box<StructWithBox>),
1340            B(Box<StructWithBox>, Box<TupleStructWithBox>),
1341        }
1342
1343        test_case! {
1344            fn enum_with_boxed_variant_and_boxed_struct for EnumWithBoxedVariantAndBoxedStruct: None
1345        }
1346
1347        #[derive(Debug, Clone, PartialEq, Eq, BFieldCodec, Arbitrary)]
1348        struct DummyPolynomial<T: FiniteField + BFieldCodec> {
1349            coefficients: Vec<T>,
1350        }
1351
1352        #[proptest]
1353        fn manual_poly_encoding_implementation_is_consistent_with_derived_bfe(
1354            #[strategy(arb())] coefficients: Vec<BFieldElement>,
1355        ) {
1356            manual_poly_encoding_implementation_is_consistent_with_derived(coefficients)?;
1357        }
1358
1359        #[proptest]
1360        fn manual_poly_encoding_implementation_is_consistent_with_derived_xfe(
1361            #[strategy(arb())] coefficients: Vec<XFieldElement>,
1362        ) {
1363            manual_poly_encoding_implementation_is_consistent_with_derived(coefficients)?;
1364        }
1365
1366        fn manual_poly_encoding_implementation_is_consistent_with_derived<FF>(
1367            coefficients: Vec<FF>,
1368        ) -> TestCaseResult
1369        where
1370            FF: FiniteField + BFieldCodec + 'static,
1371        {
1372            if coefficients.last().is_some_and(Zero::is_zero) {
1373                let rsn = "`DummyPolynomial::encode` only works for non-zero leading coefficients";
1374                return Err(TestCaseError::Reject(rsn.into()));
1375            }
1376
1377            let polynomial = Polynomial::new(coefficients.clone());
1378            let dummy_polynomial = DummyPolynomial { coefficients };
1379            prop_assert_eq!(dummy_polynomial.encode(), polynomial.encode());
1380            Ok(())
1381        }
1382    }
1383}