From ded93767ed50469ea4e27babe300bda67e11ace3 Mon Sep 17 00:00:00 2001 From: Adam Wick Date: Sat, 10 Mar 2018 18:04:56 -0800 Subject: [PATCH] Split the CryptoNum trait into pieces, in preparation for negative numbers. --- src/cryptonum/builder.rs | 14 +++++++------- src/cryptonum/traits.rs | 19 +++++++++++-------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/cryptonum/builder.rs b/src/cryptonum/builder.rs index 740bf33..203deea 100644 --- a/src/cryptonum/builder.rs +++ b/src/cryptonum/builder.rs @@ -225,9 +225,7 @@ macro_rules! construct_unsigned { } } - impl CryptoNum for $type { - type BarrettMu = $barrett; - + impl CryptoNumBase for $type { fn zero() -> $type { $type { contents: [0; $count] } } @@ -257,12 +255,10 @@ macro_rules! construct_unsigned { from_to!($type, $count, u16, from_u16, to_u16); from_to!($type, $count, u32, from_u32, to_u32); from_to!($type, $count, u64, from_u64, to_u64); + } - fn divmod(&self, a: &$type, q: &mut $type, r: &mut $type) { - generic_div(&self.contents, &a.contents, - &mut q.contents, &mut r.contents); - } + impl CryptoNumSerialization for $type { fn to_bytes(&self) -> Vec { let mut res = Vec::with_capacity($count * 8); for x in self.contents.iter() { @@ -298,6 +294,10 @@ macro_rules! construct_unsigned { assert!(i == $count); res } + } + + impl CryptoNumFastMod for $type { + type BarrettMu = $barrett; fn barrett_mu(&self) -> Option<$barrett> { // Step #0: Don't divide by 0. diff --git a/src/cryptonum/traits.rs b/src/cryptonum/traits.rs index 67d2d40..4209c39 100644 --- a/src/cryptonum/traits.rs +++ b/src/cryptonum/traits.rs @@ -1,8 +1,4 @@ -pub trait CryptoNum { - /// A related type that can hold the constant required for Barrett - /// reduction. - type BarrettMu; - +pub trait CryptoNumBase { /// Generate the zero value for this type. fn zero() -> Self; /// Generate the maximum possible value for this type. @@ -33,9 +29,9 @@ pub trait CryptoNum { /// Convert this back into a `u64`. This is the equivalent of masking off /// the lowest 64 bits and then casting to a `u64`. fn to_u64(&self) -> u64; - /// Simultaneously compute the quotient and remainder of this number and - /// the given divisor. - fn divmod(&self, a: &Self, q: &mut Self, r: &mut Self); +} + +pub trait CryptoNumSerialization { /// Convert a number to a series of bytes, in standard order (most to /// least significant) fn to_bytes(&self) -> Vec; @@ -43,6 +39,13 @@ pub trait CryptoNum { /// must be greater than or equal to the size of the number, and must be /// a multiple of 8 bytes long. Unused bytes should be ignored. fn from_bytes(&[u8]) -> Self; +} + +pub trait CryptoNumFastMod { + /// A related type that can hold the constant required for Barrett + /// reduction. + type BarrettMu; + /// Compute the Barett constant mu, using this as a modulus, which we can /// use later to perform faster mod operations. fn barrett_mu(&self) -> Option;