Skip to content

Commit

Permalink
feat(ThingBuf): add pop_with and push_with
Browse files Browse the repository at this point in the history
Signed-off-by: Eliza Weisman <[email protected]>
  • Loading branch information
hawkw committed Nov 12, 2021
1 parent 0e53279 commit 9192c60
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ impl<T> ThingBuf<T> {
}
}

#[inline]
pub fn push_with<U>(&self, f: impl FnOnce(&mut T) -> U) -> Result<U, AtCapacity> {
self.push_ref().map(|mut r| r.with_mut(f))
}
pub fn push_ref(&self) -> Result<Ref<'_, T>, AtCapacity> {
let mut backoff = Backoff::new();
let mut tail = self.tail.load(Ordering::Relaxed);
Expand Down Expand Up @@ -176,6 +180,11 @@ impl<T> ThingBuf<T> {
}
}

#[inline]
pub fn pop_with<U>(&self, f: impl FnOnce(&mut T) -> U) -> Option<U> {
self.pop_ref().map(|mut r| r.with_mut(f))
}

pub fn pop_ref(&self) -> Option<Ref<'_, T>> {
let mut backoff = Backoff::new();
let mut head = self.head.load(Ordering::Relaxed);
Expand Down Expand Up @@ -244,15 +253,15 @@ impl<T> fmt::Debug for ThingBuf<T> {

impl<T> Ref<'_, T> {
#[inline]
pub fn with<U>(&self, f: impl Fn(&T) -> U) -> U {
pub fn with<U>(&self, f: impl FnOnce(&T) -> U) -> U {
self.slot.value.with(|value| unsafe {
// Safety: if a `Ref` exists, we have exclusive ownership of the slot.
f(&*value)
})
}

#[inline]
pub fn with_mut<U>(&mut self, f: impl Fn(&mut T) -> U) -> U {
pub fn with_mut<U>(&mut self, f: impl FnOnce(&mut T) -> U) -> U {
self.slot.value.with_mut(|value| unsafe {
// Safety: if a `Ref` exists, we have exclusive ownership of the slot.
f(&mut *value)
Expand Down

0 comments on commit 9192c60

Please sign in to comment.