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 [`InfallibleStream::new`],
14    /// [`BodyStream::from_infallible`](super::BodyStream::from_infallible), or
15    /// [`SizedStream::from_infallible`](super::SizedStream::from_infallible).
16    #[must_use]
17    pub struct InfallibleStream<S> {
18        #[pin]
19        pub(super) stream: S,
20    }
21}
22
23impl<S: Stream> InfallibleStream<S> {
24    /// Creates a stream that wraps each item from `stream` in `Ok`.
25    ///
26    /// # Examples
27    ///
28    /// ```
29    /// use actix_http::body::InfallibleStream;
30    /// use futures_util::{stream, StreamExt as _};
31    ///
32    /// # actix_rt::System::new().block_on(async {
33    /// let stream = InfallibleStream::new(stream::iter([1, 2]));
34    ///
35    /// assert_eq!(stream.collect::<Vec<_>>().await, vec![Ok(1), Ok(2)]);
36    /// # });
37    /// ```
38    #[inline]
39    pub fn new(stream: S) -> Self {
40        Self { stream }
41    }
42}
43
44impl<S: Stream> Stream for InfallibleStream<S> {
45    type Item = Result<S::Item, Infallible>;
46
47    #[inline]
48    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
49        self.project().stream.poll_next(cx).map(|item| item.map(Ok))
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use futures_util::StreamExt as _;
56
57    use super::*;
58
59    #[tokio::test(flavor = "local")]
60    async fn non_byte_items() {
61        #[derive(Debug, PartialEq)]
62        struct Item(u8);
63
64        let stream = async_stream::stream! {
65            yield Item(1);
66            tokio::task::yield_now().await;
67            yield Item(2);
68        };
69        let stream = InfallibleStream::new(stream);
70
71        assert_eq!(
72            stream.collect::<Vec<_>>().await,
73            vec![Ok(Item(1)), Ok(Item(2))],
74        );
75    }
76}