Skip to content

Commit 2dab4bc

Browse files
authored
ctutils: CtAssign <=> CtSelect delegating macros (#1366)
Adds/adapts and exports macros for writing impls of `CtSelect` based on `CtAssign` and vice versa: - `impl_ct_assign_with_ct_select!` - `impl_ct_select_with_ct_assign!` The latter already existed as an internal implementation detail of `ct_select`, but this re-exports it and makes it more general by changing it from working on `Copy` types to working on `Clone` types.
1 parent 352a72c commit 2dab4bc

2 files changed

Lines changed: 29 additions & 10 deletions

File tree

ctutils/src/traits/ct_assign.rs

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,27 @@ pub trait CtAssign {
88
fn ct_assign(&mut self, other: &Self, choice: Choice);
99
}
1010

11-
// Impl `CtAssign` using the `cmov::Cmov` trait
11+
/// Impl `CtAssign` using the `CtSelect` trait.
12+
///
13+
/// In cases where `CtSelect` is more straightforward to implement, but you want to use a provided
14+
/// implementation of `CtAssign` based on it, you can use this macro to write it for you.
15+
#[macro_export]
16+
macro_rules! impl_ct_assign_with_ct_select {
17+
( $($ty:ty),+ ) => {
18+
$(
19+
impl CtAssign for $ty {
20+
#[inline]
21+
fn ct_assign(&mut self, other: &Self, choice: Choice) {
22+
*self = Self::ct_select(self, other, choice);
23+
}
24+
}
25+
)+
26+
};
27+
}
28+
29+
impl_ct_assign_with_ct_select!(cmp::Ordering);
30+
31+
/// Impl `CtAssign` using the `cmov::Cmov` trait
1232
macro_rules! impl_ct_assign_with_cmov {
1333
( $($ty:ty),+ ) => {
1434
$(
@@ -56,13 +76,6 @@ impl CtAssign for usize {
5676
}
5777
}
5878

59-
impl CtAssign for cmp::Ordering {
60-
#[inline]
61-
fn ct_assign(&mut self, other: &Self, choice: Choice) {
62-
*self = Self::ct_select(self, other, choice);
63-
}
64-
}
65-
6679
impl<T> CtAssign for [T]
6780
where
6881
T: CtAssign,

ctutils/src/traits/ct_select.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,20 @@ pub trait CtSelect: CtAssign + Sized {
2121
}
2222
}
2323

24-
// Impl `CtSelect` using the `CtAssign` trait, which in turn calls `cmov::Cmov`
24+
/// Impl `CtSelect` using the `CtAssign` trait.
25+
///
26+
/// In cases where `CtAssign` is more straightforward to implement, but you want to use a provided
27+
/// implementation of `CtSelect` based on it, you can use this macro to write it for you.
28+
///
29+
/// Requires the provided type(s) impl `Clone`.
30+
#[macro_export]
2531
macro_rules! impl_ct_select_with_ct_assign {
2632
( $($ty:ty),+ ) => {
2733
$(
2834
impl CtSelect for $ty {
2935
#[inline]
3036
fn ct_select(&self, other: &Self, choice: Choice) -> Self {
31-
let mut ret = *self;
37+
let mut ret = self.clone();
3238
ret.ct_assign(other, choice);
3339
ret
3440
}

0 commit comments

Comments
 (0)