Skip to content

Commit

Permalink
Merge branch 'add-is_cosed_method'
Browse files Browse the repository at this point in the history
  • Loading branch information
faern committed May 23, 2024
2 parents a1e58a1 + 88e1878 commit 25ed7d4
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.


## [Unreleased]
### Added
* Add `is_closed` method to the `Sender`.


## [0.1.6] - 2023-09-14
Expand Down
15 changes: 15 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,21 @@ impl<T> Sender<T> {
}
}

/// Returns true if the associated [`Receiver`] has been dropped.
///
/// If true is returned, a future call to send is guaranteed to return an error.
pub fn is_closed(&self) -> bool {
// SAFETY: The channel exists on the heap for the entire duration of this method and we
// only ever acquire shared references to it. Note that if the receiver disconnects it
// does not free the channel.
let channel = unsafe { self.channel_ptr.as_ref() };

// ORDERING: We *chose* a Relaxed ordering here as it sufficient to
// enforce the method's contract: "if true is returned, a future
// call to send is guaranteed to return an error."
channel.state.load(Relaxed) == DISCONNECTED
}

/// Consumes the Sender, returning a raw pointer to the channel on the heap.
///
/// This is intended to simplify using oneshot channels with some FFI code. The only safe thing
Expand Down
10 changes: 10 additions & 0 deletions tests/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,3 +343,13 @@ fn send_error_drops_message_correctly_on_into_inner() {
assert_eq!(counter.count(), 1);
});
}

#[test]
fn dropping_receiver_disconnects_sender() {
maybe_loom_model(|| {
let (sender, receiver) = oneshot::channel::<()>();
assert!(!sender.is_closed());
drop(receiver);
assert!(sender.is_closed());
});
}

0 comments on commit 25ed7d4

Please sign in to comment.