Skip to content

Truly independent web browser

LibWeb: Implement DOMStringList in Rust

Shannon Booth3f3cc168260b
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/dom_string_list.rs b/Libraries/LibWeb/Bindings/Rust/src/html/dom_string_list.rs
new file mode 100644
index 00000000000..39405c9e68c
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/dom_string_list.rs
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#domstringlist
+
+use core::ffi::c_void;
+
+use ak::{Span, Utf16String};
+use libjs_rust::api::{Trace, Vm};
+
+use crate::bindings::interface::{Ref, Wrappable, allocate, cell_into_abi};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct DOMStringList {
+ strings: Vec<Utf16String>,
+}
+
+impl Wrappable for DOMStringList {}
+
+impl DOMStringList {
+ pub(crate) fn create(vm: &Vm, strings: Vec<Utf16String>) -> Ref<Self> {
+ allocate(vm, |_| Self { strings })
+ }
+
+ // https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-domstringlist-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // The length getter steps are to return this's associated list's size.
+ Ok(u32::try_from(self.strings.len()).expect("a DOMStringList has fewer than 2^32 strings"))
+ }
+
+ // https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-domstringlist-item
+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<Option<Utf16String>> {
+ // The item(index) method steps are to return the indexth item in this's associated list, or null if index
+ // plus one is greater than this's associated list's size.
+ Ok(self.strings.get(index as usize).cloned())
+ }
+
+ // https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-domstringlist-contains
+ pub(crate) fn contains(&self, _: &mut CallContext, string: Utf16String) -> WebIdlResult<bool> {
+ // The contains(string) method steps are to return true if this's associated list contains string, and
+ // false otherwise.
+ Ok(self.strings.contains(&string))
+ }
+}
+
+/// # Safety
+///
+/// The caller passes the live VM and transfers ownership of each string in the span.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_dom_string_list_create(vm: &Vm, strings: Span<'_, usize>) -> *mut c_void {
+ let strings = strings
+ .as_slice()
+ .iter()
+ // SAFETY: The caller transfers one reference for each string.
+ .map(|&string| unsafe { Utf16String::from_raw_owned(string) })
+ .collect();
+ cell_into_abi(DOMStringList::create(vm, strings))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index 5e52137bb2f..926f8a8f61a 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -56,6 +56,8 @@ pub(crate) mod canvas_text_drawing_styles;
#[cfg(not(test))]
pub(crate) mod canvas_transform;
#[cfg(not(test))]
+pub(crate) mod dom_string_list;
+#[cfg(not(test))]
pub(crate) mod event_source;
#[cfg(not(test))]
pub(crate) mod exports;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs
index 15ce7dd5a5b..647c4fd83a9 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/cpp.rs
@@ -24,7 +24,6 @@ unsafe extern "C" {
fn web_indexed_db_create_dom_exception(name: ak::Span<'_, u8>, message: usize) -> *mut c_void;
fn web_indexed_db_dom_exception_from_value(value: u64) -> *mut c_void;
fn web_indexed_db_wrap_dom_exception(realm: *mut c_void, exception: *mut c_void) -> *mut c_void;
- fn web_indexed_db_create_dom_string_list(realm: *mut c_void, strings: *const usize, count: usize) -> *mut c_void;
fn web_indexed_db_queue_a_database_task(cell: *mut c_void, steps: unsafe extern "C" fn(*mut c_void, *mut c_void));
fn web_indexed_db_run_in_parallel(cell: *mut c_void, steps: unsafe extern "C" fn(*mut c_void, *mut c_void));
fn web_indexed_db_current_event_loop() -> *mut c_void;
@@ -93,17 +92,6 @@ impl DomException {
}
}
-pub(crate) fn create_dom_string_list(cx: &CallContext, strings: &[Utf16String]) -> CppInterface {
- let raw_strings: Vec<usize> = strings.iter().map(Utf16String::raw_identity).collect();
- // SAFETY: The realm is live, the strings are lent for the call, and LibWeb returns a live wrapper.
- let wrapper = unsafe {
- web_indexed_db_create_dom_string_list(cx.realm().as_ptr().cast(), raw_strings.as_ptr(), raw_strings.len())
- };
- let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns a wrapper");
- // SAFETY: The wrapper is a live wrapper of a DOMStringList.
- unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }
-}
-
unsafe extern "C" fn run_function(vm: *mut c_void, cell: *mut c_void) {
// SAFETY: LibWeb passes the VM and the cell of the function, which it kept alive.
let (vm, function) = unsafe {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_database.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_database.rs
index f691b04548a..be8bb62ee10 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_database.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_database.rs
@@ -14,10 +14,11 @@ use core::ptr::NonNull;
use ak::Utf16String;
use libjs_rust::api::{Gc, GcRefCell, MarkedVec, Realm, Trace, Vm};
-use crate::bindings::conversions::{CppInterface, DOMStringOrDOMStringSequence};
+use crate::bindings::conversions::DOMStringOrDOMStringSequence;
use crate::bindings::event_target::{CppEventTarget, GetTheParent};
use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::html::dom_string_list::DOMStringList;
use crate::indexed_db::cpp::{current_event_loop, enqueue_post_gc_task};
use crate::indexed_db::idb_object_store::{
IDBObjectStore, constraint_error, invalid_state_error, not_found_error, transaction_inactive_error,
@@ -305,7 +306,7 @@ impl IDBDatabase {
}
// https://w3c.github.io/IndexedDB/#dom-idbdatabase-objectstorenames
- pub(crate) fn object_store_names(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ pub(crate) fn object_store_names(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DOMStringList>> {
// 1. Let names be a list of the names of the object stores in this's object store set.
let names = self
.object_store_set
@@ -315,7 +316,7 @@ impl IDBDatabase {
.collect();
// 2. Return the result (a DOMStringList) of creating a sorted name list with names.
- Ok(create_a_sorted_name_list(cx, names))
+ Ok(create_a_sorted_name_list(cx.vm(), names))
}
// https://w3c.github.io/IndexedDB/#dom-idbdatabase-deleteobjectstore
diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_object_store.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_object_store.rs
index 62402635529..d98b9f1447d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_object_store.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_object_store.rs
@@ -14,9 +14,10 @@ use core::cell::RefCell;
use ak::Utf16String;
use libjs_rust::api::{Gc, GcRefCell, Must, Object, Realm, Trace, Value, Vm};
-use crate::bindings::conversions::{CppInterface, DOMStringOrDOMStringSequence, ToJs};
+use crate::bindings::conversions::{DOMStringOrDOMStringSequence, ToJs};
use crate::bindings::interface::{Ref, Wrappable, allocate, with_temporary_execution_context_and_callbacks};
use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::html::dom_string_list::DOMStringList;
use crate::indexed_db::idb_cursor::{AnyIDBCursor, CursorSourceHandle, IDBCursor, IDBCursorDirection};
use crate::indexed_db::idb_index::IDBIndex;
use crate::indexed_db::idb_request::{AnyIDBRequest, IDBRequest, IDBRequestSource};
@@ -241,12 +242,12 @@ impl IDBObjectStore {
}
// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-indexnames
- pub(crate) fn index_names(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ pub(crate) fn index_names(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DOMStringList>> {
// 1. Let names be a list of the names of the indexes in this's index set.
let names = self.indexes.borrow().iter().map(|(name, _)| name.clone()).collect();
// 2. Return the result (a DOMStringList) of creating a sorted name list with names.
- Ok(create_a_sorted_name_list(cx, names))
+ Ok(create_a_sorted_name_list(cx.vm(), names))
}
// https://w3c.github.io/IndexedDB/#dom-idbobjectstore-transaction
diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_transaction.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_transaction.rs
index dfcc27710ea..702f1af4e66 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_transaction.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/idb_transaction.rs
@@ -19,6 +19,7 @@ use crate::bindings::cpp_cell::CppCell;
use crate::bindings::event_target::{CppEventTarget, GetTheParent};
use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, WebIdlResult};
+use crate::html::dom_string_list::DOMStringList;
use crate::indexed_db::cpp::{DomException, devtools_client_is_active, notify_devtools_of_committed_changes};
use crate::indexed_db::idb_database::{IDBDatabase, IDBTransactionDurability};
use crate::indexed_db::idb_index::IDBIndex;
@@ -355,7 +356,7 @@ impl IDBTransaction {
}
// https://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstorenames
- pub(crate) fn object_store_names(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ pub(crate) fn object_store_names(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DOMStringList>> {
// 1. Let names be a list of the names of the object stores in this's scope.
let names = self
.scope
@@ -365,7 +366,7 @@ impl IDBTransaction {
.collect();
// 2. Return the result (a DOMStringList) of creating a sorted name list with names.
- Ok(create_a_sorted_name_list(cx, names))
+ Ok(create_a_sorted_name_list(cx.vm(), names))
}
pub(crate) fn mode(&self, _: &mut CallContext) -> WebIdlResult<IDBTransactionMode> {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rs
index c046354f2dd..269dedbdfea 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/indexed_db/internal/algorithms.rs
@@ -22,7 +22,7 @@ use libunicode_rust::character_types::{
code_point_has_identifier_continue_property, code_point_has_identifier_start_property,
};
-use crate::bindings::conversions::{CppInterface, ToJs, buffer_source_type_of};
+use crate::bindings::conversions::{ToJs, buffer_source_type_of};
use crate::bindings::cpp_cell::CppCell;
use crate::bindings::event_target::{CppEvent, CppEventTarget};
use crate::bindings::interface::{Interface, Ref, implementation_if, implementation_of};
@@ -30,8 +30,9 @@ use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};
use crate::dom::event::EventInit;
use crate::file_api::blob::{AnyBlob, Blob};
use crate::file_api::file::File;
+use crate::html::dom_string_list::DOMStringList;
use crate::html::structured_serialize::{structured_deserialize_for_storage, structured_serialize_for_storage};
-use crate::indexed_db::cpp::{DomException, create_dom_string_list};
+use crate::indexed_db::cpp::DomException;
use crate::indexed_db::idb_cursor::{AnyIDBCursor, IDBCursorDirection};
use crate::indexed_db::idb_database::{ConnectionState, IDBDatabase, IDBTransactionDurability};
use crate::indexed_db::idb_key_range::{IDBKeyRange, key_range_from_value};
@@ -1125,12 +1126,12 @@ pub(crate) fn is_valid_key_path(path: &KeyPath) -> bool {
}
// https://w3c.github.io/IndexedDB/#create-a-sorted-name-list
-pub(crate) fn create_a_sorted_name_list(cx: &CallContext, mut names: Vec<Utf16String>) -> CppInterface {
+pub(crate) fn create_a_sorted_name_list(vm: &Vm, mut names: Vec<Utf16String>) -> Ref<DOMStringList> {
// 1. Let sorted be names sorted in ascending order with the code unit less than algorithm.
names.sort_by(code_unit_order);
// 2. Return a new DOMStringList associated with sorted.
- create_dom_string_list(cx, &names)
+ DOMStringList::create(vm, names)
}
// https://w3c.github.io/IndexedDB/#commit-a-transaction
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 1a763ec1804..1e7b391528e 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -12085,12 +12085,12 @@ GC::Ref<HTML::DOMStringList> Document::ancestor_origins_list_creation_steps() co
VERIFY(ancestor_origins.has_value());
// 3. Let output be « ».
- Vector<String> output;
+ Vector<Utf16String> output;
// 4. For each origin of ancestorOrigins:
for (auto const& origin : ancestor_origins.value()) {
// 1. Append the serialization of origin to output.
- output.append(origin.serialize());
+ output.append(Utf16String::from_utf8(origin.serialize()));
}
// 5. Return a new DOMStringList object whose associated list is output.
diff --git a/Libraries/LibWeb/HTML/DOMStringList.cpp b/Libraries/LibWeb/HTML/DOMStringList.cpp
index bc25d600638..73df5fe47c1 100644
--- a/Libraries/LibWeb/HTML/DOMStringList.cpp
+++ b/Libraries/LibWeb/HTML/DOMStringList.cpp
@@ -4,50 +4,23 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/HTML/DOMStringList.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::HTML {
-GC_DEFINE_ALLOCATOR(DOMStringList);
+// Defined in Bindings/Rust/src/html/dom_string_list.rs.
+extern "C" void* web_dom_string_list_create(JSVM*, ReadonlySpan<FlatPtr> strings);
-GC::Ref<DOMStringList> DOMStringList::create(Vector<String> list)
+GC::Ref<DOMStringList> DOMStringList::create(Vector<Utf16String> strings)
{
- return GC::Heap::the().allocate<DOMStringList>(move(list));
-}
-
-DOMStringList::DOMStringList(Vector<String> list)
- : m_list(move(list))
-{
-}
-
-// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-domstringlist-length
-u32 DOMStringList::length() const
-{
- // The length getter steps are to return this's associated list's size.
- return m_list.size();
-}
-
-// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-domstringlist-item
-Optional<Utf16String> DOMStringList::item(u32 index) const
-{
- // The item(index) method steps are to return the indexth item in this's associated list, or null if index plus one
- // is greater than this's associated list's size.
- if (index >= m_list.size())
- return {};
+ Vector<FlatPtr> raw_strings;
+ raw_strings.ensure_capacity(strings.size());
+ for (auto& string : strings)
+ raw_strings.unchecked_append(move(string).into_raw());
- return Utf16String::from_utf8(m_list.at(index));
-}
-
-// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-domstringlist-contains
-bool DOMStringList::contains(Utf16View string)
-{
- // The contains(string) method steps are to return true if this's associated list contains string, and false otherwise.
- return any_of(m_list, [&](auto const& item) {
- auto item_utf16 = Utf16String::from_utf8(item);
- return item_utf16.utf16_view() == string;
- });
+ return GC::Ref { *static_cast<DOMStringList*>(web_dom_string_list_create(JS::HostABI::vm_to_abi(JS::VM::the()), raw_strings.span())) };
}
}
diff --git a/Libraries/LibWeb/HTML/DOMStringList.h b/Libraries/LibWeb/HTML/DOMStringList.h
index 0d99b9419e5..c2d257c4d97 100644
--- a/Libraries/LibWeb/HTML/DOMStringList.h
+++ b/Libraries/LibWeb/HTML/DOMStringList.h
@@ -6,28 +6,18 @@
#pragma once
-#include <AK/Optional.h>
-#include <AK/String.h>
+#include <AK/Utf16String.h>
#include <AK/Vector.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/DOMStringList.h>
+#include <LibWeb/Bindings/RustInterface.h>
namespace Web::HTML {
-class DOMStringList final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(DOMStringList, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(DOMStringList);
+class DOMStringList final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(DOMStringList, dom_string_list)
public:
- static GC::Ref<DOMStringList> create(Vector<String>);
-
- u32 length() const;
- Optional<Utf16String> item(u32 index) const;
- bool contains(Utf16View string);
-
-private:
- explicit DOMStringList(Vector<String>);
-
- Vector<String> m_list;
+ static GC::Ref<DOMStringList> create(Vector<Utf16String>);
};
}
diff --git a/Libraries/LibWeb/HTML/DOMStringList.idl b/Libraries/LibWeb/HTML/DOMStringList.idl
index bc45e19a98d..addea1b6398 100644
--- a/Libraries/LibWeb/HTML/DOMStringList.idl
+++ b/Libraries/LibWeb/HTML/DOMStringList.idl
@@ -1,5 +1,5 @@
// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#domstringlist
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface DOMStringList {
readonly attribute unsigned long length;
getter DOMString? item(unsigned long index);
diff --git a/Libraries/LibWeb/IndexedDB/RustIntegration.cpp b/Libraries/LibWeb/IndexedDB/RustIntegration.cpp
index dafbb3fdb45..807e6de45bf 100644
--- a/Libraries/LibWeb/IndexedDB/RustIntegration.cpp
+++ b/Libraries/LibWeb/IndexedDB/RustIntegration.cpp
@@ -16,7 +16,6 @@
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/DOM/Document.h>
-#include <LibWeb/HTML/DOMStringList.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/Page/Page.h>
@@ -36,7 +35,6 @@ void web_rust_indexed_db_check_pending_connection_wait(JSVM*, void* database);
void* web_indexed_db_create_dom_exception(ReadonlyBytes name, FlatPtr message);
void* web_indexed_db_dom_exception_from_value(JSValue);
JSObject* web_indexed_db_wrap_dom_exception(void* realm, void* exception);
-JSObject* web_indexed_db_create_dom_string_list(void* realm, FlatPtr const* strings, size_t count);
void web_indexed_db_queue_a_database_task(void* cell, void (*steps)(JSVM*, void*));
void web_indexed_db_run_in_parallel(void* cell, void (*steps)(JSVM*, void*));
void* web_indexed_db_current_event_loop();
@@ -73,17 +71,6 @@ JSObject* web_indexed_db_wrap_dom_exception(void* realm, void* exception)
return JS::HostABI::object_to_abi(Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, GC::Ref { dom_exception }).ptr());
}
-JSObject* web_indexed_db_create_dom_string_list(void* realm, FlatPtr const* strings, size_t count)
-{
- auto& js_realm = *static_cast<JS::Realm*>(realm);
- Vector<String> names;
- names.ensure_capacity(count);
- for (size_t i = 0; i < count; ++i)
- names.unchecked_append(Utf16String::from_raw(strings[i]).to_utf8());
- auto list = HTML::DOMStringList::create(move(names));
- return JS::HostABI::object_to_abi(Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, list).ptr());
-}
-
// https://w3c.github.io/IndexedDB/#queue-a-database-task
void web_indexed_db_queue_a_database_task(void* cell, void (*steps)(JSVM*, void*))
{
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index c27dbfbab52..97adda8df2d 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -72,7 +72,7 @@ ALLOWED_REALM_MENTIONS = {
),
"IndexedDB": (
4,
- 11,
+ 10,
"the C++ glue of the Rust IndexedDB creates the factory in a global's realm and wraps values in a given realm",
),
"Infra": (2, 13, "JSON parse/serialization helpers still expose JS values in selected realms"),