|
| 1 | +use Context; |
| 2 | +use core::fmt::Display; |
| 3 | + |
| 4 | +/// Extension methods for `Option`. |
| 5 | +pub trait OptionExt<T> { |
| 6 | + |
| 7 | + /// Wraps the error type in a context type. |
| 8 | + /// |
| 9 | + /// # Examples |
| 10 | + /// |
| 11 | + /// ``` |
| 12 | + /// # #[cfg(all(feature = "std", feature = "derive"))] |
| 13 | + /// # #[macro_use] extern crate failure; |
| 14 | + /// # |
| 15 | + /// # #[cfg(all(feature = "std", feature = "derive"))] |
| 16 | + /// # #[macro_use] extern crate failure_derive; |
| 17 | + /// # |
| 18 | + /// # fn main() { |
| 19 | + /// # tests::run_test(); |
| 20 | + /// # } |
| 21 | + /// # |
| 22 | + /// # #[cfg(not(all(feature = "std", feature = "derive")))] mod tests { pub fn run_test() { } } |
| 23 | + /// # |
| 24 | + /// # #[cfg(all(feature = "std", feature = "derive"))] mod tests { |
| 25 | + /// # |
| 26 | + /// # use failure::{self, OptionExt}; |
| 27 | + /// # |
| 28 | + /// # |
| 29 | + /// # pub fn run_test() { |
| 30 | + /// let opt: Option<String> = None; |
| 31 | + /// let x = opt.ok_or_context(format!("An error occured")).unwrap_err(); |
| 32 | + /// |
| 33 | + /// let x = format!("{}", x); |
| 34 | + /// |
| 35 | + /// assert_eq!(x, "An error occured"); |
| 36 | + /// # } |
| 37 | + /// |
| 38 | + /// # } |
| 39 | + /// ``` |
| 40 | + fn ok_or_context<D>(self, context: D) -> Result<T, Context<D>> |
| 41 | + where |
| 42 | + D: Display + Send + Sync + 'static; |
| 43 | +} |
| 44 | + |
| 45 | +impl<T> OptionExt<T> for Option<T> { |
| 46 | + fn ok_or_context<D>(self, context: D) -> Result<T, Context<D>> |
| 47 | + where |
| 48 | + D: Display + Send + Sync + 'static, |
| 49 | + { |
| 50 | + self.ok_or_else(|| Context::new(context)) |
| 51 | + } |
| 52 | +} |
0 commit comments