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
//! Throttling utilities.
//!
//! Throttling ensures a function is not invoked more often than a specified
//! time interval. This is helpful when reacting to bursty events (e.g., UI
//! inputs, filesystem notifications, or rapid network callbacks) where only
//! occasional execution is desired.
//!
//! This module exposes:
//! - [`Throttled`] — a wrapper storing the underlying function and throttle state.
//! - [`throttle`] — a convenience constructor returning a [`Throttled`] instance.
//!
//! Behavior:
//! - The first `call` executes immediately.
//! - Subsequent `call`s within the configured `delay` are ignored.
//! - Once `delay` has elapsed since the last successful execution, the next
//! `call` will execute again.
//!
//! Basic example:
//!
//! ```rust
//! use toolchest::functions::throttle;
//! use std::time::Duration;
//! use std::sync::atomic::{AtomicUsize, Ordering};
//!
//! let counter = AtomicUsize::new(0);
//! let throttled = throttle(|| { counter.fetch_add(1, Ordering::SeqCst); }, Duration::from_millis(200));
//!
//! throttled.call(); // executes, counter = 1
//! throttled.call(); // ignored (within 200ms)
//! assert_eq!(counter.load(Ordering::SeqCst), 1);
//! ```
//!
//! With sleeping to demonstrate subsequent execution:
//!
//! ```rust
//! use toolchest::functions::throttle;
//! use std::time::Duration;
//! use std::thread::sleep;
//! use std::sync::atomic::{AtomicUsize, Ordering};
//!
//! let counter = AtomicUsize::new(0);
//! let throttled = throttle(|| { counter.fetch_add(1, Ordering::SeqCst); }, Duration::from_millis(50));
//! throttled.call(); // executes (1)
//! throttled.call(); // ignored
//! sleep(Duration::from_millis(60));
//! throttled.call(); // executes (2)
//! assert_eq!(counter.load(Ordering::SeqCst), 2);
//! ```
use ;
use ;
/// A throttled function wrapper.
///
/// Stores the function and timing state used to ensure calls do not execute
/// more frequently than the configured delay interval.
/// Create a throttled wrapper around `func` with the provided `delay`.
///
/// The returned [`Throttled`] instance can be reused and shared across
/// threads if needed (the closure `F` must be `Sync` to share across threads).
///
/// Example:
/// ```rust
/// use toolchest::functions::throttle;
/// use std::time::Duration;
/// use std::sync::atomic::{AtomicUsize, Ordering};
/// let c = AtomicUsize::new(0);
/// let t = throttle(|| { c.fetch_add(1, Ordering::SeqCst); }, Duration::from_millis(10));
/// t.call();
/// assert_eq!(c.load(Ordering::SeqCst), 1);
/// ```