skip_error 3.1.1

Utility helping skip and log Result::Error in iterations
Documentation
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
#![deny(missing_docs)]

//! This crate provides a single macro to help skipping a error in a loop,
//! possibly logging it.
//!
//! For example, imagine you have some code like this.
//! ```edition2018
//! for string_number in &["1", "2", "three", "4"] {
//!   let number: u32 = match string_number.parse() {
//!     Ok(n) => n,
//!     Err(e) => continue,
//!   };
//! }
//! ```
//!
//! Then you can use the macro [`skip_error!`] to write like this.
//! ```edition2018
//! # #[macro_use]
//! # extern crate skip_error;
//! # fn main() {
//! for string_number in &["1", "2", "three", "4"] {
//!   let number: u32 = skip_error!(string_number.parse());
//! }
//! # }
//! ```
//!
//! Or even better, use the trait [`SkipError`] that extends [`Iterator`] and do
//! the following (essentially equivalent to [`Iterator::flatten()`] but see
//! below for logging abilities).
//! ```edition2018
//! # #[macro_use]
//! # extern crate skip_error;
//! use skip_error::SkipError;
//! # fn main() {
//! let numbers: Vec<u32> = ["1", "2", "three", "4"]
//!   .into_iter()
//!   .map(|string_number| string_number.parse())
//!   .skip_error()
//!   .collect();
//! # }
//! ```
//!
#![cfg_attr(
    any(feature = "log", feature = "tracing"),
    doc = "
# Logging

If you want the error to be logged, you can use the feature `log` or the
feature `tracing` (see [Features](#features)). See [`skip_error_and_log!`]
and [`SkipError::skip_error_and_log()`] for more information.
"
)]
//! # Features
//!
//! - `log`: emit log message with the standard `std::log` macro. Disabled by
//! default.
//! - `tracing`: emit traces with the `tracing::trace` macro. Disabled
//! by default. If both `log` and `tracing` are enabled, then `log` will be
//! ignored since `tracing` is configured in a compatibility mode with standard
//! `log`.

/// `skip_error` returns the value of a [`Result`] or continues a loop.
///
/// `skip_error` macro takes one parameter of type [`Result`]. It returns the
/// value if [`Result::Ok`] or else, it calls `continue` and ignore the
/// [`Result::Err`].
///
/// For example
/// ```edition2018
/// # #[macro_use]
/// # extern crate skip_error;
/// # fn main() {
/// for string_number in &["1", "2", "three", "4"] {
///   let number: u32 = skip_error!(string_number.parse());
/// }
/// # }
/// ```
#[macro_export]
macro_rules! skip_error {
    ($result:expr) => {{
        match $result {
            Ok(value) => value,
            Err(error) => {
                continue;
            }
        }
    }};
}

/// `skip_error_and_log` returns the value of a [`Result`] or log and continues
/// the loop.
///
/// `skip_error_and_log` macro takes two parameters. The first argument is of
/// type [`Result`]. The second argument is anything that can be turned into
#[cfg_attr(all(feature = "log", not(feature = "tracing")), doc = "[`log::Level`]")]
#[cfg_attr(feature = "tracing", doc = "[`tracing::Level`]")]
/// and defines the level to log to.  The macro returns the value if
/// [`Result::Ok`] and else, it logs the [`Result::Err`] and calls `continue`.
///
/// For example
/// ```edition2018
/// # #[macro_use]
/// # extern crate skip_error;
/// # fn main() {
/// # testing_logger::setup();
/// for string_number in &["1", "2", "three", "4"] {
#[cfg_attr(
    all(feature = "log", not(feature = "tracing")),
    doc = "  let number: u32 = skip_error_and_log!(string_number.parse(), log::Level::Warn);"
)]
#[cfg_attr(
    feature = "tracing",
    doc = "  let number: u32 = skip_error_and_log!(string_number.parse(), tracing::Level::WARN);"
)]
/// }
/// testing_logger::validate(|captured_logs| {
///   assert!(captured_logs[0].body.contains("invalid digit found in string"));
///   assert_eq!(captured_logs[0].level, log::Level::Warn);
/// });
/// # }
/// ```
#[macro_export]
#[cfg(any(feature = "log", feature = "tracing"))]
macro_rules! skip_error_and_log {
    ($result:expr, $log_level:expr) => {{
        match $result {
            Ok(value) => value,
            Err(error) => {
                $crate::__log!(error, $log_level);
                continue;
            }
        }
    }};
}

// Macro to generate new macros
#[cfg(any(feature = "log", feature = "tracing"))]
macro_rules! skip_error_macro_generation {
    ($macro_name:ident, $log_level:expr) => {
        skip_error_macro_generation!($macro_name, $log_level, $log_level);
    };
    ($macro_name:ident, $log_level:expr, $expected_log_level:expr) => {
        #[doc = concat!(
            "`",
            stringify!($macro_name),
            "` returns the value of a [`Result`] or log with [`",
            stringify!($log_level),
            "`] and continues the loop.\n\n",
            "`",
            stringify!($macro_name),
            "` macro takes one parameter which is of type [`Result`].",
            "The macro returns the value if `Result::Ok` and else,",
            "it logs the [`Result::Err`] with level [`",
            stringify!($log_level),
            "`] and calls `continue`.\n\n",
            "For example\n",
            "```edition2018\n",
            "# #[macro_use]\n",
            "# extern crate skip_error;\n",
            "# fn main() {\n",
            "# testing_logger::setup();\n",
            "for string_number in &[\"1\", \"2\", \"three\", \"4\"] {\n",
            "  let number: u32 = ", stringify!($macro_name), "!(string_number.parse());\n",
            "}\n",
            "testing_logger::validate(|captured_logs| {\n",
            "  assert!(captured_logs[0].body.contains(\"invalid digit found in string\"));\n",
            "  assert_eq!(captured_logs[0].level, ", stringify!($expected_log_level), ");\n",
            "});\n",
            "# }\n",
            "```\n",
        )]
        #[macro_export]
        macro_rules! $macro_name {
            ($result:expr) => {{
                $crate::skip_error_and_log!($result, $log_level)
            }};
        }
    };
}

#[cfg(all(feature = "log", not(feature = "tracing")))]
skip_error_macro_generation!(skip_error_and_error, log::Level::Error);
#[cfg(all(feature = "log", not(feature = "tracing")))]
skip_error_macro_generation!(skip_error_and_warn, log::Level::Warn);
#[cfg(all(feature = "log", not(feature = "tracing")))]
skip_error_macro_generation!(skip_error_and_info, log::Level::Info);
#[cfg(all(feature = "log", not(feature = "tracing")))]
skip_error_macro_generation!(skip_error_and_debug, log::Level::Debug);
#[cfg(all(feature = "log", not(feature = "tracing")))]
skip_error_macro_generation!(skip_error_and_trace, log::Level::Trace);
#[cfg(feature = "tracing")]
skip_error_macro_generation!(
    skip_error_and_error,
    tracing::Level::ERROR,
    log::Level::Error
);
#[cfg(feature = "tracing")]
skip_error_macro_generation!(skip_error_and_warn, tracing::Level::WARN, log::Level::Warn);
#[cfg(feature = "tracing")]
skip_error_macro_generation!(skip_error_and_info, tracing::Level::INFO, log::Level::Info);
#[cfg(feature = "tracing")]
skip_error_macro_generation!(
    skip_error_and_debug,
    tracing::Level::DEBUG,
    log::Level::Debug
);
#[cfg(feature = "tracing")]
skip_error_macro_generation!(
    skip_error_and_trace,
    tracing::Level::TRACE,
    log::Level::Trace
);

#[doc(hidden)]
#[macro_export]
#[cfg(all(feature = "log", not(feature = "tracing")))]
macro_rules! __log {
    ($error:expr, $log_level:expr) => {{
        log::log!(
            std::convert::Into::<log::Level>::into($log_level),
            "{}",
            $error
        );
    }};
}

#[doc(hidden)]
#[macro_export]
#[cfg(feature = "tracing")]
macro_rules! __log {
    ($error:tt, $log_level:expr) => {{
        match std::convert::Into::<tracing::Level>::into($log_level) {
            tracing::Level::INFO => tracing::info!("{}", $error),
            tracing::Level::WARN => tracing::warn!("{}", $error),
            tracing::Level::ERROR => tracing::error!("{}", $error),
            tracing::Level::DEBUG => tracing::debug!("{}", $error),
            tracing::Level::TRACE => tracing::trace!("{}", $error),
        }
    }};
}

/// An iterator that ignore errors
pub struct SkipErrorIter<I, T, E>
where
    I: Iterator<Item = Result<T, E>>,
{
    inner: I,
    #[cfg(all(feature = "log", not(feature = "tracing")))]
    log_level: Option<log::Level>,
    #[cfg(feature = "tracing")]
    log_level: Option<tracing::Level>,
}

impl<I, T, E> std::iter::Iterator for SkipErrorIter<I, T, E>
where
    I: Iterator<Item = Result<T, E>>,
    E: std::fmt::Display,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().and_then(|result| match result {
            Ok(value) => Some(value),
            Err(_error) => {
                #[cfg(any(feature = "log", feature = "tracing"))]
                if let Some(log_level) = self.log_level {
                    __log!(_error, log_level);
                }
                self.next()
            }
        })
    }
}

#[cfg(any(feature = "log", feature = "tracing"))]
macro_rules! default_impl_skip_error_iterator {
    ($method_name:ident, $log_level:expr) => {
        default_impl_skip_error_iterator!($method_name, $log_level, $log_level);
    };
    ($method_name:ident, $log_level:expr, $expected_log_level:expr) => {
        #[doc = concat!(
            "Shortcut for [`SkipError::skip_error_and_log`] with a log level of [`",
            stringify!($log_level),
            "`].\n\n",
            "For example\n",
            "```edition2018\n",
            "use skip_error::SkipError;\n",
            "# fn main() {\n",
            "# testing_logger::setup();\n",
            "vec![Ok(1), Ok(2), Err(\"'three' is not a valid number\"), Ok(4)]\n",
            "  .into_iter()\n",
            "  .", stringify!($method_name), "()\n",
            "  .collect::<Vec<_>>();\n",
            "testing_logger::validate(|captured_logs| {\n",
            "  assert!(captured_logs[0].body.contains(\"'three' is not a valid number\"));\n",
            "  assert_eq!(captured_logs[0].level, ", stringify!($expected_log_level), ");\n",
            "});\n",
            "# }\n",
            "```\n"
        )]
        fn $method_name(self) -> SkipErrorIter<I, T, E> {
            self.skip_error_and_log($log_level)
        }
    };
}

/// Trait to extend any [`Iterator`] where the [`Iterator::Item`] is a [`Result`].
/// This allows to skip errors and keep only the `Ok()` values.
pub trait SkipError<I, T, E>: Sized
where
    I: Iterator<Item = Result<T, E>>,
{
    /// Skip all errors of the [`Result`] in the original [`Iterator`].
    /// This is essentially equivalent to `.flatten()`.
    ///
    /// ```edition2018
    /// use skip_error::SkipError;
    /// let v: Vec<usize> = vec![0,1,0,0,3]
    ///   .into_iter()
    ///   .map(|v|
    ///     if v == 0 {
    ///       Ok(0)
    ///     } else {
    ///       Err(format!("Boom on {}", v))
    ///     }
    ///   )
    ///   .skip_error()
    ///   .collect();
    /// assert_eq!(v, vec![0,0,0]);
    /// ```
    fn skip_error(self) -> SkipErrorIter<I, T, E>;

    /// Skip all errors of the [`Result`] in the original [`Iterator`].  This
    /// also allows to log the errors, choosing which [`log::Level`] to use.
    ///
    /// ```edition2018
    /// use skip_error::SkipError;
    /// # testing_logger::setup();
    /// let v: Vec<usize> = vec![0,1,0,0,3]
    ///   .into_iter()
    ///   .map(|v|
    ///     if v == 0 {
    ///       Ok(0)
    ///     } else {
    ///       Err(format!("Boom on {}", v))
    ///     }
    ///   )
    ///   .skip_error_and_log(log::Level::Warn)
    ///   .collect();
    /// assert_eq!(v, vec![0,0,0]);
    /// testing_logger::validate(|captured_logs| {
    ///   assert_eq!(captured_logs[0].level, log::Level::Warn);
    ///   assert_eq!(captured_logs[0].body, "Boom on 1");
    ///   assert_eq!(captured_logs[1].level, log::Level::Warn);
    ///   assert_eq!(captured_logs[1].body, "Boom on 3");
    /// });
    /// ```
    #[cfg(all(feature = "log", not(feature = "tracing")))]
    fn skip_error_and_log<L>(self, log_level: L) -> SkipErrorIter<I, T, E>
    where
        L: Into<log::Level>;
    ///
    /// Skip all errors of the [`Result`] in the original [`Iterator`].  This
    /// also allows to log the errors, choosing which [`tracing::Level`] to use.
    ///
    /// ```edition2018
    /// use skip_error::SkipError;
    /// # testing_logger::setup();
    /// let v: Vec<usize> = vec![0,1,0,0,3]
    ///   .into_iter()
    ///   .map(|v|
    ///     if v == 0 {
    ///       Ok(0)
    ///     } else {
    ///       Err(format!("Boom on {}", v))
    ///     }
    ///   )
    ///   .skip_error_and_log(tracing::Level::WARN)
    ///   .collect();
    /// assert_eq!(v, vec![0,0,0]);
    /// testing_logger::validate(|captured_logs| {
    ///   assert_eq!(captured_logs[0].level, log::Level::Warn);
    ///   assert_eq!(captured_logs[0].body, "Boom on 1 ");
    ///   assert_eq!(captured_logs[1].level, log::Level::Warn);
    ///   assert_eq!(captured_logs[1].body, "Boom on 3 ");
    /// });
    /// ```
    #[cfg(feature = "tracing")]
    fn skip_error_and_log<L>(self, trace_level: L) -> SkipErrorIter<I, T, E>
    where
        L: Into<tracing::Level>;

    #[cfg(all(feature = "log", not(feature = "tracing")))]
    default_impl_skip_error_iterator!(skip_error_and_trace, log::Level::Trace);
    #[cfg(all(feature = "log", not(feature = "tracing")))]
    default_impl_skip_error_iterator!(skip_error_and_debug, log::Level::Debug);
    #[cfg(all(feature = "log", not(feature = "tracing")))]
    default_impl_skip_error_iterator!(skip_error_and_error, log::Level::Error);
    #[cfg(all(feature = "log", not(feature = "tracing")))]
    default_impl_skip_error_iterator!(skip_error_and_warn, log::Level::Warn);
    #[cfg(all(feature = "log", not(feature = "tracing")))]
    default_impl_skip_error_iterator!(skip_error_and_info, log::Level::Info);
    #[cfg(feature = "tracing")]
    default_impl_skip_error_iterator!(
        skip_error_and_trace,
        tracing::Level::TRACE,
        log::Level::Trace
    );
    #[cfg(feature = "tracing")]
    default_impl_skip_error_iterator!(
        skip_error_and_debug,
        tracing::Level::DEBUG,
        log::Level::Debug
    );
    #[cfg(feature = "tracing")]
    default_impl_skip_error_iterator!(
        skip_error_and_error,
        tracing::Level::ERROR,
        log::Level::Error
    );
    #[cfg(feature = "tracing")]
    default_impl_skip_error_iterator!(skip_error_and_warn, tracing::Level::WARN, log::Level::Warn);
    #[cfg(feature = "tracing")]
    default_impl_skip_error_iterator!(skip_error_and_info, tracing::Level::INFO, log::Level::Info);
}

impl<I, T, E> SkipError<I, T, E> for I
where
    I: Iterator<Item = Result<T, E>>,
{
    fn skip_error(self) -> SkipErrorIter<I, T, E> {
        SkipErrorIter {
            inner: self,
            #[cfg(any(feature = "log", feature = "tracing"))]
            log_level: None,
        }
    }
    #[cfg(all(feature = "log", not(feature = "tracing")))]
    fn skip_error_and_log<L>(self, log_level: L) -> SkipErrorIter<I, T, E>
    where
        L: Into<log::Level>,
    {
        SkipErrorIter {
            inner: self,
            log_level: Some(log_level.into()),
        }
    }
    #[cfg(feature = "tracing")]
    fn skip_error_and_log<L>(self, log_level: L) -> SkipErrorIter<I, T, E>
    where
        L: Into<tracing::Level>,
    {
        SkipErrorIter {
            inner: self,
            log_level: Some(log_level.into()),
        }
    }
}