Skip to main content

futures_util/stream/futures_unordered/
mod.rs

1//! An unbounded set of futures.
2//!
3//! This module is only available when the `std` or `alloc` feature of this
4//! library is activated, and it is activated by default.
5
6#[cfg(not(feature = "portable-atomic"))]
7use core::sync::atomic;
8
9#[cfg(not(feature = "portable-atomic-alloc"))]
10use alloc::sync::{Arc, Weak};
11
12#[cfg(feature = "portable-atomic")]
13use portable_atomic_crate as atomic;
14
15#[cfg(feature = "portable-atomic-alloc")]
16use portable_atomic_util::{Arc, Weak};
17
18use crate::task::AtomicWaker;
19use atomic::Ordering::{AcqRel, Acquire, Relaxed, Release, SeqCst};
20use atomic::{AtomicBool, AtomicPtr};
21use core::cell::UnsafeCell;
22use core::fmt::{self, Debug};
23use core::iter::FromIterator;
24use core::marker::PhantomData;
25use core::mem;
26use core::pin::Pin;
27use core::ptr;
28use futures_core::future::Future;
29use futures_core::stream::{FusedStream, Stream};
30use futures_core::task::{Context, Poll};
31use futures_task::{FutureObj, LocalFutureObj, LocalSpawn, Spawn, SpawnError};
32
33mod abort;
34
35mod iter;
36#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/102352
37pub use self::iter::{IntoIter, Iter, IterMut, IterPinMut, IterPinRef};
38
39mod task;
40use self::task::Task;
41
42mod ready_to_run_queue;
43use self::ready_to_run_queue::{Dequeue, ReadyToRunQueue};
44
45/// A set of futures which may complete in any order.
46///
47/// See [`FuturesOrdered`](crate::stream::FuturesOrdered) for a version of this
48/// type that preserves a FIFO order.
49///
50/// This structure is optimized to manage a large number of futures.
51/// Futures managed by [`FuturesUnordered`] will only be polled when they
52/// generate wake-up notifications. This reduces the required amount of work
53/// needed to poll large numbers of futures.
54///
55/// [`FuturesUnordered`] can be filled by [`collect`](Iterator::collect)ing an
56/// iterator of futures into a [`FuturesUnordered`], or by
57/// [`push`](FuturesUnordered::push)ing futures onto an existing
58/// [`FuturesUnordered`]. When new futures are added,
59/// [`poll_next`](Stream::poll_next) must be called in order to begin receiving
60/// wake-ups for new futures.
61///
62/// Note that you can create a ready-made [`FuturesUnordered`] via the
63/// [`collect`](Iterator::collect) method, or you can start with an empty set
64/// with the [`FuturesUnordered::new`] constructor.
65///
66/// This type is only available when the `std` or `alloc` feature of this
67/// library is activated, and it is activated by default.
68#[must_use = "streams do nothing unless polled"]
69pub struct FuturesUnordered<Fut> {
70    ready_to_run_queue: Arc<ReadyToRunQueue<Fut>>,
71    head_all: AtomicPtr<Task<Fut>>,
72    is_terminated: AtomicBool,
73}
74
75unsafe impl<Fut: Send> Send for FuturesUnordered<Fut> {}
76unsafe impl<Fut: Send + Sync> Sync for FuturesUnordered<Fut> {}
77impl<Fut> Unpin for FuturesUnordered<Fut> {}
78
79impl Spawn for FuturesUnordered<FutureObj<'_, ()>> {
80    fn spawn_obj(&self, future_obj: FutureObj<'static, ()>) -> Result<(), SpawnError> {
81        self.push(future_obj);
82        Ok(())
83    }
84}
85
86impl LocalSpawn for FuturesUnordered<LocalFutureObj<'_, ()>> {
87    fn spawn_local_obj(&self, future_obj: LocalFutureObj<'static, ()>) -> Result<(), SpawnError> {
88        self.push(future_obj);
89        Ok(())
90    }
91}
92
93// FuturesUnordered is implemented using two linked lists. One which links all
94// futures managed by a `FuturesUnordered` and one that tracks futures that have
95// been scheduled for polling. The first linked list allows for thread safe
96// insertion of nodes at the head as well as forward iteration, but is otherwise
97// not thread safe and is only accessed by the thread that owns the
98// `FuturesUnordered` value for any other operations. The second linked list is
99// an implementation of the intrusive MPSC queue algorithm described by
100// 1024cores.net.
101//
102// When a future is submitted to the set, a task is allocated and inserted in
103// both linked lists. The next call to `poll_next` will (eventually) see this
104// task and call `poll` on the future.
105//
106// Before a managed future is polled, the current context's waker is replaced
107// with one that is aware of the specific future being run. This ensures that
108// wake-up notifications generated by that specific future are visible to
109// `FuturesUnordered`. When a wake-up notification is received, the task is
110// inserted into the ready to run queue, so that its future can be polled later.
111//
112// Each task is wrapped in an `Arc` and thereby atomically reference counted.
113// Also, each task contains an `AtomicBool` which acts as a flag that indicates
114// whether the task is currently inserted in the atomic queue. When a wake-up
115// notification is received, the task will only be inserted into the ready to
116// run queue if it isn't inserted already.
117
118impl<Fut> Default for FuturesUnordered<Fut> {
119    fn default() -> Self {
120        Self::new()
121    }
122}
123
124impl<Fut> FuturesUnordered<Fut> {
125    /// Constructs a new, empty [`FuturesUnordered`].
126    ///
127    /// The returned [`FuturesUnordered`] does not contain any futures.
128    /// In this state, [`FuturesUnordered::poll_next`](Stream::poll_next) will
129    /// return [`Poll::Ready(None)`](Poll::Ready).
130    pub fn new() -> Self {
131        let stub = Arc::new(Task {
132            future: UnsafeCell::new(None),
133            next_all: AtomicPtr::new(ptr::null_mut()),
134            prev_all: UnsafeCell::new(ptr::null()),
135            len_all: UnsafeCell::new(0),
136            next_ready_to_run: AtomicPtr::new(ptr::null_mut()),
137            queued: AtomicBool::new(true),
138            ready_to_run_queue: Weak::new(),
139            woken: AtomicBool::new(false),
140        });
141        let stub_ptr = Arc::as_ptr(&stub);
142        let ready_to_run_queue = Arc::new(ReadyToRunQueue {
143            waker: AtomicWaker::new(),
144            head: AtomicPtr::new(stub_ptr as *mut _),
145            tail: UnsafeCell::new(stub_ptr),
146            stub,
147        });
148
149        Self {
150            head_all: AtomicPtr::new(ptr::null_mut()),
151            ready_to_run_queue,
152            is_terminated: AtomicBool::new(false),
153        }
154    }
155
156    /// Returns the number of futures contained in the set.
157    ///
158    /// This represents the total number of in-flight futures.
159    pub fn len(&self) -> usize {
160        let (_, len) = self.atomic_load_head_and_len_all();
161        len
162    }
163
164    /// Returns `true` if the set contains no futures.
165    pub fn is_empty(&self) -> bool {
166        // Relaxed ordering can be used here since we don't need to read from
167        // the head pointer, only check whether it is null.
168        self.head_all.load(Relaxed).is_null()
169    }
170
171    /// Push a future into the set.
172    ///
173    /// This method adds the given future to the set. This method will not
174    /// call [`poll`](core::future::Future::poll) on the submitted future. The caller must
175    /// ensure that [`FuturesUnordered::poll_next`](Stream::poll_next) is called
176    /// in order to receive wake-up notifications for the given future.
177    pub fn push(&self, future: Fut) {
178        let task = Arc::new(Task {
179            future: UnsafeCell::new(Some(future)),
180            next_all: AtomicPtr::new(self.pending_next_all()),
181            prev_all: UnsafeCell::new(ptr::null_mut()),
182            len_all: UnsafeCell::new(0),
183            next_ready_to_run: AtomicPtr::new(ptr::null_mut()),
184            queued: AtomicBool::new(true),
185            ready_to_run_queue: Arc::downgrade(&self.ready_to_run_queue),
186            woken: AtomicBool::new(false),
187        });
188
189        // Reset the `is_terminated` flag if we've previously marked ourselves
190        // as terminated.
191        self.is_terminated.store(false, Relaxed);
192
193        // Right now our task has a strong reference count of 1. We transfer
194        // ownership of this reference count to our internal linked list
195        // and we'll reclaim ownership through the `unlink` method below.
196        let ptr = self.link(task);
197
198        // We'll need to get the future "into the system" to start tracking it,
199        // e.g. getting its wake-up notifications going to us tracking which
200        // futures are ready. To do that we unconditionally enqueue it for
201        // polling here.
202        self.ready_to_run_queue.enqueue(ptr);
203    }
204
205    /// Returns an iterator that allows inspecting each future in the set.
206    pub fn iter(&self) -> Iter<'_, Fut>
207    where
208        Fut: Unpin,
209    {
210        Iter(Pin::new(self).iter_pin_ref())
211    }
212
213    /// Returns an iterator that allows inspecting each future in the set.
214    pub fn iter_pin_ref(self: Pin<&Self>) -> IterPinRef<'_, Fut> {
215        let (task, len) = self.atomic_load_head_and_len_all();
216        let pending_next_all = self.pending_next_all();
217
218        IterPinRef { task, len, pending_next_all, _marker: PhantomData }
219    }
220
221    /// Returns an iterator that allows modifying each future in the set.
222    pub fn iter_mut(&mut self) -> IterMut<'_, Fut>
223    where
224        Fut: Unpin,
225    {
226        IterMut(Pin::new(self).iter_pin_mut())
227    }
228
229    /// Returns an iterator that allows modifying each future in the set.
230    pub fn iter_pin_mut(mut self: Pin<&mut Self>) -> IterPinMut<'_, Fut> {
231        // `head_all` can be accessed directly and we don't need to spin on
232        // `Task::next_all` since we have exclusive access to the set.
233        let task = *self.head_all.get_mut();
234        let len = if task.is_null() { 0 } else { unsafe { *(*task).len_all.get() } };
235
236        IterPinMut { task, len, _marker: PhantomData }
237    }
238
239    /// Returns the current head node and number of futures in the list of all
240    /// futures within a context where access is shared with other threads
241    /// (mostly for use with the `len` and `iter_pin_ref` methods).
242    fn atomic_load_head_and_len_all(&self) -> (*const Task<Fut>, usize) {
243        let task = self.head_all.load(Acquire);
244        let len = if task.is_null() {
245            0
246        } else {
247            unsafe {
248                (*task).spin_next_all(self.pending_next_all(), Acquire);
249                *(*task).len_all.get()
250            }
251        };
252
253        (task, len)
254    }
255
256    /// Releases the task. It destroys the future inside and either drops
257    /// the `Arc<Task>` or transfers ownership to the ready to run queue.
258    /// The task this method is called on must have been unlinked before.
259    fn release_task(&mut self, task: Arc<Task<Fut>>) {
260        // `release_task` must only be called on unlinked tasks
261        debug_assert_eq!(task.next_all.load(Relaxed), self.pending_next_all());
262        unsafe {
263            debug_assert!((*task.prev_all.get()).is_null());
264        }
265
266        // The future is done, try to reset the queued flag. This will prevent
267        // `wake` from doing any work in the future
268        let prev = task.queued.swap(true, SeqCst);
269
270        // If the queued flag was previously set, then it means that this task
271        // is still in our internal ready to run queue. We then transfer
272        // ownership of our reference count to the ready to run queue, and it'll
273        // come along and free it later, noticing that the future is `None`.
274        //
275        // If, however, the queued flag was *not* set then we're safe to
276        // release our reference count on the task. The queued flag was set
277        // above so all future `enqueue` operations will not actually
278        // enqueue the task, so our task will never see the ready to run queue
279        // again. The task itself will be deallocated once all reference counts
280        // have been dropped elsewhere by the various wakers that contain it.
281        //
282        // Use ManuallyDrop to transfer the reference count ownership before
283        // dropping the future so unwinding won't release the reference count.
284        let md_slot;
285        let task = if prev {
286            md_slot = mem::ManuallyDrop::new(task);
287            &*md_slot
288        } else {
289            &task
290        };
291
292        // Drop the future, even if it hasn't finished yet. This is safe
293        // because we're dropping the future on the thread that owns
294        // `FuturesUnordered`, which correctly tracks `Fut`'s lifetimes and
295        // such.
296        unsafe {
297            // Set to `None` rather than `take()`ing to prevent moving the
298            // future.
299            *task.future.get() = None;
300        }
301    }
302
303    /// Insert a new task into the internal linked list.
304    fn link(&self, task: Arc<Task<Fut>>) -> *const Task<Fut> {
305        // `next_all` should already be reset to the pending state before this
306        // function is called.
307        debug_assert_eq!(task.next_all.load(Relaxed), self.pending_next_all());
308        let ptr = Arc::into_raw(task);
309
310        // Atomically swap out the old head node to get the node that should be
311        // assigned to `next_all`.
312        let next = self.head_all.swap(ptr as *mut _, AcqRel);
313
314        unsafe {
315            // Store the new list length in the new node.
316            let new_len = if next.is_null() {
317                1
318            } else {
319                // Make sure `next_all` has been written to signal that it is
320                // safe to read `len_all`.
321                (*next).spin_next_all(self.pending_next_all(), Acquire);
322                *(*next).len_all.get() + 1
323            };
324            *(*ptr).len_all.get() = new_len;
325
326            // Write the old head as the next node pointer, signaling to other
327            // threads that `len_all` and `next_all` are ready to read.
328            (*ptr).next_all.store(next, Release);
329
330            // `prev_all` updates don't need to be synchronized, as the field is
331            // only ever used after exclusive access has been acquired.
332            if !next.is_null() {
333                *(*next).prev_all.get() = ptr;
334            }
335        }
336
337        ptr
338    }
339
340    /// Remove the task from the linked list tracking all tasks currently
341    /// managed by `FuturesUnordered`.
342    /// This method is unsafe because it has be guaranteed that `task` is a
343    /// valid pointer.
344    unsafe fn unlink(&mut self, task: *const Task<Fut>) -> Arc<Task<Fut>> {
345        unsafe {
346            // Compute the new list length now in case we're removing the head node
347            // and won't be able to retrieve the correct length later.
348            let head = *self.head_all.get_mut();
349            debug_assert!(!head.is_null());
350            let new_len = *(*head).len_all.get() - 1;
351
352            let task = Arc::from_raw(task);
353            let next = task.next_all.load(Relaxed);
354            let prev = *task.prev_all.get();
355            task.next_all.store(self.pending_next_all(), Relaxed);
356            *task.prev_all.get() = ptr::null_mut();
357
358            if !next.is_null() {
359                *(*next).prev_all.get() = prev;
360            }
361
362            if !prev.is_null() {
363                (*prev).next_all.store(next, Relaxed);
364            } else {
365                *self.head_all.get_mut() = next;
366            }
367
368            // Store the new list length in the head node.
369            let head = *self.head_all.get_mut();
370            if !head.is_null() {
371                *(*head).len_all.get() = new_len;
372            }
373
374            task
375        }
376    }
377
378    /// Returns the reserved value for `Task::next_all` to indicate a pending
379    /// assignment from the thread that inserted the task.
380    ///
381    /// `FuturesUnordered::link` needs to update `Task` pointers in an order
382    /// that ensures any iterators created on other threads can correctly
383    /// traverse the entire `Task` list using the chain of `next_all` pointers.
384    /// This could be solved with a compare-exchange loop that stores the
385    /// current `head_all` in `next_all` and swaps out `head_all` with the new
386    /// `Task` pointer if the head hasn't already changed. Under heavy thread
387    /// contention, this compare-exchange loop could become costly.
388    ///
389    /// An alternative is to initialize `next_all` to a reserved pending state
390    /// first, perform an atomic swap on `head_all`, and finally update
391    /// `next_all` with the old head node. Iterators will then either see the
392    /// pending state value or the correct next node pointer, and can reload
393    /// `next_all` as needed until the correct value is loaded. The number of
394    /// retries needed (if any) would be small and will always be finite, so
395    /// this should generally perform better than the compare-exchange loop.
396    ///
397    /// A valid `Task` pointer in the `head_all` list is guaranteed to never be
398    /// this value, so it is safe to use as a reserved value until the correct
399    /// value can be written.
400    fn pending_next_all(&self) -> *mut Task<Fut> {
401        // The `ReadyToRunQueue` stub is never inserted into the `head_all`
402        // list, and its pointer value will remain valid for the lifetime of
403        // this `FuturesUnordered`, so we can make use of its value here.
404        Arc::as_ptr(&self.ready_to_run_queue.stub) as *mut _
405    }
406}
407
408impl<Fut: Future> Stream for FuturesUnordered<Fut> {
409    type Item = Fut::Output;
410
411    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
412        let len = self.len();
413
414        // Keep track of how many child futures we have polled,
415        // in case we want to forcibly yield.
416        let mut polled = 0;
417        let mut yielded = 0;
418
419        // Ensure `parent` is correctly set.
420        self.ready_to_run_queue.waker.register(cx.waker());
421
422        loop {
423            // Safety: &mut self guarantees the mutual exclusion `dequeue`
424            // expects
425            let task = match unsafe { self.ready_to_run_queue.dequeue() } {
426                Dequeue::Empty => {
427                    if self.is_empty() {
428                        // We can only consider ourselves terminated once we
429                        // have yielded a `None`
430                        *self.is_terminated.get_mut() = true;
431                        return Poll::Ready(None);
432                    } else {
433                        return Poll::Pending;
434                    }
435                }
436                Dequeue::Inconsistent => {
437                    // At this point, it may be worth yielding the thread &
438                    // spinning a few times... but for now, just yield using the
439                    // task system.
440                    cx.waker().wake_by_ref();
441                    return Poll::Pending;
442                }
443                Dequeue::Data(task) => task,
444            };
445
446            debug_assert!(task != self.ready_to_run_queue.stub());
447
448            // Safety:
449            // - `task` is a valid pointer.
450            // - We are the only thread that accesses the `UnsafeCell` that
451            //   contains the future
452            let future = match unsafe { &mut *(*task).future.get() } {
453                Some(future) => future,
454
455                // If the future has already gone away then we're just
456                // cleaning out this task. See the comment in
457                // `release_task` for more information, but we're basically
458                // just taking ownership of our reference count here.
459                None => {
460                    // This case only happens when `release_task` was called
461                    // for this task before and couldn't drop the task
462                    // because it was already enqueued in the ready to run
463                    // queue.
464
465                    // Safety: `task` is a valid pointer
466                    let task = unsafe { Arc::from_raw(task) };
467
468                    // Double check that the call to `release_task` really
469                    // happened. Calling it required the task to be unlinked.
470                    debug_assert_eq!(task.next_all.load(Relaxed), self.pending_next_all());
471                    unsafe {
472                        debug_assert!((*task.prev_all.get()).is_null());
473                    }
474                    continue;
475                }
476            };
477
478            // Safety: `task` is a valid pointer
479            let task = unsafe { self.unlink(task) };
480
481            // Unset queued flag: This must be done before polling to ensure
482            // that the future's task gets rescheduled if it sends a wake-up
483            // notification **during** the call to `poll`.
484            let prev = task.queued.swap(false, SeqCst);
485            assert!(prev);
486
487            // We're going to need to be very careful if the `poll`
488            // method below panics. We need to (a) not leak memory and
489            // (b) ensure that we still don't have any use-after-frees. To
490            // manage this we do a few things:
491            //
492            // * A "bomb" is created which if dropped abnormally will call
493            //   `release_task`. That way we'll be sure the memory management
494            //   of the `task` is managed correctly. In particular
495            //   `release_task` will drop the future. This ensures that it is
496            //   dropped on this thread and not accidentally on a different
497            //   thread (bad).
498            // * We unlink the task from our internal queue to preemptively
499            //   assume it'll panic, in which case we'll want to discard it
500            //   regardless.
501            struct Bomb<'a, Fut> {
502                queue: &'a mut FuturesUnordered<Fut>,
503                task: Option<Arc<Task<Fut>>>,
504            }
505
506            impl<Fut> Drop for Bomb<'_, Fut> {
507                fn drop(&mut self) {
508                    if let Some(task) = self.task.take() {
509                        self.queue.release_task(task);
510                    }
511                }
512            }
513
514            let mut bomb = Bomb { task: Some(task), queue: &mut *self };
515
516            // Poll the underlying future with the appropriate waker
517            // implementation. This is where a large bit of the unsafety
518            // starts to stem from internally. The waker is basically just
519            // our `Arc<Task<Fut>>` and can schedule the future for polling by
520            // enqueuing itself in the ready to run queue.
521            //
522            // Critically though `Task<Fut>` won't actually access `Fut`, the
523            // future, while it's floating around inside of wakers.
524            // These structs will basically just use `Fut` to size
525            // the internal allocation, appropriately accessing fields and
526            // deallocating the task if need be.
527            let res = {
528                let task = bomb.task.as_ref().unwrap();
529                // We are only interested in whether the future is awoken before it
530                // finishes polling, so reset the flag here.
531                task.woken.store(false, Relaxed);
532                // SAFETY: see the comments of Bomb and this block.
533                let waker = unsafe { Task::waker_ref(task) };
534                let mut cx = Context::from_waker(&waker);
535
536                // Safety: We won't move the future ever again
537                let future = unsafe { Pin::new_unchecked(future) };
538
539                future.poll(&mut cx)
540            };
541            polled += 1;
542
543            match res {
544                Poll::Pending => {
545                    let task = bomb.task.take().unwrap();
546                    // If the future was awoken during polling, we assume
547                    // the future wanted to explicitly yield.
548                    yielded += task.woken.load(Relaxed) as usize;
549                    bomb.queue.link(task);
550
551                    // If a future yields, we respect it and yield here.
552                    // If all futures have been polled, we also yield here to
553                    // avoid starving other tasks waiting on the executor.
554                    // (polling the same future twice per iteration may cause
555                    // the problem: https://github.com/rust-lang/futures-rs/pull/2333)
556                    if yielded >= 2 || polled == len {
557                        cx.waker().wake_by_ref();
558                        return Poll::Pending;
559                    }
560                    continue;
561                }
562                Poll::Ready(output) => return Poll::Ready(Some(output)),
563            }
564        }
565    }
566
567    fn size_hint(&self) -> (usize, Option<usize>) {
568        let len = self.len();
569        (len, Some(len))
570    }
571}
572
573impl<Fut> Debug for FuturesUnordered<Fut> {
574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575        write!(f, "FuturesUnordered {{ ... }}")
576    }
577}
578
579impl<Fut> FuturesUnordered<Fut> {
580    /// Clears the set, removing all futures.
581    pub fn clear(&mut self) {
582        *self = Self::new();
583    }
584}
585
586impl<Fut> Drop for FuturesUnordered<Fut> {
587    fn drop(&mut self) {
588        // Before the strong reference to the queue is dropped we need all
589        // futures to be dropped. See note at the bottom of this method.
590        //
591        // If there is a panic before this completes, we leak the queue.
592        struct LeakQueueOnDrop<'a, Fut>(&'a mut FuturesUnordered<Fut>);
593        impl<Fut> Drop for LeakQueueOnDrop<'_, Fut> {
594            fn drop(&mut self) {
595                mem::forget(Arc::clone(&self.0.ready_to_run_queue));
596            }
597        }
598        let guard = LeakQueueOnDrop(self);
599        // When a `FuturesUnordered` is dropped we want to drop all futures
600        // associated with it. At the same time though there may be tons of
601        // wakers flying around which contain `Task<Fut>` references
602        // inside them. We'll let those naturally get deallocated.
603        while !guard.0.head_all.get_mut().is_null() {
604            let head = *guard.0.head_all.get_mut();
605            let task = unsafe { guard.0.unlink(head) };
606            guard.0.release_task(task);
607        }
608        mem::forget(guard); // safe to release strong reference to queue
609
610        // Note that at this point we could still have a bunch of tasks in the
611        // ready to run queue. None of those tasks, however, have futures
612        // associated with them so they're safe to destroy on any thread. At
613        // this point the `FuturesUnordered` struct, the owner of the one strong
614        // reference to the ready to run queue will drop the strong reference.
615        // At that point whichever thread releases the strong refcount last (be
616        // it this thread or some other thread as part of an `upgrade`) will
617        // clear out the ready to run queue and free all remaining tasks.
618        //
619        // While that freeing operation isn't guaranteed to happen here, it's
620        // guaranteed to happen "promptly" as no more "blocking work" will
621        // happen while there's a strong refcount held.
622    }
623}
624
625impl<'a, Fut: Unpin> IntoIterator for &'a FuturesUnordered<Fut> {
626    type Item = &'a Fut;
627    type IntoIter = Iter<'a, Fut>;
628
629    fn into_iter(self) -> Self::IntoIter {
630        self.iter()
631    }
632}
633
634impl<'a, Fut: Unpin> IntoIterator for &'a mut FuturesUnordered<Fut> {
635    type Item = &'a mut Fut;
636    type IntoIter = IterMut<'a, Fut>;
637
638    fn into_iter(self) -> Self::IntoIter {
639        self.iter_mut()
640    }
641}
642
643impl<Fut: Unpin> IntoIterator for FuturesUnordered<Fut> {
644    type Item = Fut;
645    type IntoIter = IntoIter<Fut>;
646
647    fn into_iter(mut self) -> Self::IntoIter {
648        // `head_all` can be accessed directly and we don't need to spin on
649        // `Task::next_all` since we have exclusive access to the set.
650        let task = *self.head_all.get_mut();
651        let len = if task.is_null() { 0 } else { unsafe { *(*task).len_all.get() } };
652
653        IntoIter { len, inner: self }
654    }
655}
656
657impl<Fut> FromIterator<Fut> for FuturesUnordered<Fut> {
658    fn from_iter<I>(iter: I) -> Self
659    where
660        I: IntoIterator<Item = Fut>,
661    {
662        let acc = Self::new();
663        iter.into_iter().fold(acc, |acc, item| {
664            acc.push(item);
665            acc
666        })
667    }
668}
669
670impl<Fut: Future> FusedStream for FuturesUnordered<Fut> {
671    fn is_terminated(&self) -> bool {
672        self.is_terminated.load(Relaxed)
673    }
674}
675
676impl<Fut> Extend<Fut> for FuturesUnordered<Fut> {
677    fn extend<I>(&mut self, iter: I)
678    where
679        I: IntoIterator<Item = Fut>,
680    {
681        for item in iter {
682            self.push(item);
683        }
684    }
685}