use std::marker::PhantomData;
use wasm_bindgen::{throw_val, JsValue};
use crate::util::promise_to_void_future;
use super::{sys, IntoAsyncWrite, IntoSink, WritableStream};
#[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,
})
}
#[inline]
pub fn as_raw(&self) -> &sys::WritableStreamDefaultWriter {
&self.raw
}
pub async fn closed(&self) -> Result<(), JsValue> {
promise_to_void_future(self.as_raw().closed()).await
}
#[inline]
pub fn desired_size(&self) -> Option<f64> {
self.as_raw()
.desired_size()
.unwrap_or_else(|error| throw_val(error))
}
pub async fn ready(&self) -> Result<(), JsValue> {
promise_to_void_future(self.as_raw().ready()).await
}
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
}
pub async fn write(&mut self, chunk: JsValue) -> Result<(), JsValue> {
promise_to_void_future(self.as_raw().write_with_chunk(&chunk)).await
}
pub async fn close(&mut self) -> Result<(), JsValue> {
promise_to_void_future(self.as_raw().close()).await
}
#[inline]
pub fn into_sink(self) -> IntoSink<'stream> {
IntoSink::new(self)
}
#[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()
}
}