domani/src/util.rs

57 lines
1.4 KiB
Rust
Raw Normal View History

use std::{error, fs, io, path};
use futures::stream::futures_unordered::FuturesUnordered;
use tokio_util::sync::CancellationToken;
pub fn open_file(path: &path::Path) -> io::Result<Option<fs::File>> {
match fs::File::open(path) {
Ok(file) => Ok(Some(file)),
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(err),
},
}
}
pub struct TaskSet<E>
where
E: error::Error + Send + 'static,
{
canceller: CancellationToken,
wait_group: FuturesUnordered<tokio::task::JoinHandle<Result<(), E>>>,
}
impl<E> TaskSet<E>
where
E: error::Error + Send + 'static,
{
pub fn new() -> TaskSet<E> {
TaskSet {
canceller: CancellationToken::new(),
wait_group: FuturesUnordered::new(),
}
}
pub fn spawn<F, Fut>(&self, mut f: F)
where
Fut: futures::Future<Output = Result<(), E>> + Send + 'static,
F: FnMut(CancellationToken) -> Fut,
{
let canceller = self.canceller.clone();
let handle = tokio::spawn(f(canceller));
self.wait_group.push(handle);
}
pub async fn stop(self) -> Vec<E> {
self.canceller.cancel();
let mut res = Vec::new();
for f in self.wait_group {
if let Err(err) = f.await.expect("task failed") {
res.push(err);
}
}
res
}
}