rust-itertools / itertools

Extra iterator adaptors, iterator methods, free functions, and macros.
https://docs.rs/itertools/
Apache License 2.0
2.71k stars 309 forks source link

Feature Request: `raise_results()` adapter #898

Closed w-utter closed 6 months ago

w-utter commented 7 months ago

this iterator would be a wrapper for iterator.process_results(|items| items.map(|item| item)) when either raising the first error, or successfully raising an impl Iterator<Item = Result<T, E>> into a Result<impl Iterator<Item = T>, E>.

I find this particularily useful when using iterator.collect::<Result<Vec<_>, _>>() or likewise is not possible, say with a custom allocator (as collect_into does not to collect into a result of items at the moment) or in a nostd context. This would also provide a more ergonomic way of using the aforementioned proces_results adapter

Philippe-Cholet commented 7 months ago

The issue here is that to get a Result, we need to consume (at least partially) the iterator and therefore collect the intermediary Ok elements, which necessarily allocate. Something like

#[cfg(feature = "use_alloc")]
fn try_collect_iter<...>(&mut self) -> Result<VecIntoIter<T>, E> {
    iterator.collect::<Result<Vec<_>>, _>()?.into_iter()
}

or

#[cfg(feature = "use_alloc")]
fn try_collect_vec<...>(&mut self) -> Result<Vec<T>, E> {
    iterator.collect()
}

I'm not sure we want to add more result shortcuts as it might/should be part of #844.