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;
#[derive(Debug)]
pub struct WritableStream {
raw: sys::WritableStream,
}
impl WritableStream {
#[inline]
pub fn from_raw(raw: sys::WritableStream) -> Self {
Self { raw }
}
pub fn from_sink<Si>(sink: Si) -> Self
where
Si: Sink<JsValue, Error = JsValue> + 'static,
{
let sink = IntoUnderlyingSink::new(Box::new(sink));
let raw = sys::WritableStreamExt::new_with_into_underlying_sink(sink).unchecked_into();
Self::from_raw(raw)
}
#[inline]
pub fn as_raw(&self) -> &sys::WritableStream {
&self.raw
}
#[inline]
pub fn into_raw(self) -> sys::WritableStream {
self.raw
}
#[inline]
pub fn is_locked(&self) -> bool {
self.as_raw().locked()
}
pub async fn abort(&mut self) -> Result<(), JsValue> {
promise_to_void_future(self.as_raw().abort()).await
}
pub async fn abort_with_reason(&mut self, reason: &JsValue) -> Result<(), JsValue> {
promise_to_void_future(self.as_raw().abort_with_reason(reason)).await
}
#[inline]
pub fn get_writer(&mut self) -> WritableStreamDefaultWriter {
self.try_get_writer()
.expect_throw("already locked to a writer")
}
pub fn try_get_writer(&mut self) -> Result<WritableStreamDefaultWriter, js_sys::Error> {
WritableStreamDefaultWriter::new(self)
}
#[inline]
pub fn into_sink(self) -> IntoSink<'static> {
self.try_into_sink()
.expect_throw("already locked to a writer")
}
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())
}
pub fn into_async_write(self) -> IntoAsyncWrite<'static> {
self.try_into_async_write()
.expect_throw("already locked to a writer")
}
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,
{
#[inline]
fn from(sink: Si) -> Self {
Self::from_sink(sink)
}
}