Expand description
§try_stream-transpose
(Kind of) Convert a stream of results into a stream of OKs without consuming the stream.
Working with a stream of data, an API or your preference may require that
each item is available as a plain item. However, fetching the data usually
is a fallible operation. The straight-forward way would be to consume
(collect) the stream, which can be considered inelegant, inefficient,
infeasible or even impossible. TryStreamTranspose::transpose_with solves
this by passing a stream of the unwrapped items to a closure.
use futures_util::{Stream, stream};
use try_stream_transpose::TryStreamTranspose;
/// Return a `Result` of the product over the numbers in the stream.
fn product(
numbers: impl Stream<Item = i32>,
) -> impl Future<Output = Result<i32, Error>> {
use futures_util::{FutureExt, StreamExt};
numbers.fold(1, async |a, b| a * b).map(Ok)
}
// Exemplary usage --- the function defined above is passed for the closure
// parameter.
let nums: [Result<i32, Error>; 3] = [Ok(2), Ok(3), Ok(7)];
core::assert_matches!(
stream::iter(nums).transpose_with(2, product).await,
Ok(42)
);
let argh = [Ok(2), Err("3"), Ok(7)];
core::assert_matches!(
stream::iter(argh).transpose_with(2, product).await,
Err(Error::Message("3"))
);
// The error type must support conversion from `Error`. Conversion from
// `&'static str` is implemented to support our code above.
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
enum Error {
#[error("{0}")]
Message(&'static str),
Internal(#[from] try_stream_transpose::Error),
}
impl From<&'static str> for Error {
fn from(msg: &'static str) -> Self {
Self::Message(msg)
}
}§Copyright
This project is licensed under EUPL v. 1.2. You can find a copy of this license
in the file LICENSE.
§LLM use
Out of ethical, environmental and legal concerns, this project is entirely human-made slop.
Structs§
- Error
- Abstract the errors encountered internally.
Traits§
- TryStream
Transpose - Convenience for
TryStream, when you want to work on a stream ofOks as a stream of the values inside theOks.