diff --git a/src/libs/shared/src/ic/trap.rs b/src/libs/shared/src/ic/trap.rs index 296b3b78b..260922229 100644 --- a/src/libs/shared/src/ic/trap.rs +++ b/src/libs/shared/src/ic/trap.rs @@ -16,3 +16,27 @@ impl UnwrapOrTrap for Result { self.unwrap_or_else(|e| trap(e.to_string())) } } + +impl UnwrapOrTrap for Option { + #[inline] + fn unwrap_or_trap(self) -> T { + self.unwrap_or_else(|| trap("Expected a result to return but got none")) + } +} + +/// Unwraps a `Result, E>` into `T`, trapping on either failure. +pub trait UnwrapOrTrapResult { + /// Returns the contained `Ok(Some(T))` value, or traps. + /// + /// # Panics + /// Traps the canister execution with the error message if the `Result` is `Err`, + /// or with a default message if the `Option` is `None`. + fn unwrap_or_trap_result(self) -> T; +} + +impl UnwrapOrTrapResult for Result, E> { + #[inline] + fn unwrap_or_trap_result(self) -> T { + self.unwrap_or_trap().unwrap_or_trap() + } +}