Skip to content

Commit

Permalink
Add CtOption::into_option
Browse files Browse the repository at this point in the history
A small wrapper for `impl CtOption<T> for Option<T>` which is friendlier
for type inference purposes.

Using `Option::from(ct_option)` often doesn't work because the compiler
is unable to infer `T` for `Option<T>`, so you have to manually annotate
`Option::<T>::from`.

In practice this often winds up looking like:

    Option::<T>::from(T::constructor(x))`

which feels quite redundant.

Using an inherent method instead fixes type inference so the above can
be:

    T::constructor(x).into_option()
  • Loading branch information
tarcieri committed Feb 2, 2024
1 parent 6b6a81a commit 855cdd4
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,22 @@ impl<T> CtOption<T> {

Self::conditional_select(&self, &f, is_none)
}

/// Convert the `CtOption<T>` wrapper into an `Option<T>`, depending on whether
/// the underlying `is_some` `Choice` was a `0` or a `1` once unwrapped.
///
/// # Note
///
/// This function exists to avoid ending up with ugly, verbose and/or bad handled
/// conversions from the `CtOption<T>` wraps to an `Option<T>` or `Result<T, E>`.
/// This implementation doesn't intend to be constant-time nor try to protect the
/// leakage of the `T` since the `Option<T>` will do it anyways.
///
/// It's equivalent to the corresponding `From` impl, however this version is is
/// friendlier for type inference.
pub fn into_option(self) -> Option<T> {
self.into()
}
}

impl<T: ConditionallySelectable> ConditionallySelectable for CtOption<T> {
Expand Down

0 comments on commit 855cdd4

Please sign in to comment.