Skip to main content

junobuild_shared/ic/
trap.rs

1use ic_cdk::trap;
2use std::fmt::Display;
3
4/// Unwraps a `Result<T, String>` or traps with the error message.
5pub trait UnwrapOrTrap<T> {
6    /// Returns the contained `Ok(T)` value, or traps with the contained error message.
7    ///
8    /// # Panics
9    /// Traps the canister execution with the error string.
10    fn unwrap_or_trap(self) -> T;
11}
12
13impl<T, E: Display> UnwrapOrTrap<T> for Result<T, E> {
14    #[inline]
15    fn unwrap_or_trap(self) -> T {
16        self.unwrap_or_else(|e| trap(e.to_string()))
17    }
18}
19
20impl<T> UnwrapOrTrap<T> for Option<T> {
21    #[inline]
22    fn unwrap_or_trap(self) -> T {
23        self.unwrap_or_else(|| trap("Expected a result to return but got none"))
24    }
25}
26
27/// Unwraps a `Result<Option<T>, E>` into `T`, trapping on either failure.
28pub trait UnwrapOrTrapResult<T> {
29    /// Returns the contained `Ok(Some(T))` value, or traps.
30    ///
31    /// # Panics
32    /// Traps the canister execution with the error message if the `Result` is `Err`,
33    /// or with a default message if the `Option` is `None`.
34    fn unwrap_or_trap_result(self) -> T;
35}
36
37impl<T, E: Display> UnwrapOrTrapResult<T> for Result<Option<T>, E> {
38    #[inline]
39    fn unwrap_or_trap_result(self) -> T {
40        self.unwrap_or_trap().unwrap_or_trap()
41    }
42}