unwrap_macros/
lib.rs

1//! This tiny library provides unwrapping macros in situation where
2//! the typical unwrapping methods for Result and Option in the standard
3//! library comes short and the alternative is too verbose. Specifically when you want to have the `unwrap_or_else` logic
4//! but need to `continue` or `return`.
5
6//! # Usage
7//!
8//! This will log the error with eprintln! and skips the iteration.
9//! ```
10//! // with Result
11//! let some_stuff = vec![
12//!     Ok(1),
13//!     Ok(2),
14//!     Err(MyError::First),
15//!     Ok(4),
16//!     Err(MyError::Second),
17//! ];
18//! for thing in some_stuff {
19//!     let val = unwrap_or_else!(Result, thing, continue);
20//!     println!("{}", val);
21//! }
22//! ```
23//! You can also supply a _closure-like_
24//! argument:
25//! ```
26//! for thing in some_stuff {
27//!     let val = unwrap_or_else!(Result, thing, |e| {
28//!         // some code
29//!         eprintln!("Custom message for error: {e}");
30//!         continue,
31//!     });
32//!     println!("{}", val);
33//! }
34//! ```
35//! ```
36//! // with Option
37//! let some_stuff = vec![
38//!     Some(1),
39//!     Some(2),
40//!     None,
41//!     Some(4),
42//!     None,
43//! ];
44//! for thing in some_stuff {
45//!     let val = unwrap_or_else!(Option, thing, continue);
46//!     println!("{}", val);
47//! }
48//! ```
49//! This will log "No value" when `None` is matched.
50//! ```
51//! for thing in some_stuff {
52//!     let val = unwrap_or_else!(Option, thing, "No value", continue);
53//!     println!("{}", val);
54//! }
55//! ```
56
57#[macro_export]
58macro_rules! unwrap_or_else {
59    (Result, $x:expr, $y:expr) => {
60        match $x {
61            Ok(val) => val,
62            Err(e) => {
63                eprintln!("{}", e);
64                $y
65            }
66        }
67    };
68
69    ($x:expr, $y:expr) => {
70        match $x {
71            Ok(val) | Some(val) => val,
72            Err(e) => {
73                eprintln!("{}", e);
74                $y
75            }
76            None => $y,
77        }
78    };
79
80    (Result, $x:expr, |$e:ident| $y:expr) => {
81        match $x {
82            Ok(val) => val,
83            Err($e) => $y,
84        }
85    };
86
87    (Option, $x:expr, $y:expr) => {
88        match $x {
89            Some(val) => val,
90            None => $y,
91        }
92    };
93
94    (Option, $x:expr, $y:expr, $z:expr) => {
95        match $x {
96            Some(val) => val,
97            None => {
98                eprintln!("{}", $y);
99                $z
100            }
101        }
102    };
103}