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

Commit 2d47425

Browse files
committed
Enable calling context on Option<T> by adding an OptionExt trait.
1 parent 8f8f92f commit 2d47425

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ mod box_std;
4343
mod compat;
4444
mod context;
4545
mod result_ext;
46+
mod option_ext;
4647

4748
use core::any::TypeId;
4849
use core::fmt::{Debug, Display};
@@ -52,6 +53,7 @@ pub use backtrace::Backtrace;
5253
pub use compat::Compat;
5354
pub use context::Context;
5455
pub use result_ext::ResultExt;
56+
pub use option_ext::OptionExt;
5557

5658
#[cfg(feature = "failure_derive")]
5759
#[allow(unused_imports)]

src/option_ext.rs

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)