Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ctutils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,4 @@ mod traits;

pub use choice::Choice;
pub use ct_option::CtOption;
pub use traits::{ct_eq::CtEq, ct_gt::CtGt, ct_lt::CtLt, ct_select::CtSelect};
pub use traits::{ct_eq::CtEq, ct_gt::CtGt, ct_lt::CtLt, ct_neg::CtNeg, ct_select::CtSelect};
1 change: 1 addition & 0 deletions ctutils/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@
pub(crate) mod ct_eq;
pub(crate) mod ct_gt;
pub(crate) mod ct_lt;
pub(crate) mod ct_neg;
pub(crate) mod ct_select;
59 changes: 59 additions & 0 deletions ctutils/src/traits/ct_neg.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use crate::{Choice, CtSelect};

/// Constant-time conditional negation: negates a value when `choice` is [`Choice::TRUE`].
pub trait CtNeg: Sized {
/// Conditionally negate `self`, returning `-self` if `choice` is [`Choice::TRUE`], or `self`
/// otherwise.
fn ct_neg(&self, choice: Choice) -> Self;

/// Conditionally negate `self` in-place, replacing it with `-self` if `choice` is
/// [`Choice::TRUE`].
fn ct_neg_assign(&mut self, choice: Choice) {
*self = self.ct_neg(choice);
}
}

// Impl `CtNeg` for an integer type which impls `CtSelect`
macro_rules! impl_ct_neg {
( $($ty:ty),+ ) => {
$(
impl CtNeg for $ty {
#[inline]
fn ct_neg(&self, choice: Choice) -> Self {
let neg = -*self;
self.ct_select(&neg, choice)
}

#[inline]
fn ct_neg_assign(&mut self, choice: Choice) {
let neg = -*self;
self.ct_assign(&neg, choice)
}
}
)+
};
}

impl_ct_neg!(i8, i16, i32, i64, i128);

// TODO(tarcieri): test all signed integer types
#[cfg(test)]
mod tests {
use super::{Choice, CtNeg};

#[test]
fn i64_ct_neg() {
assert_eq!(42, 42.ct_neg(Choice::FALSE));
assert_eq!(-42, 42.ct_neg(Choice::TRUE));
}

#[test]
fn i64_ct_neg_assign() {
let mut n = 42;
n.ct_neg_assign(Choice::FALSE);
assert_eq!(42, n);

n.ct_neg_assign(Choice::TRUE);
assert_eq!(-42, n);
}
}