Truly independent web browser
LibWeb/Streams: Add pull from bytes to ReadableStream
Luke Wildeab54a15f7518
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rsindex 908ae9c88f0..42beebadedd 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rs@@ -12,6 +12,7 @@ use core::ptr::NonNull;use libjs_rust::api::{RawNativeFunctionResult, Realm, ThrowCompletionOr, Value, Vm};+use crate::bindings::conversions::BufferSource;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};@@ -202,6 +203,44 @@ pub unsafe extern "C" fn web_rust_readable_stream_enqueue_native_bytes(completion(&cx, result)}+/// The byte length of the current BYOB request view of the stream, if it has one,+/// https://streams.spec.whatwg.org/#readablestream-current-byob-request-view+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_current_byob_request_view_byte_length(+ vm: *mut c_void,+ stream: *mut c_void,+ byte_length: &mut u64,+) -> bool {+ // SAFETY: The caller passes the VM and a live ReadableStream.+ let (vm, stream) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStream>(stream)) };+ let Some(view) = ReadableStream::current_byob_request_view(stream, vm) else {+ return false;+ };+ *byte_length = BufferSource::from(view).extent().byte_length as u64;+ true+}++/// https://streams.spec.whatwg.org/#readablestream-pull-from-bytes+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStream, and the bytes must be lent for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_pull_from_bytes(+ vm: *mut c_void,+ stream: *mut c_void,+ bytes: ak::Span<'_, u8>,+) -> RawNativeFunctionResult {+ // SAFETY: The caller passes the VM and a live ReadableStream.+ let (vm, stream) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStream>(stream)) };+ let result = ReadableStream::pull_from_bytes(stream, vm, bytes.as_slice());+ completion(&stream.context(vm), result)+}+/// https://streams.spec.whatwg.org/#readablestream-close////// # Safetydiff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rsindex 9b086456490..176c1e644b8 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs@@ -34,9 +34,9 @@ use crate::streams::queuing_strategy::{QueuingStrategy, extract_high_water_mark,use crate::streams::read_request::{ReadIntoRequest, ReadRequest};use crate::streams::readable_byte_stream_controller::{ReadableByteStreamController, readable_byte_stream_controller_close, readable_byte_stream_controller_enqueue,- readable_byte_stream_controller_error, readable_byte_stream_controller_get_byob_request,- readable_byte_stream_controller_respond, set_up_readable_byte_stream_controller,- set_up_readable_byte_stream_controller_from_underlying_source,+ readable_byte_stream_controller_enqueue_native_bytes, readable_byte_stream_controller_error,+ readable_byte_stream_controller_get_byob_request, readable_byte_stream_controller_respond,+ set_up_readable_byte_stream_controller, set_up_readable_byte_stream_controller_from_underlying_source,};use crate::streams::readable_stream_byob_reader::{ReadableStreamBYOBReader, set_up_readable_stream_byob_reader};use crate::streams::readable_stream_default_controller::{@@ -768,6 +768,56 @@ impl ReadableStream {Ok(())}+ // https://streams.spec.whatwg.org/#readablestream-pull-from-bytes+ pub(crate) fn pull_from_bytes(this: Ref<Self>, vm: &Vm, bytes: &[u8]) -> WebIdlResult<()> {+ let cx = &this.context(vm);++ // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.+ let Some(ReadableStreamController::ReadableByteStreamController(controller)) = this.controller() else {+ panic!("the stream has a ReadableByteStreamController");+ };++ // 2. Let available be bytes’s length.+ let available = bytes.len();++ // 3. Let desiredSize be available.+ // 4. If stream’s current BYOB request view is non-null, then set desiredSize to stream’s current BYOB request+ // view's byte length.+ let byob_view = Self::current_byob_request_view(this, vm);+ let desired_size = byob_view.map_or(available, |byob_view| {+ BufferSource::from(byob_view).extent().byte_length+ });++ // 5. Let pullSize be the smaller value of available and desiredSize.+ let pull_size = available.min(desired_size);++ // 6. Let pulled be the first pullSize bytes of bytes.+ let pulled = &bytes[..pull_size];++ // 7. Remove the first pullSize bytes from bytes.+ // NB: The caller removes them from its own buffer, having sized bytes by the current BYOB request view.+ assert!(pull_size == available);++ // 8. If stream’s current BYOB request view is non-null, then:+ if let Some(byob_view) = byob_view {+ // 1. Write pulled into stream’s current BYOB request view.+ let extent = BufferSource::from(byob_view).extent();+ extent.buffer.overwrite(extent.byte_offset, pulled);++ // 2. Perform ? ReadableByteStreamControllerRespond(stream.[[controller]], pullSize).+ readable_byte_stream_controller_respond(cx, controller, pull_size as u64)?;+ }+ // 9. Otherwise,+ else {+ // 1. Set view to the result of creating a Uint8Array from pulled in stream’s relevant Realm.+ // 2. Perform ? ReadableByteStreamControllerEnqueue(stream.[[controller]], view).+ // NB: The bytes are enqueued without the view, which nothing could observe.+ readable_byte_stream_controller_enqueue_native_bytes(cx, controller, pulled)?;+ }++ Ok(())+ }+// https://streams.spec.whatwg.org/#readablestream-pipe-throughpub(crate) fn piped_through(this: Ref<Self>,diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 539796d5b7b..c6987f90e37 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -105,6 +105,7 @@#include <LibWeb/Painting/Scrolling.h>#include <LibWeb/PictureInPicture/PictureInPictureController.h>#include <LibWeb/ResizeObserver/ResizeObserver.h>+#include <LibWeb/Streams/ReadableStream.h>#include <LibWeb/StyleValueRustFFI.h>#include <LibWeb/WebIDL/ExceptionOr.h>#include <LibWeb/WebIDL/Promise.h>@@ -2751,6 +2752,45 @@ String Internals::viewport_overflow_x()VERIFY_NOT_REACHED();}+namespace {++// The bytes of a stream from create_stream_pulling_from_bytes() that it has not pulled yet.+struct UnpulledBytes final : public RefCounted<UnpulledBytes> {+ explicit UnpulledBytes(ByteBuffer bytes)+ : bytes(move(bytes))+ {+ }++ ByteBuffer bytes;+};++}++GC::Ref<Streams::ReadableStream> Internals::create_stream_pulling_from_bytes(String const& bytes, WebIDL::UnsignedLong pull_size)+{+ auto& realm = window().principal_realm();+ auto stream = Streams::ReadableStream::create(realm);+ auto unpulled = make_ref_counted<UnpulledBytes>(MUST(ByteBuffer::copy(bytes.bytes())));++ auto pull_algorithm = GC::create_function(realm.heap(), [realm = GC::Ref { realm }, stream, unpulled, pull_size] {+ auto& remaining = unpulled->bytes;+ auto size = min(remaining.size(), static_cast<size_t>(pull_size));+ if (auto view_byte_length = stream->current_byob_request_view_byte_length(); view_byte_length.has_value())+ size = min(size, static_cast<size_t>(*view_byte_length));++ if (size > 0) {+ MUST(stream->pull_from_bytes(remaining.bytes().trim(size)));+ remaining = MUST(remaining.slice(size, remaining.size() - size));+ }+ if (remaining.is_empty())+ stream->close();+ return WebIDL::create_resolved_promise(*realm, JS::js_undefined());+ });++ stream->set_up_with_byte_reading_support(realm, pull_algorithm);+ return stream;+}+static GC::Ref<JS::Object> create_hit_testing_result(JS::Realm& realm, Painting::HitTestResult& result){auto hit_testing_result = JS::Object::create(realm, nullptr);diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex 2cd34685ffc..18968ca1834 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -316,6 +316,8 @@ public:void set_page_muted(bool muted);String viewport_overflow_x();+ GC::Ref<Streams::ReadableStream> create_stream_pulling_from_bytes(String const& bytes, WebIDL::UnsignedLong pull_size);+private:GC::Ref<JS::Object> first_wheel_step_route_to_object(Compositing::FirstWheelStepRouteForTesting const&);Web::MouseEvent mouse_event_through_ui_process_at(Web::MouseEvent::Type, double x, double y);diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex d5fc0ad41ce..3b8203e8e3e 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -387,6 +387,10 @@ interface Internals {DOMString viewportOverflowX();+ // A byte stream that pulls at most pullSize of the bytes at a time through+ // https://streams.spec.whatwg.org/#readablestream-pull-from-bytes, and closes once it has pulled them all.+ ReadableStream createStreamPullingFromBytes(ByteString bytes, unsigned long pullSize);+};enum InternalsNavigatorCompatibilityMode { "chrome", "gecko", "webkit" };diff --git a/Libraries/LibWeb/Streams/ReadableStream.cpp b/Libraries/LibWeb/Streams/ReadableStream.cppindex b6551145c2e..7c86958c1ba 100644--- a/Libraries/LibWeb/Streams/ReadableStream.cpp+++ b/Libraries/LibWeb/Streams/ReadableStream.cpp@@ -38,6 +38,8 @@ bool web_rust_readable_stream_is_disturbed(void* stream);bool web_rust_readable_stream_close_requested(void* stream);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);+JSCompletion web_rust_readable_stream_pull_from_bytes(JSVM*, void* stream, ReadonlyBytes);void web_rust_readable_stream_close(JSVM*, void* stream);void web_rust_readable_stream_error(JSVM*, void* stream, JSValue error);void* web_rust_readable_stream_cancel(JSVM*, void* stream, JSValue reason);@@ -148,6 +150,19 @@ WebIDL::ExceptionOr<void> ReadableStream::enqueue_bytes(ReadonlyBytes bytes)return exception_or_void(web_rust_readable_stream_enqueue_native_bytes(vm_abi(), this, bytes));}+Optional<u64> ReadableStream::current_byob_request_view_byte_length()+{+ u64 byte_length = 0;+ if (!web_rust_readable_stream_current_byob_request_view_byte_length(vm_abi(), this, &byte_length))+ return {};+ return byte_length;+}++WebIDL::ExceptionOr<void> ReadableStream::pull_from_bytes(ReadonlyBytes bytes)+{+ return exception_or_void(web_rust_readable_stream_pull_from_bytes(vm_abi(), this, bytes));+}+void ReadableStream::close(){web_rust_readable_stream_close(vm_abi(), this);diff --git a/Libraries/LibWeb/Streams/ReadableStream.h b/Libraries/LibWeb/Streams/ReadableStream.hindex cecb58b9f27..7fa20a5b4dd 100644--- a/Libraries/LibWeb/Streams/ReadableStream.h+++ b/Libraries/LibWeb/Streams/ReadableStream.h@@ -62,6 +62,15 @@ public:// the bytes.WebIDL::ExceptionOr<void> enqueue_bytes(ReadonlyBytes);+ // The byte length of https://streams.spec.whatwg.org/#readablestream-current-byob-request-view, if the stream,+ // which is set up with byte reading support, has one.+ Optional<u64> current_byob_request_view_byte_length();++ // https://streams.spec.whatwg.org/#readablestream-pull-from-bytes+ // NB: The stream is set up with byte reading support, and the caller removes the pulled bytes from its own buffer,+ // having sized them by the current BYOB request view.+ WebIDL::ExceptionOr<void> pull_from_bytes(ReadonlyBytes);+// https://streams.spec.whatwg.org/#readablestream-closevoid close();diff --git a/Tests/LibWeb/Text/expected/Streams/ReadableStream-pull-from-bytes.txt b/Tests/LibWeb/Text/expected/Streams/ReadableStream-pull-from-bytes.txtnew file mode 100644index 00000000000..0a000ade6ac--- /dev/null+++ b/Tests/LibWeb/Text/expected/Streams/ReadableStream-pull-from-bytes.txt@@ -0,0 +1,3 @@+BYOB reads of 4 bytes: abcd, ef, done+BYOB reads of at least 3 bytes, pulled one at a time: abc, d, done+Default reads, pulled 4 bytes at a time: abcd, ef, donediff --git a/Tests/LibWeb/Text/input/Streams/ReadableStream-pull-from-bytes.html b/Tests/LibWeb/Text/input/Streams/ReadableStream-pull-from-bytes.htmlnew file mode 100644index 00000000000..eb3a9111b25--- /dev/null+++ b/Tests/LibWeb/Text/input/Streams/ReadableStream-pull-from-bytes.html@@ -0,0 +1,43 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ function text(view) {+ return String.fromCharCode(...view);+ }++ asyncTest(async done => {+ {+ const reader = internals.createStreamPullingFromBytes("abcdef", 16).getReader({ mode: "byob" });+ const reads = [];+ for (let i = 0; i < 3; ++i) {+ const { value, done } = await reader.read(new Uint8Array(4));+ reads.push(done ? "done" : text(value));+ }+ println(`BYOB reads of 4 bytes: ${reads.join(", ")}`);+ }++ {+ const reader = internals.createStreamPullingFromBytes("abcd", 1).getReader({ mode: "byob" });+ const reads = [];+ let read = await reader.read(new Uint8Array(4), { min: 3 });+ reads.push(text(read.value));+ read = await reader.read(new Uint8Array(4));+ reads.push(text(read.value));+ read = await reader.read(new Uint8Array(4));+ reads.push(read.done ? "done" : text(read.value));+ println(`BYOB reads of at least 3 bytes, pulled one at a time: ${reads.join(", ")}`);+ }++ {+ const reader = internals.createStreamPullingFromBytes("abcdef", 4).getReader();+ const reads = [];+ for (let i = 0; i < 3; ++i) {+ const { value, done } = await reader.read();+ reads.push(done ? "done" : text(value));+ }+ println(`Default reads, pulled 4 bytes at a time: ${reads.join(", ")}`);+ }++ done();+ });+</script>