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
//! Retry with fixed attempts and optional delay between tries.
//!
//! Provides [`retry`] for retrying an operation up to a fixed number of
//! attempts with an optional constant delay between attempts. Unlike
//! [`retry_with_backoff`](crate::functions::retry_with_backoff), the delay does
//! not increase.
//!
//! Basic example:
//! ```rust
//! use toolchest::functions::retry;
//! use std::time::Duration;
//!
//! let mut n = 0u32;
//! let res: Result<u32, &str> = retry(3, Some(Duration::from_millis(1)), || {
//! n += 1;
//! if n < 3 { Err("fail") } else { Ok(n) }
//! });
//! assert_eq!(res.unwrap(), 3);
//! ```
use thread;
use Duration;
/// Retry an operation up to `attempts` with optional fixed delay.
///
/// - `attempts`: maximum number of tries (must be ≥ 1)
/// - `delay`: fixed `Duration` to sleep after each failed attempt
/// - `op`: closure returning `Result<T, E>`
///
/// Returns `Ok(T)` on the first successful attempt. On exhaustion, returns the
/// last error from `op`.
///
/// Example that fails without delay:
/// ```rust
/// use toolchest::functions::retry;
/// let res: Result<(), &str> = retry(2, None, || Err("nope"));
/// assert_eq!(res.unwrap_err(), "nope");
/// ```