This repository has been archived by the owner on Sep 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add trait for ergonomic Options-as-Errors
- Loading branch information
Showing
2 changed files
with
41 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
use std::fmt::{Debug, Display}; | ||
use std::result::Result as StdResult; | ||
use failure::{Error, err_msg}; | ||
|
||
/// A handy alias for `Result` that carries a generic error type. | ||
pub type Result<T> = StdResult<T, Error>; | ||
|
||
/// Treat `Option::None` as Error with context | ||
pub trait NoneErrorContext<T> { | ||
/// Convert Option to Result by annotating what None means | ||
/// | ||
/// # Examples | ||
/// | ||
/// ```rust | ||
/// # extern crate quicli; | ||
/// # use quicli::prelude::*; | ||
/// # fn main() { run().unwrap() } | ||
/// # fn run() -> Result<()> { | ||
/// let xs = vec!["lorem", "ipsum"]; | ||
/// let x = xs.get(66); // will return None | ||
/// let result = x.none_means("index not found"); | ||
/// | ||
/// assert!(result.is_err()); | ||
/// if let Err(error) = result { | ||
/// assert_eq!(error.to_string(), "index not found".to_string()); | ||
/// } | ||
/// # Ok(()) } | ||
/// ``` | ||
fn none_means<E: Display + Debug + Sync + Send + 'static>(self, explanation: E) -> Result<T>; | ||
} | ||
|
||
impl<T> NoneErrorContext<T> for Option<T> { | ||
fn none_means<E: Display + Debug + Sync + Send + 'static>(self, explanation: E) -> Result<T> { | ||
match self { | ||
Some(x) => Ok(x), | ||
None => Err(err_msg(explanation)), | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters