|
| 1 | +use crate::rng::{PrivateRng, PublicRng}; |
| 2 | +use checkct_macros::checkct; |
| 3 | +use core::hint::black_box; |
| 4 | +use ctutils::{Choice, CtSelect}; |
| 5 | + |
| 6 | +macro_rules! private_integer { |
| 7 | + ($ty:ty) => {{ |
| 8 | + let mut bytes = [0u8; size_of::<$ty>()]; |
| 9 | + PrivateRng.fill_bytes(&mut bytes); |
| 10 | + <$ty>::from_le_bytes(bytes) |
| 11 | + }}; |
| 12 | +} |
| 13 | + |
| 14 | +macro_rules! scalar_checks { |
| 15 | + ($module:ident, $ty:ty, $from_lsb:ident, $from_lt:ident, $select:ident) => { |
| 16 | + mod $module { |
| 17 | + use super::*; |
| 18 | + |
| 19 | + fn inputs() -> ($ty, $ty, $ty) { |
| 20 | + // Keep both RNG hooks linked: the BINSEC script uses both. |
| 21 | + black_box(PublicRng.next_u32()); |
| 22 | + ( |
| 23 | + private_integer!($ty), |
| 24 | + private_integer!($ty), |
| 25 | + private_integer!($ty), |
| 26 | + ) |
| 27 | + } |
| 28 | + |
| 29 | + #[checkct] |
| 30 | + pub fn choice_select() { |
| 31 | + let (a, b, condition) = inputs(); |
| 32 | + black_box(select(a, b, condition)); |
| 33 | + } |
| 34 | + |
| 35 | + #[inline(never)] |
| 36 | + fn select(a: $ty, b: $ty, condition: $ty) -> $ty { |
| 37 | + Choice::$from_lsb(condition).$select(a, b) |
| 38 | + } |
| 39 | + |
| 40 | + /// A single shift-and-subtract division step, as used in crypto-bigint. |
| 41 | + /// Keep the comparison and selection together to test their optimization. |
| 42 | + #[checkct] |
| 43 | + pub fn choice_select_after_lt() { |
| 44 | + let (a, b, _) = inputs(); |
| 45 | + black_box(subtract_if_ge(a, b)); |
| 46 | + } |
| 47 | + |
| 48 | + #[inline(never)] |
| 49 | + fn subtract_if_ge(a: $ty, b: $ty) -> $ty { |
| 50 | + let choice = Choice::$from_lt(a, b); |
| 51 | + choice.$select(a.wrapping_sub(b), a) |
| 52 | + } |
| 53 | + |
| 54 | + /// Compare the const helper with the cmov-backed trait on the same expression. |
| 55 | + #[checkct] |
| 56 | + pub fn ct_select_after_lt() { |
| 57 | + let (a, b, _) = inputs(); |
| 58 | + black_box(subtract_if_ge_with_ct_select(a, b)); |
| 59 | + } |
| 60 | + |
| 61 | + #[inline(never)] |
| 62 | + fn subtract_if_ge_with_ct_select(a: $ty, b: $ty) -> $ty { |
| 63 | + let choice = Choice::$from_lt(a, b); |
| 64 | + a.wrapping_sub(b).ct_select(&a, choice) |
| 65 | + } |
| 66 | + } |
| 67 | + }; |
| 68 | +} |
| 69 | + |
| 70 | +scalar_checks!(u8_ops, u8, from_u8_lsb, from_u8_lt, select_u8); |
| 71 | +scalar_checks!(u16_ops, u16, from_u16_lsb, from_u16_lt, select_u16); |
| 72 | +scalar_checks!(u32_ops, u32, from_u32_lsb, from_u32_lt, select_u32); |
| 73 | +scalar_checks!(u64_ops, u64, from_u64_lsb, from_u64_lt, select_u64); |
| 74 | +// TODO: scalar_checks!(u128_ops, u128, from_u128_lsb, from_u128_lt, select_u128); |
0 commit comments