Skip to content

Commit

Permalink
Implement CtOption merging
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronFeickert committed Jul 8, 2024
1 parent f1f8e53 commit b18f643
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,18 @@ impl<T> CtOption<T> {
pub fn into_option(self) -> Option<T> {
self.into()
}

/// Take a `CtOption<T>` and merge it with a `CtOption<U>` to produce a
/// `CtOption<(T, U)>`.
///
/// The result contains each option's value, and is `Some` if and only if each
/// of the options is `Some`.
pub fn merge<U>(self, other: CtOption<U>) -> CtOption<(T, U)> {
CtOption {
value: (self.value, other.value),
is_some: self.is_some & other.is_some,
}
}
}

impl<T: ConditionallySelectable> ConditionallySelectable for CtOption<T> {
Expand Down
6 changes: 6 additions & 0 deletions tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,12 @@ fn test_ctoption() {
assert!(CtOption::new(1, Choice::from(1)).ct_eq(&CtOption::new(2, Choice::from(1))).unwrap_u8() == 0);
assert!(CtOption::new(1, Choice::from(1)).ct_eq(&CtOption::new(1, Choice::from(1))).unwrap_u8() == 1);
assert!(CtOption::new(1, Choice::from(1)).ct_eq(&CtOption::new(1, Choice::from(1))).unwrap_u8() == 1);

// Test merging
assert!(CtOption::new(1u8, Choice::from(0)).merge(CtOption::new(0u32, Choice::from(0))).into_option().is_none());
assert!(CtOption::new(1u8, Choice::from(1)).merge(CtOption::new(0u32, Choice::from(0))).into_option().is_none());
assert!(CtOption::new(1u8, Choice::from(0)).merge(CtOption::new(0u32, Choice::from(1))).into_option().is_none());
assert_eq!(CtOption::new(1u8, Choice::from(1)).merge(CtOption::new(0u32, Choice::from(1))).into_option(), Some((1u8, 0u32)));
}

#[test]
Expand Down

0 comments on commit b18f643

Please sign in to comment.