Skip to content

Commit 5b4468c

Browse files
committed
impl ConditionallyNegatable for BoxedUint
1 parent 2718ae6 commit 5b4468c

File tree

2 files changed

+24
-25
lines changed

2 files changed

+24
-25
lines changed

src/traits.rs

-21
Original file line numberDiff line numberDiff line change
@@ -77,27 +77,6 @@ impl<T: ConditionallySelectable> ConstantTimeSelect for T {
7777
}
7878
}
7979

80-
/// A type which can be conditionally negated in constant time.
81-
///
82-
/// Similar to `subtle`'s `ConditionallyNegate` trait, but without the `Copy` bound which allows
83-
/// it to to be impl'd for heap allocated types.
84-
pub trait ConstantTimeNegatable {
85-
/// Negate `self` according to `choice`.
86-
fn ct_negate(&mut self, choice: Choice);
87-
}
88-
89-
impl<T> ConstantTimeNegatable for T
90-
where
91-
T: ConstantTimeSelect,
92-
for<'a> &'a T: Neg<Output = T>,
93-
{
94-
#[inline]
95-
fn ct_negate(&mut self, choice: Choice) {
96-
let self_neg = -(&*self);
97-
self.ct_assign(&self_neg, choice);
98-
}
99-
}
100-
10180
/// Integer trait: represents common functionality of integer types provided by this crate.
10281
pub trait Integer:
10382
'static

src/uint/boxed/ct.rs

+24-4
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
use super::BoxedUint;
44
use crate::{ConstantTimeSelect, Limb};
5-
use subtle::{Choice, ConditionallySelectable};
5+
use subtle::{Choice, ConditionallyNegatable, ConditionallySelectable};
66

77
/// NOTE: can't impl `subtle`'s [`ConditionallySelectable`] trait due to its `Copy` bound
88
impl ConstantTimeSelect for BoxedUint {
@@ -37,11 +37,18 @@ impl ConstantTimeSelect for BoxedUint {
3737
}
3838
}
3939

40+
impl ConditionallyNegatable for BoxedUint {
41+
#[inline]
42+
fn conditional_negate(&mut self, choice: Choice) {
43+
let self_neg = self.wrapping_neg();
44+
self.ct_assign(&self_neg, choice)
45+
}
46+
}
47+
4048
#[cfg(test)]
4149
mod tests {
42-
use super::BoxedUint;
43-
use crate::ConstantTimeSelect;
44-
use subtle::Choice;
50+
use crate::{BoxedUint, ConstantTimeSelect};
51+
use subtle::{Choice, ConditionallyNegatable};
4552

4653
#[test]
4754
fn conditional_select() {
@@ -51,4 +58,17 @@ mod tests {
5158
assert_eq!(a, BoxedUint::ct_select(&a, &b, Choice::from(0)));
5259
assert_eq!(b, BoxedUint::ct_select(&a, &b, Choice::from(1)));
5360
}
61+
62+
#[test]
63+
fn conditional_negate() {
64+
let mut a = BoxedUint::from(123u64);
65+
let control = a.clone();
66+
67+
a.conditional_negate(Choice::from(0));
68+
assert_eq!(a, control);
69+
70+
a.conditional_negate(Choice::from(1));
71+
assert_ne!(a, control);
72+
assert_eq!(a, control.wrapping_neg());
73+
}
5474
}

0 commit comments

Comments
 (0)