1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
//! The [`guard!`] macro.
//!
//! The [`guard!`] macro implements a control-flow sugar that occurs very often in common Rust code:
//!
//! ```
//! fn foo(cond: bool) -> Option<i32> {
//!   if !cond {
//!     return None;
//!   }
//!
//!   // do something useful
//!
//!   Some(42)
//! }
//! ```
//!
//! This pattern of testing arguments and early-returning with an error is very typical.
//! Unfortunately, the [`?`] operator doesn’t help us here because we want to early-return on a
//! boolean value, not an error value.
//!
//! A not very idiomatic and weird way to rewrite that:
//!
//! ```
//! fn foo(cond: bool) -> Option<i32> {
//!   if cond { Some(()) } else { None }?;
//!   Some(42)
//! }
//! ```
//!
//! This crate provides the [`guard!`] macro — analoguous to the [`guard`] Haskell `Alternative`
//! function — that helps early-return from a function if a predicate is `false`:
//!
//! ```
//! #![feature(try_trait)]
//!
//! use try_guard::guard;
//!
//! fn foo(cond: bool) -> Option<i32> {
//!   guard!(cond);
//!   Some(42)
//! }
//! ```
//!
//! ## Custom guard types
//!
//! This crate also allows you to _guard_ to any time that implements [`Try<Error = NoneError>`]. For
//! instance, the following works:
//!
//! ```
//! #![feature(try_trait)]
//! # #[cfg(feature = "try-trait")] mod lol {
//!
//! use std::ops::Try;
//! use std::option::NoneError;
//! use try_guard::guard;
//!
//! enum MyGuard<T> {
//!   Just(T),
//!   Nothing
//! }
//!
//! impl<T> MyGuard<T> {
//!   fn new(x: T) -> Self {
//!     MyGuard::Just(x)
//!   }
//!
//!   fn none() -> Self {
//!     MyGuard::Nothing
//!   }
//! }
//!
//! impl<T> Try for MyGuard<T> {
//!   type Ok = T;
//!
//!   type Error = NoneError;
//!
//!   fn from_error(_: Self::Error) -> Self {
//!     MyGuard::none()
//!   }
//!
//!   fn from_ok(x: Self::Ok) -> Self {
//!     MyGuard::new(x)
//!   }
//!
//!   fn into_result(self) -> Result<Self::Ok, Self::Error> {
//!     match self {
//!       MyGuard::Just(x) => Ok(x),
//!       MyGuard::Nothing => Err(NoneError)
//!     }
//!   }
//! }
//!
//! fn foo(cond: bool) -> MyGuard<i32> {
//!   guard!(cond);
//!   MyGuard::new(42)
//! }
//!
//! # }
//! ```
//!
//! # Feature flags
//!
//!   - The `"try-trait"` flag allows to use `guard!` with any type that implements
//!     [`Try<Error = NoneError>`]. Disabling this will make `guard!` work only with
//!     [`Option`]. **Enabled by default.**
//!     - **This feature currently requires a nightly build.**
//!
//! [`guard!`]: guard
//! [`guard`]: http://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Monad.html#v:guard
//! [`?`]: https://doc.rust-lang.org/std/ops/trait.Try.html
//! [`Try<Error = NoneError>`]: https://doc.rust-lang.org/std/ops/trait.Try.html

#![cfg_attr(feature = "try-trait", feature(try_trait))]

/// The [`guard!`] macro.
///
/// [`guard!`]: guard
#[macro_export]
macro_rules! guard {
  ($e:expr) => {
    if !$e {
      #[cfg(feature = "try-trait")]
      {
        return std::ops::Try::from_error(std::option::NoneError);
      }
      #[cfg(not(feature = "try-trait"))]
      {
        return None
      }
    }
  };
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn success() {
    fn foo() -> Option<i32> {
      guard!(1 < 2);
      Some(10)
    }

    assert_eq!(foo(), Some(10));
  }

  #[test]
  fn failure() {
    fn foo() -> Option<i32> {
      guard!(1 > 2);
      Some(10)
    }

    assert_eq!(foo(), None);
  }
}