Truly independent web browser
LibWeb: Let C++ set up a WritableStream and read a desired size
Ali Mohammad Purb74b64d56ac4
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rsindex 2dd1014486d..4382fedac89 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rs@@ -257,6 +257,8 @@ pub(crate) enum WriteAlgorithm {TransformStream(Ref<TransformStream>),/// The writeAlgorithm of SetUpCrossRealmTransformWritable.CrossRealm(Gc<EmbedderCell<CrossRealmWritableState>>),+ /// The writeAlgorithm of setting up a WritableStream, given by C++.+ CppWrapper(CppPromiseAlgorithmWithArgument),}impl WriteAlgorithm {@@ -274,6 +276,7 @@ impl WriteAlgorithm {}Self::TransformStream(stream) => transform_stream_default_sink_write_algorithm(cx, *stream, chunk),Self::CrossRealm(state) => CrossRealmWritableState::write_algorithm(*state, cx, chunk),+ Self::CppWrapper(write_algorithm) => write_algorithm.call(chunk),}}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rsindex 28f14287951..d99bebc362f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rs@@ -4,8 +4,8 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The C ABI through which the C++ classes of Streams/ReadableStream.h and Streams/TransformStream.h set streams up-//! and read them, for the specifications that LibWeb implements in C++.+//! The C ABI through which the C++ classes of Streams/ReadableStream.h, Streams/TransformStream.h and+//! Streams/WritableStream.h set streams up and read them, for the specifications that LibWeb implements in C++.use core::ffi::c_void;use core::ptr::NonNull;@@ -17,7 +17,7 @@ use crate::bindings::cpp_cell::CppCell;use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_into_abi, realm_arguments};use crate::bindings::promise::WebIdlPromise;use crate::bindings::{CallContext, MustNotThrow, WebIdlResult};-use crate::streams::algorithms::{CancelAlgorithm, FlushAlgorithm, TransformAlgorithm};+use crate::streams::algorithms::{CancelAlgorithm, FlushAlgorithm, TransformAlgorithm, WriteAlgorithm};use crate::streams::cpp::{CppBytesSteps, CppPromiseAlgorithm, CppPromiseAlgorithmWithArgument, CppReadRequest, CppValueSteps,};@@ -26,12 +26,14 @@ use crate::streams::readable_stream::ReadableStreamReader;use crate::streams::readable_stream::{ReadableStream, ReadableStreamState, is_readable_stream_locked, readable_stream_cancel,};+use crate::streams::readable_stream_default_controller::readable_stream_default_controller_get_desired_size;use crate::streams::readable_stream_default_reader::ReadableStreamDefaultReader;use crate::streams::readable_stream_generic_reader::ReadableStreamGenericReader;use crate::streams::readable_stream_tee::readable_stream_tee;use crate::streams::transform_stream::TransformStream;use crate::streams::transform_stream_default_controller::transform_stream_default_controller_enqueue;use crate::streams::underlying_source::ReadableStreamController;+use crate::streams::writable_stream::WritableStream;/// # Safety///@@ -174,6 +176,27 @@ pub unsafe extern "C" fn web_rust_readable_stream_is_readable_byte_stream(stream)}+/// The desired size to fill the stream's internal queue, written to `desired_size`, or false if it is null because the+/// stream is errored, https://streams.spec.whatwg.org/#readablestream-get-the-desired-size+///+/// # Safety+///+/// `stream` must be a live ReadableStream with a ReadableStreamDefaultController, and `desired_size` must be writable.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_desired_size(stream: *mut c_void, desired_size: *mut f64) -> bool {+ // SAFETY: The caller passes a live ReadableStream.+ let stream = unsafe { cell_from_abi::<ReadableStream>(stream) };+ let Some(ReadableStreamController::ReadableStreamDefaultController(controller)) = stream.controller() else {+ panic!("only a ReadableStream with a ReadableStreamDefaultController has a desired size to read");+ };+ let Some(size) = readable_stream_default_controller_get_desired_size(controller) else {+ return false;+ };+ // SAFETY: The caller passes a writable f64.+ unsafe { desired_size.write(size) };+ true+}+/// https://streams.spec.whatwg.org/#readablestream-enqueue////// # Safety@@ -496,6 +519,48 @@ pub unsafe extern "C" fn web_rust_readable_stream_default_reader_closed_promise_realm.as_ptr().cast()}+/// A new WritableStream in the realm.+///+/// # Safety+///+/// The pointers must be the VM and a live realm.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_writable_stream_create(vm: *mut c_void, realm: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes the VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ cell_into_abi(allocate(vm, |defer_gc| WritableStream::new(defer_gc, realm)))+}++/// Sets the stream up with the writeAlgorithm that C++ gives, https://streams.spec.whatwg.org/#writablestream-set-up+///+/// # Safety+///+/// The pointers must be the VM, a live realm, a live WritableStream and the live GC::Function of the writeAlgorithm.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_writable_stream_set_up(+ vm: *mut c_void,+ realm: *mut c_void,+ stream: *mut c_void,+ write_algorithm: *mut c_void,+ high_water_mark: f64,+) {+ // SAFETY: The caller passes the VM, a live realm, a live stream and a live writeAlgorithm.+ let ((vm, realm), stream, write_algorithm) = unsafe {+ (+ realm_arguments(vm, realm),+ cell_from_abi::<WritableStream>(stream),+ CppPromiseAlgorithmWithArgument(CppCell::from_raw(write_algorithm)),+ )+ };+ let cx = CallContext::new(vm, realm);+ WritableStream::set_up(+ stream,+ &cx,+ WriteAlgorithm::CppWrapper(write_algorithm),+ high_water_mark,+ );+}+/// A new TransformStream in the realm.////// # Safetydiff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rsindex f4ebf2f5a09..a152210fb8a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rs@@ -22,7 +22,7 @@ use crate::bindings::promise::{resolve_promise,};use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};-use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};use crate::streams::abstract_operations::is_non_negative_number;use crate::streams::algorithms::{AbortAlgorithm, CloseAlgorithm, SizeAlgorithm, StartAlgorithm, WriteAlgorithm};use crate::streams::cross_realm_transform::{@@ -201,6 +201,44 @@ impl WritableStream {Ok(this)}+ // https://streams.spec.whatwg.org/#writablestream-set-up+ pub(crate) fn set_up(this: Ref<Self>, cx: &CallContext, write_algorithm: WriteAlgorithm, high_water_mark: f64) {+ // 1. Let startAlgorithm be an algorithm that returns undefined.+ let start_algorithm = StartAlgorithm::ReturnsUndefined;++ // 2. Let closeAlgorithmWrapper be an algorithm that runs these steps:+ // NB: No closeAlgorithm is given, so it returns a promise resolved with undefined.+ let close_algorithm_wrapper = CloseAlgorithm::ReturnsResolvedUndefined;++ // 3. Let abortAlgorithmWrapper be an algorithm that runs these steps given a value reason:+ // NB: No abortAlgorithm is given, so it returns a promise resolved with undefined.+ let abort_algorithm_wrapper = AbortAlgorithm::ReturnsResolvedUndefined;++ // 4. If sizeAlgorithm was not given, then set it to an algorithm that returns 1.+ let size_algorithm = SizeAlgorithm::ReturnsOne;++ // 5. Perform ! InitializeWritableStream(stream).+ initialize_writable_stream(cx.vm(), this);++ // 6. Let controller be a new WritableStreamDefaultController.+ let controller = allocate(cx.vm(), WritableStreamDefaultController::new);++ // 7. Perform ! SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm,+ // closeAlgorithmWrapper, abortAlgorithmWrapper, highWaterMark, sizeAlgorithm).+ set_up_writable_stream_default_controller(+ cx,+ this,+ controller,+ start_algorithm,+ write_algorithm,+ close_algorithm_wrapper,+ abort_algorithm_wrapper,+ high_water_mark,+ size_algorithm,+ )+ .must();+ }+// https://streams.spec.whatwg.org/#ws-lockedpub(crate) fn locked(this: &Ref<Self>, _: &mut CallContext) -> WebIdlResult<bool> {// 1. Return ! IsWritableStreamLocked(this).diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex d2a8584fee3..a50d0d1e3b3 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -843,6 +843,7 @@ set(SOURCESStorageAPI/StorageShelf.cppStreams/ReadableStream.cppStreams/TransformStream.cpp+ Streams/WritableStream.cppSVG/AttributeNames.cppSVG/AttributeParsing.cppSVG/Path.cppdiff --git a/Libraries/LibWeb/Streams/Algorithms.h b/Libraries/LibWeb/Streams/Algorithms.hindex 4781b8544c1..add2ffb6097 100644--- a/Libraries/LibWeb/Streams/Algorithms.h+++ b/Libraries/LibWeb/Streams/Algorithms.h@@ -17,5 +17,6 @@ using PullAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>()>;using CancelAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>;using FlushAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>()>;using TransformAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>;+using WriteAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>;}diff --git a/Libraries/LibWeb/Streams/ReadableStream.cpp b/Libraries/LibWeb/Streams/ReadableStream.cppindex 8acaad62096..727b8d00435 100644--- a/Libraries/LibWeb/Streams/ReadableStream.cpp+++ b/Libraries/LibWeb/Streams/ReadableStream.cpp@@ -30,6 +30,7 @@ bool web_rust_readable_stream_is_locked(void* stream);bool web_rust_readable_stream_is_disturbed(void* stream);bool web_rust_readable_stream_close_requested(void* stream);bool web_rust_readable_stream_is_readable_byte_stream(void* stream);+bool web_rust_readable_stream_desired_size(void* stream, double* desired_size);JSCompletion web_rust_readable_stream_enqueue(JSVM*, void* stream, JSValue chunk);JSCompletion web_rust_readable_stream_enqueue_native_bytes(JSVM*, void* stream, ReadonlyBytes);bool web_rust_readable_stream_current_byob_request_view_byte_length(JSVM*, void* stream, u64* byte_length);@@ -128,6 +129,14 @@ bool ReadableStream::close_requested() constreturn web_rust_readable_stream_close_requested(const_cast<ReadableStream*>(this));}+Optional<double> ReadableStream::desired_size() const+{+ double desired_size = 0;+ if (!web_rust_readable_stream_desired_size(const_cast<ReadableStream*>(this), &desired_size))+ return {};+ return desired_size;+}+WebIDL::ExceptionOr<void> ReadableStream::enqueue(JS::Value chunk){return exception_or_void(web_rust_readable_stream_enqueue(vm_abi(), this, JS::HostABI::value_to_abi(chunk)));diff --git a/Libraries/LibWeb/Streams/ReadableStream.h b/Libraries/LibWeb/Streams/ReadableStream.hindex 73f6bfb5068..d883932624b 100644--- a/Libraries/LibWeb/Streams/ReadableStream.h+++ b/Libraries/LibWeb/Streams/ReadableStream.h@@ -58,6 +58,9 @@ public:// Whether the stream's controller has been asked to close.bool close_requested() const;+ // https://streams.spec.whatwg.org/#readablestream-get-the-desired-size+ Optional<double> desired_size() const;+// https://streams.spec.whatwg.org/#readablestream-enqueueWebIDL::ExceptionOr<void> enqueue(JS::Value chunk);diff --git a/Libraries/LibWeb/Streams/WritableStream.cpp b/Libraries/LibWeb/Streams/WritableStream.cppnew file mode 100644index 00000000000..22d4b9289a8--- /dev/null+++ b/Libraries/LibWeb/Streams/WritableStream.cpp@@ -0,0 +1,31 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>+#include <LibWeb/Streams/WritableStream.h>++namespace Web::Streams {++extern "C" {++// Defined in Bindings/Rust/src/streams/exports.rs.+void* web_rust_writable_stream_create(JSVM*, void* realm);+void web_rust_writable_stream_set_up(JSVM*, void* realm, void* stream, WriteAlgorithm* write_algorithm, double high_water_mark);+}++GC::Ref<WritableStream> WritableStream::create(JS::Realm& realm)+{+ return GC::Ref { *static_cast<WritableStream*>(web_rust_writable_stream_create(JS::HostABI::vm_to_abi(realm.vm()), &realm)) };+}++// https://streams.spec.whatwg.org/#writablestream-set-up+void WritableStream::set_up(JS::Realm& realm, GC::Ref<WriteAlgorithm> write_algorithm, double high_water_mark)+{+ web_rust_writable_stream_set_up(JS::HostABI::vm_to_abi(realm.vm()), &realm, this, write_algorithm.ptr(), high_water_mark);+}++}diff --git a/Libraries/LibWeb/Streams/WritableStream.h b/Libraries/LibWeb/Streams/WritableStream.hindex 592e7c76bd5..f09130df571 100644--- a/Libraries/LibWeb/Streams/WritableStream.h+++ b/Libraries/LibWeb/Streams/WritableStream.h@@ -6,9 +6,11 @@#pragma once+#include <LibJS/Forward.h>#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Bindings/WritableStream.h>#include <LibWeb/Export.h>+#include <LibWeb/Streams/Algorithms.h>namespace Web::Streams {@@ -16,6 +18,11 @@ namespace Web::Streams {// The C++ side of a WritableStream, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/streams).class WEB_API WritableStream : public Bindings::RustInterfaceCell {WEB_RUST_INTERFACE(WritableStream, writable_stream)++public:+ [[nodiscard]] static GC::Ref<WritableStream> create(JS::Realm&);++ void set_up(JS::Realm&, GC::Ref<WriteAlgorithm>, double high_water_mark = 1);};}diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 49386adf08d..8b5eb2ca13a 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -75,7 +75,7 @@ ALLOWED_REALM_MENTIONS = {"service worker jobs, caches, and container promises still materialize results in selected realms",),"StorageAPI": (1, 3, "the C++ glue of the Rust storage keys reads the settings object of a realm's global"),- "Streams": (5, 13, "the C++ facade of the Rust streams creates streams and promises in caller-selected realms"),+ "Streams": (7, 17, "the C++ facade of the Rust streams creates streams and promises in caller-selected realms"),"TrustedTypes": (2, 9, "Trusted Types policy factory operations still use selected realms"),"WebAssembly": (2,