Debian Codegraph @

third_party/rust/tokio-util/src/time/delay_queue.rs

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