rust icon indicating copy to clipboard operation
rust copied to clipboard

Implement collect_with_capacity for Iter?

Open PaulDotSH opened this issue 1 year ago • 1 comments

Hi, a simple implementation of collect_with_capacity would be helpful to reduce boilerplate, a simple way I am doing this in my projects is

trait CollectWithCapacity: Iterator {
    fn collect_with_capacity<T>(self, capacity: usize) -> Vec<Self::Item>
        where
            Self: Sized + Iterator<Item = T>,
    {
        let mut vec = Vec::with_capacity(capacity);
        vec.extend(self);
        vec
    }
}

impl<T: ?Sized> CollectWithCapacity for T where T: Iterator {}

Is there any reason something similar to this is not part of the standard library?

PaulDotSH avatar Mar 11 '24 21:03 PaulDotSH

@PaulDotSH Is there a reason you implemented it that way? Your design is capable of feeding in a wrong capacity to with_capacity that is not guaranteed to match the size of the iterator, which is a considerable deoptimization compared to allocating with the correct capacity, which is what .collect() will do by default.

workingjubilee avatar Mar 11 '24 23:03 workingjubilee

compared to allocating with the correct capacity, which is what .collect() will do by default.

Specifically the FromIterator implementation for Vec will use Iterator::size_hint.

the8472 avatar Mar 12 '24 10:03 the8472

Closing, as this information is already used. If you're not satisfied with that, I recommend checking out https://std-dev-guide.rust-lang.org/development/feature-lifecycle.html for how to proceed.

Noratrieb avatar Mar 12 '24 14:03 Noratrieb