Skip to content

Commit

Permalink
feat: Add a way to get the current number of listeners
Browse files Browse the repository at this point in the history
Mirror of #114

Signed-off-by: John Nunley <dev@notgull.net>
  • Loading branch information
notgull committed Apr 16, 2024
1 parent 34d9dc4 commit 6b73d69
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,42 @@ impl<T> Event<T> {
}
}

/// Return the listener count by acquiring a lock.
///
/// This is just a snapshot of the number of listeners at this point in time.
/// It is possible for the actual number to change at any point.
/// The number should only ever be used as a hint.
/// This is only available when `std` feature is enabled.
///
/// # Examples
///
/// ```
/// use event_listener::Event;
///
/// let event = Event::new();
///
/// assert_eq!(event.total_listeners(), 0);
///
/// let listener1 = event.listen();
/// assert_eq!(event.total_listeners(), 1);
///
/// let listener2 = event.listen();
/// assert_eq!(event.total_listeners(), 2);
///
/// drop(listener1);
/// drop(listener2);
/// assert_eq!(event.total_listeners(), 0);
/// ```
#[cfg(feature = "std")]
#[inline]
pub fn total_listeners(&self) -> usize {
if let Some(inner) = self.try_inner() {
inner.total_listeners()
} else {
0
}
}

/// Returns a guard listening for a notification.
///
/// This method emits a `SeqCst` fence after registering a listener.
Expand Down
6 changes: 6 additions & 0 deletions src/linked_list/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ impl<T> Inner<T> {
self.notified.load(Ordering::Acquire) > 0
}

/// Get the total number of listeners.
#[inline]
pub(crate) fn total_listeners(&self) -> usize {
self.lock().guard.len
}

/// Create a listener for this linked list.
#[cold]
pub(crate) fn listen(&self) -> Listener<T> {
Expand Down

0 comments on commit 6b73d69

Please sign in to comment.