Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions tokio/src/sync/oneshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -931,6 +931,64 @@ impl<T> Receiver<T> {
}
}

/// Checks if the channel has been closed.
///
/// This happens when the corresponding sender is either dropped or sends a
/// value, or when this receiver has closed the channel.
///
/// # Examples
///
/// Sending a value.
///
/// ```
/// use tokio::sync::oneshot;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, rx) = oneshot::channel();
/// assert!(!rx.is_closed());
///
/// tx.send(0).unwrap();
/// assert!(rx.is_closed());
/// }
/// ```
///
/// Dropping the sender.
///
/// ```
/// use tokio::sync::oneshot;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, rx) = oneshot::channel::<()>();
/// assert!(!rx.is_closed());
/// drop(tx);
/// assert!(rx.is_closed());
/// }
/// ```
///
/// Closing the receiver.
///
/// ```
/// use tokio::sync::oneshot;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx) = oneshot::channel::<()>();
/// assert!(!rx.is_closed());
/// rx.close();
/// assert!(rx.is_closed());
/// }
/// ```
pub fn is_closed(&self) -> bool {
if let Some(inner) = self.inner.as_ref() {
let state = State::load(&inner.state, Acquire);
state.is_closed() || state.is_complete()
} else {
true
}
}

/// Attempts to receive a value.
///
/// If a pending value exists in the channel, it is returned. If no value
Expand Down
30 changes: 30 additions & 0 deletions tokio/tests/sync_oneshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,33 @@ fn sender_changes_task() {

assert_ready!(task2.enter(|cx, _| tx.poll_closed(cx)));
}

#[test]
fn receiver_is_closed_send() {
let (tx, rx) = oneshot::channel::<i32>();
assert!(
!rx.is_closed(),
"channel is NOT closed before value is sent"
);
tx.send(17).unwrap();
assert!(rx.is_closed(), "channel IS closed after value is sent");
}

#[test]
fn receiver_is_closed_drop() {
let (tx, rx) = oneshot::channel::<i32>();
assert!(
!rx.is_closed(),
"channel is NOT closed before sender is dropped"
);
drop(tx);
assert!(rx.is_closed(), "channel IS closed after sender is dropped");
}

#[test]
fn receiver_is_closed_rx_close() {
let (_tx, mut rx) = oneshot::channel::<i32>();
assert!(!rx.is_closed());
rx.close();
assert!(rx.is_closed());
}