use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::time::Duration;

use futures_lite::FutureExt;

use super::Backend;
use crate::spawn::JoinHandle;

pub(crate) struct AsyncStdBackend;

impl Backend for AsyncStdBackend {
    fn spawn<T: Send + 'static>(fut: impl Future<Output = T> + Send + 'static) -> JoinHandle<T> {
        let handle = async_std::task::spawn(AssertUnwindSafe(fut).catch_unwind());
        JoinHandle {
            inner: Some(handle),
        }
    }

    fn sleep(dur: Duration) -> impl Future<Output = ()> + Send {
        async_std::task::sleep(dur)
    }
}
