use core::future::Future;
use alloc::boxed::Box;
use alloc::sync::Arc;
use crate::{BoxFuture, ProgressInfo, YieldInfo, YieldProgress, Yielding, basic_yield_now};
#[derive(Clone)]
#[must_use]
pub struct Builder {
yielding: Arc<Yielding<crate::YieldFn>>,
pub(crate) progressor: Arc<crate::ProgressFn>,
}
impl Builder {
#[track_caller]
pub fn new() -> Builder {
Builder {
yielding: Arc::new(Yielding {
yielder: move |_info: &YieldInfo<'_>| -> BoxFuture<'static, ()> {
Box::pin(basic_yield_now())
},
#[cfg(feature = "log_hiccups")]
state: std::sync::Mutex::new(crate::YieldState {
last_finished_yielding: web_time::Instant::now(),
last_yield_location: core::panic::Location::caller(),
last_yield_label: None,
}),
}),
progressor: Arc::new(|_| {}),
}
}
pub fn build(self) -> YieldProgress {
let Self {
yielding,
progressor,
} = self;
YieldProgress {
start: 0.0,
end: 1.0,
label: None,
yielding,
progressor,
}
}
#[allow(clippy::missing_panics_doc)] pub fn yield_using<Y, YFut>(mut self, function: Y) -> Self
where
Y: for<'a> Fn(&'a YieldInfo<'a>) -> YFut + Send + Sync + 'static,
YFut: Future<Output = ()> + Send + 'static,
{
let new_yielding = Arc::new(Yielding {
yielder: move |info: &YieldInfo<'_>| -> BoxFuture<'static, ()> {
Box::pin(function(info))
},
#[cfg(feature = "log_hiccups")]
state: std::sync::Mutex::new(self.yielding.state.lock().unwrap().clone()),
});
self.yielding = new_yielding;
self
}
#[cfg_attr(not(feature = "sync"), allow(dead_code))]
pub(crate) fn yielding_internal(mut self, new_yielding: crate::BoxYielding) -> Self {
self.yielding = new_yielding;
self
}
pub fn progress_using<P>(mut self, function: P) -> Self
where
P: for<'a> Fn(&'a ProgressInfo<'a>) + Send + Sync + 'static,
{
self.progressor = Arc::new(function);
self
}
}
impl Default for Builder {
fn default() -> Self {
Self::new()
}
}