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

add method total_listeners() when feature std #114

Merged
merged 8 commits into from
Jan 25, 2024
Merged
Changes from 6 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
34 changes: 34 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -479,6 +479,40 @@ impl<T> Event<T> {

inner
}

/// Return the listener count by acquiring a lock
beckend marked this conversation as resolved.
Show resolved Hide resolved
/// 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.
beckend marked this conversation as resolved.
Show resolved Hide resolved
/// 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.list.total_listeners_wait()
} else {
0
}
}
}

impl Event<()> {
8 changes: 8 additions & 0 deletions src/std.rs
Original file line number Diff line number Diff line change
@@ -54,6 +54,14 @@ impl<T> List<T> {
Err(_) => Err("<locked>"),
}
}

// Get the listener count by blocking
pub(crate) fn total_listeners_wait(&self) -> usize {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Name this function total_listeners instead.

Copy link
Contributor Author

@beckend beckend Jan 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

total_listeners is already defined just above.

match self.0.lock() {
beckend marked this conversation as resolved.
Show resolved Hide resolved
Ok(mutex) => mutex.len,
Err(err) => panic!("{err}"),
}
}
}

impl<T> crate::Inner<T> {