diff --git a/src/msg.rs b/src/msg.rs index 5352efa..42ba70b 100644 --- a/src/msg.rs +++ b/src/msg.rs @@ -38,6 +38,11 @@ impl fmt::Display for InitWaitError } } +/// Provides a method of waiting on and setting a single initialisation. +/// +/// In general, it should only be set once, as multiple sets do nothing but hog `Arc`s. +/// Dropping the `Initialiser` after waiting or setting should generally be done immediately. +/// Choose the `into_wait()` and `set()` varients over the non-consuming ones. #[derive(Clone, Debug)] pub struct Initialiser { @@ -47,6 +52,7 @@ pub struct Initialiser impl Initialiser { + /// Create a new, unset initialiser pub fn new() -> Self { let (tx, rx) = watch::channel(false); @@ -56,6 +62,7 @@ impl Initialiser } } + /// Create a pre-set initialiser. Calls to `wait()` will immediately resolve. pub fn new_set() -> Self { let (tx, rx) = watch::channel(true); @@ -64,7 +71,8 @@ impl Initialiser rx, } } - + + /// Consume into a future that completes when init is set. pub fn into_wait(self) -> impl Future> + 'static { let mut rx = self.rx; @@ -80,6 +88,10 @@ impl Initialiser } } + /// Clone into a future that completes when init is set. + /// + /// This method does not clone any `Arc`s and is prefered to `self.clone().into_wait()`. + /// Use this when the `Initialiser` you want to wait on is behind a shared reference. pub fn clone_into_wait(&self) -> impl Future> + 'static { let mut rx = self.rx.clone(); @@ -94,7 +106,8 @@ impl Initialiser } } } - + + /// Completes when init is set pub async fn wait(&mut self) -> Result<(), InitWaitError> { if !*self.rx.borrow() { @@ -107,11 +120,13 @@ impl Initialiser } } + /// Is init set? pub fn is_set(&self) -> bool { *self.rx.borrow() } - + + /// Consume and set init if it's not already set pub fn set(self) -> Result<(), InitError> { if !*self.rx.borrow() { @@ -120,6 +135,20 @@ impl Initialiser Ok(()) } } + + /// Set init without consuming. + /// + /// # Note + /// It is prefered to use `set()`, as this method may make `Arc`s hang around longer than they need to. + /// Calling this multiple times is useless. + pub fn set_in_place(&self) -> Result<(), InitError> + { + if !*self.rx.borrow() { + self.tx.broadcast(true).map_err(|_| InitError) + } else { + Ok(()) + } + } } impl Future for Initialiser