use std::{borrow::Cow, sync::RwLock};
use crate::buffer::Blob;
use crate::stream_web::{
readable_byte_stream_controller_close_stream, readable_byte_stream_controller_enqueue_bytes,
readable_stream_default_controller_close_stream,
readable_stream_default_controller_enqueue_value, utils::promise::PromisePrimordials,
CancelAlgorithm, PullAlgorithm, ReadableStream, ReadableStreamControllerClass,
};
use crate::utils::bytes::ObjectBytes;
use crate::utils::primordials::Primordial;
use rquickjs::{
prelude::This, Class, Ctx, Exception, Function, IntoJs, Object, Promise, Result, TypedArray,
Value,
};
use simdutf8::basic::from_utf8;
pub(crate) fn create_text_stream<'js>(
ctx: &Ctx<'js>,
body: Option<Value<'js>>,
) -> Result<Value<'js>> {
let source = body
.map(|body| Class::<ReadableStream>::from_value(&body))
.transpose()?;
let pull = PullAlgorithm::from_fn_once(move |ctx, controller| {
let source = source.clone();
let future_ctx = ctx.clone();
Promise::wrap_future(&ctx, async move {
let text = if let Some(source) = source {
let bytes = collect_readable_stream(&source).await?;
let stripped = strip_bom(bytes);
Some(bytes_to_utf8_simd_lossy(stripped))
} else {
None
};
let ctrl = match controller {
ReadableStreamControllerClass::ReadableStreamDefaultController(c) => c,
_ => {
return Err(Exception::throw_type(
&future_ctx,
"Expected default controller",
))
}
};
if let Some(text) = text.filter(|text| !text.is_empty()) {
readable_stream_default_controller_enqueue_value(
future_ctx.clone(),
ctrl.clone(),
text.into_js(&future_ctx)?,
)?;
}
readable_stream_default_controller_close_stream(future_ctx.clone(), ctrl)?;
Ok(PromisePrimordials::get(&future_ctx)?
.promise_resolved_with_undefined
.clone())
})
});
Ok(ReadableStream::from_pull_algorithm(
ctx.clone(),
pull,
CancelAlgorithm::ReturnPromiseUndefined,
)?
.into_value())
}
pub(crate) fn create_body_value_stream<'js>(
ctx: &Ctx<'js>,
body_value: Value<'js>,
) -> Result<Value<'js>> {
let pull = PullAlgorithm::from_fn_once(
move |ctx: Ctx<'js>, controller: ReadableStreamControllerClass<'js>| {
let ctrl = match controller {
ReadableStreamControllerClass::ReadableStreamByteController(c) => c,
_ => return Err(Exception::throw_type(&ctx, "Expected byte controller")),
};
let bytes: Vec<u8> = if let Ok(ta) = TypedArray::<u8>::from_value(body_value.clone()) {
unsafe { ta.as_bytes() }.unwrap_or(&[]).to_vec()
} else if let Some(blob) = body_value.as_object().and_then(Class::<Blob>::from_object) {
blob.borrow().get_bytes()
} else {
ObjectBytes::from(&ctx, &body_value)?
.as_bytes(&ctx)?
.to_vec()
};
if !bytes.is_empty() {
let buf = rquickjs::ArrayBuffer::new_copy(ctx.clone(), &bytes)?;
readable_byte_stream_controller_enqueue_bytes(ctx.clone(), ctrl.clone(), buf)?;
}
readable_byte_stream_controller_close_stream(ctx.clone(), ctrl)?;
Ok(PromisePrimordials::get(&ctx)?
.promise_resolved_with_undefined
.clone())
},
);
let stream = ReadableStream::from_byte_pull_algorithm(
ctx.clone(),
pull,
CancelAlgorithm::ReturnPromiseUndefined,
)?;
Ok(stream.into_value())
}
pub(crate) fn create_disturbed_stream<'js>(ctx: &Ctx<'js>) -> Result<Value<'js>> {
let pull = PullAlgorithm::from_fn_once(
move |ctx: Ctx<'js>, controller: ReadableStreamControllerClass<'js>| {
let ctrl = match controller {
ReadableStreamControllerClass::ReadableStreamDefaultController(c) => c,
_ => return Err(Exception::throw_type(&ctx, "Expected default controller")),
};
readable_stream_default_controller_close_stream(ctx.clone(), ctrl)?;
Ok(PromisePrimordials::get(&ctx)?
.promise_resolved_with_undefined
.clone())
},
);
let stream = ReadableStream::from_pull_algorithm(
ctx.clone(),
pull,
CancelAlgorithm::ReturnPromiseUndefined,
)?;
stream.borrow_mut().disturbed = true;
crate::stream_web::lock_readable_stream(ctx.clone(), stream.clone())?;
Ok(stream.into_value())
}
pub(crate) async fn collect_readable_stream<'js>(
stream: &Class<'js, ReadableStream<'js>>,
) -> Result<Vec<u8>> {
if let Some(chunks) = crate::stream_web::try_sync_drain_closed_stream(stream) {
let mut result = Vec::new();
for chunk in chunks {
if let Ok(typed_array) = TypedArray::<u8>::from_value(chunk.clone()) {
if let Some(bytes) = unsafe { typed_array.as_bytes() } {
result.extend_from_slice(bytes);
}
} else {
return Err(Exception::throw_type(
stream.ctx(),
"Response body stream chunk must be a Uint8Array",
));
}
}
return Ok(result);
}
let mut result = Vec::new();
let get_reader: Function = stream.get("getReader")?;
let reader: Object = get_reader.call((This(stream.clone()),))?;
let read_fn: Function = reader.get("read")?;
loop {
let promise: Promise = read_fn.call((This(reader.clone()),))?;
let read_result: Object = promise.into_future().await?;
let done: bool = read_result.get("done").unwrap_or(true);
if done {
break;
}
let value: Value = read_result.get("value")?;
if let Ok(typed_array) = TypedArray::<u8>::from_value(value.clone()) {
if let Some(bytes) = unsafe { typed_array.as_bytes() } {
result.extend_from_slice(bytes);
}
} else {
return Err(Exception::throw_type(
stream.ctx(),
"Response body stream chunk must be a Uint8Array",
));
}
}
Ok(result)
}
pub(crate) fn strip_bom<'a>(bytes: impl Into<Cow<'a, [u8]>>) -> Cow<'a, [u8]> {
let cow = bytes.into();
if cow.starts_with(&[0xEF, 0xBB, 0xBF]) {
match cow {
Cow::Borrowed(bytes) => Cow::Borrowed(&bytes[3..]),
Cow::Owned(mut bytes) => {
bytes.drain(0..3);
Cow::Owned(bytes)
}
}
} else {
cow
}
}
pub fn bytes_to_utf8_simd_lossy(bytes: Cow<'_, [u8]>) -> String {
match bytes {
Cow::Owned(vec) => {
if from_utf8(&vec).is_ok() {
unsafe { String::from_utf8_unchecked(vec) }
} else {
String::from_utf8_lossy(&vec).into_owned()
}
}
Cow::Borrowed(b) => String::from_utf8_lossy(b).into_owned(),
}
}
pub(crate) fn is_body_stream_disturbed(body_stream: &RwLock<Option<Value<'_>>>) -> bool {
if let Some(stream_value) = body_stream.read().unwrap().as_ref() {
if let Some(stream) = stream_value
.as_object()
.and_then(Class::<ReadableStream>::from_object)
{
return stream.borrow().disturbed;
}
}
false
}
pub(crate) fn validate_stream_usable<'js>(
ctx: &Ctx<'js>,
stream: &Class<'js, ReadableStream<'js>>,
action: &str,
) -> Result<()> {
let stream_ref = stream.borrow();
if stream_ref.disturbed {
return Err(Exception::throw_type(
ctx,
&format!("Cannot {} with a disturbed ReadableStream", action),
));
}
if stream_ref.is_readable_stream_locked() {
return Err(Exception::throw_type(
ctx,
&format!("Cannot {} with a locked ReadableStream", action),
));
}
Ok(())
}