Skip to content

Commit

Permalink
Add CtOption::expect
Browse files Browse the repository at this point in the history
Along the lines of the existing `CtOption::unwrap`, this adds a
corresponding `CtOption::expect` which works like `Option::expect`:
unwraps the value if it's some, or else panics with a provided error
message.

Using `expect` over `unwrap` is generally prefered from a Rust style
perspective. This allows the caller to describe what invariant was
violated when it's expected some `CtOption` is always some.
  • Loading branch information
tarcieri committed Jan 15, 2023
1 parent b4b070c commit f8b1f59
Showing 1 changed file with 12 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 @@ -605,6 +605,18 @@ impl<T> CtOption<T> {
}
}

/// Returns the contained value, consuming the `self` value.
///
/// # Panics
///
/// Panics if the value is none with a custom panic message provided by
/// `msg`.
pub fn expect(self, msg: &str) -> T {
assert_eq!(self.is_some.unwrap_u8(), 1, "{}", msg);

self.value
}

/// This returns the underlying value but panics if it
/// is not `Some`.
#[inline]
Expand Down

0 comments on commit f8b1f59

Please sign in to comment.