@@ -931,6 +931,51 @@ impl<T> Receiver<T> {
931
931
}
932
932
}
933
933
934
+ /// Checks if a channel is empty.
935
+ ///
936
+ /// This method returns `true` if the channel has no messages.
937
+ ///
938
+ /// # Examples
939
+ ///
940
+ /// ```
941
+ /// use tokio::sync::oneshot;
942
+ ///
943
+ /// #[tokio::main]
944
+ /// async fn main() {
945
+ /// let (tx, mut rx) = oneshot::channel();
946
+ /// assert!(rx.is_empty());
947
+ ///
948
+ /// tx.send(0).unwrap();
949
+ /// assert!(!rx.is_empty());
950
+ ///
951
+ /// let _ = (&mut rx).await;
952
+ /// assert!(rx.is_empty());
953
+ /// }
954
+ /// ```
955
+ pub fn is_empty ( & self ) -> bool {
956
+ if let Some ( inner) = self . inner . as_ref ( ) {
957
+ let state = State :: load ( & inner. state , Acquire ) ;
958
+ if state. is_complete ( ) {
959
+ // SAFETY: If `state.is_complete()` returns true, then the
960
+ // `VALUE_SENT` bit has been set and the sender side of the
961
+ // channel will no longer attempt to access the inner
962
+ // `UnsafeCell`. Therefore, it is now safe for us to access the
963
+ // cell.
964
+ //
965
+ // The channel is empty if it does not have a value.
966
+ unsafe { !inner. has_value ( ) }
967
+ } else if state. is_closed ( ) {
968
+ // The receiver closed the channel...
969
+ true
970
+ } else {
971
+ // No value has been sent yet.
972
+ true
973
+ }
974
+ } else {
975
+ true
976
+ }
977
+ }
978
+
934
979
/// Attempts to receive a value.
935
980
///
936
981
/// If a pending value exists in the channel, it is returned. If no value
@@ -1233,6 +1278,19 @@ impl<T> Inner<T> {
1233
1278
unsafe fn consume_value ( & self ) -> Option < T > {
1234
1279
self . value . with_mut ( |ptr| ( * ptr) . take ( ) )
1235
1280
}
1281
+
1282
+ /// Returns true if there is a value. This function does not check `state`.
1283
+ ///
1284
+ /// # Safety
1285
+ ///
1286
+ /// Calling this method concurrently on multiple threads will result in a
1287
+ /// data race. The `VALUE_SENT` state bit is used to ensure that only the
1288
+ /// sender *or* the receiver will call this method at a given point in time.
1289
+ /// If `VALUE_SENT` is not set, then only the sender may call this method;
1290
+ /// if it is set, then only the receiver may call this method.
1291
+ unsafe fn has_value ( & self ) -> bool {
1292
+ self . value . with ( |ptr| ( * ptr) . is_some ( ) )
1293
+ }
1236
1294
}
1237
1295
1238
1296
unsafe impl < T : Send > Send for Inner < T > { }
0 commit comments