Skip to main content

actix_http/body/
infallible_stream.rs

1use std::{
2    convert::Infallible,
3    pin::Pin,
4    task::{Context, Poll},
5};
6
7use futures_core::Stream;
8use pin_project_lite::pin_project;
9
10pin_project! {
11    /// Adapts a stream into a stream of results with an [`Infallible`] error.
12    ///
13    /// Created by [`BodyStream::from_infallible`](super::BodyStream::from_infallible) or
14    /// [`SizedStream::from_infallible`](super::SizedStream::from_infallible).
15    #[must_use]
16    pub struct InfallibleStream<S> {
17        #[pin]
18        pub(super) stream: S,
19    }
20}
21
22impl<S: Stream> Stream for InfallibleStream<S> {
23    type Item = Result<S::Item, Infallible>;
24
25    #[inline]
26    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
27        self.project().stream.poll_next(cx).map(|item| item.map(Ok))
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use futures_util::StreamExt as _;
34
35    use super::*;
36
37    #[tokio::test(flavor = "local")]
38    async fn non_byte_items() {
39        #[derive(Debug, PartialEq)]
40        struct Item(u8);
41
42        let stream = async_stream::stream! {
43            yield Item(1);
44            tokio::task::yield_now().await;
45            yield Item(2);
46        };
47        let stream = InfallibleStream { stream };
48
49        assert_eq!(
50            stream.collect::<Vec<_>>().await,
51            vec![Ok(Item(1)), Ok(Item(2))],
52        );
53    }
54}