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:
+146
@@ -0,0 +1,146 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use wasm_bindgen::{throw_val, JsValue};
|
||||
|
||||
use crate::util::promise_to_void_future;
|
||||
|
||||
use super::{sys, IntoAsyncWrite, IntoSink, WritableStream};
|
||||
|
||||
/// A [`WritableStreamDefaultWriter`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultWriter)
|
||||
/// that can be used to write chunks to a [`WritableStream`](WritableStream).
|
||||
///
|
||||
/// This is returned by the [`get_writer`](WritableStream::get_writer) method.
|
||||
///
|
||||
/// When the writer is dropped, it automatically [releases its lock](https://streams.spec.whatwg.org/#release-a-lock).
|
||||
#[derive(Debug)]
|
||||
pub struct WritableStreamDefaultWriter<'stream> {
|
||||
raw: sys::WritableStreamDefaultWriter,
|
||||
_stream: PhantomData<&'stream mut WritableStream>,
|
||||
}
|
||||
|
||||
impl<'stream> WritableStreamDefaultWriter<'stream> {
|
||||
pub(crate) fn new(stream: &mut WritableStream) -> Result<Self, js_sys::Error> {
|
||||
Ok(Self {
|
||||
raw: stream.as_raw().get_writer()?,
|
||||
_stream: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
/// Acquires a reference to the underlying [JavaScript writer](sys::WritableStreamDefaultWriter).
|
||||
#[inline]
|
||||
pub fn as_raw(&self) -> &sys::WritableStreamDefaultWriter {
|
||||
&self.raw
|
||||
}
|
||||
|
||||
/// Waits for the stream to become closed.
|
||||
///
|
||||
/// This returns an error if the stream ever errors, or if the writer'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
|
||||
}
|
||||
|
||||
/// Returns the desired size to fill the stream's internal queue.
|
||||
///
|
||||
/// * It can be negative, if the queue is over-full.
|
||||
/// A producer can use this information to determine the right amount of data to write.
|
||||
/// * It will be `None` if the stream cannot be successfully written to
|
||||
/// (due to either being errored, or having an abort queued up).
|
||||
/// * It will return zero if the stream is closed.
|
||||
#[inline]
|
||||
pub fn desired_size(&self) -> Option<f64> {
|
||||
self.as_raw()
|
||||
.desired_size()
|
||||
.unwrap_or_else(|error| throw_val(error))
|
||||
}
|
||||
|
||||
/// Waits until the desired size to fill the stream's internal queue transitions
|
||||
/// from non-positive to positive, signaling that it is no longer applying backpressure.
|
||||
///
|
||||
/// Once the desired size to fill the stream's internal queue dips back to zero or below,
|
||||
/// this will return a new future that stays pending until the next transition.
|
||||
///
|
||||
/// This returns an error if the stream ever errors, or if the writer's lock is
|
||||
/// [released](https://streams.spec.whatwg.org/#release-a-lock) before the stream finishes
|
||||
/// closing.
|
||||
pub async fn ready(&self) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().ready()).await
|
||||
}
|
||||
|
||||
/// [Aborts](https://streams.spec.whatwg.org/#abort-a-writable-stream) the stream,
|
||||
/// signaling that the producer can no longer successfully write to the stream.
|
||||
///
|
||||
/// Equivalent to [`WritableStream.abort`](WritableStream::abort).
|
||||
pub async fn abort(&mut self) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().abort()).await
|
||||
}
|
||||
|
||||
/// [Aborts](https://streams.spec.whatwg.org/#abort-a-writable-stream) the stream with the
|
||||
/// given `reason`, signaling that the producer can no longer successfully write to the stream.
|
||||
///
|
||||
/// Equivalent to [`WritableStream.abort_with_reason`](WritableStream::abort_with_reason).
|
||||
pub async fn abort_with_reason(&mut self, reason: &JsValue) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().abort_with_reason(reason)).await
|
||||
}
|
||||
|
||||
/// Writes the given `chunk` to the writable stream, by waiting until any previous writes
|
||||
/// have finished successfully, and then sending the chunk to the underlying sink's `write()`
|
||||
/// method.
|
||||
///
|
||||
/// This returns `Ok(())` upon a successful write, or `Err(error)` if the write fails or stream
|
||||
/// becomes errored before the writing process is initiated.
|
||||
///
|
||||
/// Note that what "success" means is up to the underlying sink; it might indicate simply
|
||||
/// that the chunk has been accepted, and not necessarily that it is safely saved to
|
||||
/// its ultimate destination.
|
||||
pub async fn write(&mut self, chunk: JsValue) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().write_with_chunk(&chunk)).await
|
||||
}
|
||||
|
||||
/// Closes the stream.
|
||||
///
|
||||
/// The underlying sink will finish processing any previously-written chunks, before invoking
|
||||
/// its close behavior. During this time any further attempts to write will fail
|
||||
/// (without erroring the stream).
|
||||
///
|
||||
/// This returns `Ok(())` if all remaining chunks are successfully written and the stream
|
||||
/// successfully closes, or `Err(error)` if an error is encountered during this process.
|
||||
pub async fn close(&mut self) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().close()).await
|
||||
}
|
||||
|
||||
/// Converts this `WritableStreamDefaultWriter` into a [`Sink`].
|
||||
///
|
||||
/// This is similar to [`WritableStream.into_sink`](WritableStream::into_sink),
|
||||
/// except that after the returned `Sink` is dropped, the original `WritableStream` is still
|
||||
/// usable. This allows writing only a few chunks through the `Sink`, while still allowing
|
||||
/// another writer to write more chunks later on.
|
||||
///
|
||||
/// [`Sink`]: https://docs.rs/futures/0.3.30/futures/sink/trait.Sink.html
|
||||
#[inline]
|
||||
pub fn into_sink(self) -> IntoSink<'stream> {
|
||||
IntoSink::new(self)
|
||||
}
|
||||
|
||||
/// Converts this `WritableStreamDefaultWriter` into an [`AsyncWrite`].
|
||||
///
|
||||
/// The writable stream must accept [`Uint8Array`](js_sys::Uint8Array) chunks.
|
||||
///
|
||||
/// This is similar to [`WritableStream.into_async_write`](WritableStream::into_async_write),
|
||||
/// except that after the returned `AsyncWrite` is dropped, the original `WritableStream` is
|
||||
/// still usable. This allows writing only a few bytes through the `AsyncWrite`, while still
|
||||
/// allowing another writer to write more bytes later on.
|
||||
///
|
||||
/// [`AsyncWrite`]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncWrite.html
|
||||
#[inline]
|
||||
pub fn into_async_write(self) -> IntoAsyncWrite<'stream> {
|
||||
IntoAsyncWrite::new(self.into_sink())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WritableStreamDefaultWriter<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.as_raw().release_lock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use futures_util::io::AsyncWrite;
|
||||
use futures_util::ready;
|
||||
use futures_util::sink::SinkExt;
|
||||
use js_sys::Uint8Array;
|
||||
use wasm_bindgen::JsValue;
|
||||
|
||||
use crate::util::js_to_io_error;
|
||||
|
||||
use super::IntoSink;
|
||||
|
||||
/// An [`AsyncWrite`] for the [`into_async_write`](super::WritableStream::into_async_write) method.
|
||||
///
|
||||
/// This `AsyncWrite` holds a writer, and therefore locks the [`WritableStream`](super::WritableStream).
|
||||
/// When this `AsyncWrite` is dropped, it also drops its writer which in turn
|
||||
/// [releases its lock](https://streams.spec.whatwg.org/#release-a-lock).
|
||||
///
|
||||
/// [`AsyncWrite`]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncWrite.html
|
||||
#[must_use = "writers do nothing unless polled"]
|
||||
#[derive(Debug)]
|
||||
pub struct IntoAsyncWrite<'writer> {
|
||||
sink: IntoSink<'writer>,
|
||||
}
|
||||
|
||||
impl<'writer> IntoAsyncWrite<'writer> {
|
||||
#[inline]
|
||||
pub(super) fn new(sink: IntoSink<'writer>) -> Self {
|
||||
Self { sink }
|
||||
}
|
||||
|
||||
/// [Aborts](https://streams.spec.whatwg.org/#abort-a-writable-stream) the stream,
|
||||
/// signaling that the producer can no longer successfully write to the stream.
|
||||
pub async fn abort(self) -> Result<(), JsValue> {
|
||||
self.sink.abort().await
|
||||
}
|
||||
|
||||
/// [Aborts](https://streams.spec.whatwg.org/#abort-a-writable-stream) the stream,
|
||||
/// signaling that the producer can no longer successfully write to the stream.
|
||||
pub async fn abort_with_reason(self, reason: &JsValue) -> Result<(), JsValue> {
|
||||
self.sink.abort_with_reason(reason).await
|
||||
}
|
||||
}
|
||||
|
||||
impl<'writer> AsyncWrite for IntoAsyncWrite<'writer> {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<std::io::Result<usize>> {
|
||||
ready!(self
|
||||
.as_mut()
|
||||
.sink
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(js_to_io_error))?;
|
||||
self.as_mut()
|
||||
.sink
|
||||
.start_send_unpin(Uint8Array::from(buf).into())
|
||||
.map_err(js_to_io_error)?;
|
||||
Poll::Ready(Ok(buf.len()))
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
self.as_mut()
|
||||
.sink
|
||||
.poll_flush_unpin(cx)
|
||||
.map_err(js_to_io_error)
|
||||
}
|
||||
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
self.as_mut()
|
||||
.sink
|
||||
.poll_close_unpin(cx)
|
||||
.map_err(js_to_io_error)
|
||||
}
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
use core::pin::Pin;
|
||||
use core::task::{Context, Poll};
|
||||
|
||||
use futures_util::Sink;
|
||||
use futures_util::{ready, FutureExt};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use super::WritableStreamDefaultWriter;
|
||||
|
||||
/// A [`Sink`] for the [`into_sink`](super::WritableStream::into_sink) method.
|
||||
///
|
||||
/// This sink holds a writer, and therefore locks the [`WritableStream`](super::WritableStream).
|
||||
/// When this sink is dropped, it also drops its writer which in turn
|
||||
/// [releases its lock](https://streams.spec.whatwg.org/#release-a-lock).
|
||||
///
|
||||
/// [`Sink`]: https://docs.rs/futures/0.3.30/futures/sink/trait.Sink.html
|
||||
#[must_use = "sinks do nothing unless polled"]
|
||||
#[derive(Debug)]
|
||||
pub struct IntoSink<'writer> {
|
||||
writer: Option<WritableStreamDefaultWriter<'writer>>,
|
||||
/// If an error occurred, this holds the error to return on subsequent operations.
|
||||
error: Option<JsValue>,
|
||||
ready_fut: Option<JsFuture>,
|
||||
write_fut: Option<JsFuture>,
|
||||
close_fut: Option<JsFuture>,
|
||||
}
|
||||
|
||||
impl<'writer> IntoSink<'writer> {
|
||||
#[inline]
|
||||
pub(super) fn new(writer: WritableStreamDefaultWriter) -> IntoSink {
|
||||
IntoSink {
|
||||
writer: Some(writer),
|
||||
error: None,
|
||||
ready_fut: None,
|
||||
write_fut: None,
|
||||
close_fut: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// [Aborts](https://streams.spec.whatwg.org/#abort-a-writable-stream) the stream,
|
||||
/// signaling that the producer can no longer successfully write to the stream.
|
||||
pub async fn abort(mut self) -> Result<(), JsValue> {
|
||||
match self.writer.take() {
|
||||
Some(mut writer) => writer.abort().await,
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// [Aborts](https://streams.spec.whatwg.org/#abort-a-writable-stream) the stream,
|
||||
/// signaling that the producer can no longer successfully write to the stream.
|
||||
pub async fn abort_with_reason(mut self, reason: &JsValue) -> Result<(), JsValue> {
|
||||
match self.writer.take() {
|
||||
Some(mut writer) => writer.abort_with_reason(reason).await,
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the stored error, or a default "sink is closed" error.
|
||||
fn get_error(&self) -> JsValue {
|
||||
self.error
|
||||
.clone()
|
||||
.unwrap_or_else(|| JsValue::from_str("WritableStream sink is already closed"))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'writer> Sink<JsValue> for IntoSink<'writer> {
|
||||
type Error = JsValue;
|
||||
|
||||
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
let ready_fut = match self.ready_fut.as_mut() {
|
||||
Some(fut) => fut,
|
||||
None => match &self.writer {
|
||||
Some(writer) => {
|
||||
// No pending ready future yet, create one from ready promise
|
||||
let fut = JsFuture::from(writer.as_raw().ready());
|
||||
self.ready_fut.insert(fut)
|
||||
}
|
||||
None => {
|
||||
// Writer was already dropped due to error or close
|
||||
return Poll::Ready(Err(self.get_error()));
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// Poll the ready future
|
||||
let js_result = ready!(ready_fut.poll_unpin(cx));
|
||||
self.ready_fut = None;
|
||||
|
||||
// Ready future completed
|
||||
Poll::Ready(match js_result {
|
||||
Ok(js_value) => {
|
||||
debug_assert!(js_value.is_undefined());
|
||||
Ok(())
|
||||
}
|
||||
Err(js_value) => {
|
||||
// Error, store it and drop writer
|
||||
self.error = Some(js_value.clone());
|
||||
self.writer = None;
|
||||
Err(js_value)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn start_send(mut self: Pin<&mut Self>, item: JsValue) -> Result<(), Self::Error> {
|
||||
match &self.writer {
|
||||
Some(writer) => {
|
||||
let fut = JsFuture::from(writer.as_raw().write_with_chunk(&item));
|
||||
// Set or replace the pending write future
|
||||
self.write_fut = Some(fut);
|
||||
Ok(())
|
||||
}
|
||||
None => {
|
||||
// Writer was already dropped due to error or close
|
||||
Err(self.get_error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
let write_fut = match self.write_fut.as_mut() {
|
||||
Some(fut) => fut,
|
||||
None => {
|
||||
// If we're not writing, then there's nothing to flush
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
};
|
||||
|
||||
// Poll the write future
|
||||
let js_result = ready!(write_fut.poll_unpin(cx));
|
||||
self.write_fut = None;
|
||||
|
||||
// Write future completed
|
||||
Poll::Ready(match js_result {
|
||||
Ok(js_value) => {
|
||||
debug_assert!(js_value.is_undefined());
|
||||
Ok(())
|
||||
}
|
||||
Err(js_value) => {
|
||||
// Error, store it and drop writer
|
||||
self.error = Some(js_value.clone());
|
||||
self.writer = None;
|
||||
Err(js_value)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
let close_fut = match self.close_fut.as_mut() {
|
||||
Some(fut) => fut,
|
||||
None => match &self.writer {
|
||||
Some(writer) => {
|
||||
// No pending close future
|
||||
// Start closing the stream and create future from close promise
|
||||
let fut = JsFuture::from(writer.as_raw().close());
|
||||
self.close_fut.insert(fut)
|
||||
}
|
||||
None => {
|
||||
// Writer was already dropped due to error or close
|
||||
return Poll::Ready(Err(self.get_error()));
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// Poll the close future
|
||||
let js_result = ready!(close_fut.poll_unpin(cx));
|
||||
self.close_fut = None;
|
||||
|
||||
// Close future completed
|
||||
self.writer = None;
|
||||
Poll::Ready(match js_result {
|
||||
Ok(js_value) => {
|
||||
debug_assert!(js_value.is_undefined());
|
||||
Ok(())
|
||||
}
|
||||
Err(js_value) => {
|
||||
self.error = Some(js_value.clone());
|
||||
Err(js_value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
use std::cell::RefCell;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
|
||||
use futures_util::{Sink, SinkExt};
|
||||
use js_sys::Promise;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::future_to_promise;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub(crate) struct IntoUnderlyingSink {
|
||||
inner: Rc<RefCell<Inner>>,
|
||||
}
|
||||
|
||||
impl IntoUnderlyingSink {
|
||||
pub fn new(sink: Box<dyn Sink<JsValue, Error = JsValue>>) -> Self {
|
||||
IntoUnderlyingSink {
|
||||
inner: Rc::new(RefCell::new(Inner::new(sink))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::await_holding_refcell_ref)]
|
||||
#[wasm_bindgen]
|
||||
impl IntoUnderlyingSink {
|
||||
pub fn write(&mut self, chunk: JsValue) -> Promise {
|
||||
let inner = self.inner.clone();
|
||||
// SAFETY: We use the take-and-replace pattern in Inner::write() to ensure
|
||||
// that if a panic occurs, the sink 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(async move {
|
||||
// This mutable borrow can never panic, since the WritableStream always queues
|
||||
// each operation on the underlying sink.
|
||||
let mut inner = inner.try_borrow_mut().unwrap_throw();
|
||||
inner.write(chunk).await.map(|_| JsValue::undefined())
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn close(self) -> Promise {
|
||||
// SAFETY: Inner::close() takes the sink before the fallible operation.
|
||||
future_to_promise(AssertUnwindSafe(async move {
|
||||
let mut inner = self.inner.try_borrow_mut().unwrap_throw();
|
||||
inner.close().await.map(|_| JsValue::undefined())
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn abort(self, reason: JsValue) -> Promise {
|
||||
// SAFETY: Inner::abort() just sets sink to None, no fallible operation.
|
||||
future_to_promise(AssertUnwindSafe(async move {
|
||||
let mut inner = self.inner.try_borrow_mut().unwrap_throw();
|
||||
inner.abort(reason).await.map(|_| JsValue::undefined())
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
sink: Option<Pin<Box<dyn Sink<JsValue, Error = JsValue>>>>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn new(sink: Box<dyn Sink<JsValue, Error = JsValue>>) -> Self {
|
||||
Inner {
|
||||
sink: Some(sink.into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn write(&mut self, chunk: JsValue) -> Result<(), JsValue> {
|
||||
// Take the sink out before the fallible/panickable operation.
|
||||
// This ensures that if a panic occurs, self.sink is already None,
|
||||
// so any subsequent call will fail cleanly instead of using corrupted state.
|
||||
let mut sink = self.sink.take().unwrap_throw();
|
||||
|
||||
match sink.send(chunk).await {
|
||||
Ok(()) => {
|
||||
// Success: put the sink back for reuse
|
||||
self.sink = Some(sink);
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => {
|
||||
// Error: the sink is dropped, self.sink remains None
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
// Panic: sink is dropped during unwind, self.sink remains None
|
||||
}
|
||||
|
||||
async fn close(&mut self) -> Result<(), JsValue> {
|
||||
// Take ownership and close - sink is dropped after close completes
|
||||
self.sink.take().unwrap_throw().close().await
|
||||
}
|
||||
|
||||
async fn abort(&mut self, _reason: JsValue) -> Result<(), JsValue> {
|
||||
// Take and drop the sink immediately
|
||||
self.sink = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
//! Bindings and conversions for
|
||||
//! [writable streams](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).
|
||||
|
||||
use futures_util::Sink;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
pub use default_writer::WritableStreamDefaultWriter;
|
||||
pub use into_async_write::IntoAsyncWrite;
|
||||
pub use into_sink::IntoSink;
|
||||
use into_underlying_sink::IntoUnderlyingSink;
|
||||
|
||||
use crate::util::promise_to_void_future;
|
||||
|
||||
mod default_writer;
|
||||
mod into_async_write;
|
||||
mod into_sink;
|
||||
mod into_underlying_sink;
|
||||
pub mod sys;
|
||||
|
||||
/// A [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).
|
||||
///
|
||||
/// `WritableStream`s can be created from a [raw JavaScript stream](sys::WritableStream) with
|
||||
/// [`from_raw`](Self::from_raw), or from a Rust [`Sink`] with [`from_sink`](Self::from_sink).
|
||||
///
|
||||
/// They can be converted into a [raw JavaScript stream](sys::WritableStream) with
|
||||
/// [`into_raw`](Self::into_raw), or into a Rust [`Sink`] with [`into_sink`](Self::into_sink).
|
||||
///
|
||||
/// [`Sink`]: https://docs.rs/futures/0.3.30/futures/sink/trait.Sink.html
|
||||
#[derive(Debug)]
|
||||
pub struct WritableStream {
|
||||
raw: sys::WritableStream,
|
||||
}
|
||||
|
||||
impl WritableStream {
|
||||
/// Creates a new `WritableStream` from a [JavaScript stream](sys::WritableStream).
|
||||
#[inline]
|
||||
pub fn from_raw(raw: sys::WritableStream) -> Self {
|
||||
Self { raw }
|
||||
}
|
||||
|
||||
/// Creates a new `WritableStream` from a [`Sink`].
|
||||
///
|
||||
/// Items and errors must be represented as raw [`JsValue`]s.
|
||||
/// Use [`with`] and/or [`sink_map_err`] to convert a sink's items to a `JsValue`
|
||||
/// before passing it to this function.
|
||||
///
|
||||
/// [`Sink`]: https://docs.rs/futures/0.3.30/futures/sink/trait.Sink.html
|
||||
/// [`with`]: https://docs.rs/futures/0.3.30/futures/sink/trait.SinkExt.html#method.with
|
||||
/// [`sink_map_err`]: https://docs.rs/futures/0.3.30/futures/sink/trait.SinkExt.html#method.sink_map_err
|
||||
pub fn from_sink<Si>(sink: Si) -> Self
|
||||
where
|
||||
Si: Sink<JsValue, Error = JsValue> + 'static,
|
||||
{
|
||||
let sink = IntoUnderlyingSink::new(Box::new(sink));
|
||||
// Use the default queuing strategy (with a HWM of 1 chunk).
|
||||
// We shouldn't set HWM to 0, since that would break piping to the writable stream.
|
||||
let raw = sys::WritableStreamExt::new_with_into_underlying_sink(sink).unchecked_into();
|
||||
Self::from_raw(raw)
|
||||
}
|
||||
|
||||
/// Acquires a reference to the underlying [JavaScript stream](sys::WritableStream).
|
||||
#[inline]
|
||||
pub fn as_raw(&self) -> &sys::WritableStream {
|
||||
&self.raw
|
||||
}
|
||||
|
||||
/// Consumes this `WritableStream`, returning the underlying [JavaScript stream](sys::WritableStream).
|
||||
#[inline]
|
||||
pub fn into_raw(self) -> sys::WritableStream {
|
||||
self.raw
|
||||
}
|
||||
|
||||
/// Returns `true` if the stream is [locked to a writer](https://streams.spec.whatwg.org/#lock).
|
||||
#[inline]
|
||||
pub fn is_locked(&self) -> bool {
|
||||
self.as_raw().locked()
|
||||
}
|
||||
|
||||
/// [Aborts](https://streams.spec.whatwg.org/#abort-a-writable-stream) the stream,
|
||||
/// signaling that the producer can no longer successfully write to the stream
|
||||
/// and it is to be immediately moved to an errored state, with any queued-up writes discarded.
|
||||
///
|
||||
/// If the stream is currently locked to a writer, then this returns an error.
|
||||
pub async fn abort(&mut self) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().abort()).await
|
||||
}
|
||||
|
||||
/// [Aborts](https://streams.spec.whatwg.org/#abort-a-writable-stream) the stream with the
|
||||
/// given `reason`, signaling that the producer can no longer successfully write to the stream
|
||||
/// and it is to be immediately moved to an errored state, with any queued-up writes discarded.
|
||||
///
|
||||
/// If the stream is currently locked to a writer, then this returns an error.
|
||||
pub async fn abort_with_reason(&mut self, reason: &JsValue) -> Result<(), JsValue> {
|
||||
promise_to_void_future(self.as_raw().abort_with_reason(reason)).await
|
||||
}
|
||||
|
||||
/// Creates a [writer](WritableStreamDefaultWriter) and
|
||||
/// [locks](https://streams.spec.whatwg.org/#lock) the stream to the new writer.
|
||||
///
|
||||
/// While the stream is locked, no other writer can be acquired until this one is released.
|
||||
///
|
||||
/// **Panics** if the stream is already locked to a writer. For a non-panicking variant,
|
||||
/// use [`try_get_writer`](Self::try_get_writer).
|
||||
#[inline]
|
||||
pub fn get_writer(&mut self) -> WritableStreamDefaultWriter<'_> {
|
||||
self.try_get_writer()
|
||||
.expect_throw("already locked to a writer")
|
||||
}
|
||||
|
||||
/// Try to create a [writer](WritableStreamDefaultWriter) and
|
||||
/// [lock](https://streams.spec.whatwg.org/#lock) the stream to the new writer.
|
||||
///
|
||||
/// While the stream is locked, no other writer can be acquired until this one is released.
|
||||
///
|
||||
/// If the stream is already locked to a writer, then this returns an error.
|
||||
pub fn try_get_writer(&mut self) -> Result<WritableStreamDefaultWriter<'_>, js_sys::Error> {
|
||||
WritableStreamDefaultWriter::new(self)
|
||||
}
|
||||
|
||||
/// Converts this `WritableStream` into a [`Sink`].
|
||||
///
|
||||
/// Items and errors are represented by their raw [`JsValue`].
|
||||
/// Use [`with`] and/or [`sink_map_err`] on the returned stream to convert them to a more
|
||||
/// appropriate type.
|
||||
///
|
||||
/// **Panics** if the stream is already locked to a writer. For a non-panicking variant,
|
||||
/// use [`try_into_sink`](Self::try_into_sink).
|
||||
///
|
||||
/// [`Sink`]: https://docs.rs/futures/0.3.30/futures/sink/trait.Sink.html
|
||||
/// [`with`]: https://docs.rs/futures/0.3.30/futures/sink/trait.SinkExt.html#method.with
|
||||
/// [`sink_map_err`]: https://docs.rs/futures/0.3.30/futures/sink/trait.SinkExt.html#method.sink_map_err
|
||||
#[inline]
|
||||
pub fn into_sink(self) -> IntoSink<'static> {
|
||||
self.try_into_sink()
|
||||
.expect_throw("already locked to a writer")
|
||||
}
|
||||
|
||||
/// Try to convert this `WritableStream` into a [`Sink`].
|
||||
///
|
||||
/// Items and errors are represented by their raw [`JsValue`].
|
||||
/// Use [`with`] and/or [`sink_map_err`] on the returned stream to convert them to a more
|
||||
/// appropriate type.
|
||||
///
|
||||
/// If the stream is already locked to a writer, then this returns an error
|
||||
/// along with the original `WritableStream`.
|
||||
///
|
||||
/// [`Sink`]: https://docs.rs/futures/0.3.30/futures/sink/trait.Sink.html
|
||||
/// [`with`]: https://docs.rs/futures/0.3.30/futures/sink/trait.SinkExt.html#method.with
|
||||
/// [`sink_map_err`]: https://docs.rs/futures/0.3.30/futures/sink/trait.SinkExt.html#method.sink_map_err
|
||||
pub fn try_into_sink(mut self) -> Result<IntoSink<'static>, (js_sys::Error, Self)> {
|
||||
let writer = WritableStreamDefaultWriter::new(&mut self).map_err(|err| (err, self))?;
|
||||
Ok(writer.into_sink())
|
||||
}
|
||||
|
||||
/// Converts this `WritableStream` into an [`AsyncWrite`].
|
||||
///
|
||||
/// The writable stream must accept [`Uint8Array`](js_sys::Uint8Array) chunks.
|
||||
///
|
||||
/// **Panics** if the stream is already locked to a writer. For a non-panicking variant,
|
||||
/// use [`try_into_async_write`](Self::try_into_async_write).
|
||||
///
|
||||
/// [`AsyncWrite`]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncWrite.html
|
||||
pub fn into_async_write(self) -> IntoAsyncWrite<'static> {
|
||||
self.try_into_async_write()
|
||||
.expect_throw("already locked to a writer")
|
||||
}
|
||||
|
||||
/// Try to convert this `WritableStream` into an [`AsyncWrite`].
|
||||
///
|
||||
/// The writable stream must accept [`Uint8Array`](js_sys::Uint8Array) chunks.
|
||||
///
|
||||
/// If the stream is already locked to a writer, then this returns an error
|
||||
/// along with the original `WritableStream`.
|
||||
///
|
||||
/// [`AsyncWrite`]: https://docs.rs/futures/0.3.30/futures/io/trait.AsyncWrite.html
|
||||
pub fn try_into_async_write(self) -> Result<IntoAsyncWrite<'static>, (js_sys::Error, Self)> {
|
||||
Ok(IntoAsyncWrite::new(self.try_into_sink()?))
|
||||
}
|
||||
}
|
||||
|
||||
impl<Si> From<Si> for WritableStream
|
||||
where
|
||||
Si: Sink<JsValue, Error = JsValue> + 'static,
|
||||
{
|
||||
/// Equivalent to [`from_sink`](Self::from_sink).
|
||||
#[inline]
|
||||
fn from(sink: Si) -> Self {
|
||||
Self::from_sink(sink)
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
//! Raw bindings to JavaScript objects used
|
||||
//! by a [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).
|
||||
//! These are re-exported from [web-sys](https://docs.rs/web-sys/0.3.70/web_sys/struct.WritableStream.html).
|
||||
use wasm_bindgen::prelude::*;
|
||||
pub use web_sys::WritableStream;
|
||||
pub use web_sys::WritableStreamDefaultWriter;
|
||||
|
||||
use crate::writable::into_underlying_sink::IntoUnderlyingSink;
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
/// A raw [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).
|
||||
#[wasm_bindgen(js_name = WritableStream, typescript_type = "WritableStream")]
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) type WritableStreamExt;
|
||||
|
||||
#[wasm_bindgen(constructor, js_class = WritableStream)]
|
||||
pub(crate) fn new_with_into_underlying_sink(sink: IntoUnderlyingSink) -> WritableStreamExt;
|
||||
}
|
||||
Reference in New Issue
Block a user