Skip to content

Commit 9fe7405

Browse files
authored
ctutils: add Choice::select_u8/select_u16 (#1324)
Rounds out support for `const fn` predication for all of the core unsigned integer types
1 parent cf0026a commit 9fe7405

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

ctutils/src/choice.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,24 @@ impl Choice {
275275
self.select_u64(a as u64, b as u64) as i64
276276
}
277277

278+
/// `const fn` helper: return `b` if `self` is [`Choice::TRUE`], otherwise return `a`.
279+
///
280+
/// Only use this instead of the [`CtSelect`] trait in the event you're in a `const fn` context
281+
/// and can't use the trait. The former will provide better constant-time assurances.
282+
#[inline]
283+
pub const fn select_u8(self, a: u8, b: u8) -> u8 {
284+
a ^ (self.to_u8_mask() & (a ^ b))
285+
}
286+
287+
/// `const fn` helper: return `b` if `self` is [`Choice::TRUE`], otherwise return `a`.
288+
///
289+
/// Only use this instead of the [`CtSelect`] trait in the event you're in a `const fn` context
290+
/// and can't use the trait. The former will provide better constant-time assurances.
291+
#[inline]
292+
pub const fn select_u16(self, a: u16, b: u16) -> u16 {
293+
a ^ (self.to_u16_mask() & (a ^ b))
294+
}
295+
278296
/// `const fn` helper: return `b` if `self` is [`Choice::TRUE`], otherwise return `a`.
279297
///
280298
/// Only use this instead of the [`CtSelect`] trait in the event you're in a `const fn` context
@@ -802,6 +820,22 @@ mod tests {
802820
assert_eq!(Choice::FALSE.select_i64(a, b), a);
803821
}
804822

823+
#[test]
824+
fn select_u8() {
825+
let a: u8 = 1;
826+
let b: u8 = 2;
827+
assert_eq!(Choice::TRUE.select_u8(a, b), b);
828+
assert_eq!(Choice::FALSE.select_u8(a, b), a);
829+
}
830+
831+
#[test]
832+
fn select_u16() {
833+
let a: u16 = 1;
834+
let b: u16 = 2;
835+
assert_eq!(Choice::TRUE.select_u16(a, b), b);
836+
assert_eq!(Choice::FALSE.select_u16(a, b), a);
837+
}
838+
805839
#[test]
806840
fn select_u32() {
807841
let a: u32 = 1;

0 commit comments

Comments
 (0)