Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
+202
@@ -0,0 +1,202 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use js_sys::{Object, Uint8Array};
|
||||
use wasm_bindgen::{JsCast, JsValue};
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use crate::util::{checked_cast_to_usize, clamp_to_u32, promise_to_void_future};
|
||||
|
||||
use super::{sys, IntoAsyncRead, ReadableStream};
|
||||
|
||||
/// A [`ReadableStreamBYOBReader`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader)
|
||||
/// that can be used to read chunks from a [`ReadableStream`](ReadableStream).
|
||||
///
|
||||
/// This is returned by the [`get_byob_reader`](ReadableStream::get_byob_reader) method.
|
||||
///
|
||||
/// When the reader is dropped, it automatically [releases its lock](https://streams.spec.whatwg.org/#release-a-lock).
|
||||
#[derive(Debug)]
|
||||
pub struct ReadableStreamBYOBReader<'stream> {
|
||||
raw: sys::ReadableStreamBYOBReader,
|
||||
_stream: PhantomData<&'stream mut ReadableStream>,
|
||||
}
|
||||
|
||||
impl<'stream> ReadableStreamBYOBReader<'stream> {
|
||||
pub(crate) fn new(stream: &mut ReadableStream) -> Result<Self, js_sys::Error> {
|
||||
let reader_options = sys::ReadableStreamGetReaderOptions::new();
|
||||
reader_options.set_mode(sys::ReadableStreamReaderMode::Byob);
|
||||
Ok(Self {
|
||||
raw: stream
|
||||
.as_raw()
|
||||
.unchecked_ref::<sys::ReadableStreamExt>()
|
||||
.try_get_reader_with_options(&reader_options)?
|
||||
.unchecked_into(),
|
||||
_stream: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
/// Acquires a reference to the underlying [JavaScript reader](sys::ReadableStreamBYOBReader).
|
||||
#[inline]
|
||||
pub fn as_raw(&self) -> &sys::ReadableStreamBYOBReader {
|
||||
&self.raw
|
||||
}
|
||||
|
||||
/// Waits for the stream to become closed.
|
||||
///
|
||||
/// This returns an error if the stream ever errors, or if the reader's lock is
|
||||
/// [released](https://streams.spec.whatwg.org/#release-a-lock) before the stream finishes
|
||||
/// closing.
|
||||
pub async fn closed(&self) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().closed()).await
|
||||
}
|
||||
|
||||
/// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// signaling a loss of interest in the stream by a consumer.
|
||||
///
|
||||
/// Equivalent to [`ReadableStream.cancel`](ReadableStream::cancel).
|
||||
pub async fn cancel(&mut self) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().cancel()).await
|
||||
}
|
||||
|
||||
/// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// signaling a loss of interest in the stream by a consumer.
|
||||
///
|
||||
/// Equivalent to [`ReadableStream.cancel_with_reason`](ReadableStream::cancel_with_reason).
|
||||
pub async fn cancel_with_reason(&mut self, reason: &JsValue) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().cancel_with_reason(reason)).await
|
||||
}
|
||||
|
||||
/// Reads the next chunk from the stream's internal queue into `dst`,
|
||||
/// and returns the number of bytes read.
|
||||
///
|
||||
/// * If some bytes were read into `dst`, this returns `Ok(bytes_read)`.
|
||||
/// * If the stream closes and no more bytes are available, this returns `Ok(0)`.
|
||||
/// * If the stream cancels, this returns `Ok(0)`.
|
||||
/// * If the stream encounters an `error`, this returns `Err(error)`.
|
||||
///
|
||||
/// This always allocated a new temporary `Uint8Array` with the same size as `dst` to hold
|
||||
/// the result before copying to `dst`. We cannot pass a view on the backing WebAssembly memory
|
||||
/// directly, because:
|
||||
/// * `reader.read(view)` needs to transfer `view.buffer`, but `WebAssembly.Memory` buffers
|
||||
/// are non-transferable.
|
||||
/// * `view.buffer` can be invalidated if the WebAssembly memory grows while `read(view)`
|
||||
/// is still in progress.
|
||||
///
|
||||
/// Therefore, it is necessary to use a separate buffer living in the JavaScript heap.
|
||||
/// To avoid repeated allocations for repeated reads,
|
||||
/// use [`read_with_buffer`](Self::read_with_buffer).
|
||||
pub async fn read(&mut self, dst: &mut [u8]) -> Result<usize, JsValue> {
|
||||
let buffer = Uint8Array::new_with_length(clamp_to_u32(dst.len()));
|
||||
let (bytes_read, _) = self.read_with_buffer(dst, buffer).await?;
|
||||
Ok(bytes_read)
|
||||
}
|
||||
|
||||
/// Reads the next chunk from the stream's internal queue into `dst`,
|
||||
/// and returns the number of bytes read.
|
||||
///
|
||||
/// The given `buffer` is used to store the bytes before they are copied to `dst`.
|
||||
/// This buffer is returned back together with the result, so it can be re-used for subsequent
|
||||
/// reads without extra allocations. Note that the underlying `ArrayBuffer` is transferred
|
||||
/// in the process, so any other views on the original buffer will become unusable.
|
||||
///
|
||||
/// * If some bytes were read into `dst`, this returns `Ok((bytes_read, Some(buffer)))`.
|
||||
/// * If the stream closes and no more bytes are available, this returns `Ok((0, Some(buffer)))`.
|
||||
/// * If the stream cancels, this returns `Ok((0, None))`. In this case, the given buffer is
|
||||
/// not returned.
|
||||
/// * If the stream encounters an `error`, this returns `Err(error)`.
|
||||
pub async fn read_with_buffer(
|
||||
&mut self,
|
||||
dst: &mut [u8],
|
||||
buffer: Uint8Array,
|
||||
) -> Result<(usize, Option<Uint8Array>), JsValue> {
|
||||
// Save the original buffer's byte offset and length.
|
||||
let buffer_offset = buffer.byte_offset();
|
||||
let buffer_len = buffer.byte_length();
|
||||
// Limit view to destination slice's length.
|
||||
let dst_len = clamp_to_u32(dst.len());
|
||||
let view = buffer.subarray(0, dst_len).unchecked_into::<Object>();
|
||||
// Read into view. This transfers `buffer.buffer()`.
|
||||
let promise = self.as_raw().read_with_array_buffer_view(&view);
|
||||
let js_result = JsFuture::from(promise).await?;
|
||||
let result = sys::ReadableStreamReadResult::from(js_result);
|
||||
let js_value = result.get_value();
|
||||
let filled_view = if js_value.is_undefined() {
|
||||
// No new view was returned. The stream must have been canceled.
|
||||
assert!(result.get_done().unwrap_or_default());
|
||||
return Ok((0, None));
|
||||
} else {
|
||||
js_value.unchecked_into::<Uint8Array>()
|
||||
};
|
||||
let filled_len = checked_cast_to_usize(filled_view.byte_length());
|
||||
debug_assert!(filled_len <= dst.len());
|
||||
// Re-construct the original Uint8Array with the new ArrayBuffer.
|
||||
let new_buffer = Uint8Array::new_with_byte_offset_and_length(
|
||||
&filled_view.buffer(),
|
||||
buffer_offset,
|
||||
buffer_len,
|
||||
);
|
||||
if result.get_done().unwrap_or_default() {
|
||||
debug_assert_eq!(filled_len, 0);
|
||||
} else {
|
||||
filled_view.copy_to(&mut dst[0..filled_len]);
|
||||
}
|
||||
Ok((filled_len, Some(new_buffer)))
|
||||
}
|
||||
|
||||
/// [Releases](https://streams.spec.whatwg.org/#release-a-lock) this reader's lock on the
|
||||
/// corresponding stream.
|
||||
///
|
||||
/// [As of January 2022](https://github.com/whatwg/streams/commit/d5f92d9f17306d31ba6b27424d23d58e89bf64a5),
|
||||
/// the Streams standard allows the lock to be released even when there are still pending read
|
||||
/// requests. Such requests will automatically become rejected, and this function will always
|
||||
/// succeed.
|
||||
///
|
||||
/// However, if the Streams implementation is not yet up-to-date with this change, then
|
||||
/// releasing the lock while there are pending read requests will **panic**. For a non-panicking
|
||||
/// variant, use [`try_release_lock`](Self::try_release_lock).
|
||||
#[inline]
|
||||
pub fn release_lock(mut self) {
|
||||
self.release_lock_mut()
|
||||
}
|
||||
|
||||
fn release_lock_mut(&mut self) {
|
||||
self.as_raw().release_lock()
|
||||
}
|
||||
|
||||
/// Try to [release](https://streams.spec.whatwg.org/#release-a-lock) this reader's lock on the
|
||||
/// corresponding stream.
|
||||
///
|
||||
/// [As of January 2022](https://github.com/whatwg/streams/commit/d5f92d9f17306d31ba6b27424d23d58e89bf64a5),
|
||||
/// the Streams standard allows the lock to be released even when there are still pending read
|
||||
/// requests. Such requests will automatically become rejected, and this function will always
|
||||
/// return `Ok(())`.
|
||||
///
|
||||
/// However, if the Streams implementation is not yet up-to-date with this change, then
|
||||
/// the lock cannot be released while there are pending read requests. Attempting to do so will
|
||||
/// return an error and leave the reader locked to the stream.
|
||||
#[inline]
|
||||
pub fn try_release_lock(self) -> Result<(), (js_sys::Error, Self)> {
|
||||
self.as_raw()
|
||||
.unchecked_ref::<sys::ReadableStreamReaderExt>()
|
||||
.try_release_lock()
|
||||
.map_err(|err| (err, self))
|
||||
}
|
||||
|
||||
/// Converts this `ReadableStreamBYOBReader` into an [`AsyncRead`].
|
||||
///
|
||||
/// This is similar to [`ReadableStream.into_async_read`](ReadableStream::into_async_read),
|
||||
/// except that after the returned `AsyncRead` is dropped, the original `ReadableStream` is
|
||||
/// still usable. This allows reading only a few bytes from the `AsyncRead`, while still
|
||||
/// allowing another reader to read the remaining bytes later on.
|
||||
///
|
||||
/// [`AsyncRead`]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncRead.html
|
||||
#[inline]
|
||||
pub fn into_async_read(self) -> IntoAsyncRead<'stream> {
|
||||
IntoAsyncRead::new(self, false)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ReadableStreamBYOBReader<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.release_lock_mut();
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use crate::util::promise_to_void_future;
|
||||
|
||||
use super::{sys, IntoStream, ReadableStream};
|
||||
|
||||
/// A [`ReadableStreamDefaultReader`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader)
|
||||
/// that can be used to read chunks from a [`ReadableStream`](ReadableStream).
|
||||
///
|
||||
/// This is returned by the [`get_reader`](ReadableStream::get_reader) method.
|
||||
///
|
||||
/// When the reader is dropped, it automatically [releases its lock](https://streams.spec.whatwg.org/#release-a-lock).
|
||||
#[derive(Debug)]
|
||||
pub struct ReadableStreamDefaultReader<'stream> {
|
||||
raw: sys::ReadableStreamDefaultReader,
|
||||
_stream: PhantomData<&'stream mut ReadableStream>,
|
||||
}
|
||||
|
||||
impl<'stream> ReadableStreamDefaultReader<'stream> {
|
||||
pub(crate) fn new(stream: &mut ReadableStream) -> Result<Self, js_sys::Error> {
|
||||
Ok(Self {
|
||||
raw: stream
|
||||
.as_raw()
|
||||
.unchecked_ref::<sys::ReadableStreamExt>()
|
||||
.try_get_reader()?
|
||||
.unchecked_into(),
|
||||
_stream: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
/// Acquires a reference to the underlying [JavaScript reader](sys::ReadableStreamDefaultReader).
|
||||
#[inline]
|
||||
pub fn as_raw(&self) -> &sys::ReadableStreamDefaultReader {
|
||||
&self.raw
|
||||
}
|
||||
|
||||
/// Waits for the stream to become closed.
|
||||
///
|
||||
/// This returns an error if the stream ever errors, or if the reader's lock is
|
||||
/// [released](https://streams.spec.whatwg.org/#release-a-lock) before the stream finishes
|
||||
/// closing.
|
||||
pub async fn closed(&self) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().closed()).await
|
||||
}
|
||||
|
||||
/// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// signaling a loss of interest in the stream by a consumer.
|
||||
///
|
||||
/// Equivalent to [`ReadableStream.cancel`](ReadableStream::cancel).
|
||||
pub async fn cancel(&mut self) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().cancel()).await
|
||||
}
|
||||
|
||||
/// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// signaling a loss of interest in the stream by a consumer.
|
||||
///
|
||||
/// Equivalent to [`ReadableStream.cancel_with_reason`](ReadableStream::cancel_with_reason).
|
||||
pub async fn cancel_with_reason(&mut self, reason: &JsValue) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().cancel_with_reason(reason)).await
|
||||
}
|
||||
|
||||
/// Reads the next chunk from the stream's internal queue.
|
||||
///
|
||||
/// * If a next `chunk` becomes available, this returns `Ok(Some(chunk))`.
|
||||
/// * If the stream closes and no more chunks are available, this returns `Ok(None)`.
|
||||
/// * If the stream encounters an `error`, this returns `Err(error)`.
|
||||
pub async fn read(&mut self) -> Result<Option<JsValue>, JsValue> {
|
||||
let promise = self.as_raw().read();
|
||||
let js_result = JsFuture::from(promise).await?;
|
||||
let result = sys::ReadableStreamReadResult::from(js_result);
|
||||
if result.get_done().unwrap_or_default() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(result.get_value()))
|
||||
}
|
||||
}
|
||||
|
||||
/// [Releases](https://streams.spec.whatwg.org/#release-a-lock) this reader's lock on the
|
||||
/// corresponding stream.
|
||||
///
|
||||
/// [As of January 2022](https://github.com/whatwg/streams/commit/d5f92d9f17306d31ba6b27424d23d58e89bf64a5),
|
||||
/// the Streams standard allows the lock to be released even when there are still pending read
|
||||
/// requests. Such requests will automatically become rejected, and this function will always
|
||||
/// succeed.
|
||||
///
|
||||
/// However, if the Streams implementation is not yet up-to-date with this change, then
|
||||
/// releasing the lock while there are pending read requests will **panic**. For a non-panicking
|
||||
/// variant, use [`try_release_lock`](Self::try_release_lock).
|
||||
#[inline]
|
||||
pub fn release_lock(mut self) {
|
||||
self.release_lock_mut()
|
||||
}
|
||||
|
||||
fn release_lock_mut(&mut self) {
|
||||
self.as_raw().release_lock()
|
||||
}
|
||||
|
||||
/// Try to [release](https://streams.spec.whatwg.org/#release-a-lock) this reader's lock on the
|
||||
/// corresponding stream.
|
||||
///
|
||||
/// [As of January 2022](https://github.com/whatwg/streams/commit/d5f92d9f17306d31ba6b27424d23d58e89bf64a5),
|
||||
/// the Streams standard allows the lock to be released even when there are still pending read
|
||||
/// requests. Such requests will automatically become rejected, and this function will always
|
||||
/// return `Ok(())`.
|
||||
///
|
||||
/// However, if the Streams implementation is not yet up-to-date with this change, then
|
||||
/// the lock cannot be released while there are pending read requests. Attempting to do so will
|
||||
/// return an error and leave the reader locked to the stream.
|
||||
#[inline]
|
||||
pub fn try_release_lock(self) -> Result<(), (js_sys::Error, Self)> {
|
||||
self.as_raw()
|
||||
.unchecked_ref::<sys::ReadableStreamReaderExt>()
|
||||
.try_release_lock()
|
||||
.map_err(|err| (err, self))
|
||||
}
|
||||
|
||||
/// Converts this `ReadableStreamDefaultReader` into a [`Stream`].
|
||||
///
|
||||
/// This is similar to [`ReadableStream.into_stream`](ReadableStream::into_stream),
|
||||
/// except that after the returned `Stream` is dropped, the original `ReadableStream` is still
|
||||
/// usable. This allows reading only a few chunks from the `Stream`, while still allowing
|
||||
/// another reader to read the remaining chunks later on.
|
||||
///
|
||||
/// [`Stream`]: https://docs.rs/futures/0.3.30/futures/stream/trait.Stream.html
|
||||
#[inline]
|
||||
pub fn into_stream(self) -> IntoStream<'stream> {
|
||||
IntoStream::new(self, false)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ReadableStreamDefaultReader<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.release_lock_mut();
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
use core::pin::Pin;
|
||||
use core::task::{Context, Poll};
|
||||
|
||||
use futures_util::io::{AsyncRead, Error};
|
||||
use futures_util::ready;
|
||||
use futures_util::FutureExt;
|
||||
use js_sys::{Object, Uint8Array};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use crate::util::{checked_cast_to_usize, clamp_to_u32, js_to_io_error};
|
||||
|
||||
use super::sys::ReadableStreamReadResult;
|
||||
use super::ReadableStreamBYOBReader;
|
||||
|
||||
/// An [`AsyncRead`] for the [`into_async_read`](super::ReadableStream::into_async_read) method.
|
||||
///
|
||||
/// This `AsyncRead` holds a reader, and therefore locks the [`ReadableStream`](super::ReadableStream).
|
||||
/// When this `AsyncRead` is dropped, it also drops its reader which in turn
|
||||
/// [releases its lock](https://streams.spec.whatwg.org/#release-a-lock).
|
||||
///
|
||||
/// [`AsyncRead`]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncRead.html
|
||||
#[must_use = "readers do nothing unless polled"]
|
||||
#[derive(Debug)]
|
||||
pub struct IntoAsyncRead<'reader> {
|
||||
reader: Option<ReadableStreamBYOBReader<'reader>>,
|
||||
buffer: Option<Uint8Array>,
|
||||
fut: Option<JsFuture>,
|
||||
cancel_on_drop: bool,
|
||||
}
|
||||
|
||||
impl<'reader> IntoAsyncRead<'reader> {
|
||||
#[inline]
|
||||
pub(super) fn new(reader: ReadableStreamBYOBReader, cancel_on_drop: bool) -> IntoAsyncRead {
|
||||
IntoAsyncRead {
|
||||
reader: Some(reader),
|
||||
buffer: None,
|
||||
fut: None,
|
||||
cancel_on_drop,
|
||||
}
|
||||
}
|
||||
|
||||
/// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// signaling a loss of interest in the stream by a consumer.
|
||||
pub async fn cancel(mut self) -> Result<(), JsValue> {
|
||||
match self.reader.take() {
|
||||
Some(mut reader) => reader.cancel().await,
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// signaling a loss of interest in the stream by a consumer.
|
||||
pub async fn cancel_with_reason(mut self, reason: &JsValue) -> Result<(), JsValue> {
|
||||
match self.reader.take() {
|
||||
Some(mut reader) => reader.cancel_with_reason(reason).await,
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn discard_reader(mut self: Pin<&mut Self>) {
|
||||
self.reader = None;
|
||||
self.buffer = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl<'reader> AsyncRead for IntoAsyncRead<'reader> {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut [u8],
|
||||
) -> Poll<Result<usize, Error>> {
|
||||
let read_fut = match self.fut.as_mut() {
|
||||
Some(fut) => fut,
|
||||
None => {
|
||||
// No pending read, start reading the next bytes
|
||||
let buf_len = clamp_to_u32(buf.len());
|
||||
let buffer = match self.buffer.take() {
|
||||
// Re-use the internal buffer if it is large enough,
|
||||
// otherwise allocate a new one
|
||||
Some(buffer) if buffer.byte_length() >= buf_len => buffer,
|
||||
_ => Uint8Array::new_with_length(buf_len),
|
||||
};
|
||||
// Limit to output buffer size
|
||||
let buffer = buffer.subarray(0, buf_len).unchecked_into::<Object>();
|
||||
match &self.reader {
|
||||
Some(reader) => {
|
||||
// Read into internal buffer and store its future
|
||||
let fut =
|
||||
JsFuture::from(reader.as_raw().read_with_array_buffer_view(&buffer));
|
||||
self.fut.insert(fut)
|
||||
}
|
||||
None => {
|
||||
// Reader was already dropped
|
||||
return Poll::Ready(Ok(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Poll the future for the pending read
|
||||
let js_result = ready!(read_fut.poll_unpin(cx));
|
||||
self.fut = None;
|
||||
|
||||
// Read completed
|
||||
Poll::Ready(match js_result {
|
||||
Ok(js_value) => {
|
||||
let result = ReadableStreamReadResult::from(js_value);
|
||||
if result.get_done().unwrap_or_default() {
|
||||
// End of stream
|
||||
self.discard_reader();
|
||||
Ok(0)
|
||||
} else {
|
||||
// Cannot be canceled, so view must exist
|
||||
let filled_view = result.get_value().unchecked_into::<Uint8Array>();
|
||||
// Copy bytes to output buffer
|
||||
let filled_len = checked_cast_to_usize(filled_view.byte_length());
|
||||
debug_assert!(filled_len <= buf.len());
|
||||
filled_view.copy_to(&mut buf[0..filled_len]);
|
||||
// Re-construct internal buffer with the new ArrayBuffer
|
||||
self.buffer = Some(Uint8Array::new(&filled_view.buffer()));
|
||||
Ok(filled_len)
|
||||
}
|
||||
}
|
||||
Err(js_value) => {
|
||||
// Error
|
||||
self.discard_reader();
|
||||
Err(js_to_io_error(js_value))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'reader> Drop for IntoAsyncRead<'reader> {
|
||||
fn drop(&mut self) {
|
||||
if self.cancel_on_drop {
|
||||
if let Some(reader) = self.reader.take() {
|
||||
let on_rejected = Closure::once(|_| {});
|
||||
let _ = reader.as_raw().cancel().catch(&on_rejected);
|
||||
on_rejected.forget();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
use core::pin::Pin;
|
||||
use core::task::{Context, Poll};
|
||||
|
||||
use futures_util::ready;
|
||||
use futures_util::stream::{FusedStream, Stream};
|
||||
use futures_util::FutureExt;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use super::sys::ReadableStreamReadResult;
|
||||
use super::ReadableStreamDefaultReader;
|
||||
|
||||
/// A [`Stream`] for the [`into_stream`](super::ReadableStream::into_stream) method.
|
||||
///
|
||||
/// This `Stream` holds a reader, and therefore locks the [`ReadableStream`](super::ReadableStream).
|
||||
/// When this `Stream` is dropped, it also drops its reader which in turn
|
||||
/// [releases its lock](https://streams.spec.whatwg.org/#release-a-lock).
|
||||
///
|
||||
/// [`Stream`]: https://docs.rs/futures/0.3.30/futures/stream/trait.Stream.html
|
||||
#[must_use = "streams do nothing unless polled"]
|
||||
#[derive(Debug)]
|
||||
pub struct IntoStream<'reader> {
|
||||
reader: Option<ReadableStreamDefaultReader<'reader>>,
|
||||
fut: Option<JsFuture>,
|
||||
cancel_on_drop: bool,
|
||||
}
|
||||
|
||||
impl<'reader> IntoStream<'reader> {
|
||||
#[inline]
|
||||
pub(super) fn new(reader: ReadableStreamDefaultReader, cancel_on_drop: bool) -> IntoStream {
|
||||
IntoStream {
|
||||
reader: Some(reader),
|
||||
fut: None,
|
||||
cancel_on_drop,
|
||||
}
|
||||
}
|
||||
|
||||
/// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// signaling a loss of interest in the stream by a consumer.
|
||||
pub async fn cancel(mut self) -> Result<(), JsValue> {
|
||||
match self.reader.take() {
|
||||
Some(mut reader) => reader.cancel().await,
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// signaling a loss of interest in the stream by a consumer.
|
||||
pub async fn cancel_with_reason(mut self, reason: &JsValue) -> Result<(), JsValue> {
|
||||
match self.reader.take() {
|
||||
Some(mut reader) => reader.cancel_with_reason(reason).await,
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FusedStream for IntoStream<'_> {
|
||||
fn is_terminated(&self) -> bool {
|
||||
self.reader.is_none() && self.fut.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'reader> Stream for IntoStream<'reader> {
|
||||
type Item = Result<JsValue, JsValue>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let read_fut = match self.fut.as_mut() {
|
||||
Some(fut) => fut,
|
||||
None => match &self.reader {
|
||||
Some(reader) => {
|
||||
// No pending read
|
||||
// Start reading the next chunk and create future from read promise
|
||||
let fut = JsFuture::from(reader.as_raw().read());
|
||||
self.fut.insert(fut)
|
||||
}
|
||||
None => {
|
||||
// Reader was already dropped
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// Poll the future for the pending read
|
||||
let js_result = ready!(read_fut.poll_unpin(cx));
|
||||
self.fut = None;
|
||||
|
||||
// Read completed
|
||||
Poll::Ready(match js_result {
|
||||
Ok(js_value) => {
|
||||
let result = ReadableStreamReadResult::from(js_value);
|
||||
if result.get_done().unwrap_or_default() {
|
||||
// End of stream, drop reader
|
||||
self.reader = None;
|
||||
None
|
||||
} else {
|
||||
Some(Ok(result.get_value()))
|
||||
}
|
||||
}
|
||||
Err(js_value) => {
|
||||
// Error, drop reader
|
||||
self.reader = None;
|
||||
Some(Err(js_value))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'reader> Drop for IntoStream<'reader> {
|
||||
fn drop(&mut self) {
|
||||
if self.cancel_on_drop {
|
||||
if let Some(reader) = self.reader.take() {
|
||||
let on_rejected = Closure::once(|_| {});
|
||||
let _ = reader.as_raw().cancel().catch(&on_rejected);
|
||||
on_rejected.forget();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
use std::cell::RefCell;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
|
||||
use futures_util::future::{abortable, AbortHandle, TryFutureExt};
|
||||
use futures_util::io::{AsyncRead, AsyncReadExt};
|
||||
use js_sys::{Error as JsError, Promise, Uint8Array};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::future_to_promise;
|
||||
|
||||
use crate::util::{checked_cast_to_u32, clamp_to_usize};
|
||||
|
||||
use super::sys;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub(crate) struct IntoUnderlyingByteSource {
|
||||
inner: Rc<RefCell<Inner>>,
|
||||
default_buffer_len: usize,
|
||||
controller: Option<sys::ReadableByteStreamController>,
|
||||
pull_handle: Option<AbortHandle>,
|
||||
}
|
||||
|
||||
impl IntoUnderlyingByteSource {
|
||||
pub fn new(async_read: Box<dyn AsyncRead>, default_buffer_len: usize) -> Self {
|
||||
IntoUnderlyingByteSource {
|
||||
inner: Rc::new(RefCell::new(Inner::new(async_read))),
|
||||
default_buffer_len,
|
||||
controller: None,
|
||||
pull_handle: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::await_holding_refcell_ref)]
|
||||
#[wasm_bindgen]
|
||||
impl IntoUnderlyingByteSource {
|
||||
#[wasm_bindgen(getter, js_name = type)]
|
||||
pub fn type_(&self) -> sys::ReadableStreamType {
|
||||
sys::ReadableStreamType::Bytes
|
||||
}
|
||||
|
||||
#[wasm_bindgen(getter, js_name = autoAllocateChunkSize)]
|
||||
pub fn auto_allocate_chunk_size(&self) -> usize {
|
||||
self.default_buffer_len
|
||||
}
|
||||
|
||||
pub fn start(&mut self, controller: sys::ReadableByteStreamController) {
|
||||
self.controller = Some(controller);
|
||||
}
|
||||
|
||||
pub fn pull(&mut self, controller: sys::ReadableByteStreamController) -> Promise {
|
||||
let inner = self.inner.clone();
|
||||
let fut = async move {
|
||||
// This mutable borrow can never panic, since the ReadableStream always queues
|
||||
// each operation on the underlying source.
|
||||
let mut inner = inner.try_borrow_mut().unwrap_throw();
|
||||
inner.pull(controller).await
|
||||
};
|
||||
|
||||
// Allow aborting the future from cancel().
|
||||
let (fut, handle) = abortable(fut);
|
||||
// Ignore errors from aborting the future.
|
||||
let fut = fut.unwrap_or_else(|_| Ok(JsValue::undefined()));
|
||||
|
||||
self.pull_handle = Some(handle);
|
||||
// SAFETY: We use the take-and-replace pattern in Inner::pull() to ensure
|
||||
// that if a panic occurs, the async_read is already taken out of the Option,
|
||||
// leaving it in a clean None state. This prevents use of corrupted state
|
||||
// after a panic is caught.
|
||||
future_to_promise(AssertUnwindSafe(fut))
|
||||
}
|
||||
|
||||
pub fn cancel(self) {
|
||||
// The stream has been canceled, drop everything.
|
||||
drop(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for IntoUnderlyingByteSource {
|
||||
fn drop(&mut self) {
|
||||
// Abort the pending pull, if any.
|
||||
if let Some(handle) = self.pull_handle.take() {
|
||||
handle.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
async_read: Option<Pin<Box<dyn AsyncRead>>>,
|
||||
buffer: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn new(async_read: Box<dyn AsyncRead>) -> Self {
|
||||
Inner {
|
||||
async_read: Some(async_read.into()),
|
||||
buffer: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn pull(
|
||||
&mut self,
|
||||
controller: sys::ReadableByteStreamController,
|
||||
) -> Result<JsValue, JsValue> {
|
||||
// We set autoAllocateChunkSize, so there should always be a BYOB request.
|
||||
let request = controller.byob_request().unwrap_throw();
|
||||
// Resize the buffer to fit the BYOB request.
|
||||
let request_view = request.view().unwrap_throw().unchecked_into::<Uint8Array>();
|
||||
let request_len = clamp_to_usize(request_view.byte_length());
|
||||
if self.buffer.len() < request_len {
|
||||
self.buffer.resize(request_len, 0);
|
||||
}
|
||||
|
||||
// Take the async_read out before the fallible/panickable operation.
|
||||
// This ensures that if a panic occurs, self.async_read is already None,
|
||||
// so any subsequent call will fail cleanly instead of using corrupted state.
|
||||
let mut async_read = self.async_read.take().unwrap_throw();
|
||||
|
||||
match async_read.read(&mut self.buffer[0..request_len]).await {
|
||||
Ok(0) => {
|
||||
// Stream closed: don't put it back, clear buffer, close controller
|
||||
self.buffer = Vec::new();
|
||||
controller.close()?;
|
||||
request.respond_with_u32(0)?;
|
||||
}
|
||||
Ok(bytes_read) => {
|
||||
// Success: put the async_read back for reuse
|
||||
self.async_read = Some(async_read);
|
||||
// Copy read bytes from buffer to BYOB request view
|
||||
debug_assert!(bytes_read <= request_len);
|
||||
let bytes_read_u32 = checked_cast_to_u32(bytes_read);
|
||||
let dest = Uint8Array::new_with_byte_offset_and_length(
|
||||
&request_view.buffer(),
|
||||
request_view.byte_offset(),
|
||||
bytes_read_u32,
|
||||
);
|
||||
dest.copy_from(&self.buffer[0..bytes_read]);
|
||||
// Respond to BYOB request
|
||||
request.respond_with_u32(bytes_read_u32)?;
|
||||
}
|
||||
Err(err) => {
|
||||
// Error: don't put it back, clear buffer, return error
|
||||
self.buffer = Vec::new();
|
||||
return Err(JsError::new(&err.to_string()).into());
|
||||
}
|
||||
};
|
||||
// Panic: async_read is dropped during unwind, self.async_read remains None
|
||||
Ok(JsValue::undefined())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
use std::cell::RefCell;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
|
||||
use futures_util::future::{abortable, AbortHandle, TryFutureExt};
|
||||
use futures_util::stream::{Stream, TryStreamExt};
|
||||
use js_sys::Promise;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::future_to_promise;
|
||||
|
||||
use super::sys;
|
||||
|
||||
type JsValueStream = dyn Stream<Item = Result<JsValue, JsValue>>;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub(crate) struct IntoUnderlyingSource {
|
||||
inner: Rc<RefCell<Inner>>,
|
||||
pull_handle: Option<AbortHandle>,
|
||||
}
|
||||
|
||||
impl IntoUnderlyingSource {
|
||||
pub fn new(stream: Box<JsValueStream>) -> Self {
|
||||
IntoUnderlyingSource {
|
||||
inner: Rc::new(RefCell::new(Inner::new(stream))),
|
||||
pull_handle: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::await_holding_refcell_ref)]
|
||||
#[wasm_bindgen]
|
||||
impl IntoUnderlyingSource {
|
||||
pub fn pull(&mut self, controller: sys::ReadableStreamDefaultController) -> Promise {
|
||||
let inner = self.inner.clone();
|
||||
let fut = async move {
|
||||
// This mutable borrow can never panic, since the ReadableStream always queues
|
||||
// each operation on the underlying source.
|
||||
let mut inner = inner.try_borrow_mut().unwrap_throw();
|
||||
inner.pull(controller).await
|
||||
};
|
||||
|
||||
// Allow aborting the future from cancel().
|
||||
let (fut, handle) = abortable(fut);
|
||||
// Ignore errors from aborting the future.
|
||||
let fut = fut.unwrap_or_else(|_| Ok(JsValue::undefined()));
|
||||
|
||||
self.pull_handle = Some(handle);
|
||||
// SAFETY: We use the take-and-replace pattern in Inner::pull() to ensure
|
||||
// that if a panic occurs, the stream is already taken out of the Option,
|
||||
// leaving it in a clean None state. This prevents use of corrupted state
|
||||
// after a panic is caught.
|
||||
future_to_promise(AssertUnwindSafe(fut))
|
||||
}
|
||||
|
||||
pub fn cancel(self) {
|
||||
// The stream has been canceled, drop everything.
|
||||
drop(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for IntoUnderlyingSource {
|
||||
fn drop(&mut self) {
|
||||
// Abort the pending pull, if any.
|
||||
if let Some(handle) = self.pull_handle.take() {
|
||||
handle.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
stream: Option<Pin<Box<JsValueStream>>>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn new(stream: Box<JsValueStream>) -> Self {
|
||||
Inner {
|
||||
stream: Some(stream.into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn pull(
|
||||
&mut self,
|
||||
controller: sys::ReadableStreamDefaultController,
|
||||
) -> Result<JsValue, JsValue> {
|
||||
// Take the stream out before the fallible/panickable operation.
|
||||
// This ensures that if a panic occurs, self.stream is already None,
|
||||
// so any subsequent call will fail cleanly instead of using corrupted state.
|
||||
let mut stream = self.stream.take().unwrap_throw();
|
||||
|
||||
match stream.try_next().await {
|
||||
Ok(Some(chunk)) => {
|
||||
// Success with chunk: put the stream back and enqueue
|
||||
self.stream = Some(stream);
|
||||
controller.enqueue_with_chunk(&chunk)?;
|
||||
}
|
||||
Ok(None) => {
|
||||
// Stream closed: don't put it back (it's exhausted), close controller
|
||||
controller.close()?;
|
||||
}
|
||||
Err(err) => {
|
||||
// Error: don't put it back, return the error
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
// Panic: stream is dropped during unwind, self.stream remains None
|
||||
Ok(JsValue::undefined())
|
||||
}
|
||||
}
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
//! Bindings and conversions for
|
||||
//! [readable streams](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).
|
||||
use futures_util::io::AsyncRead;
|
||||
use futures_util::Stream;
|
||||
use js_sys::Object;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen::JsCast;
|
||||
|
||||
pub use byob_reader::ReadableStreamBYOBReader;
|
||||
pub use default_reader::ReadableStreamDefaultReader;
|
||||
pub use into_async_read::IntoAsyncRead;
|
||||
pub use into_stream::IntoStream;
|
||||
use into_underlying_source::IntoUnderlyingSource;
|
||||
pub use pipe_options::PipeOptions;
|
||||
|
||||
use crate::queuing_strategy::QueuingStrategy;
|
||||
use crate::readable::into_underlying_byte_source::IntoUnderlyingByteSource;
|
||||
use crate::util::promise_to_void_future;
|
||||
use crate::writable::WritableStream;
|
||||
|
||||
mod byob_reader;
|
||||
mod default_reader;
|
||||
mod into_async_read;
|
||||
mod into_stream;
|
||||
mod into_underlying_byte_source;
|
||||
mod into_underlying_source;
|
||||
mod pipe_options;
|
||||
pub mod sys;
|
||||
|
||||
/// A [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).
|
||||
///
|
||||
/// `ReadableStream`s can be created from a [raw JavaScript stream](sys::ReadableStream) with
|
||||
/// [`from_raw`](Self::from_raw), or from a Rust [`Stream`] with [`from_stream`](Self::from_stream).
|
||||
///
|
||||
/// They can be converted into a [raw JavaScript stream](sys::ReadableStream) with
|
||||
/// [`into_raw`](Self::into_raw), or into a Rust [`Stream`] with [`into_stream`](Self::into_stream).
|
||||
///
|
||||
/// If the browser supports [readable byte streams](https://streams.spec.whatwg.org/#readable-byte-stream),
|
||||
/// then they can be created from a Rust [`AsyncRead`] with [`from_async_read`](Self::from_async_read),
|
||||
/// or converted into one with [`into_async_read`](Self::into_async_read).
|
||||
///
|
||||
/// [`Stream`]: https://docs.rs/futures/0.3.30/futures/stream/trait.Stream.html
|
||||
/// [`AsyncRead`]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncRead.html
|
||||
#[derive(Debug)]
|
||||
pub struct ReadableStream {
|
||||
raw: sys::ReadableStream,
|
||||
}
|
||||
|
||||
impl ReadableStream {
|
||||
/// Creates a new `ReadableStream` from a [JavaScript stream](sys::ReadableStream).
|
||||
#[inline]
|
||||
pub fn from_raw(raw: sys::ReadableStream) -> Self {
|
||||
Self { raw }
|
||||
}
|
||||
|
||||
/// Creates a new `ReadableStream` from a [`Stream`].
|
||||
///
|
||||
/// Items and errors must be represented as raw [`JsValue`]s.
|
||||
/// Use [`map`], [`map_ok`] and/or [`map_err`] to convert a stream's items to a `JsValue`
|
||||
/// before passing it to this function.
|
||||
///
|
||||
/// [`Stream`]: https://docs.rs/futures/0.3.30/futures/stream/trait.Stream.html
|
||||
/// [`map`]: https://docs.rs/futures/0.3.30/futures/stream/trait.StreamExt.html#method.map
|
||||
/// [`map_ok`]: https://docs.rs/futures/0.3.30/futures/stream/trait.TryStreamExt.html#method.map_ok
|
||||
/// [`map_err`]: https://docs.rs/futures/0.3.30/futures/stream/trait.TryStreamExt.html#method.map_err
|
||||
pub fn from_stream<St>(stream: St) -> Self
|
||||
where
|
||||
St: Stream<Item = Result<JsValue, JsValue>> + 'static,
|
||||
{
|
||||
let source = IntoUnderlyingSource::new(Box::new(stream));
|
||||
// Set HWM to 0 to prevent the JS ReadableStream from buffering chunks in its queue,
|
||||
// since the original Rust stream is better suited to handle that.
|
||||
let strategy = QueuingStrategy::new(0.0);
|
||||
let raw =
|
||||
sys::ReadableStreamExt::new_with_into_underlying_source(source, strategy.into_raw())
|
||||
.unchecked_into();
|
||||
Self::from_raw(raw)
|
||||
}
|
||||
|
||||
/// Creates a new `ReadableStream` from an [`AsyncRead`].
|
||||
///
|
||||
/// This creates a readable byte stream whose `autoAllocateChunkSize` is `default_buffer_len`.
|
||||
/// Therefore, if a default reader is used to consume the stream, the given `async_read`
|
||||
/// will be [polled][AsyncRead::poll_read] with a buffer of this size. If a BYOB reader is used,
|
||||
/// then it will be polled with a buffer of the same size as the BYOB read request instead.
|
||||
///
|
||||
/// **Panics** if readable byte streams are not supported by the browser.
|
||||
///
|
||||
/// [`AsyncRead`]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncRead.html
|
||||
/// [AsyncRead::poll_read]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncRead.html#tymethod.poll_read
|
||||
// TODO Non-panicking variant?
|
||||
pub fn from_async_read<R>(async_read: R, default_buffer_len: usize) -> Self
|
||||
where
|
||||
R: AsyncRead + 'static,
|
||||
{
|
||||
let source = IntoUnderlyingByteSource::new(Box::new(async_read), default_buffer_len);
|
||||
let raw = sys::ReadableStreamExt::new_with_into_underlying_byte_source(source)
|
||||
.expect_throw("readable byte streams not supported")
|
||||
.unchecked_into();
|
||||
Self::from_raw(raw)
|
||||
}
|
||||
|
||||
/// Creates a new `ReadableStream` wrapping the provided [iterable] or [async iterable].
|
||||
///
|
||||
/// This can be used to adapt various kinds of objects into a readable stream,
|
||||
/// such as an [array], an [async generator] or a [Node.js readable stream][Readable].
|
||||
///
|
||||
/// **Panics** if `ReadableStream.from()` is not supported by the browser,
|
||||
/// or if the given object is not a valid iterable or async iterable.
|
||||
/// For a non-panicking variant, use [`try_from`](Self::try_from).
|
||||
///
|
||||
/// [iterable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol
|
||||
/// [async iterable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols
|
||||
/// [array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
|
||||
/// [async generator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator
|
||||
/// [Readable]: https://nodejs.org/api/stream.html#class-streamreadable
|
||||
pub fn from(async_iterable: Object) -> Self {
|
||||
Self::try_from(async_iterable).unwrap_throw()
|
||||
}
|
||||
|
||||
/// Try to create a new `ReadableStream` wrapping the provided [iterable] or [async iterable].
|
||||
///
|
||||
/// This can be used to adapt various kinds of objects into a readable stream,
|
||||
/// such as an [array], an [async generator] or a [Node.js readable stream][Readable].
|
||||
///
|
||||
/// If `ReadableStream.from()` is not supported by the browser,
|
||||
/// or if the given object is not a valid iterable or async iterable,
|
||||
/// then this returns an error.
|
||||
///
|
||||
/// [iterable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol
|
||||
/// [async iterable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols
|
||||
/// [array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
|
||||
/// [async generator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator
|
||||
/// [Readable]: https://nodejs.org/api/stream.html#class-streamreadable
|
||||
pub fn try_from(async_iterable: Object) -> Result<Self, js_sys::Error> {
|
||||
let raw = sys::ReadableStreamExt::from_async_iterable(&async_iterable)?.unchecked_into();
|
||||
Ok(Self::from_raw(raw))
|
||||
}
|
||||
|
||||
/// Acquires a reference to the underlying [JavaScript stream](sys::ReadableStream).
|
||||
#[inline]
|
||||
pub fn as_raw(&self) -> &sys::ReadableStream {
|
||||
&self.raw
|
||||
}
|
||||
|
||||
/// Consumes this `ReadableStream`, returning the underlying [JavaScript stream](sys::ReadableStream).
|
||||
#[inline]
|
||||
pub fn into_raw(self) -> sys::ReadableStream {
|
||||
self.raw
|
||||
}
|
||||
|
||||
/// Returns `true` if the stream is [locked to a reader](https://streams.spec.whatwg.org/#lock).
|
||||
#[inline]
|
||||
pub fn is_locked(&self) -> bool {
|
||||
self.as_raw().locked()
|
||||
}
|
||||
|
||||
/// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// signaling a loss of interest in the stream by a consumer.
|
||||
///
|
||||
/// If the stream is currently locked to a reader, then this returns an error.
|
||||
pub async fn cancel(&mut self) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().cancel()).await
|
||||
}
|
||||
|
||||
/// [Cancels](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// signaling a loss of interest in the stream by a consumer.
|
||||
///
|
||||
/// The supplied `reason` will be given to the underlying source, which may or may not use it.
|
||||
///
|
||||
/// If the stream is currently locked to a reader, then this returns an error.
|
||||
pub async fn cancel_with_reason(&mut self, reason: &JsValue) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().cancel_with_reason(reason)).await
|
||||
}
|
||||
|
||||
/// Creates a [default reader](ReadableStreamDefaultReader) and
|
||||
/// [locks](https://streams.spec.whatwg.org/#lock) the stream to the new reader.
|
||||
///
|
||||
/// While the stream is locked, no other reader can be acquired until this one is released.
|
||||
///
|
||||
/// **Panics** if the stream is already locked to a reader. For a non-panicking variant,
|
||||
/// use [`try_get_reader`](Self::try_get_reader).
|
||||
#[inline]
|
||||
pub fn get_reader(&mut self) -> ReadableStreamDefaultReader<'_> {
|
||||
self.try_get_reader()
|
||||
.expect_throw("already locked to a reader")
|
||||
}
|
||||
|
||||
/// Try to create a [default reader](ReadableStreamDefaultReader) and
|
||||
/// [lock](https://streams.spec.whatwg.org/#lock) the stream to the new reader.
|
||||
///
|
||||
/// While the stream is locked, no other reader can be acquired until this one is released.
|
||||
///
|
||||
/// If the stream is already locked to a reader, then this returns an error.
|
||||
pub fn try_get_reader(&mut self) -> Result<ReadableStreamDefaultReader<'_>, js_sys::Error> {
|
||||
ReadableStreamDefaultReader::new(self)
|
||||
}
|
||||
|
||||
/// Creates a [BYOB reader](ReadableStreamBYOBReader) and
|
||||
/// [locks](https://streams.spec.whatwg.org/#lock) the stream to the new reader.
|
||||
///
|
||||
/// While the stream is locked, no other reader can be acquired until this one is released.
|
||||
///
|
||||
/// **Panics** if the stream is already locked to a reader, or if this stream is not a readable
|
||||
/// byte stream. For a non-panicking variant, use [`try_get_reader`](Self::try_get_reader).
|
||||
pub fn get_byob_reader(&mut self) -> ReadableStreamBYOBReader<'_> {
|
||||
self.try_get_byob_reader()
|
||||
.expect_throw("already locked to a reader, or not a readable byte stream")
|
||||
}
|
||||
|
||||
/// Try to create a [BYOB reader](ReadableStreamBYOBReader) and
|
||||
/// [lock](https://streams.spec.whatwg.org/#lock) the stream to the new reader.
|
||||
///
|
||||
/// While the stream is locked, no other reader can be acquired until this one is released.
|
||||
///
|
||||
/// If the stream is already locked to a reader, then this returns an error.
|
||||
pub fn try_get_byob_reader(&mut self) -> Result<ReadableStreamBYOBReader<'_>, js_sys::Error> {
|
||||
ReadableStreamBYOBReader::new(self)
|
||||
}
|
||||
|
||||
/// [Pipes](https://streams.spec.whatwg.org/#piping) this readable stream to a given
|
||||
/// writable stream.
|
||||
///
|
||||
/// Piping a stream will [lock](https://streams.spec.whatwg.org/#lock) it for the duration
|
||||
/// of the pipe, preventing any other consumer from acquiring a reader.
|
||||
///
|
||||
/// This returns `()` if the pipe completes successfully, or `Err(error)` if any `error`
|
||||
/// was encountered during the process.
|
||||
pub async fn pipe_to<'a>(&'a mut self, dest: &'a mut WritableStream) -> Result<(), JsValue> {
|
||||
self.pipe_to_with_options(dest, &PipeOptions::default())
|
||||
.await
|
||||
}
|
||||
|
||||
/// [Pipes](https://streams.spec.whatwg.org/#piping) this readable stream to a given
|
||||
/// writable stream.
|
||||
///
|
||||
/// Piping a stream will [lock](https://streams.spec.whatwg.org/#lock) it for the duration
|
||||
/// of the pipe, preventing any other consumer from acquiring a reader.
|
||||
///
|
||||
/// Errors and closures of the source and destination streams propagate as follows:
|
||||
/// * An error in the source readable stream will [abort](https://streams.spec.whatwg.org/#abort-a-writable-stream)
|
||||
/// the destination writable stream, unless [`options.prevent_abort`](PipeOptions::prevent_abort)
|
||||
/// is `true`.
|
||||
/// * An error in the destination writable stream will [cancel](https://streams.spec.whatwg.org/#cancel-a-readable-stream)
|
||||
/// the source readable stream, unless [`options.prevent_cancel`](PipeOptions::prevent_cancel)
|
||||
/// is `true`.
|
||||
/// * When the source readable stream closes, the destination writable stream will be closed,
|
||||
/// unless [`options.prevent_close`](PipeOptions::prevent_close) is `true`.
|
||||
/// * If the destination writable stream starts out closed or closing, the source readable stream
|
||||
/// will be [canceled](https://streams.spec.whatwg.org/#cancel-a-readable-stream),
|
||||
/// unless unless [`options.prevent_cancel`](PipeOptions::prevent_cancel) is `true`.
|
||||
///
|
||||
/// This returns `()` if the pipe completes successfully, or `Err(error)` if any `error`
|
||||
/// was encountered during the process.
|
||||
pub async fn pipe_to_with_options<'a>(
|
||||
&'a mut self,
|
||||
dest: &'a mut WritableStream,
|
||||
options: &PipeOptions,
|
||||
) -> Result<(), JsValue> {
|
||||
let promise = self
|
||||
.as_raw()
|
||||
.pipe_to_with_options(dest.as_raw(), &options.clone().into_raw());
|
||||
promise_to_void_future(promise).await
|
||||
}
|
||||
|
||||
/// [Tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) this readable stream,
|
||||
/// returning the two resulting branches as new [`ReadableStream`] instances.
|
||||
///
|
||||
/// Teeing a stream will [lock](https://streams.spec.whatwg.org/#lock) it, preventing any other
|
||||
/// consumer from acquiring a reader.
|
||||
/// To [cancel](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// cancel both of the resulting branches; a composite cancellation reason will then be
|
||||
/// propagated to the stream's underlying source.
|
||||
///
|
||||
/// Note that the chunks seen in each branch will be the same object.
|
||||
/// If the chunks are not immutable, this could allow interference between the two branches.
|
||||
///
|
||||
/// **Panics** if the stream is already locked to a reader. For a non-panicking variant,
|
||||
/// use [`try_tee`](Self::try_tee).
|
||||
pub fn tee(self) -> (ReadableStream, ReadableStream) {
|
||||
self.try_tee().expect_throw("already locked to a reader")
|
||||
}
|
||||
|
||||
/// Tries to [tee](https://streams.spec.whatwg.org/#tee-a-readable-stream) this readable stream,
|
||||
/// returning the two resulting branches as new [`ReadableStream`] instances.
|
||||
///
|
||||
/// Teeing a stream will [lock](https://streams.spec.whatwg.org/#lock) it, preventing any other
|
||||
/// consumer from acquiring a reader.
|
||||
/// To [cancel](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream,
|
||||
/// cancel both of the resulting branches; a composite cancellation reason will then be
|
||||
/// propagated to the stream's underlying source.
|
||||
///
|
||||
/// Note that the chunks seen in each branch will be the same object.
|
||||
/// If the chunks are not immutable, this could allow interference between the two branches.
|
||||
///
|
||||
/// If the stream is already locked to a reader, then this returns an error
|
||||
/// along with the original `ReadableStream`.
|
||||
pub fn try_tee(self) -> Result<(ReadableStream, ReadableStream), (js_sys::Error, Self)> {
|
||||
let branches = self
|
||||
.as_raw()
|
||||
.unchecked_ref::<sys::ReadableStreamExt>()
|
||||
.try_tee()
|
||||
.map_err(|err| (err, self))?;
|
||||
debug_assert_eq!(branches.length(), 2);
|
||||
let (left, right) = (branches.get(0), branches.get(1));
|
||||
Ok((
|
||||
Self::from_raw(left.unchecked_into()),
|
||||
Self::from_raw(right.unchecked_into()),
|
||||
))
|
||||
}
|
||||
|
||||
/// Converts this `ReadableStream` into a [`Stream`].
|
||||
///
|
||||
/// Items and errors are represented by their raw [`JsValue`].
|
||||
/// Use [`map`], [`map_ok`] and/or [`map_err`] on the returned stream to convert them to a more
|
||||
/// appropriate type.
|
||||
///
|
||||
/// **Panics** if the stream is already locked to a reader. For a non-panicking variant,
|
||||
/// use [`try_into_stream`](Self::try_into_stream).
|
||||
///
|
||||
/// [`Stream`]: https://docs.rs/futures/0.3.30/futures/stream/trait.Stream.html
|
||||
/// [`map`]: https://docs.rs/futures/0.3.30/futures/stream/trait.StreamExt.html#method.map
|
||||
/// [`map_ok`]: https://docs.rs/futures/0.3.30/futures/stream/trait.TryStreamExt.html#method.map_ok
|
||||
/// [`map_err`]: https://docs.rs/futures/0.3.30/futures/stream/trait.TryStreamExt.html#method.map_err
|
||||
#[inline]
|
||||
pub fn into_stream(self) -> IntoStream<'static> {
|
||||
self.try_into_stream()
|
||||
.expect_throw("already locked to a reader")
|
||||
}
|
||||
|
||||
/// Try to convert this `ReadableStream` into a [`Stream`].
|
||||
///
|
||||
/// Items and errors are represented by their raw [`JsValue`].
|
||||
/// Use [`map`], [`map_ok`] and/or [`map_err`] on the returned stream to convert them to a more
|
||||
/// appropriate type.
|
||||
///
|
||||
/// If the stream is already locked to a reader, then this returns an error
|
||||
/// along with the original `ReadableStream`.
|
||||
///
|
||||
/// [`Stream`]: https://docs.rs/futures/0.3.30/futures/stream/trait.Stream.html
|
||||
/// [`map`]: https://docs.rs/futures/0.3.30/futures/stream/trait.StreamExt.html#method.map
|
||||
/// [`map_ok`]: https://docs.rs/futures/0.3.30/futures/stream/trait.TryStreamExt.html#method.map_ok
|
||||
/// [`map_err`]: https://docs.rs/futures/0.3.30/futures/stream/trait.TryStreamExt.html#method.map_err
|
||||
pub fn try_into_stream(mut self) -> Result<IntoStream<'static>, (js_sys::Error, Self)> {
|
||||
let reader = ReadableStreamDefaultReader::new(&mut self).map_err(|err| (err, self))?;
|
||||
Ok(IntoStream::new(reader, true))
|
||||
}
|
||||
|
||||
/// Converts this `ReadableStream` into an [`AsyncRead`].
|
||||
///
|
||||
/// **Panics** if the stream is already locked to a reader, or if this stream is not a readable
|
||||
/// byte stream. For a non-panicking variant, use [`try_into_async_read`](Self::try_into_async_read).
|
||||
///
|
||||
/// [`AsyncRead`]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncRead.html
|
||||
#[inline]
|
||||
pub fn into_async_read(self) -> IntoAsyncRead<'static> {
|
||||
self.try_into_async_read()
|
||||
.expect_throw("already locked to a reader, or not a readable byte stream")
|
||||
}
|
||||
|
||||
/// Try to convert this `ReadableStream` into an [`AsyncRead`].
|
||||
///
|
||||
/// If the stream is already locked to a reader, or if this stream is not a readable byte
|
||||
/// stream, then this returns an error along with the original `ReadableStream`.
|
||||
///
|
||||
/// [`AsyncRead`]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncRead.html
|
||||
pub fn try_into_async_read(mut self) -> Result<IntoAsyncRead<'static>, (js_sys::Error, Self)> {
|
||||
let reader = ReadableStreamBYOBReader::new(&mut self).map_err(|err| (err, self))?;
|
||||
Ok(IntoAsyncRead::new(reader, true))
|
||||
}
|
||||
}
|
||||
|
||||
impl<St> From<St> for ReadableStream
|
||||
where
|
||||
St: Stream<Item = Result<JsValue, JsValue>> + 'static,
|
||||
{
|
||||
/// Equivalent to [`from_stream`](Self::from_stream).
|
||||
#[inline]
|
||||
fn from(stream: St) -> Self {
|
||||
Self::from_stream(stream)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use web_sys::AbortSignal;
|
||||
|
||||
use super::sys;
|
||||
|
||||
/// Options for [`pipe_to_with_options`](super::ReadableStream::pipe_to_with_options).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PipeOptions {
|
||||
raw: sys::PipeOptions,
|
||||
}
|
||||
|
||||
impl PipeOptions {
|
||||
/// Creates a blank new set of pipe options.
|
||||
///
|
||||
/// Equivalent to [`PipeOptions::default`](Default::default).
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Creates a set of pipe options from a raw [`PipeOptions`](sys::PipeOptions) object.
|
||||
#[inline]
|
||||
pub fn from_raw(raw: sys::PipeOptions) -> Self {
|
||||
Self { raw }
|
||||
}
|
||||
|
||||
/// Convert this to a raw [`PipeOptions`](sys::PipeOptions) object.
|
||||
#[inline]
|
||||
pub fn into_raw(self) -> sys::PipeOptions {
|
||||
self.raw
|
||||
}
|
||||
|
||||
/// Sets whether the destination writable stream should be closed
|
||||
/// when the source readable stream closes.
|
||||
pub fn prevent_close(&mut self, prevent_close: bool) -> &mut Self {
|
||||
self.raw.set_prevent_close(prevent_close);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the source readable stream should be [canceled](https://streams.spec.whatwg.org/#cancel-a-readable-stream)
|
||||
/// when the destination writable stream errors.
|
||||
pub fn prevent_cancel(&mut self, prevent_cancel: bool) -> &mut Self {
|
||||
self.raw.set_prevent_cancel(prevent_cancel);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the destination writable stream should be [aborted](https://streams.spec.whatwg.org/#abort-a-writable-stream)
|
||||
/// when the source readable stream errors.
|
||||
pub fn prevent_abort(&mut self, prevent_abort: bool) -> &mut Self {
|
||||
self.raw.set_prevent_abort(prevent_abort);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets an abort signal to abort the ongoing pipe operation.
|
||||
/// When the signal is aborted, the source readable stream will be canceled
|
||||
/// and the destination writable stream will be aborted
|
||||
/// unless the respective options [`prevent_cancel`](Self::prevent_cancel)
|
||||
/// or [`prevent_abort`](Self::prevent_abort) are set.
|
||||
pub fn signal(&mut self, signal: AbortSignal) -> &mut Self {
|
||||
self.raw.set_signal(&signal);
|
||||
self
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
//! Raw bindings to JavaScript objects used
|
||||
//! by a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).
|
||||
//! These are re-exported from [web-sys](https://docs.rs/web-sys/0.3.70/web_sys/struct.ReadableStream.html).
|
||||
use js_sys::{Array, Error, Object};
|
||||
use wasm_bindgen::prelude::*;
|
||||
pub use web_sys::ReadableByteStreamController;
|
||||
// Re-export from web-sys
|
||||
pub use web_sys::ReadableStream;
|
||||
pub use web_sys::ReadableStreamByobReader as ReadableStreamBYOBReader;
|
||||
pub use web_sys::ReadableStreamByobRequest as ReadableStreamBYOBRequest;
|
||||
pub use web_sys::ReadableStreamDefaultController;
|
||||
pub use web_sys::ReadableStreamDefaultReader;
|
||||
pub use web_sys::ReadableStreamGetReaderOptions;
|
||||
pub use web_sys::ReadableStreamReadResult;
|
||||
pub use web_sys::ReadableStreamReaderMode;
|
||||
pub use web_sys::ReadableStreamType;
|
||||
pub use web_sys::StreamPipeOptions as PipeOptions;
|
||||
|
||||
use crate::queuing_strategy::sys::QueuingStrategy;
|
||||
use crate::readable::into_underlying_byte_source::IntoUnderlyingByteSource;
|
||||
use crate::readable::into_underlying_source::IntoUnderlyingSource;
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
/// Additional methods for [`ReadableStream`](web_sys::ReadableStream).
|
||||
#[wasm_bindgen(js_name = ReadableStream, typescript_type = "ReadableStream")]
|
||||
pub(crate) type ReadableStreamExt;
|
||||
|
||||
#[wasm_bindgen(constructor, js_class = ReadableStream)]
|
||||
pub(crate) fn new_with_into_underlying_source(
|
||||
source: IntoUnderlyingSource,
|
||||
strategy: QueuingStrategy,
|
||||
) -> ReadableStreamExt;
|
||||
|
||||
#[wasm_bindgen(constructor, catch, js_class = ReadableStream)]
|
||||
pub(crate) fn new_with_into_underlying_byte_source(
|
||||
source: IntoUnderlyingByteSource,
|
||||
) -> Result<ReadableStreamExt, Error>;
|
||||
|
||||
#[wasm_bindgen(method, catch, js_class = ReadableStream, js_name = getReader)]
|
||||
pub(crate) fn try_get_reader(this: &ReadableStreamExt) -> Result<Object, Error>;
|
||||
|
||||
#[wasm_bindgen(method, catch, js_class = ReadableStream, js_name = getReader)]
|
||||
pub(crate) fn try_get_reader_with_options(
|
||||
this: &ReadableStreamExt,
|
||||
options: &ReadableStreamGetReaderOptions,
|
||||
) -> Result<Object, Error>;
|
||||
|
||||
#[wasm_bindgen(method, catch, js_class = ReadableStream, js_name = tee)]
|
||||
pub(crate) fn try_tee(this: &ReadableStreamExt) -> Result<Array, Error>;
|
||||
|
||||
#[wasm_bindgen(catch, static_method_of = ReadableStreamExt, js_class = ReadableStream, js_name = from)]
|
||||
pub(crate) fn from_async_iterable(async_iterable: &Object) -> Result<ReadableStreamExt, Error>;
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
/// Additional methods for [`ReadableStreamDefaultReader`](web_sys::ReadableStreamDefaultReader)
|
||||
/// and [`ReadableStreamByobReader`](web_sys::ReadableStreamByobReader).
|
||||
pub(crate) type ReadableStreamReaderExt;
|
||||
|
||||
#[wasm_bindgen(method, catch, js_name = releaseLock)]
|
||||
pub(crate) fn try_release_lock(this: &ReadableStreamReaderExt) -> Result<(), Error>;
|
||||
}
|
||||
Reference in New Issue
Block a user