pub struct Defer<S> { /* private fields */ }
Expand description
A simple, thread-safe utility designed to make it easier to deal with double-&mut errors.
fn broken(&mut self) {
if let Some(val) = self.hold_mutable_ref() {
self.do_mutable_thing(val); // error: self borrowed mutably twice
}
}
fn working(&mut self) {
if let Some(val) = self.hold_mutable_ref() {
self.do_later.defer(val); // no error thanks to interior mutability
}
self.do_later.execute(|val| {
self.do_mutable_thing(val); // runs only if `defer` was called earlier
});
}
Implementations
sourceimpl<S> Defer<S>
impl<S> Defer<S>
sourcepub fn is_deferred(&self) -> bool
pub fn is_deferred(&self) -> bool
Returns true if a deferred state is stored
sourcepub fn defer(&self, state: S)
pub fn defer(&self, state: S)
Stores the provided deferred state atomically. Will replace any existing value.
Check status with is_deferred
first if you don’t want to replace the value.
Panics if the lock is held elsewhere. Use try_defer
to invoke safely in
multi-threaded contexts.
sourcepub fn try_defer(&self, state: S) -> bool
pub fn try_defer(&self, state: S) -> bool
Stores a deferred state only if one isn’t already pending. Unlike defer
, this will
not panic if the lock is currently held elsewhere. Returns true
if the state was stored,
false
otherwise.
sourcepub fn execute<F: FnOnce(S)>(&self, f: F) -> bool
pub fn execute<F: FnOnce(S)>(&self, f: F) -> bool
Runs the given closure with a deferred state if and only if one is currently stored.
Returns true
if the closure was executed.
Panics if the lock is held elsewhere. Use try_execute
to invoke safely in
multi-threaded or re-entrant contexts.
sourcepub fn try_execute<F: FnOnce(S)>(&self, f: F) -> Result<bool, ()>
pub fn try_execute<F: FnOnce(S)>(&self, f: F) -> Result<bool, ()>
Runs the given closure with a deferred state if and only if one is currently stored.
Unlike execute
, this will not panic if the lock is already held elsewhere.
Returns Err(())
if the lock was held, this means the closure wasn’t run.
If the lock wasn’t already held, this returns ’Ok(true)if the closure was ran and
Ok(false)` if not.
Auto Trait Implementations
impl<S> !RefUnwindSafe for Defer<S>
impl<S> Send for Defer<S> where
S: Send,
impl<S> !Sync for Defer<S>
impl<S> Unpin for Defer<S> where
S: Unpin,
impl<S> UnwindSafe for Defer<S> where
S: UnwindSafe,
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more