Skip to content

Instantly share code, notes, and snippets.

@Nyrox
Created January 5, 2024 16:42
Show Gist options
  • Save Nyrox/91f9f9a6a8823cd85e148a097fe9d74d to your computer and use it in GitHub Desktop.
Save Nyrox/91f9f9a6a8823cd85e148a097fe9d74d to your computer and use it in GitHub Desktop.
use std::fmt::Debug;
/// # Partial Result
///
/// Result type for operations which can fail, but still return some data
///
/// Conceptionally, this is a (D, Option<E>)
///
/// The design of this type is intended to force handling of errors, but also
/// grant access to partial results in case of errors
pub enum PartialResult<D, E> {
Ok(D),
Err(D, E),
}
impl<D, E> PartialResult<D, E> {
/// Consume self and return data, ignoring the error
/// In case of errors, returns partial data
pub fn ok(self) -> D {
match self {
PartialResult::Ok(data) => data,
PartialResult::Err(data, _) => data,
}
}
}
// Impl. conversion into Result<D, E>
impl<D, E> From<PartialResult<D, E>> for Result<D, E> {
fn from(partial_result: PartialResult<D, E>) -> Self {
match partial_result {
PartialResult::Ok(data) => Ok(data),
PartialResult::Err(_, error) => Err(error),
}
}
}
// Impl. basic methods which are analogous to std::result::Result
impl<D, E> PartialResult<D, E> {
pub fn is_ok(&self) -> bool {
match self {
PartialResult::Ok(_) => true,
PartialResult::Err(_, _) => false,
}
}
pub fn is_err(&self) -> bool {
!self.is_ok()
}
}
impl<D, E> PartialResult<D, E>
where
E: Debug,
{
pub fn unwrap(self) -> D {
match self {
PartialResult::Ok(data) => data,
PartialResult::Err(_, err) => panic!("Called unwrap on PartialResult::Err: {:?}", err),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment