Skip to content

Truly independent web browser

Meta+LibWeb: Convert ByteString in the Rust bindings

Shannon Boothbcfe869b84d7
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index f1c6e5c9d2f..a0736d1c1db 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -141,6 +141,24 @@ impl From<UsvString> for Utf16String {
}
}
+/// https://webidl.spec.whatwg.org/#idl-ByteString
+#[derive(Clone, Eq, PartialEq)]
+pub(crate) struct ByteString(Vec<u8>);
+
+impl ByteString {
+ pub(crate) fn from_bytes(bytes: Vec<u8>) -> Self {
+ Self(bytes)
+ }
+
+ pub(crate) fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
+
+ pub(crate) fn into_bytes(self) -> Vec<u8> {
+ self.0
+ }
+}
+
/// A JS value converted to a DOMString, https://webidl.spec.whatwg.org/#es-DOMString
pub(crate) fn to_dom_string(vm: &Vm, value: Value) -> ThrowCompletionOr<Utf16String> {
value.to_utf16_string(vm)
@@ -165,6 +183,31 @@ pub(crate) fn to_usv_string(vm: &Vm, value: Value) -> ThrowCompletionOr<UsvStrin
Ok(UsvString(to_well_formed(&string)))
}
+/// https://webidl.spec.whatwg.org/#es-ByteString
+pub(crate) fn to_byte_string(vm: &Vm, value: Value) -> ThrowCompletionOr<ByteString> {
+ // 1. Let x be ? ToString(V).
+ let x = value.to_utf16_string(vm)?;
+
+ let code_units = match x.as_units() {
+ Utf16StringUnits::Ascii(bytes) | Utf16StringUnits::Latin1(bytes) => return Ok(ByteString(bytes.to_vec())),
+ Utf16StringUnits::Utf16(code_units) => code_units,
+ };
+
+ // 2. If the value of any element of x is greater than 255, then throw a TypeError.
+ if let Some((index, code_unit)) = code_units.iter().enumerate().find(|(_, code_unit)| **code_unit > 0xFF) {
+ let message = format!(
+ "Invalid byte 0x{code_unit:X} at index {index}, must be an integer no less than 0 and no greater than 0xFF"
+ );
+ return vm.throw_completion_with_utf16_message(ErrorKind::TypeError, Utf16String::from_utf8(&message));
+ }
+
+ // 3. Return an IDL ByteString value whose length is the length of x, and where the value of each element is the
+ // value of the corresponding element of x.
+ Ok(ByteString(
+ code_units.iter().map(|code_unit| *code_unit as u8).collect(),
+ ))
+}
+
/// The value of an enumeration that a JS value names, https://webidl.spec.whatwg.org/#js-enumeration: the index of
/// the string that the value converts to among the values of the enumeration, which are ASCII.
pub(crate) fn to_enumeration_value(
@@ -1171,6 +1214,21 @@ impl ToJs for UsvString {
}
}
+/// https://webidl.spec.whatwg.org/#js-ByteString
+impl ToJs for ByteString {
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {
+ // The result of converting an IDL ByteString value to a JavaScript value is a String value whose length is the
+ // length of the ByteString, and the value of each element of which is the value of the corresponding element
+ // of the ByteString.
+ let string = if self.0.is_ascii() {
+ Utf16String::from_ascii(&self.0)
+ } else {
+ Utf16String::from_utf16(&self.0.iter().map(|byte| u16::from(*byte)).collect::<Vec<_>>())
+ };
+ string.to_js(cx)
+ }
+}
+
impl ToJs for Gc<TypedArrayBase> {
fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {
Ok(Value::from_object(self))
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index fb914259b40..7457bc6b8c2 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -1129,9 +1129,9 @@ RUST_BINDINGS_IMPORTS = """ #![allow(unused_imports)]
};
use crate::bindings::conversions::{
- ArrayBufferView, BufferSource, BufferSourceRules, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
+ ArrayBufferView, BufferSource, BufferSourceRules, ByteString, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
frozen_array_to_js, implements_cpp_interface, iterator_method, record_from_js, record_to_js, rooted_sequence_to_js,
- sequence_from_js, sequence_to_js, to_array_buffer_view, to_boolean, to_buffer_source, to_cpp_interface,
+ sequence_from_js, sequence_to_js, to_array_buffer_view, to_boolean, to_buffer_source, to_byte_string, to_cpp_interface,
to_cpp_interface_in_union, to_dom_string,
to_dom_string_treating_null_as_empty, to_double, to_float, to_long, to_long_enforcing_range, to_long_long,
to_long_long_clamping, to_long_long_enforcing_range, to_object, to_promise, to_typed_array,
@@ -2484,11 +2484,11 @@ pub(crate) mod definitions {
use crate::bindings::CallContext;
use crate::bindings::callback::{CallbackFunction, CallbackInterface, PromiseCallbackFunction};
use crate::bindings::conversions::{
- ArrayBufferView, BufferSource, BufferSourceRules, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
+ ArrayBufferView, BufferSource, BufferSourceRules, ByteString, CppInterface, EmptyDictionary, FromJs, ToJs, UsvString,
buffer_source_if, dictionary_member, dictionary_object, enumeration_value_to_js, implements_cpp_interface,
frozen_array_to_js, iterator_method, record_from_js, record_to_js, rooted_sequence_to_js, sequence_from_iterable, sequence_from_js,
sequence_to_js, throw_no_union_types_matched, to_array_buffer_view, to_boolean, to_buffer_source,
- to_cpp_interface,
+ to_byte_string, to_cpp_interface,
to_dom_string, to_dom_string_treating_null_as_empty, to_double, to_enumeration_value, to_float, to_long,
to_long_enforcing_range, to_long_long, to_long_long_enforcing_range, to_object, to_typed_array,
to_unrestricted_double, to_unrestricted_float, to_unsigned_long, to_unsigned_long_enforcing_range,
diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
index 1ac80851409..4cfefe3df04 100644
--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py
+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py
@@ -57,7 +57,7 @@ from Utils.webidl_parser import OperationParameter
# NB: CSSOMString is a string type that an implementation chooses, https://drafts.csswg.org/cssom/#cssomstring-type,
# and it is a DOMString here, as it is in the C++ bindings.
DOM_STRING_TYPES = ("CSSOMString", "DOMString")
-STRING_TYPES = (*DOM_STRING_TYPES, "USVString")
+STRING_TYPES = ("ByteString", *DOM_STRING_TYPES, "USVString")
def buffer_source_rules(idl_type: IDLType, parameter_attributes: dict[str, str]) -> str:
@@ -124,6 +124,8 @@ def rust_to_idl_value(
return f"to_dom_string(vm, {value})"
if name == "USVString":
return f"to_usv_string(vm, {value})"
+ if name == "ByteString":
+ return f"to_byte_string(vm, {value})"
if name == "boolean":
return f"to_boolean({value})"
if name == "any":
@@ -315,7 +317,9 @@ def rust_numeric_literal(literal: Optional[str], idl_type_name: str) -> Optional
def rust_string_literal(default_value: Optional[str], idl_type_name: str, what: str) -> Optional[str]:
"""The Rust expression of a string of the IDL, if the default value is one, as a value of the string type."""
- if idl_type_name not in STRING_TYPES or default_value is None or not default_value.startswith('"'):
+ if idl_type_name not in STRING_TYPES or idl_type_name == "ByteString":
+ return None
+ if default_value is None or not default_value.startswith('"'):
return None
string = default_value[1:-1]
if not string.isascii() or "\\" in string:
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
index 78f61a362b0..97f619869fe 100644
--- a/Meta/Generators/libweb_bindings/rust_types.py
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -65,6 +65,7 @@ FLOATING_POINT_TYPES = {"float": "f32", "unrestricted float": "f32", "double": "
# The types whose values are plain data, with the Rust type of their values. None of these Rust types is or holds a
# cell, which holds_cells() relies on.
PLAIN_DATA_TYPES = {
+ "ByteString": "ByteString",
"CSSOMString": "Utf16String",
"DOMString": "Utf16String",
"USVString": "UsvString",
@@ -423,7 +424,7 @@ def rust_type(idl_type: IDLType, context: GenerationContext, what: str, is_resul
return "WebIdlPromise"
if name == "record":
key_type, value_type = idl_type.parameters
- if key_type.name not in ("DOMString", "USVString"):
+ if key_type.name not in ("ByteString", "DOMString", "USVString"):
raise UnsupportedByRustBindings(f"{what} has a record with keys of the type {key_type}")
return f"Vec<({rust_type(key_type, context, what)}, {rust_type(value_type, context, what)})>"
raise UnsupportedByRustBindings(f"{what} has the type {idl_type}, which the Rust bindings do not convert yet")