Skip to content
Merged
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
34 changes: 34 additions & 0 deletions ctutils/src/choice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,24 @@ impl Choice {
self.select_u64(a as u64, b as u64) as i64
}

/// `const fn` helper: return `b` if `self` is [`Choice::TRUE`], otherwise return `a`.
///
/// Only use this instead of the [`CtSelect`] trait in the event you're in a `const fn` context
/// and can't use the trait. The former will provide better constant-time assurances.
#[inline]
pub const fn select_u8(self, a: u8, b: u8) -> u8 {
a ^ (self.to_u8_mask() & (a ^ b))
}

/// `const fn` helper: return `b` if `self` is [`Choice::TRUE`], otherwise return `a`.
///
/// Only use this instead of the [`CtSelect`] trait in the event you're in a `const fn` context
/// and can't use the trait. The former will provide better constant-time assurances.
#[inline]
pub const fn select_u16(self, a: u16, b: u16) -> u16 {
a ^ (self.to_u16_mask() & (a ^ b))
}

/// `const fn` helper: return `b` if `self` is [`Choice::TRUE`], otherwise return `a`.
///
/// Only use this instead of the [`CtSelect`] trait in the event you're in a `const fn` context
Expand Down Expand Up @@ -802,6 +820,22 @@ mod tests {
assert_eq!(Choice::FALSE.select_i64(a, b), a);
}

#[test]
fn select_u8() {
let a: u8 = 1;
let b: u8 = 2;
assert_eq!(Choice::TRUE.select_u8(a, b), b);
assert_eq!(Choice::FALSE.select_u8(a, b), a);
}

#[test]
fn select_u16() {
let a: u16 = 1;
let b: u16 = 2;
assert_eq!(Choice::TRUE.select_u16(a, b), b);
assert_eq!(Choice::FALSE.select_u16(a, b), a);
}

#[test]
fn select_u32() {
let a: u32 = 1;
Expand Down