Skip to content

Commit

Permalink
add len method to Receiver
Browse files Browse the repository at this point in the history
  • Loading branch information
b-naber committed Feb 25, 2022
1 parent e8f19e7 commit 7aae066
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions tokio/src/sync/broadcast.rs
Expand Up @@ -691,6 +691,35 @@ impl<T> Drop for Sender<T> {
}

impl<T> Receiver<T> {
/// Returns the number of messages that were sent into the channel and that
/// this [`Receiver`] has yet to receive.
///
/// [`Receiver`]: crate::sync::broadcast::Receiver
///
/// # Examples
///
/// ```
/// use tokio::sync::broadcast;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx1) = broadcast::channel(16);
///
/// tx.send(10).unwrap();
/// tx.send(20).unwrap();
///
/// assert_eq!(rx1.len(), 2);
/// assert_eq!(rx1.recv().await.unwrap(), 10);
/// assert_eq!(rx1.len(), 1);
/// assert_eq!(rx1.recv().await.unwrap(), 20);
/// assert_eq!(rx1.len(), 0);
/// }
/// ```
pub fn len(&self) -> u64 {
let next_send_pos = self.shared.tail.lock().pos;
next_send_pos - self.next
}

/// Locks the next value if there is one.
fn recv_ref(
&mut self,
Expand Down

0 comments on commit 7aae066

Please sign in to comment.