Skip to main content

windjammer_runtime/
async_runtime.rs

1//! Async runtime utilities
2//!
3//! Windjammer's `std::async` module maps to these functions.
4
5use tokio::runtime::Runtime;
6use tokio::task::JoinHandle;
7
8/// Spawn an async task
9pub fn spawn<F, T>(future: F) -> JoinHandle<T>
10where
11    F: std::future::Future<Output = T> + Send + 'static,
12    T: Send + 'static,
13{
14    tokio::spawn(future)
15}
16
17/// Block on an async function (creates a runtime)
18pub fn block_on<F, T>(future: F) -> T
19where
20    F: std::future::Future<Output = T>,
21{
22    let rt = Runtime::new().expect("Failed to create tokio runtime");
23    rt.block_on(future)
24}
25
26/// Blocking sleep (milliseconds) — for tests and sync callers.
27pub fn sleep_ms_blocking(ms: u64) {
28    block_on(async { sleep_ms(ms).await });
29}
30
31/// Sleep for a duration (milliseconds)
32pub async fn sleep_ms(ms: u64) {
33    tokio::time::sleep(tokio::time::Duration::from_millis(ms)).await;
34}
35
36/// Sleep for a duration (seconds)
37pub async fn sleep(secs: u64) {
38    tokio::time::sleep(tokio::time::Duration::from_secs(secs)).await;
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[tokio::test]
46    async fn test_sleep() {
47        let start = std::time::Instant::now();
48        sleep_ms(100).await;
49        let elapsed = start.elapsed();
50        assert!(elapsed.as_millis() >= 100);
51    }
52
53    #[test]
54    fn test_block_on() {
55        let result = block_on(async { 42 });
56        assert_eq!(result, 42);
57    }
58
59    #[test]
60    fn test_sleep_ms_blocking() {
61        let start = std::time::Instant::now();
62        sleep_ms_blocking(25);
63        assert!(start.elapsed().as_millis() >= 20);
64    }
65}