Skip to content

Commit 969cef0

Browse files
jxhorJakub Horak
authored andcommitted
Add len, is_empty methods for UnboundedSender
- add `len`, `is_empty` methods to inspect how many messages are enqueued in the message queue. - add test for `len` and `is_empty`
1 parent 28cb6a2 commit 969cef0

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

futures-channel/src/mpsc/mod.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -836,6 +836,20 @@ impl<T> UnboundedSender<T> {
836836
let ptr = self.0.as_ref().map(|inner| inner.ptr());
837837
ptr.hash(hasher);
838838
}
839+
840+
/// Return the number of messages in the queue or 0 if channel is disconnected.
841+
pub fn len(&self) -> usize {
842+
if let Some(sender) = &self.0 {
843+
decode_state(sender.inner.state.load(SeqCst)).num_messages
844+
} else {
845+
0
846+
}
847+
}
848+
849+
/// Return false is channel has no queued messages, true otherwise.
850+
pub fn is_empty(&self) -> bool {
851+
self.len() == 0
852+
}
839853
}
840854

841855
impl<T> Clone for Sender<T> {

futures-channel/tests/mpsc.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -630,3 +630,26 @@ fn send_backpressure_multi_senders() {
630630
let item = block_on(rx.next()).unwrap();
631631
assert_eq!(item, 2);
632632
}
633+
634+
/// Test that empty channel has zero length and that non-empty channel has length equal to number
635+
/// of enqueued items
636+
#[test]
637+
fn unbounded_len() {
638+
let (tx, mut rx) = mpsc::unbounded();
639+
assert_eq!(tx.len(), 0);
640+
assert!(tx.is_empty());
641+
tx.unbounded_send(1).unwrap();
642+
assert_eq!(tx.len(), 1);
643+
assert!(!tx.is_empty());
644+
tx.unbounded_send(2).unwrap();
645+
assert_eq!(tx.len(), 2);
646+
assert!(!tx.is_empty());
647+
let item = block_on(rx.next()).unwrap();
648+
assert_eq!(item, 1);
649+
assert_eq!(tx.len(), 1);
650+
assert!(!tx.is_empty());
651+
let item = block_on(rx.next()).unwrap();
652+
assert_eq!(item, 2);
653+
assert_eq!(tx.len(), 0);
654+
assert!(tx.is_empty());
655+
}

0 commit comments

Comments
 (0)