use std::future::Future;
use std::time::Duration;
pub use tokio::sync::Mutex;
pub use tokio::sync::mpsc::{
Receiver, Sender, UnboundedReceiver, UnboundedSender, channel, error::SendError,
unbounded_channel,
};
pub use tokio::sync::oneshot::{Receiver as OneshotReceiver, Sender as OneshotSender};
pub fn bounded<T>(buffer: usize) -> (Sender<T>, Receiver<T>) {
channel(buffer)
}
pub fn unbounded<T>() -> (UnboundedSender<T>, UnboundedReceiver<T>) {
unbounded_channel()
}
pub fn oneshot<T>() -> (OneshotSender<T>, OneshotReceiver<T>) {
tokio::sync::oneshot::channel()
}
#[derive(Debug)]
pub struct AbortHandle(tokio::task::AbortHandle);
impl AbortHandle {
pub fn abort(&self) -> bool {
self.0.abort();
true
}
}
pub fn spawn<F>(future: F) -> tokio::task::JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
tokio::spawn(future)
}
pub fn spawn_with_abort<F>(future: F) -> AbortHandle
where
F: Future<Output = ()> + Send + 'static,
{
let handle = tokio::spawn(future);
AbortHandle(handle.abort_handle())
}
pub async fn sleep(duration: Duration) {
tokio::time::sleep(duration).await;
}
pub async fn timeout<F, T>(duration: Duration, future: F) -> Option<T>
where
F: Future<Output = T>,
{
(tokio::time::timeout(duration, future).await).ok()
}