From 67e559570290b4407c10485ae9a889a64c20c303 Mon Sep 17 00:00:00 2001 From: Volker Mische Date: Fri, 25 Nov 2022 11:03:47 +0100 Subject: [PATCH] Improve 64-bit to 32-bit limb conversion The code base is now on Rust 1.56 and Rust edition 2021. As per https://github.com/zcash/pasta_curves/pull/31#discussion_r824826344 the code can now be simplified. This commit is also adding a test for the u64_to_u32 function. --- src/fields.rs | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/fields.rs b/src/fields.rs index ccad57a..c98fd92 100644 --- a/src/fields.rs +++ b/src/fields.rs @@ -12,10 +12,28 @@ pub use fq::*; fn u64_to_u32(limbs: &[u64]) -> alloc::vec::Vec { limbs .iter() - .flat_map(|limb| { - Some((limb & 0xFFFF_FFFF) as u32) - .into_iter() - .chain(Some((limb >> 32) as u32)) - }) + .flat_map(|limb| [(limb & 0xFFFF_FFFF) as u32, (limb >> 32) as u32].into_iter()) .collect() } + +#[cfg(feature = "gpu")] +#[test] +fn test_u64_to_u32() { + use rand::{RngCore, SeedableRng}; + use rand_xorshift::XorShiftRng; + + let mut rng = XorShiftRng::from_seed([0; 16]); + let u64_limbs: alloc::vec::Vec = (0..6).map(|_| rng.next_u64()).collect(); + let u32_limbs = crate::fields::u64_to_u32(&u64_limbs); + + let u64_le_bytes: alloc::vec::Vec = u64_limbs + .iter() + .flat_map(|limb| limb.to_le_bytes()) + .collect(); + let u32_le_bytes: alloc::vec::Vec = u32_limbs + .iter() + .flat_map(|limb| limb.to_le_bytes()) + .collect(); + + assert_eq!(u64_le_bytes, u32_le_bytes); +}