Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an ensure_whatever macro. #330

Merged
merged 1 commit into from May 3, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
82 changes: 66 additions & 16 deletions src/lib.rs
Expand Up @@ -207,7 +207,7 @@ pub mod prelude {
}

#[cfg(any(feature = "std", test))]
pub use crate::whatever;
pub use crate::{ensure_whatever, whatever};

#[cfg(feature = "futures")]
pub use crate::futures::{TryFutureExt as _, TryStreamExt as _};
Expand Down Expand Up @@ -333,6 +333,8 @@ pub use no_std_error::Error;
/// Ensure a condition is true. If it is not, return from the function
/// with an error.
///
/// ## Examples
///
/// ```rust
/// use snafu::prelude::*;
///
Expand Down Expand Up @@ -369,26 +371,33 @@ macro_rules! ensure {
/// Provide a format string and any optional arguments. The macro will
/// unconditionally exit the calling function with an error.
///
/// ## Examples
///
/// ```rust
/// use snafu::prelude::*;
/// use snafu::{Whatever, prelude::*};
///
/// #[derive(Debug, Snafu)]
/// #[snafu(whatever, display("Error was: {message}"))]
/// struct Error {
/// message: String,
/// type Result<T, E = Whatever> = std::result::Result<T, E>;
///
/// enum Status {
/// Sleeping,
/// Chilling,
/// Working,
/// }
/// type Result<T, E = Error> = std::result::Result<T, E>;
///
/// fn get_bank_account_balance(account_id: &str) -> Result<u8> {
/// # fn moon_is_rising() -> bool { false }
/// if moon_is_rising() {
/// whatever!(
/// "We are recalibrating the dynamos for account {}, sorry",
/// account_id,
/// );
/// # fn stand_up() {}
/// # fn go_downstairs() {}
/// fn do_laundry(status: Status, items: u8) -> Result<()> {
/// match status {
/// Status::Sleeping => whatever!("Cannot launder {items} clothes when I am asleep"),
/// Status::Chilling => {
/// stand_up();
/// go_downstairs();
/// }
/// Status::Working => {
/// go_downstairs();
/// }
/// }
///
/// Ok(100)
/// Ok(())
/// }
/// ```
///
Expand All @@ -401,6 +410,8 @@ macro_rules! ensure {
/// not an error, the macro will evaluate to the `Ok` value of the
/// `Result`.
///
/// ## Examples
///
/// ```rust
/// use snafu::prelude::*;
///
Expand Down Expand Up @@ -448,6 +459,45 @@ macro_rules! whatever {
};
}

/// Ensure a condition is true. If it is not, return a stringly-typed
/// error message.
///
/// This can be used with the provided [`Whatever`][] type or with a
/// custom error type that uses `snafu(whatever)`.
///
/// ## Examples
///
/// ```rust
/// use snafu::prelude::*;
///
/// #[derive(Debug, Snafu)]
/// #[snafu(whatever, display("Error was: {message}"))]
/// struct Error {
/// message: String,
/// }
/// type Result<T, E = Error> = std::result::Result<T, E>;
///
/// fn get_bank_account_balance(account_id: &str) -> Result<u8> {
/// # fn moon_is_rising() -> bool { false }
/// ensure_whatever!(
/// moon_is_rising(),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was it intended to negate the condition? If I'm not mistaken, this changes it from if moon_is_rising() to (after macro expansion) if !moon_is_rising().

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not intended, per se, but I’m ok with it. Since it’s just an example, whatever shows the feature easiest is a good choice, IMO. I don’t expect anyone will remember the example from one version to the next 😅

/// "We are recalibrating the dynamos for account {}, sorry",
/// account_id,
/// );
///
/// Ok(100)
/// }
/// ```
#[macro_export]
#[cfg(any(feature = "std", test))]
macro_rules! ensure_whatever {
($predicate:expr, $fmt:literal$(, $($arg:expr),* $(,)?)?) => {
if !$predicate {
$crate::whatever!($fmt$(, $($arg),*)*);
}
};
}

/// Additions to [`Result`](std::result::Result).
pub trait ResultExt<T, E>: Sized {
/// Extend a [`Result`]'s error with additional context-sensitive information.
Expand Down