skip_fail/lib.rs
1//! This crate provides a single macro to help skipping a error in a loop,
2//! possibly logging it.
3//!
4//! For example, imagine you have some code like this.
5//! ```edition2018
6//! for string_number in &["1", "2", "three", "4"] {
7//! let number: u32 = match string_number.parse() {
8//! Ok(n) => n,
9//! Err(e) => continue,
10//! };
11//! }
12//! ```
13//!
14//! Then you can use the macro `skip_fail!` to write like this.
15//! ```edition2018
16//! # #[macro_use]
17//! # extern crate skip_fail;
18//! # fn main() {
19//! for string_number in &["1", "2", "three", "4"] {
20//! let number: u32 = skip_fail!(string_number.parse());
21//! }
22//! # }
23//! ```
24//!
25//! If you want the error to be logged, you can use the feature `log`. The
26//! logging will be done in WARN level with the standard logging interface
27//! provided by [`log`](https://crates.io/crates/log).
28
29/// `skip_fail` returns the value of a `Result` or continues a loop.
30///
31/// `skip_fail` macro takes one parameter of type `std::result::Result`. It
32/// returns the value if `Result::Ok` or else, it calls `continue` and ignore
33/// the `Result::Error`.
34///
35/// For example
36/// ```edition2018
37/// # #[macro_use]
38/// # extern crate skip_fail;
39/// # fn main() {
40/// for string_number in &["1", "2", "three", "4"] {
41/// let number: u32 = skip_fail!(string_number.parse());
42/// }
43/// # }
44/// ```
45#[macro_export]
46macro_rules! skip_fail {
47 ($result:expr) => {{
48 match $result {
49 Ok(value) => value,
50 Err(error) => {
51 continue;
52 }
53 }
54 }};
55}
56
57/// `skip_fail_and_log` returns the value of a `Result` or log and continues a loop.
58///
59/// `skip_fail_and_log` macro takes two parameters. The first argument is of
60/// type `std::result::Result`. The second argument take the `log::Level` to use
61/// for the logging. The macro returns the value if `Result::Ok` and else, it
62/// logs the `Result::Error` and calls `continue`.
63///
64/// For example
65/// ```edition2018
66/// # #[macro_use]
67/// # extern crate skip_fail;
68/// # fn main() {
69/// for string_number in &["1", "2", "three", "4"] {
70/// let number: u32 = skip_fail_and_log!(string_number.parse(), log::Level::Warn);
71/// }
72/// # }
73/// ```
74#[macro_export]
75#[cfg(feature = "log")]
76macro_rules! skip_fail_and_log {
77 ($result:expr, $log_level:expr) => {{
78 match $result {
79 Ok(value) => value,
80 Err(error) => {
81 log::log!($log_level, "{}", error);
82 continue;
83 }
84 }
85 }};
86}