grafix_toolbox/kit/policies/
task.rs

1pub mod pre {
2	pub use futures_lite::{future, stream, Future, FutureExt, Stream, StreamExt};
3	pub use io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
4	pub use tokio::{fs, io, sync::Notify};
5}
6
7pub fn Runtime() -> &'static RT {
8	static S: OnceLock<RT> = OnceLock::new();
9	S.get_or_init(|| {
10		RT(rt::Builder::new_multi_thread()
11			.worker_threads(1)
12			.enable_time()
13			.build()
14			.expect("E| Cannot create async runtime"))
15	})
16}
17impl RT {
18	pub fn spawn<F: Future + SendStat>(&self, future: F) -> Task<F::Output>
19	where
20		F::Output: SendStat,
21	{
22		Task(Some(self.0.spawn(future)))
23	}
24	pub fn finish<T>(&self, mut t: Task<T>) -> T {
25		self.finish_ref(&mut t)
26	}
27	pub fn finish_ref<T>(&self, t: &mut Task<T>) -> T {
28		let t = t.0.take().valid();
29		self.0.block_on(t).valid()
30	}
31}
32pub struct RT(rt::Runtime);
33
34pub struct Task<T>(Option<tokio::task::JoinHandle<T>>);
35impl<T> Task<T> {
36	pub fn new_uninit() -> Self {
37		Self(None)
38	}
39	pub fn is_ready(&self) -> bool {
40		self.0.as_ref().map_or(false, |s| s.is_finished())
41	}
42}
43impl<T> Drop for Task<T> {
44	fn drop(&mut self) {
45		if let Some(h) = self.0.take() {
46			h.abort()
47		}
48	}
49}
50
51use {crate::lib::*, pre::*, std::sync::OnceLock, tokio::runtime as rt};