From 2d474259e1d4eb980a56c17ff722b77cbe375bcf Mon Sep 17 00:00:00 2001 From: Marcin Mielniczuk Date: Tue, 27 Nov 2018 16:59:13 +0100 Subject: [PATCH] Enable calling context on Option by adding an OptionExt trait. --- src/lib.rs | 2 ++ src/option_ext.rs | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 src/option_ext.rs diff --git a/src/lib.rs b/src/lib.rs index 82c021f..03de177 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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}; @@ -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)] diff --git a/src/option_ext.rs b/src/option_ext.rs new file mode 100644 index 0000000..024ec58 --- /dev/null +++ b/src/option_ext.rs @@ -0,0 +1,52 @@ +use Context; +use core::fmt::Display; + +/// Extension methods for `Option`. +pub trait OptionExt { + + /// 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 = 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(self, context: D) -> Result> + where + D: Display + Send + Sync + 'static; +} + +impl OptionExt for Option { + fn ok_or_context(self, context: D) -> Result> + where + D: Display + Send + Sync + 'static, + { + self.ok_or_else(|| Context::new(context)) + } +}