domani/src/util.rs

64 lines
1.5 KiB
Rust
Raw Normal View History

use std::{error, fs, io, path};
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),
},
}
}
struct Task<E>
where
E: error::Error + Send + 'static,
{
canceller: CancellationToken,
handle: tokio::task::JoinHandle<Result<(), E>>,
}
pub struct TaskStack<E>
where
E: error::Error + Send + 'static,
{
wait_group: Vec<Task<E>>,
}
impl<E> TaskStack<E>
where
E: error::Error + Send + 'static,
{
pub fn new() -> TaskStack<E> {
TaskStack {
wait_group: Vec::new(),
}
}
pub fn push_spawn<F, Fut>(&mut self, mut f: F)
where
Fut: futures::Future<Output = Result<(), E>> + Send + 'static,
F: FnMut(CancellationToken) -> Fut,
{
let canceller = CancellationToken::new();
let handle = tokio::spawn(f(canceller.clone()));
self.wait_group.push(Task { canceller, handle });
}
pub async fn stop(mut self) -> Result<(), E> {
// reverse wait_group in place, so we stop the most recently added first. Since this method
// consumes self this is fine.
self.wait_group.reverse();
for t in self.wait_group {
t.canceller.cancel();
if let Err(err) = t.handle.await.expect("task failed") {
return Err(err);
}
}
Ok(())
}
}