Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sync: make watch::send_replace infallible #4195

Merged
merged 4 commits into from Oct 27, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 10 additions & 8 deletions tokio/src/sync/watch.rs
Expand Up @@ -428,14 +428,21 @@ impl<T> Sender<T> {
/// This method fails if the channel has been closed, which happens when
/// every receiver has been dropped.
pub fn send(&self, value: T) -> Result<(), error::SendError<T>> {
self.send_replace(value)?;
// This is pretty much only useful as a hint anyway, so synchronization isn't critical.
if 0 == self.receiver_count() {
return Err(error::SendError(value));
}

self.send_replace(value);
Ok(())
}

/// Sends a new value via the channel, notifying all receivers and returning
/// the previous value in the channel.
///
/// This can be useful for reusing the buffers inside a watched value.
/// Additionally, this method permits sending values even when there are no
/// receivers.
///
/// # Examples
///
Expand All @@ -446,12 +453,7 @@ impl<T> Sender<T> {
/// assert_eq!(tx.send_replace(2).unwrap(), 1);
/// assert_eq!(tx.send_replace(3).unwrap(), 2);
Darksonn marked this conversation as resolved.
Show resolved Hide resolved
/// ```
pub fn send_replace(&self, value: T) -> Result<T, error::SendError<T>> {
// This is pretty much only useful as a hint anyway, so synchronization isn't critical.
if 0 == self.receiver_count() {
return Err(error::SendError(value));
}

pub fn send_replace(&self, value: T) -> T {
let old = {
// Acquire the write lock and update the value.
let mut lock = self.shared.value.write().unwrap();
Expand All @@ -472,7 +474,7 @@ impl<T> Sender<T> {
// Notify all watchers
self.shared.notify_rx.notify_waiters();

Ok(old)
old
}

/// Returns a reference to the most recently sent value
Expand Down