subtle icon indicating copy to clipboard operation
subtle copied to clipboard

Implement `ConditionallySelectable` for `[T; N]`?

Open mark-schultz-wu opened this issue 4 years ago • 1 comments

This kind of implementation seems fairly natural for big-int libraries (for example curve25519-dalek essentially does this for the specific type [u64; 5]). Now that min-const-generics are stabilized, it would nice to have a general implementation of this.

I am imagining a straightforward generalization of the curve25519-dalek technique:

impl<const N: usize> ConditionallySelectable for [T; N] where T : Copy + Default {
fn conditional_select(
    a: &[T; N],
    b: &[T; N],
    choice: Choice,
) -> [T; N] {
    let mut output = [T::default(); N];
    for i in 0..N {
        output[i] = T::conditionally_selectable(&a[i], &b[i], choice);
    }
    output
}

I don't know if the trait bound I give for T is precisely what is required though. It's not fully clear to me currently why ConditionallySelectable requires T to be Copy.

For my particular use case, I have a simple wrapper type around a [u64; N] that is not Copy (I want to write some constant-time bigint arithmetic that minimizes stack allocations. As a theorist who is trying to learn Rust I have no clue how actually useful this is, but it is the project I chose). If the above was implemented for [T; N], I could implement ConditionallySelectable. It could also potentially replace the code in curve25519-dalek, but as you probably want the loop unrolled that might not be worth it (although hopefully the compiler would unroll it of course).

mark-schultz-wu avatar Feb 20 '21 19:02 mark-schultz-wu

I agree that the Copy bound is a hindrance (previous discussion in https://github.com/dalek-cryptography/subtle/issues/56). While it's true that these traits should probably only be implemented on types that (are wrappers of types that) are Copy, I personally like it when the compiler reminds me everywhere data is copied, instead of doing it implicitly.

@mark-schultz seems like what you're doing has a lot of overlap with what I'm doing in https://github.com/ycrypto/rsa-cortex-m4. Would be interested in a chat with you out-of-band (e.g. on Matrix, @nickray:solokeys.com).

nickray avatar Apr 16 '21 16:04 nickray

We have this as of #90 which is including in the release of 2.5

isislovecruft avatar Feb 28 '23 19:02 isislovecruft