Skip to main content

tokio_util/time/
delay_queue.rs

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