Skip to content

Collect to slice #71387

Open
Open
@leonardo-m

Description

@leonardo-m

This is an enhancement suggestion. Beside the current collect() to collection like Vec, Hash, etc, and the future collect to array:

#69985

I find it useful to also collect to a slice when I don't know at compile-time the exact length of the resulting array, but I know an upper bound of its length.

I have adapted the following code from this crate:
https://github.com/kchmck/collect_slice
https://crates.io/crates/collect_slice

trait CollectSlice<'a>: Iterator {
    fn inner(&mut self, slice: &'a mut [Self::Item]) -> &'a [Self::Item];
    fn inner_mut(&mut self, slice: &'a mut [Self::Item]) -> &'a mut [Self::Item];

    fn collect_slice(&mut self, slice: &'a mut [Self::Item]) -> &'a [Self::Item] {
        let result = self.inner(slice);
        assert!(self.next().is_none());
        result
    }

    fn collect_slice_mut(&mut self, slice: &'a mut [Self::Item]) -> &'a mut [Self::Item] {
        let result = self.inner_mut(slice);
        assert!(self.next().is_none());
        result
    }
}

impl<I: ?Sized> CollectSlice<'a> for I where I: Iterator {
    fn inner(&mut self, slice: &'a mut [Self::Item]) -> &'a [Self::Item] {
        let count = slice.iter_mut().zip(self).fold(0, |count, (dest, item)| {
            *dest = item;
            count + 1
        });
        &slice[.. count]
    }

    fn inner_mut(&mut self, slice: &'a mut [Self::Item]) -> &'a mut [Self::Item] {
        let count = slice.iter_mut().zip(self).fold(0, |count, (dest, item)| {
            *dest = item;
            count + 1
        });
        &mut slice[.. count]
    }
}

This code should be improved and simplified. And as in Issue #69985 we could return a Result<> instead, and remove the asserts.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-collectionsArea: `std::collections`A-iteratorsArea: IteratorsC-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions