Skip to main content

binius_field/
binary_field.rs

1// Copyright 2023-2025 Irreducible Inc.
2// Copyright 2026 The Binius Developers
3
4use std::{
5	fmt::{Debug, Display, Formatter},
6	iter::{Product, Sum},
7	ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign},
8};
9
10use bytemuck::Zeroable;
11
12use super::{Underlier, UnderlierView, field::ExtensionField};
13use crate::{Field, underlier::U1};
14
15/// A finite field with characteristic 2.
16pub trait BinaryField: ExtensionField<BinaryField1b> + UnderlierView<Underlier: Underlier> {
17	const N_BITS: usize = Self::ORDER_EXPONENT;
18
19	/// An element whose absolute trace is 1.
20	///
21	/// The absolute trace is the $\mathbb{F}_2$-linear map
22	///
23	/// $$\operatorname{Tr}(x) = \sum_{i=0}^{n-1} x^{2^i},$$
24	///
25	/// which lands in $\mathbb{F}_2$ and is surjective, so such an element always exists and
26	/// exactly half the field has trace 1. Which one is named here is arbitrary; each field picks
27	/// a single-bit element, the lowest one that qualifies.
28	///
29	/// The NTT's Gao-Mateer domain context seeds its basis with this: the descent
30	/// $\beta_i = \beta_{i+1}^2 + \beta_{i+1}$ reaches $\beta_0 = 1$ exactly when it starts from
31	/// an element of trace 1.
32	const TRACE_ONE_ELEMENT: Self;
33}
34
35/// Generates a binary field type over an underlier `$typ`.
36///
37/// `$gen` is the multiplicative generator and `$trace_one` an element of trace 1, both as raw
38/// underlier values.
39///
40/// The default form derives the field's arithmetic from its width-one packing.
41/// The `custom_arithmetic` form omits that, for a field that defines its own arithmetic.
42macro_rules! binary_field {
43	// Default: the field's arithmetic is its width-one packing's arithmetic.
44	($vis:vis $name:ident($typ:ty), $gen:expr, $trace_one:expr) => {
45		binary_field!(@base $vis $name($typ), $gen, $trace_one);
46		binary_field!(@arithmetic_via_packed $name, $typ);
47	};
48	// The field provides its own `Mul`/`Square`/`InvertOrZero`/`WideMul` separately.
49	(custom_arithmetic $vis:vis $name:ident($typ:ty), $gen:expr, $trace_one:expr) => {
50		binary_field!(@base $vis $name($typ), $gen, $trace_one);
51	};
52
53	(@base $vis:vis $name:ident($typ:ty), $gen:expr, $trace_one:expr) => {
54		#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Zeroable, bytemuck::TransparentWrapper)]
55		#[repr(transparent)]
56		$vis struct $name(pub(crate) $typ);
57
58		// NOTE: `new` is intentionally NOT generated here. Each field defines its own `new` so it
59		// can take an ergonomic constructor type independent of the underlier (e.g.
60		// `Ghash128b::new` takes `u128` even though its underlier is `M128`).
61		impl $name {
62			pub const fn val(self) -> $typ {
63				self.0
64			}
65		}
66
67		unsafe impl $crate::underlier::UnderlierView for $name {
68			type Underlier = $typ;
69		}
70
71		// Serialization forwards to the underlier.
72		impl binius_utils::SerializeBytes for $name {
73			fn serialize(&self, write_buf: impl binius_utils::bytes::BufMut) -> Result<(), binius_utils::SerializationError> {
74				self.0.serialize(write_buf)
75			}
76		}
77
78		impl binius_utils::DeserializeBytes for $name {
79			fn deserialize(read_buf: impl binius_utils::bytes::Buf) -> Result<Self, binius_utils::SerializationError> {
80				Ok(Self(binius_utils::DeserializeBytes::deserialize(read_buf)?))
81			}
82		}
83
84		impl binius_utils::FixedSizeSerializeBytes for $name {
85			const BYTE_SIZE: usize = <$typ as binius_utils::FixedSizeSerializeBytes>::BYTE_SIZE;
86		}
87
88		impl Neg for $name {
89			type Output = Self;
90
91			fn neg(self) -> Self::Output {
92				self
93			}
94		}
95
96		impl Add<Self> for $name {
97			type Output = Self;
98
99			#[allow(clippy::suspicious_arithmetic_impl)]
100			fn add(self, rhs: Self) -> Self::Output {
101				$name(self.0 ^ rhs.0)
102			}
103		}
104
105		impl Add<&Self> for $name {
106			type Output = Self;
107
108			#[allow(clippy::suspicious_arithmetic_impl)]
109			fn add(self, rhs: &Self) -> Self::Output {
110				$name(self.0 ^ rhs.0)
111			}
112		}
113
114		impl Sub<Self> for $name {
115			type Output = Self;
116
117			#[allow(clippy::suspicious_arithmetic_impl)]
118			fn sub(self, rhs: Self) -> Self::Output {
119				$name(self.0 ^ rhs.0)
120			}
121		}
122
123		impl Sub<&Self> for $name {
124			type Output = Self;
125
126			#[allow(clippy::suspicious_arithmetic_impl)]
127			fn sub(self, rhs: &Self) -> Self::Output {
128				$name(self.0 ^ rhs.0)
129			}
130		}
131
132		impl Mul<&Self> for $name {
133			type Output = Self;
134
135			fn mul(self, rhs: &Self) -> Self::Output {
136				self * *rhs
137			}
138		}
139
140		impl AddAssign<Self> for $name {
141			fn add_assign(&mut self, rhs: Self) {
142				*self = *self + rhs;
143			}
144		}
145
146		impl AddAssign<&Self> for $name {
147			fn add_assign(&mut self, rhs: &Self) {
148				*self = *self + *rhs;
149			}
150		}
151
152		impl SubAssign<Self> for $name {
153			fn sub_assign(&mut self, rhs: Self) {
154				*self = *self - rhs;
155			}
156		}
157
158		impl SubAssign<&Self> for $name {
159			fn sub_assign(&mut self, rhs: &Self) {
160				*self = *self - *rhs;
161			}
162		}
163
164		impl MulAssign<Self> for $name {
165			fn mul_assign(&mut self, rhs: Self) {
166				*self = *self * rhs;
167			}
168		}
169
170		impl MulAssign<&Self> for $name {
171			fn mul_assign(&mut self, rhs: &Self) {
172				*self = *self * rhs;
173			}
174		}
175
176		impl Sum<Self> for $name {
177			fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
178				iter.fold(Self::ZERO, |acc, x| acc + x)
179			}
180		}
181
182		impl<'a> Sum<&'a Self> for $name {
183			fn sum<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
184				iter.fold(Self::ZERO, |acc, x| acc + x)
185			}
186		}
187
188		impl Product<Self> for $name {
189			fn product<I: Iterator<Item=Self>>(iter: I) -> Self {
190				iter.fold(Self::ONE, |acc, x| acc * x)
191			}
192		}
193
194		impl<'a> Product<&'a Self> for $name {
195			fn product<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
196				iter.fold(Self::ONE, |acc, x| acc * x)
197			}
198		}
199
200
201		impl Field for $name {
202			const ZERO: Self = $name(<$typ as $crate::underlier::Underlier>::ZERO);
203			const ONE: Self = $name(<$typ as $crate::underlier::Underlier>::ONE);
204			const CHARACTERISTIC: usize = 2;
205			const ORDER_EXPONENT: usize = <$typ as $crate::underlier::Underlier>::BITS;
206			const MULTIPLICATIVE_GENERATOR: $name = $name($gen);
207
208			fn double(&self) -> Self {
209				Self::ZERO
210			}
211		}
212
213		// A field element divides into exactly one element of itself. This makes the field a
214		// degenerate packed field of width one (see the `PackedField` impl below).
215		impl $crate::Divisible<$name> for $name {
216			const LOG_N: usize = 0;
217
218			#[inline]
219			fn value_iter(value: Self) -> impl ExactSizeIterator<Item = $name> + Send + Clone {
220				std::iter::once(value)
221			}
222
223			#[inline]
224			fn ref_iter(value: &Self) -> impl ExactSizeIterator<Item = $name> + Send + Clone + '_ {
225				std::iter::once(*value)
226			}
227
228			#[inline]
229			fn slice_iter(slice: &[Self]) -> impl ExactSizeIterator<Item = $name> + Send + Clone + '_ {
230				slice.iter().copied()
231			}
232
233			#[inline]
234			unsafe fn get_unchecked(&self, _index: usize) -> $name {
235				*self
236			}
237
238			#[inline]
239			unsafe fn set_unchecked(&mut self, _index: usize, val: $name) {
240				*self = val;
241			}
242
243			#[inline]
244			fn broadcast(val: $name) -> Self {
245				val
246			}
247
248			#[inline]
249			fn from_iter(mut iter: impl Iterator<Item = $name>) -> Self {
250				iter.next().unwrap_or(Self::ZERO)
251			}
252		}
253
254		// As a width-one packed field, a field element is masked by its single selector: kept
255		// when selected, otherwise zeroed. Uses the same underlier bitmask strategy as
256		// PackedPrimitiveType so the mask type and AND operation are consistent.
257		impl $crate::Maskable<$name> for $name {
258			type Mask = $typ;
259
260			#[inline]
261			fn make_mask(mut selectors: impl Iterator<Item = bool>) -> $typ {
262				<$typ as $crate::Divisible<_>>::broadcast(
263					$crate::underlier::U1::from(selectors.next().unwrap_or(false)),
264				)
265			}
266
267			#[inline]
268			fn select(&self, mask: &$typ) -> Self {
269				Self(self.0 & *mask)
270			}
271		}
272
273		impl $crate::PackedField for $name {
274			fn interleave(self, _other: Self, _log_block_len: usize) -> (Self, Self) {
275				panic!("cannot interleave when WIDTH = 1");
276			}
277
278			fn unzip(self, _other: Self, _log_block_len: usize) -> (Self, Self) {
279				panic!("cannot transpose when WIDTH = 1");
280			}
281
282			#[inline]
283			fn from_fn(mut f: impl FnMut(usize) -> Self::Scalar) -> Self {
284				f(0)
285			}
286
287			#[inline]
288			unsafe fn spread_unchecked(self, _log_block_len: usize, _block_idx: usize) -> Self {
289				self
290			}
291		}
292
293		impl ::rand::distr::Distribution<$name> for ::rand::distr::StandardUniform {
294			fn sample<R: ::rand::Rng + ?Sized>(&self, rng: &mut R) -> $name {
295				$name(::rand::distr::StandardUniform.sample(rng))
296			}
297		}
298
299		impl Display for $name {
300			fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
301				write!(f, "0x{repr:0>width$x}", repr=self.val(), width=Self::N_BITS.max(4) / 4)
302			}
303		}
304
305		impl Debug for $name {
306			fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
307				let structure_name = std::any::type_name::<$name>().split("::").last().expect("exist");
308
309				write!(f, "{}({})",structure_name, self)
310			}
311		}
312
313		impl BinaryField for $name {
314			const TRACE_ONE_ELEMENT: Self = $name($trace_one);
315		}
316
317		impl From<$typ> for $name {
318			fn from(val: $typ) -> Self {
319				return Self(val)
320			}
321		}
322
323		impl From<$name> for $typ {
324			fn from(val: $name) -> Self {
325				return val.0
326			}
327		}
328	};
329
330	// Each op lifts the underlier into the width-one packing, runs its arithmetic, and lowers back.
331	(@arithmetic_via_packed $name:ident, $typ:ty) => {
332		impl Mul<Self> for $name {
333			type Output = Self;
334
335			#[inline]
336			fn mul(self, rhs: Self) -> Self {
337				type P = $crate::packed_fields::primitive::PackedPrimitiveType<$typ, $name>;
338				Self((P::from_underlier(self.0) * P::from_underlier(rhs.0)).to_underlier())
339			}
340		}
341
342		impl $crate::arithmetic_traits::Square for $name {
343			#[inline]
344			fn square(self) -> Self {
345				type P = $crate::packed_fields::primitive::PackedPrimitiveType<$typ, $name>;
346				Self(
347					$crate::arithmetic_traits::Square::square(P::from_underlier(self.0)).to_underlier(),
348				)
349			}
350		}
351
352		impl $crate::arithmetic_traits::InvertOrZero for $name {
353			#[inline]
354			fn invert_or_zero(self) -> Self {
355				type P = $crate::packed_fields::primitive::PackedPrimitiveType<$typ, $name>;
356				Self(
357					$crate::arithmetic_traits::InvertOrZero::invert_or_zero(P::from_underlier(self.0))
358						.to_underlier(),
359				)
360			}
361		}
362
363		impl $crate::arithmetic_traits::WideMul for $name {
364			type Output = <$crate::packed_fields::primitive::PackedPrimitiveType<$typ, $name> as $crate::arithmetic_traits::WideMul>::Output;
365
366			#[inline]
367			fn wide_mul(a: Self, b: Self) -> Self::Output {
368				type P = $crate::packed_fields::primitive::PackedPrimitiveType<$typ, $name>;
369				<P as $crate::arithmetic_traits::WideMul>::wide_mul(
370					P::from_underlier(a.0),
371					P::from_underlier(b.0),
372				)
373			}
374
375			#[inline]
376			fn reduce(wide: Self::Output) -> Self {
377				type P = $crate::packed_fields::primitive::PackedPrimitiveType<$typ, $name>;
378				Self(<P as $crate::arithmetic_traits::WideMul>::reduce(wide).to_underlier())
379			}
380		}
381	};
382}
383
384pub(crate) use binary_field;
385
386macro_rules! impl_field_extension {
387	($subfield_name:ident($subfield_typ:ty) < @$log_degree:expr => $name:ident($typ:ty)) => {
388		impl TryFrom<$name> for $subfield_name {
389			type Error = ();
390
391			#[inline]
392			fn try_from(elem: $name) -> Result<Self, Self::Error> {
393				use $crate::{Divisible, underlier::Underlier};
394
395				// `elem` lies in the subfield iff every subfield-underlier limb above the
396				// least-significant one is zero (equivalent to `elem >> N_BITS == 0`).
397				let in_subfield = Divisible::<$subfield_typ>::ref_iter(&elem.0)
398					.skip(1)
399					.all(|limb| limb == <$subfield_typ as Underlier>::ZERO);
400				if in_subfield {
401					Ok($subfield_name(Divisible::<$subfield_typ>::get(&elem.0, 0)))
402				} else {
403					Err(())
404				}
405			}
406		}
407
408		impl From<$subfield_name> for $name {
409			#[inline]
410			fn from(elem: $subfield_name) -> Self {
411				$name(<$typ>::from(elem.val()))
412			}
413		}
414
415		impl Add<$subfield_name> for $name {
416			type Output = Self;
417
418			#[inline]
419			fn add(self, rhs: $subfield_name) -> Self::Output {
420				self + Self::from(rhs)
421			}
422		}
423
424		impl Sub<$subfield_name> for $name {
425			type Output = Self;
426
427			#[inline]
428			fn sub(self, rhs: $subfield_name) -> Self::Output {
429				self - Self::from(rhs)
430			}
431		}
432
433		// The subfield coordinates are literally `$typ`'s `$subfield_typ` limbs (see `basis`
434		// below), so multiplying by a subfield scalar is linear in each limb: reinterpret `self`
435		// as a `PackedPrimitiveType` of the subfield, broadcast-multiply by `rhs`, and cast back.
436		impl Mul<$subfield_name> for $name {
437			type Output = Self;
438
439			#[inline]
440			fn mul(self, rhs: $subfield_name) -> Self::Output {
441				type P =
442					$crate::packed_fields::primitive::PackedPrimitiveType<$typ, $subfield_name>;
443				Self((P::from_underlier(self.0) * P::broadcast(rhs)).to_underlier())
444			}
445		}
446
447		impl AddAssign<$subfield_name> for $name {
448			#[inline]
449			fn add_assign(&mut self, rhs: $subfield_name) {
450				*self = *self + rhs;
451			}
452		}
453
454		impl SubAssign<$subfield_name> for $name {
455			#[inline]
456			fn sub_assign(&mut self, rhs: $subfield_name) {
457				*self = *self - rhs;
458			}
459		}
460
461		impl MulAssign<$subfield_name> for $name {
462			#[inline]
463			fn mul_assign(&mut self, rhs: $subfield_name) {
464				*self = *self * rhs;
465			}
466		}
467
468		impl Add<$name> for $subfield_name {
469			type Output = $name;
470
471			#[inline]
472			fn add(self, rhs: $name) -> Self::Output {
473				rhs + self
474			}
475		}
476
477		impl Sub<$name> for $subfield_name {
478			type Output = $name;
479
480			#[allow(clippy::suspicious_arithmetic_impl)]
481			#[inline]
482			fn sub(self, rhs: $name) -> Self::Output {
483				rhs + self
484			}
485		}
486
487		impl Mul<$name> for $subfield_name {
488			type Output = $name;
489
490			#[inline]
491			fn mul(self, rhs: $name) -> Self::Output {
492				rhs * self
493			}
494		}
495
496		impl ExtensionField<$subfield_name> for $name {
497			const LOG_DEGREE: usize = $log_degree;
498
499			#[inline]
500			fn basis(i: usize) -> Self {
501				use $crate::{Divisible, underlier::Underlier};
502
503				assert!(
504					i < 1 << $log_degree,
505					"index {} out of range for degree {}",
506					i,
507					1 << $log_degree
508				);
509				// The `i`-th basis element sets subfield-underlier limb `i` to one, i.e. bit
510				// `i * N_BITS` (equivalent to `ONE << (i * N_BITS)`).
511				let mut underlier = <$typ as Underlier>::ZERO;
512				Divisible::<$subfield_typ>::set(
513					&mut underlier,
514					i,
515					<$subfield_typ as Underlier>::ONE,
516				);
517				Self(underlier)
518			}
519
520			#[inline]
521			fn from_bases_sparse(
522				base_elems: impl IntoIterator<Item = $subfield_name>,
523				log_stride: usize,
524			) -> Self {
525				use $crate::{Divisible, underlier::Underlier};
526
527				debug_assert!($name::N_BITS.is_power_of_two());
528				let shift_step = ($subfield_name::N_BITS << log_stride) & ($name::N_BITS - 1);
529				let mut underlier = <$typ as Underlier>::ZERO;
530				let mut shift = 0;
531
532				for elem in base_elems.into_iter() {
533					assert!(shift < $name::N_BITS, "too many base elements for extension degree");
534					// `shift` is a multiple of the subfield width, so it addresses limb
535					// `shift / N_BITS`; OR the element in (matching the previous `|= .. << shift`).
536					let limb = shift / $subfield_name::N_BITS;
537					let acc = Divisible::<$subfield_typ>::get(&underlier, limb) | elem.val();
538					Divisible::<$subfield_typ>::set(&mut underlier, limb, acc);
539					shift += shift_step;
540				}
541
542				Self(underlier)
543			}
544
545			#[inline]
546			fn iter_bases(&self) -> impl Iterator<Item = $subfield_name> {
547				use binius_utils::iter::IterExtensions;
548				use $crate::{Divisible, underlier::UnderlierView};
549
550				Divisible::<<$subfield_name as UnderlierView>::Underlier>::ref_iter(&self.0)
551					.map_skippable($subfield_name::from)
552			}
553
554			#[inline]
555			unsafe fn get_base_unchecked(&self, i: usize) -> $subfield_name {
556				use $crate::{Divisible, underlier::UnderlierView};
557				// Safety: the caller guarantees `i < Self::N` (over subfield elements).
558				unsafe {
559					$subfield_name::from_underlier(Divisible::<
560						<$subfield_name as UnderlierView>::Underlier,
561					>::get_unchecked(&self.to_underlier(), i))
562				}
563			}
564
565			#[inline]
566			fn square_transpose(values: &mut [Self]) {
567				crate::transpose::square_transforms_extension_field::<$subfield_name, Self>(values)
568			}
569		}
570	};
571}
572
573pub(crate) use impl_field_extension;
574
575// The trace over the prime field is the identity here, so `ONE` is the only trace-1 element.
576binary_field!(pub BinaryField1b(U1), U1::new(0x1), U1::new(0x1));
577
578impl BinaryField1b {
579	pub const fn new(value: U1) -> Self {
580		Self(value)
581	}
582}
583
584impl From<u8> for BinaryField1b {
585	#[inline]
586	fn from(val: u8) -> Self {
587		Self::new(U1::new(val))
588	}
589}
590
591impl From<BinaryField1b> for u8 {
592	#[inline]
593	fn from(value: BinaryField1b) -> Self {
594		value.val().into()
595	}
596}
597
598impl From<bool> for BinaryField1b {
599	#[inline]
600	fn from(value: bool) -> Self {
601		Self::from(U1::new_unchecked(value.into()))
602	}
603}
604
605#[cfg(test)]
606pub(crate) mod tests {
607	use binius_utils::{DeserializeBytes, SerializeBytes, bytes::BytesMut};
608	use proptest::prelude::*;
609
610	use crate::{
611		BinaryField, BinaryField1b, ExtensionField, Field, Ghash128b, GhashSq256b, Rijndael8b,
612		arithmetic_traits::InvertOrZero,
613	};
614
615	#[test]
616	fn test_gf2_add() {
617		assert_eq!(BinaryField1b::from(0) + BinaryField1b::from(0), BinaryField1b::from(0));
618		assert_eq!(BinaryField1b::from(0) + BinaryField1b::from(1), BinaryField1b::from(1));
619		assert_eq!(BinaryField1b::from(1) + BinaryField1b::from(0), BinaryField1b::from(1));
620		assert_eq!(BinaryField1b::from(1) + BinaryField1b::from(1), BinaryField1b::from(0));
621	}
622
623	#[test]
624	fn test_gf2_sub() {
625		assert_eq!(BinaryField1b::from(0) - BinaryField1b::from(0), BinaryField1b::from(0));
626		assert_eq!(BinaryField1b::from(0) - BinaryField1b::from(1), BinaryField1b::from(1));
627		assert_eq!(BinaryField1b::from(1) - BinaryField1b::from(0), BinaryField1b::from(1));
628		assert_eq!(BinaryField1b::from(1) - BinaryField1b::from(1), BinaryField1b::from(0));
629	}
630
631	#[test]
632	fn test_gf2_mul() {
633		assert_eq!(BinaryField1b::from(0) * BinaryField1b::from(0), BinaryField1b::from(0));
634		assert_eq!(BinaryField1b::from(0) * BinaryField1b::from(1), BinaryField1b::from(0));
635		assert_eq!(BinaryField1b::from(1) * BinaryField1b::from(0), BinaryField1b::from(0));
636		assert_eq!(BinaryField1b::from(1) * BinaryField1b::from(1), BinaryField1b::from(1));
637	}
638
639	pub(crate) fn is_binary_field_valid_generator<F: BinaryField>() -> bool {
640		// Binary fields should contain a multiplicative subgroup of size 2^n - 1
641		let mut order = if F::N_BITS == 128 {
642			u128::MAX
643		} else {
644			(1 << F::N_BITS) - 1
645		};
646
647		// Naive factorization of group order - represented as a multiset of prime factors
648		let mut factorization = Vec::new();
649
650		let mut prime = 2;
651		while prime * prime <= order {
652			while order.is_multiple_of(prime) {
653				order /= prime;
654				factorization.push(prime);
655			}
656
657			prime += if prime > 2 { 2 } else { 1 };
658		}
659
660		if order > 1 {
661			factorization.push(order);
662		}
663
664		// Iterate over all divisors (some may be tested several times if order is non-square-free)
665		for mask in 0..(1 << factorization.len()) {
666			let mut divisor = 1;
667
668			for (bit_index, &prime) in factorization.iter().enumerate() {
669				if (1 << bit_index) & mask != 0 {
670					divisor *= prime;
671				}
672			}
673
674			// Compute pow(generator, divisor) in log time
675			divisor = divisor.reverse_bits();
676
677			let mut pow_divisor = F::ONE;
678			while divisor > 0 {
679				pow_divisor *= pow_divisor;
680
681				if divisor & 1 != 0 {
682					pow_divisor *= F::MULTIPLICATIVE_GENERATOR;
683				}
684
685				divisor >>= 1;
686			}
687
688			// Generator invariant
689			let is_root_of_unity = pow_divisor == F::ONE;
690			let is_full_group = mask + 1 == 1 << factorization.len();
691
692			if is_root_of_unity && !is_full_group || !is_root_of_unity && is_full_group {
693				return false;
694			}
695		}
696
697		true
698	}
699
700	#[test]
701	fn test_multiplicative_generators() {
702		assert!(is_binary_field_valid_generator::<BinaryField1b>());
703		assert!(is_binary_field_valid_generator::<Rijndael8b>());
704		assert!(is_binary_field_valid_generator::<Ghash128b>());
705	}
706
707	/// The absolute trace $\operatorname{Tr}(x) = \sum_{i=0}^{n-1} x^{2^i}$, computed by repeated
708	/// squaring rather than by any property of the field's representation.
709	fn trace<F: BinaryField>(x: F) -> F {
710		let mut acc = F::ZERO;
711		let mut square = x;
712		for _ in 0..F::N_BITS {
713			acc += square;
714			square = square.square();
715		}
716		acc
717	}
718
719	/// Every field's declared element really has trace 1.
720	///
721	/// A wrong constant would not fail loudly on its own: the Gao-Mateer basis it seeds asserts
722	/// $\beta_0 = 1$, so it would surface as a panic deep inside NTT setup rather than here.
723	#[test]
724	fn test_trace_one_elements() {
725		fn check<F: BinaryField>() {
726			assert_eq!(trace(F::TRACE_ONE_ELEMENT), F::ONE);
727		}
728		check::<BinaryField1b>();
729		check::<Rijndael8b>();
730		check::<Ghash128b>();
731		check::<GhashSq256b>();
732	}
733
734	/// The trace lands in $\mathbb{F}_2$ for every element, not just the declared one. This pins
735	/// the helper above, so a `trace` that silently computed something else could not make the
736	/// previous test pass.
737	#[test]
738	fn test_trace_lands_in_the_prime_subfield() {
739		for value in 0..=u8::MAX {
740			let t = trace(Rijndael8b::new(value));
741			assert!(t == Rijndael8b::ZERO || t == Rijndael8b::ONE, "value {value:#04x}");
742		}
743	}
744
745	#[test]
746	fn test_field_degrees() {
747		assert_eq!(BinaryField1b::N_BITS, 1);
748		assert_eq!(Rijndael8b::N_BITS, 8);
749		assert_eq!(Ghash128b::N_BITS, 128);
750	}
751
752	#[test]
753	fn test_field_formatting() {
754		assert_eq!(format!("{}", BinaryField1b::from(1)), "0x1");
755		assert_eq!(format!("{}", Rijndael8b::from(3)), "0x03");
756		assert_eq!(format!("{}", Ghash128b::new(5)), "0x00000000000000000000000000000005");
757	}
758
759	#[test]
760	fn test_inverse_on_zero() {
761		assert!(BinaryField1b::ZERO.invert_or_zero().is_zero());
762		assert!(Rijndael8b::ZERO.invert_or_zero().is_zero());
763		assert!(Ghash128b::ZERO.invert_or_zero().is_zero());
764	}
765
766	proptest! {
767		#[test]
768		fn test_inverse_8b(val in 1u8..) {
769			let x = Rijndael8b::new(val);
770			// Safety: `val` is in `1..`, so `x` is non-zero.
771			let x_inverse = unsafe { x.invert() };
772			assert_eq!(x * x_inverse, Rijndael8b::ONE);
773		}
774
775		#[test]
776		fn test_inverse_128b(val in 1u128..) {
777			let x = Ghash128b::from(val);
778			// Safety: `val` is in `1..`, so `x` is non-zero.
779			let x_inverse = unsafe { x.invert() };
780			assert_eq!(x * x_inverse, Ghash128b::ONE);
781		}
782	}
783
784	/// Checks the `TryFrom` conversion narrowing an extension field element to its subfield:
785	/// elements embedded from the subfield must round-trip, and elements with a nonzero
786	/// coefficient outside the subfield must be rejected.
787	fn assert_subfield_extraction<FSub: Field, F: ExtensionField<FSub>>() {
788		assert_eq!(TryInto::<FSub>::try_into(F::from(FSub::ZERO)).ok(), Some(FSub::ZERO));
789
790		// `BinaryField1b` has a trivial multiplicative group, so for the three pairs with that
791		// subfield this sweeps `ONE` alone, which together with `ZERO` is already the whole field.
792		// Only `Ghash128b` in `GhashSq256b` walks non-trivial subfield values.
793		let mut elem = FSub::ONE;
794		for _ in 0..4 {
795			assert_eq!(TryInto::<FSub>::try_into(F::from(elem)).ok(), Some(elem));
796			elem *= FSub::MULTIPLICATIVE_GENERATOR;
797		}
798
799		// `basis(i)` for `i > 0` has a zero coefficient of `1` and a nonzero higher coefficient,
800		// so it lies outside the subfield - with or without a subfield part added on.
801		for i in 1..F::DEGREE {
802			assert!(TryInto::<FSub>::try_into(F::basis(i)).is_err());
803			assert!(TryInto::<FSub>::try_into(F::basis(i) + F::ONE).is_err());
804		}
805	}
806
807	#[test]
808	fn test_subfield_extraction() {
809		assert_subfield_extraction::<BinaryField1b, Ghash128b>();
810		assert_subfield_extraction::<BinaryField1b, Rijndael8b>();
811		assert_subfield_extraction::<Ghash128b, GhashSq256b>();
812		assert_subfield_extraction::<BinaryField1b, GhashSq256b>();
813	}
814
815	#[test]
816	fn test_serialization() {
817		let mut buffer = BytesMut::new();
818		let b1 = BinaryField1b::from(0x1);
819		let b8 = Rijndael8b::new(0x12);
820		let b128 = Ghash128b::new(0x147AD0369CF258BE8899AABBCCDDEEFF);
821
822		b1.serialize(&mut buffer).unwrap();
823		b8.serialize(&mut buffer).unwrap();
824		b128.serialize(&mut buffer).unwrap();
825
826		let mut read_buffer = buffer.freeze();
827
828		assert_eq!(BinaryField1b::deserialize(&mut read_buffer).unwrap(), b1);
829		assert_eq!(Rijndael8b::deserialize(&mut read_buffer).unwrap(), b8);
830		assert_eq!(Ghash128b::deserialize(&mut read_buffer).unwrap(), b128);
831	}
832}