How to drain FuturesUnordered?

Is there any way to do drain on FuturesUnordered like it is possible on Vec ?

FuturesUnordered is a Stream, and thus &mut FuturesUnordered is one, too, which can be be collected, AFAICT.

You want to take ownership of all of the futures? In that case, you can use .into_iter() on it. To keep the behavior of drain that leaves an empty collection in its place, you can do this:

let iter = std::mem::take(&mut my_futures_unordered).into_iter();
1 Like

That works, too, but one advantage of drain is that the Vec can retain some resources (e.g. its allocation). I don’t know how possible (i.e. whether there are any resources/allocations that can be re-used), and if yes, how relevant this would be for a FuturesUnordered and the context it’s usually used in though.

Thank you @alice. This simplifies a lot what I wish to do!

A futures unordered stores its futures in a linked list and those allocations can't be reused.

1 Like

Peeking into the code for a second, I believe the whole thing might be using linked data structures without retaining any allocations when empty (besides a constant number of structs [maybe 2 Arcs?] for the data structure around it and tail of list or something…), so std::mem::take might be optimal anyways.

The Stream-based approach might still be useful in case the “drain”-like operation is supposed to happen without blocking, in an async fn.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.