2023-06-19 18:56:14 +00:00
|
|
|
use std::{error, fs, io, path};
|
|
|
|
|
|
|
|
use futures::stream::futures_unordered::FuturesUnordered;
|
|
|
|
use tokio_util::sync::CancellationToken;
|
2023-06-14 18:22:10 +00:00
|
|
|
|
|
|
|
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),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2023-06-19 18:56:14 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|