Skip to main content

binius_field/
arithmetic_traits.rs

1// Copyright 2024-2025 Irreducible Inc.
2
3/// Value that can be multiplied by itself
4pub trait Square {
5	/// Returns the value multiplied by itself
6	fn square(self) -> Self;
7}
8
9/// Value that can be inverted
10pub trait InvertOrZero {
11	/// Returns the inverted value or zero in case when `self` is zero
12	fn invert_or_zero(self) -> Self;
13}
14
15/// Multiplication that is parameterized with some some strategy.
16pub trait TaggedMul<Strategy> {
17	fn mul(self, rhs: Self) -> Self;
18}
19
20macro_rules! impl_mul_with {
21	($name:ident @ $strategy:ty) => {
22		impl std::ops::Mul for $name {
23			type Output = Self;
24
25			#[inline]
26			fn mul(self, rhs: Self) -> Self {
27				$crate::tracing::trace_multiplication!($name);
28
29				$crate::arithmetic_traits::TaggedMul::<$strategy>::mul(self, rhs)
30			}
31		}
32	};
33	($name:ty => $bigger:ty) => {
34		impl std::ops::Mul for $name {
35			type Output = Self;
36
37			#[inline]
38			fn mul(self, rhs: Self) -> Self {
39				$crate::arch::portable::packed::mul_as_bigger_type::<_, $bigger>(self, rhs)
40			}
41		}
42	};
43}
44
45pub(crate) use impl_mul_with;
46
47/// Square operation that is parameterized with some some strategy.
48pub trait TaggedSquare<Strategy> {
49	fn square(self) -> Self;
50}
51
52macro_rules! impl_square_with {
53	($name:ident @ $strategy:ty) => {
54		impl $crate::arithmetic_traits::Square for $name {
55			#[inline]
56			fn square(self) -> Self {
57				$crate::arithmetic_traits::TaggedSquare::<$strategy>::square(self)
58			}
59		}
60	};
61	($name:ty => $bigger:ty) => {
62		impl $crate::arithmetic_traits::Square for $name {
63			#[inline]
64			fn square(self) -> Self {
65				$crate::arch::portable::packed::square_as_bigger_type::<_, $bigger>(self)
66			}
67		}
68	};
69}
70
71pub(crate) use impl_square_with;
72
73/// Invert or zero operation that is parameterized with some some strategy.
74pub trait TaggedInvertOrZero<Strategy> {
75	fn invert_or_zero(self) -> Self;
76}
77
78macro_rules! impl_invert_with {
79	($name:ident @ $strategy:ty) => {
80		impl $crate::arithmetic_traits::InvertOrZero for $name {
81			#[inline]
82			fn invert_or_zero(self) -> Self {
83				$crate::arithmetic_traits::TaggedInvertOrZero::<$strategy>::invert_or_zero(self)
84			}
85		}
86	};
87	($name:ty => $bigger:ty) => {
88		impl $crate::arithmetic_traits::InvertOrZero for $name {
89			#[inline]
90			fn invert_or_zero(self) -> Self {
91				$crate::arch::portable::packed::invert_as_bigger_type::<_, $bigger>(self)
92			}
93		}
94	};
95}
96
97pub(crate) use impl_invert_with;