RFC 1257: drain-range-2

libs (collections)

Summary

Implement .drain(range) and .drain() respectively as appropriate on collections.

Motivation

The drain methods and their draining iterators serve to mass remove elements from a collection, receiving them by value in an iterator, while the collection keeps its allocation intact (if applicable).

The range parameterized variants of drain are a generalization of drain, to affect just a subrange of the collection, for example removing just an index range from a vector.

drain thus serves both to consume all or some elements from a collection without consuming the collection itself. The ranged drain allows bulk removal of elements, more efficently than any other safe API.

Detailed design

Collections

Vec and String already have ranged drain, so they are complete.

HashMap and HashSet already have .drain(), so they are complete; their elements have no meaningful order.

BinaryHeap already has .drain(), and just like its other iterators, it promises no particular order. So this collection is already complete.

The following collections need updated implementations:

VecDeque should implement .drain(range) for index ranges, just like Vec does.

LinkedList should implement .drain(range) for index ranges. Just like the other seqences, this is a O(n) operation, and LinkedList already has other indexed methods (.split_off()).

BTreeMap and BTreeSet

BTreeMap already has a ranged iterator, .range(a, b), and drain for BTreeMap and BTreeSet should have arguments completely consistent the range method. This will be addressed separately.

Stabilization

The following can be stabilized as they are:

The following can be stabilized, but their argument's trait is not stable:

The following will be heading towards stabilization after changes:

Drawbacks

Alternatives

Unresolved questions