chromium / subspace

A concept-centered standard library for C++20, enabling safer and more reliable products and a more modern feel for C++ code.; Also home of Subdoc the code-documentation generator.
https://suslib.cc
Apache License 2.0
89 stars 15 forks source link

Add Iterator::try_collect() #308

Closed danakj closed 1 year ago

danakj commented 1 year ago

Closes #295

try_collect can collect from an iterator of T: Try into a container C<U> that supports FromIterator<T: Try> to create the C<U>.

The actual Try types do not need to support FromIterator then, and this replaces the need for Option or Result to implement FromIterator, if the user calls .try_collect() instead of .collect().

We needed to add another operation on Try types for this, which is to convert from T: Try in an error state to U: Try in an error state, where they have the same (or a convertible) error type. This new concept is sus::ops::TryErrorConvertibleTo and it's accessed through sus::ops::try_preserve_error().

The TryErrorConvertibleTo concept is implemented for Option, Result and std::optional.

Then we also needed a way to take a TryType and a type Bar and produce the type TryType so that we can say try_collect<Vec> on an iterator of Option and get back Option<Vec>. This is done through sus::ops::TryRemapOutputType<TryType, NewOutputType>.