Skip to content

Commit a59f884

Browse files
committed
review: reference is_terminated() in documentation
NB: this commit means that this branch (tokio-rs#7153) is dependent upon interfaces proposed in (tokio-rs#7152). pr tokio-rs#7152 proposes a `is_terminated()` method for the oneshot channel's receiver. that is the proper method to use to check whether or not it is safe to poll a oneshot receiver as a future. this commit adds a note cross-referencing this method to the documentation of `is_empty()`, to help mitigate misuse. this method only reports whether a value is currently waiting in the channel; a channel that has already received and yielded a value to its receiver is also empty, but would panic when polled. Signed-off-by: katelyn martin <[email protected]>
1 parent 9bb5b6c commit a59f884

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

tokio/src/sync/oneshot.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -993,8 +993,14 @@ impl<T> Receiver<T> {
993993
///
994994
/// This method returns `true` if the channel has no messages.
995995
///
996+
/// It is not necessarily safe to poll an empty receiver, which may have
997+
/// already yielded a value. Use [`is_terminated()`][Self::is_terminated]
998+
/// to check whether or not a receiver can be safely polled, instead.
999+
///
9961000
/// # Examples
9971001
///
1002+
/// Sending a value.
1003+
///
9981004
/// ```
9991005
/// use tokio::sync::oneshot;
10001006
///
@@ -1010,6 +1016,42 @@ impl<T> Receiver<T> {
10101016
/// assert!(rx.is_empty());
10111017
/// }
10121018
/// ```
1019+
///
1020+
/// Dropping the sender.
1021+
///
1022+
/// ```
1023+
/// use tokio::sync::oneshot;
1024+
///
1025+
/// #[tokio::main]
1026+
/// async fn main() {
1027+
/// let (tx, mut rx) = oneshot::channel::<()>();
1028+
///
1029+
/// // A channel is empty if the sender is dropped.
1030+
/// drop(tx);
1031+
/// assert!(rx.is_empty());
1032+
///
1033+
/// // A closed channel still yields an error, however.
1034+
/// (&mut rx).await.expect_err("should yield an error");
1035+
/// assert!(rx.is_empty());
1036+
/// }
1037+
/// ```
1038+
///
1039+
/// Terminated channels are empty.
1040+
///
1041+
/// ```should_panic
1042+
/// use tokio::sync::oneshot;
1043+
///
1044+
/// #[tokio::main]
1045+
/// async fn main() {
1046+
/// let (tx, mut rx) = oneshot::channel();
1047+
/// tx.send(0).unwrap();
1048+
/// let _ = (&mut rx).await;
1049+
///
1050+
/// // NB: an empty channel is not necessarily safe to poll!
1051+
/// assert!(rx.is_empty());
1052+
/// let _ = (&mut rx).await;
1053+
/// }
1054+
/// ```
10131055
pub fn is_empty(&self) -> bool {
10141056
let Some(inner) = self.inner.as_ref() else {
10151057
// The channel has already terminated.

0 commit comments

Comments
 (0)