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
//! Execute a closure with timeout (thread-based).
//!
//! Spawns a worker thread to run the provided closure and waits up to the
//! specified duration for a result. If the timeout elapses first, returns
//! `None`; otherwise returns `Some(T)`.
//!
//! Notes:
//! - Uses a channel to communicate the result. The worker thread is not
//! cancelled on timeout; it simply continues running to completion in the
//! background.
//! - `T` must be `Send + 'static` because it crosses the thread boundary.
//! - This is a simple building block; for cancellation, consider additional
//! coordination.
//!
//! Basic example:
//! ```rust
//! use toolchest::functions::with_timeout;
//! use std::time::Duration;
//! use std::thread::sleep;
//!
//! let res = with_timeout(Duration::from_millis(10), || 42);
//! assert_eq!(res, Some(42));
//!
//! let slow = with_timeout(Duration::from_millis(1), || {
//! sleep(Duration::from_millis(50));
//! 5
//! });
//! assert_eq!(slow, None);
//! ```
use mpsc;
use thread;
use Duration;
/// Run closure `f` with a timeout; returns `None` on timeout.
///
/// Spawns a thread to execute `f` and waits up to `dur` for a result. If the
/// timeout elapses first, `None` is returned; otherwise `Some(T)`.