Skip to content
This repository was archived by the owner on Aug 16, 2021. It is now read-only.

Enable calling context on Option<T> by adding an OptionExt trait. #277

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ mod box_std;
mod compat;
mod context;
mod result_ext;
mod option_ext;

use core::any::TypeId;
use core::fmt::{Debug, Display};
Expand All @@ -52,6 +53,7 @@ pub use backtrace::Backtrace;
pub use compat::Compat;
pub use context::Context;
pub use result_ext::ResultExt;
pub use option_ext::OptionExt;

#[cfg(feature = "failure_derive")]
#[allow(unused_imports)]
Expand Down
52 changes: 52 additions & 0 deletions src/option_ext.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use Context;
use core::fmt::Display;

/// Extension methods for `Option`.
pub trait OptionExt<T> {

/// Wraps the error type in a context type.
///
/// # Examples
///
/// ```
/// # #[cfg(all(feature = "std", feature = "derive"))]
/// # #[macro_use] extern crate failure;
/// #
/// # #[cfg(all(feature = "std", feature = "derive"))]
/// # #[macro_use] extern crate failure_derive;
/// #
/// # fn main() {
/// # tests::run_test();
/// # }
/// #
/// # #[cfg(not(all(feature = "std", feature = "derive")))] mod tests { pub fn run_test() { } }
/// #
/// # #[cfg(all(feature = "std", feature = "derive"))] mod tests {
/// #
/// # use failure::{self, OptionExt};
/// #
/// #
/// # pub fn run_test() {
/// let opt: Option<String> = None;
/// let x = opt.ok_or_context(format!("An error occured")).unwrap_err();
///
/// let x = format!("{}", x);
///
/// assert_eq!(x, "An error occured");
/// # }
///
/// # }
/// ```
fn ok_or_context<D>(self, context: D) -> Result<T, Context<D>>
where
D: Display + Send + Sync + 'static;
}

impl<T> OptionExt<T> for Option<T> {
fn ok_or_context<D>(self, context: D) -> Result<T, Context<D>>
where
D: Display + Send + Sync + 'static,
{
self.ok_or_else(|| Context::new(context))
}
}