diff --git a/src/field.rs b/src/field.rs index 865d633..e0e4767 100644 --- a/src/field.rs +++ b/src/field.rs @@ -803,7 +803,7 @@ impl FieldElement { mod test { use field::*; use test::Bencher; - use util::conditional_negate; + use util::CTNegateable; #[bench] fn bench_fieldelement_a_mul_a(b: &mut Bencher) { @@ -939,11 +939,11 @@ mod test { let one = FieldElement([ 1,0,0,0,0,0,0,0,0,0]); let minus_one = FieldElement([-1,0,0,0,0,0,0,0,0,0]); let mut x = one; - conditional_negate(&mut x,1u8); + x.conditional_negate(1u8); assert_eq!(x, minus_one); - conditional_negate(&mut x,0u8); + x.conditional_negate(0u8); assert_eq!(x, minus_one); - conditional_negate(&mut x,1u8); + x.conditional_negate(1u8); assert_eq!(x, one); } } diff --git a/src/util.rs b/src/util.rs index 86d91aa..2d08f79 100644 --- a/src/util.rs +++ b/src/util.rs @@ -21,13 +21,24 @@ pub trait CTAssignable { fn conditional_assign(&mut self, other: &Self, choice: u8); } -/// Conditionally negate an element if `choice == 1u8`. -pub fn conditional_negate(x: &mut T, choice: u8) +/// Trait for items which can be conditionally negated in constant time. +/// +/// Note: it is not necessary to implement this trait, as a generic +/// implementation is provided. +pub trait CTNegateable +{ + /// Conditionally negate an element if `choice == 1u8`. + fn conditional_negate(&mut self, choice: u8); +} + +impl CTNegateable for T where T: CTAssignable, for<'a> &'a T: Neg { - // Need to cast to discard mutability - let x_neg = -(x as &T); - x.conditional_assign(&x_neg, choice); + fn conditional_negate(&mut self, choice: u8) { + // Need to cast to eliminate mutability + let self_neg: T = -(self as &T); + self.conditional_assign(&self_neg, choice); + } } /// Check equality of two bytes in constant time.