Truly independent web browser
LibJS: Make typed arrays from arrays without the iterator protocol
Andreas Klingd60c38d67dad
diff --git a/Libraries/LibJS/Rust/src/gc/root.rs b/Libraries/LibJS/Rust/src/gc/root.rsindex 17130436f9e..2f6364360cb 100644--- a/Libraries/LibJS/Rust/src/gc/root.rs+++ b/Libraries/LibJS/Rust/src/gc/root.rs@@ -116,6 +116,10 @@ impl<'vm, T: Trace + Clone + 'static> MarkedVec<'vm, T> {self.rooted_values().borrow_mut().push(value);}+ pub fn extend_from_slice(&self, values: &[T]) {+ self.rooted_values().borrow_mut().extend_from_slice(values);+ }+pub fn insert(&self, index: usize, value: T) {self.rooted_values().borrow_mut().insert(index, value);}diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rsindex a5640ef0a30..007ea650484 100644--- a/Libraries/LibJS/Rust/src/runtime/object.rs+++ b/Libraries/LibJS/Rust/src/runtime/object.rs@@ -4400,10 +4400,10 @@ impl Object {// For FunctionPrototype.apply fast pathpub fn indexed_packed_elements<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, Value> {let count = self.indexed_packed_elements_span_size();- let elements = MarkedVec::with_capacity(vm, count as usize);- for index in 0..count {- elements.push(self.indexed_element(index));- }+ // NB: Reading the elements does not collect, so they need no root until they are copied out.+ let values: Vec<Value> = (0..count).map(|index| self.indexed_element(index)).collect();+ let elements = MarkedVec::new(vm);+ elements.extend_from_slice(&values);elements}diff --git a/Libraries/LibJS/Rust/src/runtime/typed_array.rs b/Libraries/LibJS/Rust/src/runtime/typed_array.rsindex aeb407c552b..ab891e3b31a 100644--- a/Libraries/LibJS/Rust/src/runtime/typed_array.rs+++ b/Libraries/LibJS/Rust/src/runtime/typed_array.rs@@ -21,9 +21,10 @@ use crate::runtime::abstract_operations::{CanonicalIndexMode, IntrinsicDefaultPrototype, call_function_object, canonical_numeric_index_string, construct,get_prototype_from_constructor, length_of_array_like,};+use crate::runtime::array::Array;use crate::runtime::array_buffer::{ArrayBuffer, ElementType, INVALID_DATA_OFFSET, Order, ReadWriteModifyOperation, allocate_array_buffer,- array_buffer_byte_length, clone_array_buffer,+ array_buffer_byte_length, clone_array_buffer, f64_to_binary16_bits,};use crate::runtime::byte_length::{ByteLength, ByteLengthSlot};use crate::runtime::canonical_index::{CanonicalIndex, CanonicalIndexType};@@ -36,15 +37,17 @@ use crate::runtime::iterator::{get_iterator_from_method_impl, iterator_to_list};use crate::runtime::native_function::{NativeFunction, define_native_function_class};use crate::runtime::object::{CacheableGetPropertyMetadata, CacheableSetPropertyMetadata, MayInterfereWithIndexedPropertyAccess,- ORDINARY_OBJECT_METHODS, ObjectMethods, PropertyLookupPhase, ShouldThrowExceptions, define_object_class,+ ORDINARY_OBJECT_METHODS, ObjectMethods, PropertyLookupPhase, define_object_class,};use crate::runtime::primitive_string::PrimitiveString;use crate::runtime::property_attributes::{Attribute, PropertyAttributes};use crate::runtime::property_descriptor::PropertyDescriptor;use crate::runtime::property_key::PropertyKey;use crate::runtime::realm::Realm;+use crate::runtime::realm_watchpoints;use crate::runtime::uint8_array::{Uint8ArrayConstructorHelpers, Uint8ArrayPrototypeHelpers};use crate::runtime::value::same_value;+use crate::runtime::value_conversions;pub use crate::layout::object::TypedArrayBase;@@ -1330,6 +1333,80 @@ fn allocate_typed_array_buffer(vm: &Vm, typed_array: &TypedArrayBase, length: usOk(())}+/// ? IteratorToList(? GetIteratorFromMethod(source, usingIterator)), as the typed array constructors and+/// %TypedArray%.from ( ) take the values of an iterable.+pub(crate) fn iterable_to_list(+ vm: &Vm,+ source: Value,+ using_iterator: Gc<FunctionObject>,+) -> ThrowCompletionOr<MarkedVec<'_, Value>> {+ // OPTIMIZATION: Iterating a packed array with the original array iterator cannot be observed, and produces its+ // elements.+ let realm = vm.current_realm().expect("iterables are iterated in a realm");+ if source.is_object()+ && let Some(array) = source.as_object().downcast::<Array>()+ && using_iterator == realm.array_prototype_values_function()+ && array.is_simple_packed_array()+ && realm_watchpoints::array_iterators_have_builtin_next(vm, realm)+ {+ return Ok(array.indexed_packed_elements(vm));+ }+ iterator_to_list(vm, &get_iterator_from_method_impl(vm, source, using_iterator)?)+}++/// OPTIMIZATION: Performs TypedArraySetElement(typedArray, 𝔽(k), values[k]) for every k at once, if that cannot be+/// observed: the values are numbers, whose conversion runs no code, for a typed array of numbers whose elements at+/// those indices are valid, in a buffer that is not shared. Returns whether it did.+pub(crate) fn set_elements_to_numbers_if_unobservable(typed_array: &TypedArrayBase, values: &[Value]) -> bool {+ if values.is_empty()+ || typed_array.content_type() != ContentType::Number+ || !values.iter().all(|value| value.is_number())+ {+ return false;+ }+ let Ok(last_index) = u32::try_from(values.len() - 1) else {+ return false;+ };+ // NB: Valid integer indices are those below the length of a typed array whose buffer is not detached.+ let buffer = typed_array.viewed_array_buffer();+ if !is_valid_integer_index(typed_array, CanonicalIndex::new(CanonicalIndexType::Index, last_index))+ || buffer.is_shared_array_buffer()+ {+ return false;+ }+ let bytes = match typed_array.kind().element_type() {+ ElementType::Int8 | ElementType::Uint8 => encode_numbers(values, |value| [number_to_i32(value) as u8]),+ ElementType::Uint8Clamped => encode_numbers(values, |value| [value_conversions::to_u8_clamp(value.as_f64())]),+ ElementType::Int16 | ElementType::Uint16 => {+ encode_numbers(values, |value| (number_to_i32(value) as u16).to_le_bytes())+ }+ ElementType::Int32 | ElementType::Uint32 => encode_numbers(values, |value| number_to_i32(value).to_le_bytes()),+ ElementType::Float16 => encode_numbers(values, |value| f64_to_binary16_bits(value.as_f64()).to_le_bytes()),+ ElementType::Float32 => encode_numbers(values, |value| (value.as_f64() as f32).to_bits().to_le_bytes()),+ ElementType::Float64 => encode_numbers(values, |value| value.as_f64().to_bits().to_le_bytes()),+ ElementType::BigInt64 | ElementType::BigUint64 => unreachable!("the typed array holds numbers"),+ };+ buffer.overwrite(typed_array.byte_offset() as usize, &bytes);+ true+}++/// The little-endian bytes of the elements that `encode` makes of each of the numbers `values`.+fn encode_numbers<const SIZE: usize>(values: &[Value], encode: impl Fn(Value) -> [u8; SIZE]) -> Vec<u8> {+ let mut bytes = vec![0; values.len() * SIZE];+ for (element, value) in bytes.as_chunks_mut::<SIZE>().0.iter_mut().zip(values) {+ *element = encode(*value);+ }+ bytes+}++/// ToInt32 of the number `value`.+fn number_to_i32(value: Value) -> i32 {+ if value.is_int32() {+ return value.as_i32();+ }+ value_conversions::to_i32(value.as_f64())+}+// 23.2.5.1.5 InitializeTypedArrayFromArrayLike, https://tc39.es/ecma262/#sec-initializetypedarrayfromarraylikefn initialize_typed_array_from_array_like(vm: &Vm,@@ -1350,7 +1427,14 @@ fn initialize_typed_array_from_array_like(let k_value = array_like.get(vm, &PropertyKey::from_number(k))?;// c. Perform ? Set(O, Pk, kValue, true).- typed_array.set(vm, &PropertyKey::from_number(k), k_value, ShouldThrowExceptions::Yes)?;+ // NB: [[Set]] of a typed array with an index key and the typed array as the receiver is+ // TypedArraySetElement.+ typed_array_set_element(+ vm,+ typed_array,+ CanonicalIndex::new(CanonicalIndexType::Index, k as u32),+ k_value,+ )?;// d. Set k to k + 1.}@@ -1371,6 +1455,10 @@ fn initialize_typed_array_from_list(// 2. Perform ? AllocateTypedArrayBuffer(O, len).allocate_typed_array_buffer(vm, typed_array, length)?;+ if list.with_values(|values| set_elements_to_numbers_if_unobservable(typed_array, values)) {+ return Ok(());+ }+// 3. Let k be 0.// 4. Repeat, while k < len,for k in 0..length {@@ -1379,11 +1467,12 @@ fn initialize_typed_array_from_list(let value = list.get(k).expect("the index is in bounds");// c. Perform ? Set(O, Pk, kValue, true).- typed_array.set(+ // NB: See initialize_typed_array_from_array_like().+ typed_array_set_element(vm,- &PropertyKey::from_number(k as u64),+ typed_array,+ CanonicalIndex::new(CanonicalIndexType::Index, k as u32),value,- ShouldThrowExceptions::Yes,)?;// d. Set k to k + 1.@@ -1828,7 +1917,7 @@ fn construct_typed_array(vm: &Vm, kind: Kind, new_target: Gc<FunctionObject>) ->} else if let Some(iterator) =first_argument.get_method(vm, &PropertyKey::from(vm.well_known_symbols().iterator))?{- let values = iterator_to_list(vm, &get_iterator_from_method_impl(vm, first_argument, iterator)?)?;+ let values = iterable_to_list(vm, first_argument, iterator)?;initialize_typed_array_from_list(vm, &typed_array, &values)?;} else {initialize_typed_array_from_array_like(vm, &typed_array, &first_object)?;diff --git a/Libraries/LibJS/Rust/src/runtime/typed_array_constructor.rs b/Libraries/LibJS/Rust/src/runtime/typed_array_constructor.rsindex 129dcbcd26e..f6d65445691 100644--- a/Libraries/LibJS/Rust/src/runtime/typed_array_constructor.rs+++ b/Libraries/LibJS/Rust/src/runtime/typed_array_constructor.rs@@ -12,17 +12,19 @@ use crate::layout::cell::Gc;use crate::layout::object::Object;use crate::layout::value::Value;use crate::runtime::abstract_operations::{call_function_object, length_of_array_like};+use crate::runtime::canonical_index::{CanonicalIndex, CanonicalIndexType};use crate::runtime::completion::{Must, ThrowCompletionOr};use crate::runtime::error::ErrorKind;use crate::runtime::error_types::ErrorType;use crate::runtime::function_object::FunctionObject;-use crate::runtime::iterator::{get_iterator_from_method_impl, iterator_to_list};use crate::runtime::native_function::{NativeFunction, define_native_function_class, raw_native};use crate::runtime::object::ShouldThrowExceptions;use crate::runtime::property_attributes::{Attribute, PropertyAttributes};use crate::runtime::property_key::PropertyKey;use crate::runtime::realm::Realm;-use crate::runtime::typed_array::typed_array_create;+use crate::runtime::typed_array::{+ iterable_to_list, set_elements_to_numbers_if_unobservable, typed_array_create, typed_array_set_element,+};/// %TypedArray%.#[repr(C)]@@ -150,7 +152,7 @@ impl TypedArrayConstructor {// 6. If usingIterator is not undefined, thenif let Some(using_iterator) = using_iterator {// a. Let values be ? IteratorToList(? GetIteratorFromMethod(source, usingIterator)).- let values = iterator_to_list(vm, &get_iterator_from_method_impl(vm, source, using_iterator)?)?;+ let values = iterable_to_list(vm, source, using_iterator)?;// b. Let len be the number of elements in values.let length = values.len();@@ -158,11 +160,18 @@ impl TypedArrayConstructor {// c. Let targetObj be ? TypedArrayCreate(C, « 𝔽(len) »).let target_object = typed_array_create(vm, constructor.as_function(), &[Value::from_f64(length as f64)])?;+ if map_fn.is_none()+ && values.with_values(|values| set_elements_to_numbers_if_unobservable(&target_object, values))+ {+ return Ok(Value::from_object(target_object));+ }+// d. Let k be 0.// e. Repeat, while k < len,for k in 0..length {// i. Let Pk be ! ToString(𝔽(k)).- let property_key = PropertyKey::from_number(k as u64);+ // NB: TypedArrayCreate made targetObj at least len elements long, which fits an index.+ let index = CanonicalIndex::new(CanonicalIndexType::Index, k as u32);// ii. Let kValue be the first element of values.// iii. Remove the first element from values.@@ -179,7 +188,9 @@ impl TypedArrayConstructor {};// vi. Perform ? Set(targetObj, Pk, mappedValue, true).- target_object.set(vm, &property_key, mapped_value, ShouldThrowExceptions::Yes)?;+ // NB: [[Set]] of a typed array with an index key and the typed array as the receiver is+ // TypedArraySetElement.+ typed_array_set_element(vm, &target_object, index, mapped_value)?;// vii. Set k to k + 1.}@@ -221,7 +232,9 @@ impl TypedArrayConstructor {};// e. Perform ? Set(targetObj, Pk, mappedValue, true).- target_object.set(vm, &property_key, mapped_value, ShouldThrowExceptions::Yes)?;+ // NB: See step 6.e.vi; len fits an index too.+ let index = CanonicalIndex::new(CanonicalIndexType::Index, k as u32);+ typed_array_set_element(vm, &target_object, index, mapped_value)?;// f. Set k to k + 1.}diff --git a/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-from-arrays.js b/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-from-arrays.jsnew file mode 100644index 00000000000..f72f530c587--- /dev/null+++ b/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-from-arrays.js@@ -0,0 +1,108 @@+// Typed array constructors and %TypedArray%.from take the values of arrays like the iterator protocol does, whether+// iterating the array can be observed or not.++const create = {+ constructor: (T, source) => new T(source),+ from: (T, source) => T.from(source),+};++describe("typed arrays from arrays", () => {+ for (const [name, make] of Object.entries(create)) {+ test(`${name}: packed arrays`, () => {+ const source = [];+ for (let i = 0; i < 1000; ++i) source.push((i * 31) & 255);+ const array = make(Uint8Array, source);+ expect(array.length).toBe(1000);+ for (let i = 0; i < 1000; ++i) expect(array[i]).toBe((i * 31) & 255);+ expect(Array.from(make(Int8Array, [127, 128, -129, 1.5, "3", true]))).toEqual([127, -128, 127, 1, 3, 1]);+ expect(Array.from(make(Float64Array, [0.5, -0, null, undefined]))).toEqual([0.5, -0, 0, NaN]);+ expect(Array.from(make(BigInt64Array, [1n, -2n]))).toEqual([1n, -2n]);+ });++ test(`${name}: holes and accessors read through the prototype chain`, () => {+ expect(Array.from(make(Int32Array, [1, , 3]))).toEqual([1, 0, 3]);+ Array.prototype[1] = 42;+ try {+ expect(Array.from(make(Int32Array, [1, , 3]))).toEqual([1, 42, 3]);+ } finally {+ delete Array.prototype[1];+ }+ const withGetter = [1, 2, 3];+ Object.defineProperty(withGetter, 1, { get: () => 7 });+ expect(Array.from(make(Int32Array, withGetter))).toEqual([1, 7, 3]);+ });++ test(`${name}: elements convert in order`, () => {+ const order = [];+ const element = value => ({+ valueOf() {+ order.push(value);+ return value;+ },+ });+ expect(Array.from(make(Uint16Array, [element(1), element(2), element(3)]))).toEqual([1, 2, 3]);+ expect(order).toEqual([1, 2, 3]);+ const throwing = [+ 1,+ {+ valueOf() {+ throw new Error("element");+ },+ },+ ];+ expect(() => make(Uint8Array, throwing)).toThrowWithMessage(Error, "element");+ expect(() => make(BigInt64Array, [1])).toThrow(TypeError);+ });++ test(`${name}: replaced iterators are used`, () => {+ const source = [1, 2, 3];+ source[Symbol.iterator] = function* () {+ yield 9;+ };+ expect(Array.from(make(Uint8Array, source))).toEqual([9]);++ const values = Array.prototype[Symbol.iterator];+ Array.prototype[Symbol.iterator] = function* () {+ yield* values.call(this);+ yield 4;+ };+ try {+ expect(Array.from(make(Uint8Array, [1, 2, 3]))).toEqual([1, 2, 3, 4]);+ } finally {+ Array.prototype[Symbol.iterator] = values;+ }++ const iteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());+ const next = iteratorPrototype.next;+ let calls = 0;+ iteratorPrototype.next = function () {+ ++calls;+ return next.call(this);+ };+ try {+ const array = make(Uint8Array, [1, 2, 3]);+ expect(calls).toBe(4);+ expect(Array.from(array)).toEqual([1, 2, 3]);+ } finally {+ iteratorPrototype.next = next;+ }+ });+ }++ test("from: mapping functions see the values and may detach the buffer", () => {+ let target;+ class Captured extends Uint8Array {+ constructor(length) {+ super(length);+ target = this;+ }+ }+ const mapped = Captured.from([1, 2, 3], (value, index) => {+ if (index === 1) target.buffer.transfer();+ return value * 10;+ });+ expect(mapped).toBe(target);+ expect(mapped.length).toBe(0);+ expect(Array.from(Uint8Array.from([1, 2, 3], value => value * 2))).toEqual([2, 4, 6]);+ });+});