@@ -992,6 +992,51 @@ impl<T> Receiver<T> {
992
992
self . inner . is_none ( )
993
993
}
994
994
995
+ /// Checks if a channel is empty.
996
+ ///
997
+ /// This method returns `true` if the channel has no messages.
998
+ ///
999
+ /// # Examples
1000
+ ///
1001
+ /// ```
1002
+ /// use tokio::sync::oneshot;
1003
+ ///
1004
+ /// #[tokio::main]
1005
+ /// async fn main() {
1006
+ /// let (tx, mut rx) = oneshot::channel();
1007
+ /// assert!(rx.is_empty());
1008
+ ///
1009
+ /// tx.send(0).unwrap();
1010
+ /// assert!(!rx.is_empty());
1011
+ ///
1012
+ /// let _ = (&mut rx).await;
1013
+ /// assert!(rx.is_empty());
1014
+ /// }
1015
+ /// ```
1016
+ pub fn is_empty ( & self ) -> bool {
1017
+ if let Some ( inner) = self . inner . as_ref ( ) {
1018
+ let state = State :: load ( & inner. state , Acquire ) ;
1019
+ if state. is_complete ( ) {
1020
+ // SAFETY: If `state.is_complete()` returns true, then the
1021
+ // `VALUE_SENT` bit has been set and the sender side of the
1022
+ // channel will no longer attempt to access the inner
1023
+ // `UnsafeCell`. Therefore, it is now safe for us to access the
1024
+ // cell.
1025
+ //
1026
+ // The channel is empty if it does not have a value.
1027
+ unsafe { !inner. has_value ( ) }
1028
+ } else if state. is_closed ( ) {
1029
+ // The receiver closed the channel...
1030
+ true
1031
+ } else {
1032
+ // No value has been sent yet.
1033
+ true
1034
+ }
1035
+ } else {
1036
+ true
1037
+ }
1038
+ }
1039
+
995
1040
/// Attempts to receive a value.
996
1041
///
997
1042
/// If a pending value exists in the channel, it is returned. If no value
@@ -1294,6 +1339,19 @@ impl<T> Inner<T> {
1294
1339
unsafe fn consume_value ( & self ) -> Option < T > {
1295
1340
self . value . with_mut ( |ptr| ( * ptr) . take ( ) )
1296
1341
}
1342
+
1343
+ /// Returns true if there is a value. This function does not check `state`.
1344
+ ///
1345
+ /// # Safety
1346
+ ///
1347
+ /// Calling this method concurrently on multiple threads will result in a
1348
+ /// data race. The `VALUE_SENT` state bit is used to ensure that only the
1349
+ /// sender *or* the receiver will call this method at a given point in time.
1350
+ /// If `VALUE_SENT` is not set, then only the sender may call this method;
1351
+ /// if it is set, then only the receiver may call this method.
1352
+ unsafe fn has_value ( & self ) -> bool {
1353
+ self . value . with ( |ptr| ( * ptr) . is_some ( ) )
1354
+ }
1297
1355
}
1298
1356
1299
1357
unsafe impl < T : Send > Send for Inner < T > { }
0 commit comments