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