From 1ecff8b4ad3b6f14635109ecba43213ab230d4ef Mon Sep 17 00:00:00 2001 From: Robin Salen Date: Tue, 14 Feb 2023 15:34:37 -0500 Subject: [PATCH] Override from_noncanonical_u96() for Goldilocks field --- field/src/field_testing.rs | 14 ++++++++++++++ field/src/goldilocks_field.rs | 13 +++++++++++++ 2 files changed, 27 insertions(+) diff --git a/field/src/field_testing.rs b/field/src/field_testing.rs index 4c53c23453..3aab9557e5 100644 --- a/field/src/field_testing.rs +++ b/field/src/field_testing.rs @@ -11,8 +11,22 @@ macro_rules! test_field_arithmetic { use num::bigint::BigUint; use rand::rngs::OsRng; use rand::Rng; + use rand::RngCore; use $crate::types::{Field, Sample}; + #[test] + fn modular_reduction() { + let mut rng = OsRng; + for _ in 0..10 { + let x_lo = rng.next_u64(); + let x_hi = rng.next_u32(); + let x = (x_lo as u128) + ((x_hi as u128) << 64); + let a = <$field>::from_noncanonical_u128(x); + let b = <$field>::from_noncanonical_u96((x_lo, x_hi)); + assert_eq!(a, b); + } + } + #[test] fn batch_inversion() { for n in 0..20 { diff --git a/field/src/goldilocks_field.rs b/field/src/goldilocks_field.rs index 9f0b0519d2..8c8d8bc305 100644 --- a/field/src/goldilocks_field.rs +++ b/field/src/goldilocks_field.rs @@ -110,6 +110,10 @@ impl Field for GoldilocksField { Self(n) } + fn from_noncanonical_u96((n_lo, n_hi): (u64, u32)) -> Self { + reduce96((n_lo, n_hi)) + } + fn from_noncanonical_u128(n: u128) -> Self { reduce128(n) } @@ -337,6 +341,15 @@ unsafe fn add_no_canonicalize_trashing_input(x: u64, y: u64) -> u64 { res_wrapped + EPSILON * (carry as u64) } +/// Reduces to a 64-bit value. The result might not be in canonical form; it could be in between the +/// field order and `2^64`. +#[inline] +fn reduce96((x_lo, x_hi): (u64, u32)) -> GoldilocksField { + let t1 = x_hi as u64 * EPSILON; + let t2 = unsafe { add_no_canonicalize_trashing_input(x_lo, t1) }; + GoldilocksField(t2) +} + /// Reduces to a 64-bit value. The result might not be in canonical form; it could be in between the /// field order and `2^64`. #[inline]