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

util: add DelayQueue::try_remove #5052

Merged
merged 4 commits into from
Sep 28, 2022
Merged
Changes from 2 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
38 changes: 38 additions & 0 deletions tokio-util/src/time/delay_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,44 @@ impl<T> DelayQueue<T> {
}
}

/// Attempts to remove the item associated with `key` from the queue.
///
/// Removes the item associated with `key`, and returns it along with the
/// `Instant` at which it would have expired, if it exists.
///
/// Returns `None` if `key` is not in the queue.
///
/// # Examples
///
/// Basic usage
///
/// ```rust
/// use tokio_util::time::DelayQueue;
/// use std::time::Duration;
///
/// # #[tokio::main]
Darksonn marked this conversation as resolved.
Show resolved Hide resolved
/// # async fn main() {
/// let mut delay_queue = DelayQueue::new();
/// let key = delay_queue.insert("foo", Duration::from_secs(5));
///
/// // The item is in the queue, `try_remove` returns `Some(Expired("foo"))`.
/// let item = delay_queue.try_remove(&key);
/// assert_eq!(item.unwrap().into_inner(), "foo");
///
/// // The item is not in the queue anymore, `try_remove` returns `None`.
/// let item = delay_queue.try_remove(&key);
/// assert!(item.is_none());
/// # }
/// ```
#[track_caller]
Darksonn marked this conversation as resolved.
Show resolved Hide resolved
pub fn try_remove(&mut self, key: &Key) -> Option<Expired<T>> {
if self.slab.contains(key) {
Some(self.remove(key))
} else {
None
}
}

/// Sets the delay of the item associated with `key` to expire at `when`.
///
/// This function is identical to `reset` but takes an `Instant` instead of
Expand Down