Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add forget method to semaphore guards #73

Merged
merged 7 commits into from
Dec 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions src/semaphore.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use core::fmt;
use core::mem;
use core::pin::Pin;
use core::sync::atomic::{AtomicUsize, Ordering};
use core::task::Poll;
Expand Down Expand Up @@ -151,7 +152,7 @@ impl Semaphore {
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => return Some(SemaphoreGuardArc(self.clone())),
Ok(_) => return Some(SemaphoreGuardArc(Some(self.clone()))),
Err(c) => count = c,
}
}
Expand Down Expand Up @@ -337,6 +338,14 @@ impl EventListenerFuture for AcquireArcInner {
#[derive(Debug)]
pub struct SemaphoreGuard<'a>(&'a Semaphore);

impl SemaphoreGuard<'_> {
/// Drops the guard _without_ releasing the acquired permit.
#[inline]
pub fn forget(self) {
mem::forget(self);
}
}

impl Drop for SemaphoreGuard<'_> {
fn drop(&mut self) {
self.0.count.fetch_add(1, Ordering::AcqRel);
Expand All @@ -347,11 +356,24 @@ impl Drop for SemaphoreGuard<'_> {
/// An owned guard that releases the acquired permit.
#[clippy::has_significant_drop]
#[derive(Debug)]
pub struct SemaphoreGuardArc(Arc<Semaphore>);
pub struct SemaphoreGuardArc(Option<Arc<Semaphore>>);

impl SemaphoreGuardArc {
/// Drops the guard _without_ releasing the acquired permit.
/// (Will still decrement the `Arc` reference count.)
#[inline]
pub fn forget(mut self) {
// Drop the inner `Arc` in order to decrement the reference count.
// FIXME: get rid of the `Option` once RFC 3466 or equivalent becomes available.
drop(self.0.take());
mem::forget(self);
}
}

impl Drop for SemaphoreGuardArc {
fn drop(&mut self) {
self.0.count.fetch_add(1, Ordering::AcqRel);
self.0.event.notify(1);
let opt = self.0.take().unwrap();
opt.count.fetch_add(1, Ordering::AcqRel);
opt.event.notify(1);
}
}