variant/lib.rs
1//! The [`try_variant`](`try_variant`) macro matches an expression against a
2//! given pattern returning a [`Result`](`core::result::Result`). If the pattern
3//! matches, then the [`Ok`](`core::result::Result::Ok`) branch is returned
4//! including any assignments from the pattern (or [`unit`] if none are given).
5//! If the match fails then [`Err`](`core::result::Result::Err`) is returned
6//! with either a given error, or a default `Box<dyn std::error::Error>`
7//! otherwise.
8//!
9//! The [`get_variant`](`get_variant`) macro works in exactly the same way,
10//! except it returns [`Some`](`core::option::Option::Some`) if the pattern
11//! matches and [`None`](`core::option::Option::None`), otherwise.
12//!
13//! Finally, the [`variant`](`variant`) macro also works the same way, but
14//! panics if the pattern does not match.
15//!
16//! ## Simple Example
17//!
18//! ```
19//! use variant::{get_variant, try_variant, variant};
20//!
21//! let val = Some((0, 1));
22//! let res = try_variant!(val, Some((i, _))).expect("i");
23//! assert_eq!(res, 0);
24//!
25//! let res = try_variant!(val, Some((10, j)));
26//! assert!(res.is_err());
27//!
28//! // Using get_variant instead
29//! let opt = get_variant!(val, Some((i, _)));
30//! assert_eq!(opt, Some(0));
31//!
32//! let opt = get_variant!(val, Some((10, j)));
33//! assert_eq!(opt, None);
34//!
35//! // Using just variant
36//! let var = variant!(val, Some((i, _)));
37//! assert_eq!(var, 0);
38//!
39//! // calling `variant!(val, Some((10, j)))` will panic.
40//! ```
41//!
42//! ## Guards
43//!
44//! Conditional guards work the same as with [`matches!`][matches].
45//!
46//! ```
47//! use variant::try_variant;
48//!
49//! struct Foo {
50//! a: usize,
51//! b: Option<bool>,
52//! }
53//!
54//! let val = Foo { a: 20, b: None };
55//! let res = try_variant!(val, Foo { a, .. } if a == 20).expect("a");
56//! assert_eq!(res, 20);
57//!
58//! let res = try_variant!(val, Foo { b, .. } if b.is_some());
59//! assert!(res.is_err());
60//! ```
61//!
62//! ## Multiple Assignments
63//!
64//! When there is more than one assignment within a matching pattern all
65//! assignments are returned in a tuple. Since assignments in a pattern may not
66//! be ordered linearly, multiple assignments will be returned in lexicographic
67//! order.
68//!
69//! ```
70//! use variant::try_variant;
71//!
72//! let val = (Some(10), Some(true));
73//! let (a, b) = try_variant!(val, (Some(b), Some(a))).expect("tuple");
74//! assert_eq!((a, b), (true, 10));
75//! ```
76//!
77//! ## Custom Errors
78//!
79//! ```
80//! use variant::try_variant;
81//!
82//! #[derive(Debug)]
83//! enum MyError {
84//! Bad,
85//! Worse,
86//! Expensive,
87//! }
88//!
89//! let val = Some(1);
90//! let res = try_variant!(val, Some(i), MyError::Bad).expect("i");
91//! assert_eq!(res, 1);
92//!
93//! let res = try_variant!(val, Some(50), MyError::Worse);
94//! assert!(matches!(res, Err(MyError::Worse)));
95//!
96//! // We can also use an error returning closure with the following syntax
97//! let err_closure = || MyError::Expensive;
98//! let res = try_variant!(val, Some(50), else err_closure);
99//! assert!(matches!(res, Err(MyError::Expensive)));
100//!
101//! // Doesn't have to be a closure, any callable taking no parameters will do
102//! fn make_err() -> MyError { MyError::Expensive }
103//! let res = try_variant!(val, Some(50), else make_err);
104//! assert!(matches!(res, Err(MyError::Expensive)));
105//! ```
106//!
107//! ## Or Patterns
108//!
109//! None of the macros support `Or` patterns at any level. This is because
110//! there is no simple expected way to signal to the user what values are
111//! returned in the case where only some assignments may match. If a pragmatic
112//! solution to this problem is found then adding this feature in the future
113//! may be possible.
114//!
115//! [unit]: https://doc.rust-lang.org/std/primitive.unit.html
116//! [matches]: https://doc.rust-lang.org/std/macro.matches.html
117
118// Not public API.
119#[doc(hidden)]
120pub mod __private {
121 // Ensures `extract_variant_assign` is callable regardless of where
122 // `variant` is called.
123 pub use extract_variant_internal::extract_variant_assign;
124}
125
126#[macro_export]
127macro_rules! try_variant {
128 ($expression:expr, $pattern:pat_param $(if $guard:expr)?) => {
129 match $expression {
130 $pattern $(if $guard)? => {
131 core::result::Result::Ok($crate::__private::extract_variant_assign!($pattern))
132 }
133 _ => {
134 let msg = "pattern does not match, or guard not satisfied".into();
135 core::result::Result::<_, std::boxed::Box<dyn std::error::Error>>::Err(msg)
136 }
137 }
138 };
139 ($expression:expr, $pattern:pat_param $(if $guard:expr)?, $err:expr) => {
140 match $expression {
141 $pattern $(if $guard)? => {
142 core::result::Result::Ok($crate::__private::extract_variant_assign!($pattern))
143 }
144 _ => core::result::Result::Err($err),
145 }
146 };
147 // `err` is callable with no parameters.
148 ($expression:expr, $pattern:pat_param $(if $guard:expr)?, else $err:expr) => {
149 match $expression {
150 $pattern $(if $guard)? => {
151 core::result::Result::Ok($crate::__private::extract_variant_assign!($pattern))
152 }
153 _ => core::result::Result::Err($err()),
154 }
155 };
156}
157
158#[macro_export]
159macro_rules! get_variant {
160 ($expression:expr, $pattern:pat_param $(if $guard:expr)?) => {
161 match $expression {
162 $pattern $(if $guard)? => {
163 core::option::Option::Some($crate::__private::extract_variant_assign!($pattern))
164 }
165 _ => core::option::Option::None,
166 }
167 };
168}
169
170#[macro_export]
171macro_rules! variant {
172 ($expression:expr, $pattern:pat_param $(if $guard:expr)?) => {
173 match $expression {
174 $pattern $(if $guard)? => {
175 $crate::__private::extract_variant_assign!($pattern)
176 }
177 _ => panic!("pattern does not match, or guard not satisfied"),
178 }
179 };
180}