timer_kit/delay_queue.rs
1//! A queue of delayed elements. This is ported from `tokio_util::time::delay_queue`.
2//!
3//! See [`DelayQueue`] for more details.
4//!
5//! [`DelayQueue`]: struct@DelayQueue
6
7use futures_util::ready;
8
9use core::ops::{Index, IndexMut};
10use slab::Slab;
11use std::cmp;
12use std::collections::HashMap;
13use std::convert::From;
14use std::fmt;
15use std::fmt::Debug;
16use std::future::Future;
17use std::marker::PhantomData;
18use std::pin::Pin;
19use std::task::{self, Poll, Waker};
20
21use crate::wheel::{self, Wheel};
22use crate::{Duration, Instant, Sleep, Delay};
23
24/// A queue of delayed elements. This is ported from `tokio_util::time::delay_queue`.
25///
26/// Once an element is inserted into the `DelayQueue`, it is yielded once the
27/// specified deadline has been reached.
28///
29/// # Usage
30///
31/// Elements are inserted into `DelayQueue` using the [`insert`] or
32/// [`insert_at`] methods. A deadline is provided with the item and a [`Key`] is
33/// returned. The key is used to remove the entry or to change the deadline at
34/// which it should be yielded back.
35///
36/// Once delays have been configured, the `DelayQueue` is used via its
37/// [`Stream`] implementation. [`poll_expired`] is called. If an entry has reached its
38/// deadline, it is returned. If not, `Poll::Pending` is returned indicating that the
39/// current task will be notified once the deadline has been reached.
40///
41/// # `Stream` implementation
42///
43/// Items are retrieved from the queue via [`DelayQueue::poll_expired`]. If no delays have
44/// expired, no items are returned. In this case, `Poll::Pending` is returned and the
45/// current task is registered to be notified once the next item's delay has
46/// expired.
47///
48/// If no items are in the queue, i.e. `is_empty()` returns `true`, then `poll`
49/// returns `Poll::Ready(None)`. This indicates that the stream has reached an end.
50/// However, if a new item is inserted *after*, `poll` will once again start
51/// returning items or `Poll::Pending`.
52///
53/// Items are returned ordered by their expirations. Items that are configured
54/// to expire first will be returned first. There are no ordering guarantees
55/// for items configured to expire at the same instant. Also note that delays are
56/// rounded to the closest millisecond.
57///
58/// # Implementation
59///
60/// The [`DelayQueue`] is backed by a separate instance of a timer wheel similar to that used internally
61/// by Tokio's standalone timer utilities such as [`sleep`]. Because of this, it offers the same
62/// performance and scalability benefits.
63///
64/// State associated with each entry is stored in a [`slab`]. This amortizes the cost of allocation,
65/// and allows reuse of the memory allocated for expired entires.
66///
67/// Capacity can be checked using [`capacity`] and allocated preemptively by using
68/// the [`reserve`] method.
69///
70/// # Usage
71///
72/// Using `DelayQueue` to manage cache entries.
73///
74/// ```rust,no_run
75/// // TODO: add example
76/// ```
77///
78/// [`insert`]: method@Self::insert
79/// [`insert_at`]: method@Self::insert_at
80/// [`Key`]: struct@Key
81/// [`Stream`]: https://docs.rs/futures/0.1/futures/stream/trait.Stream.html
82/// [`poll_expired`]: method@Self::poll_expired
83/// [`Stream::poll_expired`]: method@Self::poll_expired
84/// [`DelayQueue`]: struct@DelayQueue
85/// [`sleep`]: fn@tokio::time::sleep
86/// [`slab`]: slab
87/// [`capacity`]: method@Self::capacity
88/// [`reserve`]: method@Self::reserve
89#[derive(Debug)]
90pub struct DelayQueue<D: Delay, T> {
91 /// Stores data associated with entries
92 slab: SlabStorage<T>,
93
94 /// Lookup structure tracking all delays in the queue
95 wheel: Wheel<Stack<T>>,
96
97 /// Delays that were inserted when already expired. These cannot be stored
98 /// in the wheel
99 expired: Stack<T>,
100
101 /// Delay expiring when the *first* item in the queue expires
102 delay: Option<Pin<Box<Sleep<D>>>>,
103
104 /// Wheel polling state
105 wheel_now: u64,
106
107 /// Instant at which the timer starts
108 start: D::Instant,
109
110 /// Waker that is invoked when we potentially need to reset the timer.
111 /// Because we lazily create the timer when the first entry is created, we
112 /// need to awaken any poller that polled us before that point.
113 waker: Option<Waker>,
114}
115
116#[derive(Default)]
117struct SlabStorage<T> {
118 inner: Slab<Data<T>>,
119
120 // A `compact` call requires a re-mapping of the `Key`s that were changed
121 // during the `compact` call of the `slab`. Since the keys that were given out
122 // cannot be changed retroactively we need to keep track of these re-mappings.
123 // The keys of `key_map` correspond to the old keys that were given out and
124 // the values to the `Key`s that were re-mapped by the `compact` call.
125 key_map: HashMap<Key, KeyInternal>,
126
127 // Index used to create new keys to hand out.
128 next_key_index: usize,
129
130 // Whether `compact` has been called, necessary in order to decide whether
131 // to include keys in `key_map`.
132 compact_called: bool,
133}
134
135impl<T> SlabStorage<T> {
136 pub(crate) fn with_capacity(capacity: usize) -> SlabStorage<T> {
137 SlabStorage {
138 inner: Slab::with_capacity(capacity),
139 key_map: HashMap::new(),
140 next_key_index: 0,
141 compact_called: false,
142 }
143 }
144
145 // Inserts data into the inner slab and re-maps keys if necessary
146 pub(crate) fn insert(&mut self, val: Data<T>) -> Key {
147 let mut key = KeyInternal::new(self.inner.insert(val));
148 let key_contained = self.key_map.contains_key(&key.into());
149
150 if key_contained {
151 // It's possible that a `compact` call creates capacity in `self.inner` in
152 // such a way that a `self.inner.insert` call creates a `key` which was
153 // previously given out during an `insert` call prior to the `compact` call.
154 // If `key` is contained in `self.key_map`, we have encountered this exact situation,
155 // We need to create a new key `key_to_give_out` and include the relation
156 // `key_to_give_out` -> `key` in `self.key_map`.
157 let key_to_give_out = self.create_new_key();
158 assert!(!self.key_map.contains_key(&key_to_give_out.into()));
159 self.key_map.insert(key_to_give_out.into(), key);
160 key = key_to_give_out;
161 } else if self.compact_called {
162 // Include an identity mapping in `self.key_map` in order to allow us to
163 // panic if a key that was handed out is removed more than once.
164 self.key_map.insert(key.into(), key);
165 }
166
167 key.into()
168 }
169
170 // Re-map the key in case compact was previously called.
171 // Note: Since we include identity mappings in key_map after compact was called,
172 // we have information about all keys that were handed out. In the case in which
173 // compact was called and we try to remove a Key that was previously removed
174 // we can detect invalid keys if no key is found in `key_map`. This is necessary
175 // in order to prevent situations in which a previously removed key
176 // corresponds to a re-mapped key internally and which would then be incorrectly
177 // removed from the slab.
178 //
179 // Example to illuminate this problem:
180 //
181 // Let's assume our `key_map` is {1 -> 2, 2 -> 1} and we call remove(1). If we
182 // were to remove 1 again, we would not find it inside `key_map` anymore.
183 // If we were to imply from this that no re-mapping was necessary, we would
184 // incorrectly remove 1 from `self.slab.inner`, which corresponds to the
185 // handed-out key 2.
186 pub(crate) fn remove(&mut self, key: &Key) -> Data<T> {
187 let remapped_key = if self.compact_called {
188 match self.key_map.remove(key) {
189 Some(key_internal) => key_internal,
190 None => panic!("invalid key"),
191 }
192 } else {
193 (*key).into()
194 };
195
196 self.inner.remove(remapped_key.index)
197 }
198
199 pub(crate) fn shrink_to_fit(&mut self) {
200 self.inner.shrink_to_fit();
201 self.key_map.shrink_to_fit();
202 }
203
204 pub(crate) fn compact(&mut self) {
205 if !self.compact_called {
206 for (key, _) in self.inner.iter() {
207 self.key_map.insert(Key::new(key), KeyInternal::new(key));
208 }
209 }
210
211 let mut remapping = HashMap::new();
212 self.inner.compact(|_, from, to| {
213 remapping.insert(from, to);
214 true
215 });
216
217 // At this point `key_map` contains a mapping for every element.
218 for internal_key in self.key_map.values_mut() {
219 if let Some(new_internal_key) = remapping.get(&internal_key.index) {
220 *internal_key = KeyInternal::new(*new_internal_key);
221 }
222 }
223
224 if self.key_map.capacity() > 2 * self.key_map.len() {
225 self.key_map.shrink_to_fit();
226 }
227
228 self.compact_called = true;
229 }
230
231 // Tries to re-map a `Key` that was given out to the user to its
232 // corresponding internal key.
233 fn remap_key(&self, key: &Key) -> Option<KeyInternal> {
234 let key_map = &self.key_map;
235 if self.compact_called {
236 key_map.get(key).copied()
237 } else {
238 Some((*key).into())
239 }
240 }
241
242 fn create_new_key(&mut self) -> KeyInternal {
243 while self.key_map.contains_key(&Key::new(self.next_key_index)) {
244 self.next_key_index = self.next_key_index.wrapping_add(1);
245 }
246
247 KeyInternal::new(self.next_key_index)
248 }
249
250 pub(crate) fn len(&self) -> usize {
251 self.inner.len()
252 }
253
254 pub(crate) fn capacity(&self) -> usize {
255 self.inner.capacity()
256 }
257
258 pub(crate) fn clear(&mut self) {
259 self.inner.clear();
260 self.key_map.clear();
261 self.compact_called = false;
262 }
263
264 pub(crate) fn reserve(&mut self, additional: usize) {
265 self.inner.reserve(additional);
266
267 if self.compact_called {
268 self.key_map.reserve(additional);
269 }
270 }
271
272 pub(crate) fn is_empty(&self) -> bool {
273 self.inner.is_empty()
274 }
275
276 pub(crate) fn contains(&self, key: &Key) -> bool {
277 let remapped_key = self.remap_key(key);
278
279 match remapped_key {
280 Some(internal_key) => self.inner.contains(internal_key.index),
281 None => false,
282 }
283 }
284}
285
286impl<T> fmt::Debug for SlabStorage<T>
287where
288 T: fmt::Debug,
289{
290 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
291 if fmt.alternate() {
292 fmt.debug_map().entries(self.inner.iter()).finish()
293 } else {
294 fmt.debug_struct("Slab")
295 .field("len", &self.len())
296 .field("cap", &self.capacity())
297 .finish()
298 }
299 }
300}
301
302impl<T> Index<Key> for SlabStorage<T> {
303 type Output = Data<T>;
304
305 fn index(&self, key: Key) -> &Self::Output {
306 let remapped_key = self.remap_key(&key);
307
308 match remapped_key {
309 Some(internal_key) => &self.inner[internal_key.index],
310 None => panic!("Invalid index {}", key.index),
311 }
312 }
313}
314
315impl<T> IndexMut<Key> for SlabStorage<T> {
316 fn index_mut(&mut self, key: Key) -> &mut Data<T> {
317 let remapped_key = self.remap_key(&key);
318
319 match remapped_key {
320 Some(internal_key) => &mut self.inner[internal_key.index],
321 None => panic!("Invalid index {}", key.index),
322 }
323 }
324}
325
326/// An entry in `DelayQueue` that has expired and been removed.
327///
328/// Values are returned by [`DelayQueue::poll_expired`].
329///
330/// [`DelayQueue::poll_expired`]: method@DelayQueue::poll_expired
331#[derive(Debug)]
332pub struct Expired<T, I: Instant> {
333 /// The data stored in the queue
334 data: T,
335
336 /// The expiration time
337 deadline: I,
338
339 /// The key associated with the entry
340 key: Key,
341}
342
343/// Token to a value stored in a `DelayQueue`.
344///
345/// Instances of `Key` are returned by [`DelayQueue::insert`]. See [`DelayQueue`]
346/// documentation for more details.
347///
348/// [`DelayQueue`]: struct@DelayQueue
349/// [`DelayQueue::insert`]: method@DelayQueue::insert
350#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
351pub struct Key {
352 index: usize,
353}
354
355// Whereas `Key` is given out to users that use `DelayQueue`, internally we use
356// `KeyInternal` as the key type in order to make the logic of mapping between keys
357// as a result of `compact` calls clearer.
358#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
359struct KeyInternal {
360 index: usize,
361}
362
363#[derive(Debug)]
364struct Stack<T> {
365 /// Head of the stack
366 head: Option<Key>,
367 _p: PhantomData<fn() -> T>,
368}
369
370#[derive(Debug)]
371struct Data<T> {
372 /// The data being stored in the queue and will be returned at the requested
373 /// instant.
374 inner: T,
375
376 /// The instant at which the item is returned.
377 when: u64,
378
379 /// Set to true when stored in the `expired` queue
380 expired: bool,
381
382 /// Next entry in the stack
383 next: Option<Key>,
384
385 /// Previous entry in the stack
386 prev: Option<Key>,
387}
388
389/// Maximum number of entries the queue can handle
390const MAX_ENTRIES: usize = (1 << 30) - 1;
391
392impl<D, T> DelayQueue<D, T>
393where
394 D: Delay,
395 D::Instant: Unpin,
396{
397 /// Creates a new, empty, `DelayQueue`.
398 ///
399 /// The queue will not allocate storage until items are inserted into it.
400 ///
401 /// # Examples
402 ///
403 /// ```rust
404 /// # use tokio_util::time::DelayQueue;
405 /// let delay_queue: DelayQueue<u32> = DelayQueue::new();
406 /// ```
407 pub fn new() -> DelayQueue<D, T> {
408 DelayQueue::with_capacity(0)
409 }
410
411 /// Creates a new, empty, `DelayQueue` with the specified capacity.
412 ///
413 /// The queue will be able to hold at least `capacity` elements without
414 /// reallocating. If `capacity` is 0, the queue will not allocate for
415 /// storage.
416 ///
417 /// # Examples
418 ///
419 /// ```rust,ignore
420 /// # use tokio_util::time::DelayQueue;
421 /// # use std::time::Duration;
422 ///
423 /// # #[tokio::main]
424 /// # async fn main() {
425 /// let mut delay_queue = DelayQueue::with_capacity(10);
426 ///
427 /// // These insertions are done without further allocation
428 /// for i in 0..10 {
429 /// delay_queue.insert(i, Duration::from_secs(i));
430 /// }
431 ///
432 /// // This will make the queue allocate additional storage
433 /// delay_queue.insert(11, Duration::from_secs(11));
434 /// # }
435 /// ```
436 pub fn with_capacity(capacity: usize) -> DelayQueue<D, T> {
437 DelayQueue {
438 wheel: Wheel::new(),
439 slab: SlabStorage::with_capacity(capacity),
440 expired: Stack::default(),
441 delay: None,
442 wheel_now: 0,
443 start: Instant::now(),
444 waker: None,
445 }
446 }
447
448 /// Inserts `value` into the queue set to expire at a specific instant in
449 /// time.
450 ///
451 /// This function is identical to `insert`, but takes an `Instant` instead
452 /// of a `Duration`.
453 ///
454 /// `value` is stored in the queue until `when` is reached. At which point,
455 /// `value` will be returned from [`poll_expired`]. If `when` has already been
456 /// reached, then `value` is immediately made available to poll.
457 ///
458 /// The return value represents the insertion and is used as an argument to
459 /// [`remove`] and [`reset`]. Note that [`Key`] is a token and is reused once
460 /// `value` is removed from the queue either by calling [`poll_expired`] after
461 /// `when` is reached or by calling [`remove`]. At this point, the caller
462 /// must take care to not use the returned [`Key`] again as it may reference
463 /// a different item in the queue.
464 ///
465 /// See [type] level documentation for more details.
466 ///
467 /// # Panics
468 ///
469 /// This function panics if `when` is too far in the future.
470 ///
471 /// # Examples
472 ///
473 /// Basic usage
474 ///
475 /// ```rust,ignore
476 /// use tokio::time::{Duration, Instant};
477 /// use tokio_util::time::DelayQueue;
478 ///
479 /// # #[tokio::main]
480 /// # async fn main() {
481 /// let mut delay_queue = DelayQueue::new();
482 /// let key = delay_queue.insert_at(
483 /// "foo", Instant::now() + Duration::from_secs(5));
484 ///
485 /// // Remove the entry
486 /// let item = delay_queue.remove(&key);
487 /// assert_eq!(*item.get_ref(), "foo");
488 /// # }
489 /// ```
490 ///
491 /// [`poll_expired`]: method@Self::poll_expired
492 /// [`remove`]: method@Self::remove
493 /// [`reset`]: method@Self::reset
494 /// [`Key`]: struct@Key
495 /// [type]: #
496 #[track_caller]
497 pub fn insert_at(&mut self, value: T, when: D::Instant) -> Key {
498 assert!(self.slab.len() < MAX_ENTRIES, "max entries exceeded");
499
500 // Normalize the deadline. Values cannot be set to expire in the past.
501 let when = self.normalize_deadline(when);
502
503 // Insert the value in the store
504 let key = self.slab.insert(Data {
505 inner: value,
506 when,
507 expired: false,
508 next: None,
509 prev: None,
510 });
511
512 self.insert_idx(when, key);
513
514 // Set a new delay if the current's deadline is later than the one of the new item
515 let should_set_delay = if let Some(ref delay) = self.delay {
516 let current_exp = self.normalize_deadline(delay.deadline());
517 current_exp > when
518 } else {
519 true
520 };
521
522 if should_set_delay {
523 if let Some(waker) = self.waker.take() {
524 waker.wake();
525 }
526
527 let delay_time = self.start + Duration::from_millis(when);
528 if let Some(ref mut delay) = &mut self.delay {
529 delay.as_mut().reset(delay_time);
530 } else {
531 let delay = Sleep::new_until(delay_time);
532 self.delay = Some(Box::pin(delay));
533 }
534 }
535
536 key
537 }
538
539 /// Attempts to pull out the next value of the delay queue, registering the
540 /// current task for wakeup if the value is not yet available, and returning
541 /// `None` if the queue is exhausted.
542 pub fn poll_expired(&mut self, cx: &mut task::Context<'_>) -> Poll<Option<Expired<T, D::Instant>>> {
543 if !self
544 .waker
545 .as_ref()
546 .map(|w| w.will_wake(cx.waker()))
547 .unwrap_or(false)
548 {
549 self.waker = Some(cx.waker().clone());
550 }
551
552 let item = ready!(self.poll_idx(cx));
553 Poll::Ready(item.map(|key| {
554 let data = self.slab.remove(&key);
555 debug_assert!(data.next.is_none());
556 debug_assert!(data.prev.is_none());
557
558 Expired {
559 key,
560 data: data.inner,
561 deadline: self.start + Duration::from_millis(data.when),
562 }
563 }))
564 }
565
566 /// Inserts `value` into the queue set to expire after the requested duration
567 /// elapses.
568 ///
569 /// This function is identical to `insert_at`, but takes a `Duration`
570 /// instead of an `Instant`.
571 ///
572 /// `value` is stored in the queue until `timeout` duration has
573 /// elapsed after `insert` was called. At that point, `value` will
574 /// be returned from [`poll_expired`]. If `timeout` is a `Duration` of
575 /// zero, then `value` is immediately made available to poll.
576 ///
577 /// The return value represents the insertion and is used as an
578 /// argument to [`remove`] and [`reset`]. Note that [`Key`] is a
579 /// token and is reused once `value` is removed from the queue
580 /// either by calling [`poll_expired`] after `timeout` has elapsed
581 /// or by calling [`remove`]. At this point, the caller must not
582 /// use the returned [`Key`] again as it may reference a different
583 /// item in the queue.
584 ///
585 /// See [type] level documentation for more details.
586 ///
587 /// # Panics
588 ///
589 /// This function panics if `timeout` is greater than the maximum
590 /// duration supported by the timer in the current `Runtime`.
591 ///
592 /// # Examples
593 ///
594 /// Basic usage
595 ///
596 /// ```rust,ignore
597 /// use tokio_util::time::DelayQueue;
598 /// use std::time::Duration;
599 ///
600 /// # #[tokio::main]
601 /// # async fn main() {
602 /// let mut delay_queue = DelayQueue::new();
603 /// let key = delay_queue.insert("foo", Duration::from_secs(5));
604 ///
605 /// // Remove the entry
606 /// let item = delay_queue.remove(&key);
607 /// assert_eq!(*item.get_ref(), "foo");
608 /// # }
609 /// ```
610 ///
611 /// [`poll_expired`]: method@Self::poll_expired
612 /// [`remove`]: method@Self::remove
613 /// [`reset`]: method@Self::reset
614 /// [`Key`]: struct@Key
615 /// [type]: #
616 #[track_caller]
617 pub fn insert(&mut self, value: T, timeout: Duration) -> Key {
618 self.insert_at(value, D::Instant::now() + timeout)
619 }
620
621 #[track_caller]
622 fn insert_idx(&mut self, when: u64, key: Key) {
623 use self::wheel::{InsertError, Stack};
624
625 // Register the deadline with the timer wheel
626 match self.wheel.insert(when, key, &mut self.slab) {
627 Ok(_) => {}
628 Err((_, InsertError::Elapsed)) => {
629 self.slab[key].expired = true;
630 // The delay is already expired, store it in the expired queue
631 self.expired.push(key, &mut self.slab);
632 }
633 Err((_, err)) => panic!("invalid deadline; err={:?}", err),
634 }
635 }
636
637 /// Removes the key from the expired queue or the timer wheel
638 /// depending on its expiration status.
639 ///
640 /// # Panics
641 ///
642 /// Panics if the key is not contained in the expired queue or the wheel.
643 #[track_caller]
644 fn remove_key(&mut self, key: &Key) {
645 use crate::wheel::Stack;
646
647 // Special case the `expired` queue
648 if self.slab[*key].expired {
649 self.expired.remove(key, &mut self.slab);
650 } else {
651 self.wheel.remove(key, &mut self.slab);
652 }
653 }
654
655 /// Removes the item associated with `key` from the queue.
656 ///
657 /// There must be an item associated with `key`. The function returns the
658 /// removed item as well as the `Instant` at which it will the delay will
659 /// have expired.
660 ///
661 /// # Panics
662 ///
663 /// The function panics if `key` is not contained by the queue.
664 ///
665 /// # Examples
666 ///
667 /// Basic usage
668 ///
669 /// ```rust,ignore
670 /// use tokio_util::time::DelayQueue;
671 /// use std::time::Duration;
672 ///
673 /// # #[tokio::main]
674 /// # async fn main() {
675 /// let mut delay_queue = DelayQueue::new();
676 /// let key = delay_queue.insert("foo", Duration::from_secs(5));
677 ///
678 /// // Remove the entry
679 /// let item = delay_queue.remove(&key);
680 /// assert_eq!(*item.get_ref(), "foo");
681 /// # }
682 /// ```
683 #[track_caller]
684 pub fn remove(&mut self, key: &Key) -> Expired<T, D::Instant> {
685 let prev_deadline = self.next_deadline();
686
687 self.remove_key(key);
688 let data = self.slab.remove(key);
689
690 let next_deadline = self.next_deadline();
691 if prev_deadline != next_deadline {
692 match (next_deadline, &mut self.delay) {
693 (None, _) => self.delay = None,
694 (Some(deadline), Some(delay)) => delay.as_mut().reset(deadline),
695 (Some(deadline), None) => self.delay = Some(Box::pin(Sleep::new_until(deadline))),
696 }
697 }
698
699 Expired {
700 key: Key::new(key.index),
701 data: data.inner,
702 deadline: self.start + Duration::from_millis(data.when),
703 }
704 }
705
706 /// Attempts to remove the item associated with `key` from the queue.
707 ///
708 /// Removes the item associated with `key`, and returns it along with the
709 /// `Instant` at which it would have expired, if it exists.
710 ///
711 /// Returns `None` if `key` is not in the queue.
712 ///
713 /// # Examples
714 ///
715 /// Basic usage
716 ///
717 /// ```rust,ignore
718 /// use tokio_util::time::DelayQueue;
719 /// use std::time::Duration;
720 ///
721 /// # #[tokio::main(flavor = "current_thread")]
722 /// # async fn main() {
723 /// let mut delay_queue = DelayQueue::new();
724 /// let key = delay_queue.insert("foo", Duration::from_secs(5));
725 ///
726 /// // The item is in the queue, `try_remove` returns `Some(Expired("foo"))`.
727 /// let item = delay_queue.try_remove(&key);
728 /// assert_eq!(item.unwrap().into_inner(), "foo");
729 ///
730 /// // The item is not in the queue anymore, `try_remove` returns `None`.
731 /// let item = delay_queue.try_remove(&key);
732 /// assert!(item.is_none());
733 /// # }
734 /// ```
735 pub fn try_remove(&mut self, key: &Key) -> Option<Expired<T, D::Instant>> {
736 if self.slab.contains(key) {
737 Some(self.remove(key))
738 } else {
739 None
740 }
741 }
742
743 /// Sets the delay of the item associated with `key` to expire at `when`.
744 ///
745 /// This function is identical to `reset` but takes an `Instant` instead of
746 /// a `Duration`.
747 ///
748 /// The item remains in the queue but the delay is set to expire at `when`.
749 /// If `when` is in the past, then the item is immediately made available to
750 /// the caller.
751 ///
752 /// # Panics
753 ///
754 /// This function panics if `when` is too far in the future or if `key` is
755 /// not contained by the queue.
756 ///
757 /// # Examples
758 ///
759 /// Basic usage
760 ///
761 /// ```rust,ignore
762 /// use tokio::time::{Duration, Instant};
763 /// use tokio_util::time::DelayQueue;
764 ///
765 /// # #[tokio::main]
766 /// # async fn main() {
767 /// let mut delay_queue = DelayQueue::new();
768 /// let key = delay_queue.insert("foo", Duration::from_secs(5));
769 ///
770 /// // "foo" is scheduled to be returned in 5 seconds
771 ///
772 /// delay_queue.reset_at(&key, Instant::now() + Duration::from_secs(10));
773 ///
774 /// // "foo" is now scheduled to be returned in 10 seconds
775 /// # }
776 /// ```
777 #[track_caller]
778 pub fn reset_at(&mut self, key: &Key, when: D::Instant) {
779 self.remove_key(key);
780
781 // Normalize the deadline. Values cannot be set to expire in the past.
782 let when = self.normalize_deadline(when);
783
784 self.slab[*key].when = when;
785 self.slab[*key].expired = false;
786
787 self.insert_idx(when, *key);
788
789 let next_deadline = self.next_deadline();
790 if let (Some(ref mut delay), Some(deadline)) = (&mut self.delay, next_deadline) {
791 // This should awaken us if necessary (ie, if already expired)
792 delay.as_mut().reset(deadline);
793 }
794 }
795
796 /// Shrink the capacity of the slab, which `DelayQueue` uses internally for storage allocation.
797 /// This function is not guaranteed to, and in most cases, won't decrease the capacity of the slab
798 /// to the number of elements still contained in it, because elements cannot be moved to a different
799 /// index. To decrease the capacity to the size of the slab use [`compact`].
800 ///
801 /// This function can take O(n) time even when the capacity cannot be reduced or the allocation is
802 /// shrunk in place. Repeated calls run in O(1) though.
803 ///
804 /// [`compact`]: method@Self::compact
805 pub fn shrink_to_fit(&mut self) {
806 self.slab.shrink_to_fit();
807 }
808
809 /// Shrink the capacity of the slab, which `DelayQueue` uses internally for storage allocation,
810 /// to the number of elements that are contained in it.
811 ///
812 /// This methods runs in O(n).
813 ///
814 /// # Examples
815 ///
816 /// Basic usage
817 ///
818 /// ```rust,ignore
819 /// use tokio_util::time::DelayQueue;
820 /// use std::time::Duration;
821 ///
822 /// # #[tokio::main]
823 /// # async fn main() {
824 /// let mut delay_queue = DelayQueue::with_capacity(10);
825 ///
826 /// let key1 = delay_queue.insert(5, Duration::from_secs(5));
827 /// let key2 = delay_queue.insert(10, Duration::from_secs(10));
828 /// let key3 = delay_queue.insert(15, Duration::from_secs(15));
829 ///
830 /// delay_queue.remove(&key2);
831 ///
832 /// delay_queue.compact();
833 /// assert_eq!(delay_queue.capacity(), 2);
834 /// # }
835 /// ```
836 pub fn compact(&mut self) {
837 self.slab.compact();
838 }
839
840 /// Returns the next time to poll as determined by the wheel
841 fn next_deadline(&mut self) -> Option<D::Instant> {
842 self.wheel
843 .poll_at()
844 .map(|poll_at| self.start + Duration::from_millis(poll_at))
845 }
846
847 /// Sets the delay of the item associated with `key` to expire after
848 /// `timeout`.
849 ///
850 /// This function is identical to `reset_at` but takes a `Duration` instead
851 /// of an `Instant`.
852 ///
853 /// The item remains in the queue but the delay is set to expire after
854 /// `timeout`. If `timeout` is zero, then the item is immediately made
855 /// available to the caller.
856 ///
857 /// # Panics
858 ///
859 /// This function panics if `timeout` is greater than the maximum supported
860 /// duration or if `key` is not contained by the queue.
861 ///
862 /// # Examples
863 ///
864 /// Basic usage
865 ///
866 /// ```rust,ignore
867 /// use tokio_util::time::DelayQueue;
868 /// use std::time::Duration;
869 ///
870 /// # #[tokio::main]
871 /// # async fn main() {
872 /// let mut delay_queue = DelayQueue::new();
873 /// let key = delay_queue.insert("foo", Duration::from_secs(5));
874 ///
875 /// // "foo" is scheduled to be returned in 5 seconds
876 ///
877 /// delay_queue.reset(&key, Duration::from_secs(10));
878 ///
879 /// // "foo"is now scheduled to be returned in 10 seconds
880 /// # }
881 /// ```
882 #[track_caller]
883 pub fn reset(&mut self, key: &Key, timeout: Duration) {
884 self.reset_at(key, D::Instant::now() + timeout);
885 }
886
887 /// Clears the queue, removing all items.
888 ///
889 /// After calling `clear`, [`poll_expired`] will return `Ok(Ready(None))`.
890 ///
891 /// Note that this method has no effect on the allocated capacity.
892 ///
893 /// [`poll_expired`]: method@Self::poll_expired
894 ///
895 /// # Examples
896 ///
897 /// ```rust,ignore
898 /// use tokio_util::time::DelayQueue;
899 /// use std::time::Duration;
900 ///
901 /// # #[tokio::main]
902 /// # async fn main() {
903 /// let mut delay_queue = DelayQueue::new();
904 ///
905 /// delay_queue.insert("foo", Duration::from_secs(5));
906 ///
907 /// assert!(!delay_queue.is_empty());
908 ///
909 /// delay_queue.clear();
910 ///
911 /// assert!(delay_queue.is_empty());
912 /// # }
913 /// ```
914 pub fn clear(&mut self) {
915 self.slab.clear();
916 self.expired = Stack::default();
917 self.wheel = Wheel::new();
918 self.delay = None;
919 }
920
921 /// Returns the number of elements the queue can hold without reallocating.
922 ///
923 /// # Examples
924 ///
925 /// ```rust,ignore
926 /// use tokio_util::time::DelayQueue;
927 ///
928 /// let delay_queue: DelayQueue<i32> = DelayQueue::with_capacity(10);
929 /// assert_eq!(delay_queue.capacity(), 10);
930 /// ```
931 pub fn capacity(&self) -> usize {
932 self.slab.capacity()
933 }
934
935 /// Returns the number of elements currently in the queue.
936 ///
937 /// # Examples
938 ///
939 /// ```rust,ignore
940 /// use tokio_util::time::DelayQueue;
941 /// use std::time::Duration;
942 ///
943 /// # #[tokio::main]
944 /// # async fn main() {
945 /// let mut delay_queue: DelayQueue<i32> = DelayQueue::with_capacity(10);
946 /// assert_eq!(delay_queue.len(), 0);
947 /// delay_queue.insert(3, Duration::from_secs(5));
948 /// assert_eq!(delay_queue.len(), 1);
949 /// # }
950 /// ```
951 pub fn len(&self) -> usize {
952 self.slab.len()
953 }
954
955 /// Reserves capacity for at least `additional` more items to be queued
956 /// without allocating.
957 ///
958 /// `reserve` does nothing if the queue already has sufficient capacity for
959 /// `additional` more values. If more capacity is required, a new segment of
960 /// memory will be allocated and all existing values will be copied into it.
961 /// As such, if the queue is already very large, a call to `reserve` can end
962 /// up being expensive.
963 ///
964 /// The queue may reserve more than `additional` extra space in order to
965 /// avoid frequent reallocations.
966 ///
967 /// # Panics
968 ///
969 /// Panics if the new capacity exceeds the maximum number of entries the
970 /// queue can contain.
971 ///
972 /// # Examples
973 ///
974 /// ```rust,ignore
975 /// use tokio_util::time::DelayQueue;
976 /// use std::time::Duration;
977 ///
978 /// # #[tokio::main]
979 /// # async fn main() {
980 /// let mut delay_queue = DelayQueue::new();
981 ///
982 /// delay_queue.insert("hello", Duration::from_secs(10));
983 /// delay_queue.reserve(10);
984 ///
985 /// assert!(delay_queue.capacity() >= 11);
986 /// # }
987 /// ```
988 #[track_caller]
989 pub fn reserve(&mut self, additional: usize) {
990 assert!(
991 self.slab.capacity() + additional <= MAX_ENTRIES,
992 "max queue capacity exceeded"
993 );
994 self.slab.reserve(additional);
995 }
996
997 /// Returns `true` if there are no items in the queue.
998 ///
999 /// Note that this function returns `false` even if all items have not yet
1000 /// expired and a call to `poll` will return `Poll::Pending`.
1001 ///
1002 /// # Examples
1003 ///
1004 /// ```rust,ignore
1005 /// use tokio_util::time::DelayQueue;
1006 /// use std::time::Duration;
1007 ///
1008 /// # #[tokio::main]
1009 /// # async fn main() {
1010 /// let mut delay_queue = DelayQueue::new();
1011 /// assert!(delay_queue.is_empty());
1012 ///
1013 /// delay_queue.insert("hello", Duration::from_secs(5));
1014 /// assert!(!delay_queue.is_empty());
1015 /// # }
1016 /// ```
1017 pub fn is_empty(&self) -> bool {
1018 self.slab.is_empty()
1019 }
1020
1021 /// Polls the queue, returning the index of the next slot in the slab that
1022 /// should be returned.
1023 ///
1024 /// A slot should be returned when the associated deadline has been reached.
1025 fn poll_idx(&mut self, cx: &mut task::Context<'_>) -> Poll<Option<Key>> {
1026 use self::wheel::Stack;
1027
1028 let expired = self.expired.pop(&mut self.slab);
1029
1030 if expired.is_some() {
1031 return Poll::Ready(expired);
1032 }
1033
1034 loop {
1035 if let Some(ref mut delay) = self.delay {
1036 ready!(Pin::new(&mut *delay).poll(cx));
1037 let now = crate::util::ms(delay.deadline() - self.start, crate::util::Round::Down);
1038
1039 self.wheel_now = now;
1040 }
1041
1042 // We poll the wheel to get the next value out before finding the next deadline.
1043 let wheel_idx = self.wheel.poll(self.wheel_now, &mut self.slab);
1044
1045 self.delay = self.next_deadline().map(|when| Box::pin(Sleep::new_until(when)));
1046
1047 if let Some(idx) = wheel_idx {
1048 return Poll::Ready(Some(idx));
1049 }
1050
1051 if self.delay.is_none() {
1052 return Poll::Ready(None);
1053 }
1054 }
1055 }
1056
1057 fn normalize_deadline(&self, when: D::Instant) -> u64 {
1058 let when = if when < self.start {
1059 0
1060 } else {
1061 crate::util::ms(when - self.start, crate::util::Round::Up)
1062 };
1063
1064 cmp::max(when, self.wheel.elapsed())
1065 }
1066}
1067
1068// We never put `T` in a `Pin`...
1069impl<D, T> Unpin for DelayQueue<D, T> where D: Delay {}
1070
1071impl<D, T> Default for DelayQueue<D, T>
1072where
1073 D: Delay,
1074 D::Instant: Unpin,
1075{
1076 fn default() -> DelayQueue<D, T> {
1077 DelayQueue::new()
1078 }
1079}
1080
1081impl<D, T> futures_util::Stream for DelayQueue<D, T>
1082where
1083 D: Delay,
1084 D::Instant: Unpin,
1085{
1086 // DelayQueue seems much more specific, where a user may care that it
1087 // has reached capacity, so return those errors instead of panicking.
1088 type Item = Expired<T, D::Instant>;
1089
1090 fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
1091 DelayQueue::poll_expired(self.get_mut(), cx)
1092 }
1093}
1094
1095impl<T> wheel::Stack for Stack<T> {
1096 type Owned = Key;
1097 type Borrowed = Key;
1098 type Store = SlabStorage<T>;
1099
1100 fn is_empty(&self) -> bool {
1101 self.head.is_none()
1102 }
1103
1104 fn push(&mut self, item: Self::Owned, store: &mut Self::Store) {
1105 // Ensure the entry is not already in a stack.
1106 debug_assert!(store[item].next.is_none());
1107 debug_assert!(store[item].prev.is_none());
1108
1109 // Remove the old head entry
1110 let old = self.head.take();
1111
1112 if let Some(idx) = old {
1113 store[idx].prev = Some(item);
1114 }
1115
1116 store[item].next = old;
1117 self.head = Some(item);
1118 }
1119
1120 fn pop(&mut self, store: &mut Self::Store) -> Option<Self::Owned> {
1121 if let Some(key) = self.head {
1122 self.head = store[key].next;
1123
1124 if let Some(idx) = self.head {
1125 store[idx].prev = None;
1126 }
1127
1128 store[key].next = None;
1129 debug_assert!(store[key].prev.is_none());
1130
1131 Some(key)
1132 } else {
1133 None
1134 }
1135 }
1136
1137 #[track_caller]
1138 fn remove(&mut self, item: &Self::Borrowed, store: &mut Self::Store) {
1139 let key = *item;
1140 assert!(store.contains(item));
1141
1142 // Ensure that the entry is in fact contained by the stack
1143 debug_assert!({
1144 // This walks the full linked list even if an entry is found.
1145 let mut next = self.head;
1146 let mut contains = false;
1147
1148 while let Some(idx) = next {
1149 let data = &store[idx];
1150
1151 if idx == *item {
1152 debug_assert!(!contains);
1153 contains = true;
1154 }
1155
1156 next = data.next;
1157 }
1158
1159 contains
1160 });
1161
1162 if let Some(next) = store[key].next {
1163 store[next].prev = store[key].prev;
1164 }
1165
1166 if let Some(prev) = store[key].prev {
1167 store[prev].next = store[key].next;
1168 } else {
1169 self.head = store[key].next;
1170 }
1171
1172 store[key].next = None;
1173 store[key].prev = None;
1174 }
1175
1176 fn when(item: &Self::Borrowed, store: &Self::Store) -> u64 {
1177 store[*item].when
1178 }
1179}
1180
1181impl<T> Default for Stack<T> {
1182 fn default() -> Stack<T> {
1183 Stack {
1184 head: None,
1185 _p: PhantomData,
1186 }
1187 }
1188}
1189
1190impl Key {
1191 pub(crate) fn new(index: usize) -> Key {
1192 Key { index }
1193 }
1194}
1195
1196impl KeyInternal {
1197 pub(crate) fn new(index: usize) -> KeyInternal {
1198 KeyInternal { index }
1199 }
1200}
1201
1202impl From<Key> for KeyInternal {
1203 fn from(item: Key) -> Self {
1204 KeyInternal::new(item.index)
1205 }
1206}
1207
1208impl From<KeyInternal> for Key {
1209 fn from(item: KeyInternal) -> Self {
1210 Key::new(item.index)
1211 }
1212}
1213
1214impl<T, I: Instant> Expired<T, I> {
1215 /// Returns a reference to the inner value.
1216 pub fn get_ref(&self) -> &T {
1217 &self.data
1218 }
1219
1220 /// Returns a mutable reference to the inner value.
1221 pub fn get_mut(&mut self) -> &mut T {
1222 &mut self.data
1223 }
1224
1225 /// Consumes `self` and returns the inner value.
1226 pub fn into_inner(self) -> T {
1227 self.data
1228 }
1229
1230 /// Returns the deadline that the expiration was set to.
1231 pub fn deadline(&self) -> I {
1232 self.deadline
1233 }
1234
1235 /// Returns the key that the expiration is indexed by.
1236 pub fn key(&self) -> Key {
1237 self.key
1238 }
1239}