wasm_streams/readable/
into_stream.rs

1use core::pin::Pin;
2use core::task::{Context, Poll};
3
4use futures_util::ready;
5use futures_util::stream::{FusedStream, Stream};
6use futures_util::FutureExt;
7use wasm_bindgen::prelude::*;
8use wasm_bindgen_futures::JsFuture;
9
10use super::sys::ReadableStreamReadResult;
11use super::ReadableStreamDefaultReader;
12
13/// A [`Stream`] for the [`into_stream`](super::ReadableStream::into_stream) method.
14///
15/// This `Stream` holds a reader, and therefore locks the [`ReadableStream`](super::ReadableStream).
16/// When this `Stream` is dropped, it also drops its reader which in turn
17/// [releases its lock](https://streams.spec.whatwg.org/#release-a-lock).
18///
19/// When used through [`ReadableStream::into_stream`](super::ReadableStream::into_stream),
20/// the stream is automatically cancelled before dropping the reader, discarding any pending read requests.
21/// When used through [`ReadableStreamDefaultReader::into_stream`](super::ReadableStreamDefaultReader::into_stream),
22/// it is up to the user to either manually [cancel](Self::cancel) the stream,
23/// or to ensure that there are no pending read requests when dropped.
24/// See the documentation on [`ReadableStreamDefaultReader`] for more details on the drop behavior.
25///
26/// [`Stream`]: https://docs.rs/futures/0.3.18/futures/stream/trait.Stream.html
27#[must_use = "streams do nothing unless polled"]
28#[derive(Debug)]
29pub struct IntoStream<'reader> {
30    reader: Option<ReadableStreamDefaultReader<'reader>>,
31    fut: Option<JsFuture>,
32    cancel_on_drop: bool,
33}
34
35impl<'reader> IntoStream<'reader> {
36    #[inline]
37    pub(super) fn new(reader: ReadableStreamDefaultReader, cancel_on_drop: bool) -> IntoStream {
38        IntoStream {
39            reader: Some(reader),
40            fut: None,
41            cancel_on_drop,
42        }
43    }
44
45    /// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
46    /// signaling a loss of interest in the stream by a consumer.
47    pub async fn cancel(mut self) -> Result<(), JsValue> {
48        match self.reader.take() {
49            Some(mut reader) => reader.cancel().await,
50            None => Ok(()),
51        }
52    }
53
54    /// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
55    /// signaling a loss of interest in the stream by a consumer.
56    pub async fn cancel_with_reason(mut self, reason: &JsValue) -> Result<(), JsValue> {
57        match self.reader.take() {
58            Some(mut reader) => reader.cancel_with_reason(reason).await,
59            None => Ok(()),
60        }
61    }
62}
63
64impl FusedStream for IntoStream<'_> {
65    fn is_terminated(&self) -> bool {
66        self.reader.is_none() && self.fut.is_none()
67    }
68}
69
70impl<'reader> Stream for IntoStream<'reader> {
71    type Item = Result<JsValue, JsValue>;
72
73    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
74        let read_fut = match self.fut.as_mut() {
75            Some(fut) => fut,
76            None => match &self.reader {
77                Some(reader) => {
78                    // No pending read
79                    // Start reading the next chunk and create future from read promise
80                    let fut = JsFuture::from(reader.as_raw().read());
81                    self.fut.insert(fut)
82                }
83                None => {
84                    // Reader was already dropped
85                    return Poll::Ready(None);
86                }
87            },
88        };
89
90        // Poll the future for the pending read
91        let js_result = ready!(read_fut.poll_unpin(cx));
92        self.fut = None;
93
94        // Read completed
95        Poll::Ready(match js_result {
96            Ok(js_value) => {
97                let result = ReadableStreamReadResult::from(js_value);
98                if result.is_done() {
99                    // End of stream, drop reader
100                    self.reader = None;
101                    None
102                } else {
103                    Some(Ok(result.value()))
104                }
105            }
106            Err(js_value) => {
107                // Error, drop reader
108                self.reader = None;
109                Some(Err(js_value))
110            }
111        })
112    }
113}
114
115impl<'reader> Drop for IntoStream<'reader> {
116    fn drop(&mut self) {
117        if self.cancel_on_drop {
118            if let Some(reader) = self.reader.take() {
119                let _ = reader.as_raw().cancel().catch(&Closure::once(|_| {}));
120            }
121        }
122    }
123}