Skip to main content

miden_field/native/
mod.rs

1//! Off-chain implementation of [`crate::Felt`].
2
3use alloc::{format, vec, vec::Vec};
4use core::{
5    array, fmt,
6    hash::{Hash, Hasher},
7    iter::{Product, Sum},
8    mem::{align_of, size_of},
9    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
10};
11
12use miden_serde_utils::{
13    ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
14};
15use num_bigint::BigUint;
16use p3_challenger::UniformSamplingField;
17use p3_field::{
18    Field, InjectiveMonomial, Packable, PermutationMonomial, PrimeCharacteristicRing, PrimeField,
19    PrimeField64, RawDataSerializable, TwoAdicField,
20    extension::{
21        Binomial, BinomiallyExtendable, ExtensionAlgebra, HasTwoAdicBinomialExtension,
22        binomial_mul, binomial_square,
23    },
24    impl_raw_serializable_primefield64,
25    integers::QuotientMap,
26    quotient_map_large_iint, quotient_map_large_uint, quotient_map_small_int,
27};
28use p3_goldilocks::Goldilocks;
29use p3_util::flatten_to_base;
30use rand::{
31    Rng,
32    distr::{Distribution, StandardUniform},
33};
34use subtle::{ConditionallySelectable, ConstantTimeLess};
35
36#[cfg(any(
37    all(target_arch = "x86_64", target_feature = "avx2"),
38    all(target_arch = "aarch64", target_feature = "neon"),
39    all(target_arch = "wasm32", target_feature = "simd128"),
40))]
41mod packed;
42#[cfg(any(
43    all(target_arch = "x86_64", target_feature = "avx2"),
44    all(target_arch = "aarch64", target_feature = "neon"),
45    all(target_arch = "wasm32", target_feature = "simd128"),
46))]
47pub use packed::PackedFelt;
48
49#[cfg(test)]
50mod tests;
51
52// FELT
53// ================================================================================================
54
55/// A `Felt` backed by Plonky3's Goldilocks field element.
56///
57/// Round-trip equality is safe even though `Felt` may hold non-canonical internal values:
58/// `PartialEq for Felt` delegates to `Goldilocks::eq`, which compares `as_canonical_u64()` on
59/// both sides, so canonicalization by serialization is invisible to equality.
60#[derive(Copy, Clone, Default, serde::Serialize, serde::Deserialize)]
61#[repr(transparent)]
62#[cfg_attr(
63    all(feature = "arbitrary", test),
64    miden_test_serialization_macros::serialization_test
65)]
66pub struct Felt(Goldilocks);
67
68impl Felt {
69    /// Order of the field.
70    pub const ORDER: u64 = <Goldilocks as PrimeField64>::ORDER_U64;
71
72    pub const ZERO: Self = Self(Goldilocks::ZERO);
73    pub const ONE: Self = Self(Goldilocks::ONE);
74
75    /// The largest valid field element, equal to `ORDER - 1`.
76    pub const MAX: Self = Self::new_unchecked(Self::ORDER - 1);
77
78    /// The number of bytes which this field element occupies in memory.
79    pub const NUM_BYTES: usize = Goldilocks::NUM_BYTES;
80
81    /// Constructs a new field element from the provided `value`.
82    ///
83    /// # Errors
84    ///
85    /// - [`FeltFromIntError`] if the provided `value` is not a valid input.
86    pub fn new(value: u64) -> Result<Self, FeltFromIntError> {
87        Felt::from_canonical_checked(value).ok_or(FeltFromIntError(value))
88    }
89
90    /// Creates a new field element from any `u64` without performing reduction.
91    ///
92    /// Any `u64` value is accepted. No reduction is performed since Goldilocks uses a
93    /// non-canonical internal representation.
94    #[inline]
95    pub const fn new_unchecked(value: u64) -> Self {
96        Self(Goldilocks::new(value))
97    }
98
99    /// Constructs a field element from a `u8`.
100    #[inline]
101    pub const fn from_u8(value: u8) -> Self {
102        Self::new_unchecked(value as u64)
103    }
104
105    /// Constructs a field element from a `u16`.
106    #[inline]
107    pub const fn from_u16(value: u16) -> Self {
108        Self::new_unchecked(value as u64)
109    }
110
111    /// Constructs a field element from a `u32`.
112    #[inline]
113    pub const fn from_u32(value: u32) -> Self {
114        Self::new_unchecked(value as u64)
115    }
116
117    /// The elementary function `double(a) = 2*a`.
118    #[inline]
119    pub fn double(&self) -> Self {
120        <Self as PrimeCharacteristicRing>::double(self)
121    }
122
123    /// The elementary function `square(a) = a^2`.
124    #[inline]
125    pub fn square(&self) -> Self {
126        <Self as PrimeCharacteristicRing>::square(self)
127    }
128
129    /// Exponentiation by a `u64` power.
130    #[inline]
131    pub fn exp_u64(&self, power: u64) -> Self {
132        <Self as PrimeCharacteristicRing>::exp_u64(self, power)
133    }
134
135    /// Exponentiation by a small constant power.
136    #[inline]
137    pub fn exp_const_u64<const POWER: u64>(&self) -> Self {
138        <Self as PrimeCharacteristicRing>::exp_const_u64::<POWER>(self)
139    }
140
141    /// Return the representative of element in canonical form which lies in the range
142    /// `0 <= x < ORDER`.
143    #[inline]
144    pub fn as_canonical_u64(&self) -> u64 {
145        <Self as PrimeField64>::as_canonical_u64(self)
146    }
147
148    /// Constant-time equivalent of `as_canonical_u64()` using the same reduction logic as
149    /// Plonky3's Goldilocks implementation.
150    #[inline]
151    pub fn as_canonical_u64_ct(&self) -> u64 {
152        let raw = raw_felt_u64(*self);
153        // Mirrors Goldilocks::as_canonical_u64: conditional subtraction of ORDER.
154        // A single subtraction is sufficient for any u64 value since 2*ORDER > u64::MAX.
155        let reduced = raw.wrapping_sub(Self::ORDER);
156        let reduce = !raw.ct_lt(&Self::ORDER);
157        u64::conditional_select(&raw, &reduced, reduce)
158    }
159}
160
161#[inline]
162fn raw_felt_u64(value: Felt) -> u64 {
163    const _: () = {
164        assert!(size_of::<Felt>() == size_of::<u64>());
165        assert!(align_of::<Felt>() == align_of::<u64>());
166        assert!(2u128 * (Felt::ORDER as u128) > u64::MAX as u128);
167    };
168    // SAFETY: Felt is repr(transparent) over Goldilocks, which is repr(transparent) over u64.
169    unsafe { core::mem::transmute_copy(&value) }
170}
171
172/// Reinterprets a `Felt` slice as `Goldilocks`.
173///
174/// # Safety
175///
176/// `Felt` is `#[repr(transparent)]` over `Goldilocks`, so the element layout matches.
177#[inline]
178fn felts_as_goldilocks_slice(s: &[Felt]) -> &[Goldilocks] {
179    // SAFETY: `Felt` is `#[repr(transparent)]` over `Goldilocks`, so the element layout matches.
180    unsafe { core::slice::from_raw_parts(s.as_ptr().cast::<Goldilocks>(), s.len()) }
181}
182
183/// Reinterprets a `Felt` array as `Goldilocks`.
184///
185/// # Safety
186///
187/// `Felt` is `#[repr(transparent)]` over `Goldilocks`, so `[Felt; N]` matches `[Goldilocks; N]`.
188#[inline]
189fn felts_as_goldilocks_array<const N: usize>(a: &[Felt; N]) -> &[Goldilocks; N] {
190    // SAFETY: same layout as `felts_as_goldilocks_slice`, for a fixed `N`.
191    unsafe { &*(a as *const [Felt; N] as *const [Goldilocks; N]) }
192}
193
194impl fmt::Display for Felt {
195    #[inline]
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        fmt::Display::fmt(&self.0, f)
198    }
199}
200
201impl fmt::Debug for Felt {
202    #[inline]
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        fmt::Debug::fmt(&self.0, f)
205    }
206}
207
208impl Hash for Felt {
209    #[inline]
210    fn hash<H: Hasher>(&self, state: &mut H) {
211        state.write_u64(self.as_canonical_u64());
212    }
213}
214
215// FIELD
216// ================================================================================================
217
218impl Field for Felt {
219    #[cfg(all(target_arch = "x86_64", target_feature = "avx2", not(target_feature = "avx512f")))]
220    type Packing = PackedFelt;
221
222    #[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
223    type Packing = PackedFelt;
224
225    #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
226    type Packing = PackedFelt;
227
228    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
229    type Packing = PackedFelt;
230
231    #[cfg(not(any(
232        all(target_arch = "x86_64", target_feature = "avx2", not(target_feature = "avx512f")),
233        all(target_arch = "x86_64", target_feature = "avx512f"),
234        target_arch = "aarch64",
235        all(target_arch = "wasm32", target_feature = "simd128"),
236    )))]
237    type Packing = Self;
238
239    const GENERATOR: Self = Self(Goldilocks::GENERATOR);
240
241    #[inline]
242    fn is_zero(&self) -> bool {
243        self.0.is_zero()
244    }
245
246    #[inline]
247    fn try_inverse(&self) -> Option<Self> {
248        self.0.try_inverse().map(Self)
249    }
250
251    #[inline]
252    fn order() -> BigUint {
253        <Goldilocks as Field>::order()
254    }
255}
256
257impl Packable for Felt {}
258
259impl PrimeCharacteristicRing for Felt {
260    type PrimeSubfield = Goldilocks;
261
262    const ZERO: Self = Self(Goldilocks::ZERO);
263    const ONE: Self = Self(Goldilocks::ONE);
264    const TWO: Self = Self(Goldilocks::TWO);
265    const NEG_ONE: Self = Self(Goldilocks::NEG_ONE);
266
267    #[inline]
268    fn from_prime_subfield(f: Self::PrimeSubfield) -> Self {
269        Self(f)
270    }
271
272    #[inline]
273    fn from_bool(value: bool) -> Self {
274        Self::new_unchecked(value.into())
275    }
276
277    #[inline]
278    fn halve(&self) -> Self {
279        Self(self.0.halve())
280    }
281
282    #[inline]
283    fn square(&self) -> Self {
284        Self(self.0.square())
285    }
286
287    #[inline]
288    fn mul_2exp_u64(&self, exp: u64) -> Self {
289        Self(self.0.mul_2exp_u64(exp))
290    }
291
292    #[inline]
293    fn div_2exp_u64(&self, exp: u64) -> Self {
294        Self(self.0.div_2exp_u64(exp))
295    }
296
297    #[inline]
298    fn exp_u64(&self, power: u64) -> Self {
299        self.0.exp_u64(power).into()
300    }
301
302    #[inline]
303    fn sum_array<const N: usize>(input: &[Self]) -> Self {
304        assert_eq!(N, input.len());
305        let g = felts_as_goldilocks_slice(input);
306        Self(Goldilocks::sum_array::<N>(g))
307    }
308
309    #[inline]
310    fn dot_product<const N: usize>(lhs: &[Self; N], rhs: &[Self; N]) -> Self {
311        let lhs_g = felts_as_goldilocks_array(lhs);
312        let rhs_g = felts_as_goldilocks_array(rhs);
313        Self(Goldilocks::dot_product(lhs_g, rhs_g))
314    }
315
316    #[inline]
317    fn zero_vec(len: usize) -> Vec<Self> {
318        // SAFETY:
319        // Due to `#[repr(transparent)]`, Felt, Goldilocks and u64 have the same size,
320        // alignment and memory layout making `flatten_to_base` safe.
321        // This will create a vector of Felt elements with value set to 0.
322        unsafe { flatten_to_base(vec![0u64; len]) }
323    }
324}
325
326quotient_map_small_int!(Felt, u64, [u8, u16, u32]);
327quotient_map_small_int!(Felt, i64, [i8, i16, i32]);
328
329quotient_map_large_uint!(
330    Felt,
331    u64,
332    Felt::ORDER_U64,
333    "`[0, 2^64 - 2^32]`",
334    "`[0, 2^64 - 1]`",
335    [u128]
336);
337quotient_map_large_iint!(
338    Felt,
339    i64,
340    "`[-(2^63 - 2^31), 2^63 - 2^31]`",
341    "`[1 + 2^32 - 2^64, 2^64 - 1]`",
342    [(i128, u128)]
343);
344
345impl QuotientMap<u64> for Felt {
346    #[inline]
347    fn from_int(int: u64) -> Self {
348        Goldilocks::from_int(int).into()
349    }
350
351    #[inline]
352    fn from_canonical_checked(int: u64) -> Option<Self> {
353        Goldilocks::from_canonical_checked(int).map(From::from)
354    }
355
356    #[inline(always)]
357    unsafe fn from_canonical_unchecked(int: u64) -> Self {
358        Goldilocks::new(int).into()
359    }
360}
361
362impl QuotientMap<i64> for Felt {
363    #[inline]
364    fn from_int(int: i64) -> Self {
365        Goldilocks::from_int(int).into()
366    }
367
368    #[inline]
369    fn from_canonical_checked(int: i64) -> Option<Self> {
370        Goldilocks::from_canonical_checked(int).map(From::from)
371    }
372
373    #[inline(always)]
374    unsafe fn from_canonical_unchecked(int: i64) -> Self {
375        unsafe { Goldilocks::from_canonical_unchecked(int).into() }
376    }
377}
378
379impl PrimeField for Felt {
380    #[inline]
381    fn as_canonical_biguint(&self) -> BigUint {
382        <Goldilocks as PrimeField>::as_canonical_biguint(&self.0)
383    }
384}
385
386impl PrimeField64 for Felt {
387    const ORDER_U64: u64 = <Goldilocks as PrimeField64>::ORDER_U64;
388
389    #[inline]
390    fn as_canonical_u64(&self) -> u64 {
391        self.0.as_canonical_u64()
392    }
393}
394
395impl TwoAdicField for Felt {
396    const TWO_ADICITY: usize = <Goldilocks as TwoAdicField>::TWO_ADICITY;
397
398    #[inline]
399    fn two_adic_generator(bits: usize) -> Self {
400        Self(<Goldilocks as TwoAdicField>::two_adic_generator(bits))
401    }
402}
403
404// EXTENSION FIELDS
405// ================================================================================================
406
407impl ExtensionAlgebra<Self, 2, Binomial<Self>> for Felt {
408    #[inline]
409    fn ext_mul(a: &[Self; 2], b: &[Self; 2], res: &mut [Self; 2]) {
410        binomial_mul::<Self, Self, Self, 2>(a, b, res, <Self as BinomiallyExtendable<2>>::W);
411    }
412
413    #[inline]
414    fn ext_square(a: &[Self; 2], res: &mut [Self; 2]) {
415        binomial_square::<Self, Self, 2>(a, res, <Self as BinomiallyExtendable<2>>::W);
416    }
417}
418
419impl BinomiallyExtendable<2> for Felt {
420    fn binomial_algebra_id() -> Vec<u8> {
421        <Goldilocks as BinomiallyExtendable<2>>::binomial_algebra_id()
422    }
423
424    const W: Self = Self(<Goldilocks as BinomiallyExtendable<2>>::W);
425
426    const DTH_ROOT: Self = Self(<Goldilocks as BinomiallyExtendable<2>>::DTH_ROOT);
427
428    const EXT_GENERATOR: [Self; 2] = [
429        Self(<Goldilocks as BinomiallyExtendable<2>>::EXT_GENERATOR[0]),
430        Self(<Goldilocks as BinomiallyExtendable<2>>::EXT_GENERATOR[1]),
431    ];
432}
433
434impl HasTwoAdicBinomialExtension<2> for Felt {
435    const EXT_TWO_ADICITY: usize = <Goldilocks as HasTwoAdicBinomialExtension<2>>::EXT_TWO_ADICITY;
436
437    #[inline]
438    fn ext_two_adic_generator(bits: usize) -> [Self; 2] {
439        let [a, b] = <Goldilocks as HasTwoAdicBinomialExtension<2>>::ext_two_adic_generator(bits);
440        [Self(a), Self(b)]
441    }
442}
443
444impl ExtensionAlgebra<Self, 5, Binomial<Self>> for Felt {
445    #[inline]
446    fn ext_mul(a: &[Self; 5], b: &[Self; 5], res: &mut [Self; 5]) {
447        binomial_mul::<Self, Self, Self, 5>(a, b, res, <Self as BinomiallyExtendable<5>>::W);
448    }
449
450    #[inline]
451    fn ext_square(a: &[Self; 5], res: &mut [Self; 5]) {
452        binomial_square::<Self, Self, 5>(a, res, <Self as BinomiallyExtendable<5>>::W);
453    }
454}
455
456impl BinomiallyExtendable<5> for Felt {
457    fn binomial_algebra_id() -> Vec<u8> {
458        <Goldilocks as BinomiallyExtendable<5>>::binomial_algebra_id()
459    }
460
461    const W: Self = Self(<Goldilocks as BinomiallyExtendable<5>>::W);
462
463    const DTH_ROOT: Self = Self(<Goldilocks as BinomiallyExtendable<5>>::DTH_ROOT);
464
465    const EXT_GENERATOR: [Self; 5] = [
466        Self(<Goldilocks as BinomiallyExtendable<5>>::EXT_GENERATOR[0]),
467        Self(<Goldilocks as BinomiallyExtendable<5>>::EXT_GENERATOR[1]),
468        Self(<Goldilocks as BinomiallyExtendable<5>>::EXT_GENERATOR[2]),
469        Self(<Goldilocks as BinomiallyExtendable<5>>::EXT_GENERATOR[3]),
470        Self(<Goldilocks as BinomiallyExtendable<5>>::EXT_GENERATOR[4]),
471    ];
472}
473
474impl HasTwoAdicBinomialExtension<5> for Felt {
475    const EXT_TWO_ADICITY: usize = <Goldilocks as HasTwoAdicBinomialExtension<5>>::EXT_TWO_ADICITY;
476
477    #[inline]
478    fn ext_two_adic_generator(bits: usize) -> [Self; 5] {
479        let ext_generator =
480            <Goldilocks as HasTwoAdicBinomialExtension<5>>::ext_two_adic_generator(bits);
481        [
482            Self(ext_generator[0]),
483            Self(ext_generator[1]),
484            Self(ext_generator[2]),
485            Self(ext_generator[3]),
486            Self(ext_generator[4]),
487        ]
488    }
489}
490
491impl RawDataSerializable for Felt {
492    impl_raw_serializable_primefield64!();
493}
494
495impl Distribution<Felt> for StandardUniform {
496    #[inline]
497    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Felt {
498        let inner = <StandardUniform as Distribution<Goldilocks>>::sample(self, rng);
499        Felt(inner)
500    }
501}
502
503impl UniformSamplingField for Felt {
504    const MAX_SINGLE_SAMPLE_BITS: usize =
505        <Goldilocks as UniformSamplingField>::MAX_SINGLE_SAMPLE_BITS;
506    const SAMPLING_BITS_M: [u64; 64] = <Goldilocks as UniformSamplingField>::SAMPLING_BITS_M;
507}
508
509impl InjectiveMonomial<7> for Felt {}
510
511impl PermutationMonomial<7> for Felt {
512    #[inline]
513    fn injective_exp_root_n(&self) -> Self {
514        Self(self.0.injective_exp_root_n())
515    }
516}
517
518// CONVERSIONS
519// ================================================================================================
520
521impl From<u8> for Felt {
522    fn from(int: u8) -> Self {
523        Self::from_u8(int)
524    }
525}
526
527impl From<u16> for Felt {
528    fn from(int: u16) -> Self {
529        Self::from_u16(int)
530    }
531}
532
533impl From<u32> for Felt {
534    fn from(int: u32) -> Self {
535        Self::from_u32(int)
536    }
537}
538
539impl TryFrom<u64> for Felt {
540    type Error = FeltFromIntError;
541
542    fn try_from(int: u64) -> Result<Felt, Self::Error> {
543        Felt::new(int)
544    }
545}
546
547#[derive(Debug, thiserror::Error)]
548#[error("integer {0} is equal to or exceeds the felt modulus {modulus}", modulus = Felt::ORDER)]
549pub struct FeltFromIntError(u64);
550
551impl FeltFromIntError {
552    /// Returns the integer for which the conversion failed.
553    pub fn as_u64(&self) -> u64 {
554        self.0
555    }
556}
557
558impl From<Goldilocks> for Felt {
559    #[inline]
560    fn from(value: Goldilocks) -> Self {
561        Self(value)
562    }
563}
564
565impl From<Felt> for Goldilocks {
566    #[inline]
567    fn from(value: Felt) -> Self {
568        value.0
569    }
570}
571
572// ARITHMETIC OPERATIONS
573// ================================================================================================
574
575impl Add for Felt {
576    type Output = Self;
577
578    #[inline]
579    fn add(self, other: Self) -> Self {
580        Self(self.0 + other.0)
581    }
582}
583
584impl AddAssign for Felt {
585    #[inline]
586    fn add_assign(&mut self, other: Self) {
587        *self = *self + other;
588    }
589}
590
591impl Sub for Felt {
592    type Output = Self;
593
594    #[inline]
595    fn sub(self, other: Self) -> Self {
596        Self(self.0 - other.0)
597    }
598}
599
600impl SubAssign for Felt {
601    #[inline]
602    fn sub_assign(&mut self, other: Self) {
603        *self = *self - other;
604    }
605}
606
607impl Mul for Felt {
608    type Output = Self;
609
610    #[inline]
611    fn mul(self, other: Self) -> Self {
612        Self(self.0 * other.0)
613    }
614}
615
616impl MulAssign for Felt {
617    #[inline]
618    fn mul_assign(&mut self, other: Self) {
619        *self = *self * other;
620    }
621}
622
623impl Div for Felt {
624    type Output = Self;
625
626    #[inline]
627    fn div(self, other: Self) -> Self {
628        Self(self.0 / other.0)
629    }
630}
631
632impl DivAssign for Felt {
633    #[inline]
634    fn div_assign(&mut self, other: Self) {
635        *self = *self / other;
636    }
637}
638
639impl Neg for Felt {
640    type Output = Self;
641
642    #[inline]
643    fn neg(self) -> Self {
644        Self(-self.0)
645    }
646}
647
648impl Sum for Felt {
649    #[inline]
650    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
651        Self(iter.map(|x| x.0).sum())
652    }
653}
654
655impl<'a> Sum<&'a Felt> for Felt {
656    #[inline]
657    fn sum<I: Iterator<Item = &'a Felt>>(iter: I) -> Self {
658        Self(iter.map(|x| x.0).sum())
659    }
660}
661
662impl Product for Felt {
663    #[inline]
664    fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
665        Self(iter.map(|x| x.0).product())
666    }
667}
668
669impl<'a> Product<&'a Felt> for Felt {
670    #[inline]
671    fn product<I: Iterator<Item = &'a Felt>>(iter: I) -> Self {
672        Self(iter.map(|x| x.0).product())
673    }
674}
675
676// EQUALITY AND COMPARISON OPERATIONS
677// ================================================================================================
678
679impl PartialEq for Felt {
680    #[inline]
681    fn eq(&self, other: &Self) -> bool {
682        self.0 == other.0
683    }
684}
685
686impl PartialEq<Goldilocks> for Felt {
687    #[inline]
688    fn eq(&self, other: &Goldilocks) -> bool {
689        self.0 == *other
690    }
691}
692
693impl Eq for Felt {}
694
695impl PartialOrd for Felt {
696    #[inline]
697    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
698        Some(self.cmp(other))
699    }
700}
701
702impl Ord for Felt {
703    #[inline]
704    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
705        self.0.cmp(&other.0)
706    }
707}
708
709// SERIALIZATION
710// ================================================================================================
711
712impl Serializable for Felt {
713    fn write_into<W: ByteWriter>(&self, target: &mut W) {
714        target.write_u64(self.as_canonical_u64());
715    }
716
717    fn get_size_hint(&self) -> usize {
718        size_of::<u64>()
719    }
720}
721
722impl Deserializable for Felt {
723    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
724        let value = source.read_u64()?;
725        Self::from_canonical_checked(value).ok_or_else(|| {
726            DeserializationError::InvalidValue(format!("value {value} is not a valid felt"))
727        })
728    }
729}
730
731// ARBITRARY (proptest)
732// ================================================================================================
733
734#[cfg(all(any(test, feature = "arbitrary"), not(all(target_family = "wasm", miden))))]
735mod arbitrary {
736    use proptest::prelude::*;
737
738    use super::Felt;
739
740    impl Arbitrary for Felt {
741        type Parameters = ();
742        type Strategy = BoxedStrategy<Self>;
743
744        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
745            prop_oneof![4 => arb_felt_canonical(), 1 => arb_felt_noncanonical()].boxed()
746        }
747    }
748
749    /// Boundary values of the canonical regime, hit by construction: zero,
750    /// one, both sides of the 2^32 seam, and the two elements adjacent to
751    /// the modulus. The edge index derives from `r / 8` — a component
752    /// independent of the branch gate `r % 8` (the run-#84 correlation
753    /// lesson).
754    pub(super) const CANONICAL_EDGES: [u64; 6] =
755        [0, 1, (1 << 32) - 1, 1 << 32, Felt::ORDER - 2, Felt::ORDER - 1];
756
757    /// Generates field elements with canonical representations: ~7/8 of
758    /// draws are uniform over `[0, ORDER)` and ~1/8 are boundary values
759    /// hit by construction (uniform sampling leaves them measure-zero,
760    /// which under-covers every wire test's Felt fields). The branch gate
761    /// and the value draw are INDEPENDENT components — deriving both from
762    /// one `u64` would remove every canonical value congruent to the gate
763    /// class from the generator's range (the run-#84 correlation lesson at
764    /// full depth).
765    pub fn arb_felt_canonical() -> impl Strategy<Value = Felt> {
766        (any::<u64>(), any::<u64>()).prop_map(|(gate, value)| {
767            if gate % 8 == 7 {
768                Felt::new_unchecked(CANONICAL_EDGES[(gate / 8) as usize % CANONICAL_EDGES.len()])
769            } else {
770                Felt::new_unchecked(value % Felt::ORDER)
771            }
772        })
773    }
774
775    /// Boundary values of the non-canonical regime: the first and last
776    /// non-canonical representations (ORDER aliases canonical zero;
777    /// u64::MAX is the largest).
778    pub(super) const NONCANONICAL_EDGES: [u64; 3] = [Felt::ORDER, u64::MAX - 1, u64::MAX];
779
780    /// Generates field elements with non-canonical representations: ~3/4
781    /// uniform over `[ORDER, u64::MAX]` and ~1/4 boundary values, with the
782    /// same independent gate/value components as the canonical adapter.
783    pub fn arb_felt_noncanonical() -> impl Strategy<Value = Felt> {
784        (any::<u64>(), any::<u64>()).prop_map(|(gate, value)| {
785            if gate % 4 == 3 {
786                Felt::new_unchecked(
787                    NONCANONICAL_EDGES[(gate / 4) as usize % NONCANONICAL_EDGES.len()],
788                )
789            } else {
790                Felt::new_unchecked(Felt::ORDER + value % (u64::MAX - Felt::ORDER + 1))
791            }
792        })
793    }
794}
795
796#[cfg(all(any(test, feature = "arbitrary"), not(all(target_family = "wasm", miden))))]
797pub use arbitrary::{arb_felt_canonical, arb_felt_noncanonical};
798
799#[cfg(all(test, not(all(target_family = "wasm", miden))))]
800mod arbitrary_boundary_tests {
801    use proptest::{
802        strategy::{Strategy, ValueTree},
803        test_runner::TestRunner,
804    };
805
806    use super::{
807        Felt,
808        arbitrary::{
809            CANONICAL_EDGES, NONCANONICAL_EDGES, arb_felt_canonical, arb_felt_noncanonical,
810        },
811    };
812
813    /// The boundary values are reachable BY CONSTRUCTION — pin it
814    /// empirically so a future refactor of the branch gating cannot
815    /// silently drop edges (the run-#84 correlation regression).
816    #[test]
817    fn boundary_values_are_reached_by_construction() {
818        let mut runner = TestRunner::deterministic();
819        let samples = 10_000;
820
821        let mut canonical_hits = [0usize; CANONICAL_EDGES.len()];
822        for _ in 0..samples {
823            let felt = arb_felt_canonical().new_tree(&mut runner).unwrap().current();
824            for (i, edge) in CANONICAL_EDGES.iter().enumerate() {
825                if super::raw_felt_u64(felt) == *edge {
826                    canonical_hits[i] += 1;
827                }
828            }
829        }
830        for (edge, hits) in CANONICAL_EDGES.iter().zip(canonical_hits) {
831            assert!(hits > 0, "canonical boundary {edge} never sampled");
832        }
833
834        let mut noncanonical_hits = [0usize; NONCANONICAL_EDGES.len()];
835        for _ in 0..samples {
836            let felt = arb_felt_noncanonical().new_tree(&mut runner).unwrap().current();
837            for (i, edge) in NONCANONICAL_EDGES.iter().enumerate() {
838                if super::raw_felt_u64(felt) == *edge {
839                    noncanonical_hits[i] += 1;
840                }
841            }
842        }
843        for (edge, hits) in NONCANONICAL_EDGES.iter().zip(noncanonical_hits) {
844            assert!(hits > 0, "non-canonical boundary {edge} never sampled");
845        }
846
847        // The canonical adapter never leaves the canonical regime.
848        for _ in 0..samples {
849            let felt = arb_felt_canonical().new_tree(&mut runner).unwrap().current();
850            assert!(
851                super::raw_felt_u64(felt) < Felt::ORDER,
852                "canonical adapter emitted a non-canonical element",
853            );
854        }
855
856        // Every residue class mod 8 must occur among NON-boundary draws —
857        // pinning that the gate and the value are independent components
858        // (deriving both from one u64 removes the gate class from the
859        // generator's range, the run-#430 regression).
860        let mut residue_seen = [false; 8];
861        for _ in 0..samples {
862            let felt = arb_felt_canonical().new_tree(&mut runner).unwrap().current();
863            let raw = super::raw_felt_u64(felt);
864            if !CANONICAL_EDGES.contains(&raw) {
865                residue_seen[(raw % 8) as usize] = true;
866            }
867        }
868        assert!(
869            residue_seen.iter().all(|&seen| seen),
870            "a residue class mod 8 is missing from non-boundary draws: {residue_seen:?}",
871        );
872    }
873}