Skip to main content

ghpascon_rust/utils/
functions.rs

1use std::future::Future;
2use std::time::Duration;
3
4/// Executes a closure after a specified delay, always asynchronously.
5///
6/// # Arguments
7///
8/// * `delay` - Duration to wait before executing
9/// * `func` - Async closure or function to execute after the delay
10///
11/// # Returns
12///
13/// The result of the closure.
14pub async fn delayed_function<F, Fut, T>(delay: Duration, func: F) -> T
15where
16    F: FnOnce() -> Fut,
17    Fut: Future<Output = T>,
18{
19    tokio::time::sleep(delay).await;
20    func().await
21}
22
23#[cfg(test)]
24mod tests {
25    use super::*;
26
27    #[tokio::test]
28    async fn test_delayed_returns_value() {
29        let result = delayed_function(Duration::from_millis(10), || async { 42 }).await;
30        assert_eq!(result, 42);
31    }
32
33    #[tokio::test]
34    async fn test_delayed_with_string() {
35        let result = delayed_function(Duration::from_millis(10), || async { "hello" }).await;
36        assert_eq!(result, "hello");
37    }
38
39    #[tokio::test]
40    async fn test_delayed_with_bool() {
41        let result = delayed_function(Duration::from_millis(10), || async { true }).await;
42        assert!(result);
43    }
44}