use core::fmt::Display;
use crate::errors::BunsenResult;
pub trait WithOkOrPanic<T> {
#[track_caller]
fn ok_or_panic(self) -> T;
}
impl<T, E> WithOkOrPanic<T> for Result<T, E>
where
E: Display,
{
#[track_caller]
fn ok_or_panic(self) -> T {
match self {
Ok(t) => t,
Err(e) => panic!("{e:#}"),
}
}
}
pub trait ResultContext<T> {
#[track_caller]
fn context(
self,
frame: impl Display,
) -> BunsenResult<T>;
#[track_caller]
fn with_context<D, F>(
self,
f: F,
) -> BunsenResult<T>
where
D: Display,
F: FnOnce() -> D;
#[track_caller]
fn context_details<M, D, F>(
self,
f: F,
) -> BunsenResult<T>
where
M: Display,
D: Display,
F: FnOnce() -> (M, D);
#[track_caller]
#[allow(clippy::wrong_self_convention)]
fn as_policy(self) -> BunsenResult<T>;
#[track_caller]
#[allow(clippy::wrong_self_convention)]
fn as_internal(self) -> BunsenResult<T>;
#[track_caller]
#[allow(clippy::wrong_self_convention)]
fn as_illegal(self) -> BunsenResult<T>;
}
impl<T> ResultContext<T> for BunsenResult<T> {
#[track_caller]
fn context(
self,
frame: impl Display,
) -> BunsenResult<T> {
match self {
Ok(t) => Ok(t),
Err(e) => Err(e.context(frame)),
}
}
#[track_caller]
fn with_context<D, F>(
self,
f: F,
) -> BunsenResult<T>
where
D: Display,
F: FnOnce() -> D,
{
match self {
Ok(t) => Ok(t),
Err(e) => Err(e.context(f())),
}
}
#[track_caller]
fn context_details<M, D, F>(
self,
f: F,
) -> BunsenResult<T>
where
M: Display,
D: Display,
F: FnOnce() -> (M, D),
{
match self {
Ok(t) => Ok(t),
Err(e) => {
let (frame, details) = f();
Err(e.context_details(frame, details))
}
}
}
#[track_caller]
fn as_policy(self) -> BunsenResult<T> {
match self {
Ok(t) => Ok(t),
Err(e) => Err(e.as_policy()),
}
}
#[track_caller]
fn as_internal(self) -> BunsenResult<T> {
match self {
Ok(t) => Ok(t),
Err(e) => Err(e.as_internal()),
}
}
#[track_caller]
fn as_illegal(self) -> BunsenResult<T> {
match self {
Ok(t) => Ok(t),
Err(e) => Err(e.as_illegal()),
}
}
}
#[cfg(test)]
mod tests {
use alloc::string::{
String,
ToString,
};
use super::*;
use crate::errors::BunsenError;
fn try_example(
value: i32,
throw: bool,
) -> Result<i32, String> {
if throw {
Err("throwing".to_string())
} else {
Ok(value)
}
}
#[test]
fn test_expect_unwrap() {
let result = try_example(42, false);
assert_eq!(result.ok_or_panic(), 42);
}
#[should_panic(expected = "throwing")]
#[test]
fn test_expect_unwrap_panic() {
let result = try_example(42, true);
result.ok_or_panic();
}
#[should_panic(expected = "error[Illegal]: stride is zero")]
#[test]
fn test_ok_or_panic_prints_the_report() {
let result: BunsenResult<()> = Err(BunsenError::illegal("stride is zero"));
result.ok_or_panic();
}
#[test]
fn test_context_on_ok_is_untouched() {
let r: BunsenResult<i32> = Ok(3);
assert_eq!(r.context("x").as_illegal().unwrap(), 3);
}
}