Open
Description
This is an enhancement suggestion. Beside the current collect() to collection like Vec, Hash, etc, and the future collect to array:
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.