Skip to content

Commit

Permalink
Add len, is_empty methods for UnboundedSender (#2750)
Browse files Browse the repository at this point in the history
- add `len`, `is_empty` methods to inspect how many messages are
  enqueued in the message queue.
- add test for `len` and `is_empty`

Co-authored-by: Jakub Horak <jakub.horak@ibawizard.net>
  • Loading branch information
2 people authored and taiki-e committed Sep 6, 2023
1 parent 36581d6 commit 247e1f0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
14 changes: 14 additions & 0 deletions futures-channel/src/mpsc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -842,6 +842,20 @@ impl<T> UnboundedSender<T> {
let ptr = self.0.as_ref().map(|inner| inner.ptr());
ptr.hash(hasher);
}

/// Return the number of messages in the queue or 0 if channel is disconnected.
pub fn len(&self) -> usize {
if let Some(sender) = &self.0 {
decode_state(sender.inner.state.load(SeqCst)).num_messages
} else {
0
}
}

/// Return false is channel has no queued messages, true otherwise.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}

impl<T> Clone for Sender<T> {
Expand Down
23 changes: 23 additions & 0 deletions futures-channel/tests/mpsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -632,3 +632,26 @@ fn send_backpressure_multi_senders() {
let item = block_on(rx.next()).unwrap();
assert_eq!(item, 2);
}

/// Test that empty channel has zero length and that non-empty channel has length equal to number
/// of enqueued items
#[test]
fn unbounded_len() {
let (tx, mut rx) = mpsc::unbounded();
assert_eq!(tx.len(), 0);
assert!(tx.is_empty());
tx.unbounded_send(1).unwrap();
assert_eq!(tx.len(), 1);
assert!(!tx.is_empty());
tx.unbounded_send(2).unwrap();
assert_eq!(tx.len(), 2);
assert!(!tx.is_empty());
let item = block_on(rx.next()).unwrap();
assert_eq!(item, 1);
assert_eq!(tx.len(), 1);
assert!(!tx.is_empty());
let item = block_on(rx.next()).unwrap();
assert_eq!(item, 2);
assert_eq!(tx.len(), 0);
assert!(tx.is_empty());
}

0 comments on commit 247e1f0

Please sign in to comment.