File tree Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -836,6 +836,20 @@ impl<T> UnboundedSender<T> {
836
836
let ptr = self . 0 . as_ref ( ) . map ( |inner| inner. ptr ( ) ) ;
837
837
ptr. hash ( hasher) ;
838
838
}
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
+ }
839
853
}
840
854
841
855
impl < T > Clone for Sender < T > {
Original file line number Diff line number Diff line change @@ -630,3 +630,26 @@ fn send_backpressure_multi_senders() {
630
630
let item = block_on ( rx. next ( ) ) . unwrap ( ) ;
631
631
assert_eq ! ( item, 2 ) ;
632
632
}
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
+ }
You can’t perform that action at this time.
0 commit comments