Truly independent web browser
LibJS: Convert typed array elements to another type in one pass
Andreas Kling83ed7634c1cd
diff --git a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs b/Libraries/LibJS/Rust/src/runtime/array_buffer.rsindex 846a9b6c740..b5fc90d0913 100644--- a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs+++ b/Libraries/LibJS/Rust/src/runtime/array_buffer.rs@@ -43,6 +43,7 @@ use crate::runtime::object::MayInterfereWithIndexedPropertyAccess;use crate::runtime::realm::Realm;use crate::runtime::typed_array::TypedArrayBase;use crate::runtime::value::same_value;+use crate::runtime::value_conversions;use crate::runtime::value_conversions::MAX_ARRAY_LIKE_INDEX;pub use crate::gc::primitive_storage::cage_base as primitive_storage_cage_base;@@ -1034,6 +1035,58 @@ impl ArrayBuffer {source_block.copy_to_block(&destination_block, source_offset, destination_offset, count);}+ /// GetValueFromBuffer of `count` elements of `source_type` from `source_offset` of this buffer, each followed by+ /// SetValueInBuffer of the value as `destination_type` into `destination` from `destination_offset`, unordered and+ /// little-endian, as typed arrays of different element types copy between each other.+ /// OPTIMIZATION: For buffers that are neither shared nor the same, this is one pass over both blocks, without the+ /// checks and borrows of an access to each element.+ pub fn convert_elements_to(+ &self,+ destination: &ArrayBuffer,+ source_offset: usize,+ source_type: ElementType,+ destination_offset: usize,+ destination_type: ElementType,+ count: usize,+ ) {+ assert!(!core::ptr::eq(self, destination));+ assert!(source_type.is_bigint() == destination_type.is_bigint());+ if count == 0 {+ return;+ }+ let source_block = self.data_block.borrow();+ let destination_block = destination.data_block.borrow();+ assert!(source_block.is_shared == Shared::No && destination_block.is_shared == Shared::No);+ let (source_size, destination_size) = (source_type.size(), destination_type.size());+ let in_bounds = |block: &DataBlock, offset: usize, element_size: usize| {+ count+ .checked_mul(element_size)+ .and_then(|length| length.checked_add(offset))+ .is_some_and(|end| end <= block.size())+ };+ assert!(in_bounds(&source_block, source_offset, source_size));+ assert!(in_bounds(&destination_block, destination_offset, destination_size));+ let source = source_block.data_at(source_offset);+ let target = destination_block.data_at(destination_offset);+ for index in 0..count {+ // NB: The blocks of two buffers can still be the same external storage, as the buffers of a wasm memory in+ // two realms are. Each element is read before it is written, in the order of the spec's steps, so+ // such blocks end up as they would element by element.+ // SAFETY: The blocks have the elements' bytes, which only this thread accesses, and nothing makes a+ // reference to them.+ unsafe {+ let bits = read_element_bits(source.add(index * source_size), source_size);+ // NB: BigInt64 and BigUint64 elements of the same BigInt have the same bits.+ let bits = if source_type.is_bigint() {+ bits+ } else {+ number_to_element_bits(destination_type, number_from_element_bits(source_type, bits))+ };+ write_element_bits(target.add(index * destination_size), destination_size, bits);+ }+ }+ }+pub fn copy_data_to_block(&self,destination: &DataBlock,@@ -1893,6 +1946,60 @@ pub fn binary16_bits_to_f64(bits: u16) -> f64 {sign * magnitude}+/// NumericToRawBytes of the Number `number` as an element of the Number element type `element_type`, as a+/// little-endian bit string in the low Element Size bytes.+fn number_to_element_bits(element_type: ElementType, number: f64) -> u64 {+ match element_type {+ ElementType::Float16 => u64::from(f64_to_binary16_bits(number)),+ ElementType::Float32 => u64::from((number as f32).to_bits()),+ ElementType::Float64 => number.to_bits(),+ ElementType::Int32 => u64::from(value_conversions::to_i32(number) as u32),+ ElementType::Int16 => u64::from(value_conversions::to_i16(number) as u16),+ ElementType::Int8 => u64::from(value_conversions::to_i8(number) as u8),+ ElementType::Uint32 => u64::from(value_conversions::to_u32(number)),+ ElementType::Uint16 => u64::from(value_conversions::to_u16(number)),+ ElementType::Uint8 => u64::from(value_conversions::to_u8(number)),+ ElementType::Uint8Clamped => u64::from(value_conversions::to_u8_clamp(number)),+ ElementType::BigInt64 | ElementType::BigUint64 => unreachable!("BigInt elements are no Numbers"),+ }+}++/// The little-endian bits of the element of `size` bytes at `address`.+///+/// # Safety+///+/// `address` must have the element's bytes, which nothing writes concurrently.+unsafe fn read_element_bits(address: *const u8, size: usize) -> u64 {+ // SAFETY: The caller passes an address that has the element's bytes.+ unsafe {+ match size {+ 1 => u64::from(address.read()),+ 2 => u64::from(u16::from_le(address.cast::<u16>().read_unaligned())),+ 4 => u64::from(u32::from_le(address.cast::<u32>().read_unaligned())),+ 8 => u64::from_le(address.cast::<u64>().read_unaligned()),+ _ => unreachable!("elements have 1, 2, 4 or 8 bytes"),+ }+ }+}++/// Writes the low `size` bytes of `bits` little-endian to `address`.+///+/// # Safety+///+/// `address` must have room for the element's bytes, which nothing accesses concurrently.+unsafe fn write_element_bits(address: *mut u8, size: usize, bits: u64) {+ // SAFETY: The caller passes an address with room for the element's bytes.+ unsafe {+ match size {+ 1 => address.write(bits as u8),+ 2 => address.cast::<u16>().write_unaligned((bits as u16).to_le()),+ 4 => address.cast::<u32>().write_unaligned((bits as u32).to_le()),+ 8 => address.cast::<u64>().write_unaligned(bits.to_le()),+ _ => unreachable!("elements have 1, 2, 4 or 8 bytes"),+ }+ }+}+// 25.1.3.14 RawBytesToNumeric ( type, rawBytes, isLittleEndian ), https://tc39.es/ecma262/#sec-rawbytestonumericpub fn raw_bytes_to_numeric(vm: &Vm, element_type: ElementType, raw_value: &mut [u8], is_little_endian: bool) -> Value {// 1. Let elementSize be the Element Size value specified in Table 70 for Element Type type.@@ -1908,6 +2015,25 @@ pub fn raw_bytes_to_numeric(vm: &Vm, element_type: ElementType, raw_value: &mutbytes[..raw_value.len()].copy_from_slice(raw_value);let little_endian_value = u64::from_le_bytes(bytes);+ match element_type {+ // 8. If IsBigIntElementType(type) is true, return the BigInt value that corresponds to intValue.+ ElementType::BigInt64 => Value::from_bigint(BigInt::create(vm, NumBigInt::from(little_endian_value as i64))),+ ElementType::BigUint64 => Value::from_bigint(BigInt::create(vm, NumBigInt::from(little_endian_value))),+ // OPTIMIZATION: The Number values of the integer elements that fit in an i32 are made as int32 values directly.+ ElementType::Uint8 | ElementType::Uint8Clamped => Value::from_i32(i32::from(little_endian_value as u8)),+ ElementType::Uint16 => Value::from_i32(i32::from(little_endian_value as u16)),+ ElementType::Int8 => Value::from_i32(i32::from(little_endian_value as u8 as i8)),+ ElementType::Int16 => Value::from_i32(i32::from(little_endian_value as u16 as i16)),+ ElementType::Int32 => Value::from_i32(little_endian_value as u32 as i32),+ ElementType::Uint32 | ElementType::Float16 | ElementType::Float32 | ElementType::Float64 => {+ Value::from_f64(number_from_element_bits(element_type, little_endian_value))+ }+ }+}++/// Steps 3 to 7 and 9 of RawBytesToNumeric, for a Number element type and the element's bytes concatenated as a+/// little-endian bit string.+fn number_from_element_bits(element_type: ElementType, little_endian_value: u64) -> f64 {match element_type {// 3. If type is Float16, thenElementType::Float16 => {@@ -1916,11 +2042,11 @@ pub fn raw_bytes_to_numeric(vm: &Vm, element_type: ElementType, raw_value: &mut// b. If value is an IEEE 754-2019 binary16 NaN value, return the NaN Number value.if value.is_nan() {- return Value::from_f64(f64::NAN);+ return f64::NAN;}// c. Return the Number value that corresponds to value.- Value::from_f64(value)+ value}// 4. If type is Float32, thenElementType::Float32 => {@@ -1929,11 +2055,11 @@ pub fn raw_bytes_to_numeric(vm: &Vm, element_type: ElementType, raw_value: &mut// b. If value is an IEEE 754-2019 binary32 NaN value, return the NaN Number value.if value.is_nan() {- return Value::from_f64(f64::NAN);+ return f64::NAN;}// c. Return the Number value that corresponds to value.- Value::from_f64(f64::from(value))+ f64::from(value)}// 5. If type is Float64, thenElementType::Float64 => {@@ -1942,27 +2068,25 @@ pub fn raw_bytes_to_numeric(vm: &Vm, element_type: ElementType, raw_value: &mut// b. If value is an IEEE 754-2019 binary64 NaN value, return the NaN Number value.if value.is_nan() {- return Value::from_f64(f64::NAN);+ return f64::NAN;}// c. Return the Number value that corresponds to value.- Value::from_f64(value)+ value}// 6. If IsUnsignedElementType(type) is true, then// a. Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of an unsigned little-endian binary number.// 7. Else,// a. Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of a binary little-endian two's complement number of bit length elementSize × 8.//- // 8. If IsBigIntElementType(type) is true, return the BigInt value that corresponds to intValue.- ElementType::BigInt64 => Value::from_bigint(BigInt::create(vm, NumBigInt::from(little_endian_value as i64))),- ElementType::BigUint64 => Value::from_bigint(BigInt::create(vm, NumBigInt::from(little_endian_value))),// 9. Otherwise, return the Number value that corresponds to intValue.- ElementType::Uint8 | ElementType::Uint8Clamped => Value::from_i32(i32::from(little_endian_value as u8)),- ElementType::Uint16 => Value::from_i32(i32::from(little_endian_value as u16)),- ElementType::Uint32 => Value::from_f64(f64::from(little_endian_value as u32)),- ElementType::Int8 => Value::from_i32(i32::from(little_endian_value as u8 as i8)),- ElementType::Int16 => Value::from_i32(i32::from(little_endian_value as u16 as i16)),- ElementType::Int32 => Value::from_i32(little_endian_value as u32 as i32),+ ElementType::Uint8 | ElementType::Uint8Clamped => f64::from(little_endian_value as u8),+ ElementType::Uint16 => f64::from(little_endian_value as u16),+ ElementType::Uint32 => f64::from(little_endian_value as u32),+ ElementType::Int8 => f64::from(little_endian_value as u8 as i8),+ ElementType::Int16 => f64::from(little_endian_value as u16 as i16),+ ElementType::Int32 => f64::from(little_endian_value as u32 as i32),+ ElementType::BigInt64 | ElementType::BigUint64 => unreachable!("BigInt elements are no Numbers"),}}@@ -1971,18 +2095,21 @@ pub fn raw_bytes_to_numeric(vm: &Vm, element_type: ElementType, raw_value: &mutpub fn numeric_to_raw_bytes(vm: &Vm, element_type: ElementType, value: Value, is_little_endian: bool) -> [u8; 8] {assert!(value.is_number() || value.is_bigint());let little_endian_bytes: u64 = match element_type {- ElementType::Float16 => u64::from(f64_to_binary16_bits(value.to_double(vm).must())),- ElementType::Float32 => u64::from((value.to_double(vm).must() as f32).to_bits()),- ElementType::Float64 => value.to_double(vm).must().to_bits(),ElementType::BigInt64 => value.to_bigint_int64(vm).must() as u64,ElementType::BigUint64 => value.to_bigint_uint64(vm).must(),- ElementType::Int32 => u64::from(value.to_i32(vm).must() as u32),- ElementType::Int16 => u64::from(value.to_i16(vm).must() as u16),- ElementType::Int8 => u64::from(value.to_i8(vm).must() as u8),- ElementType::Uint32 => u64::from(value.to_u32(vm).must()),- ElementType::Uint16 => u64::from(value.to_u16(vm).must()),- ElementType::Uint8 => u64::from(value.to_u8(vm).must()),- ElementType::Uint8Clamped => u64::from(value.to_u8_clamp(vm).must()),+ // OPTIMIZATION: ToInt8 to ToUint32 of an int32 are its low bits, and ToUint8Clamp of one is it clamped.+ ElementType::Uint8Clamped if value.is_int32() => u64::from(value.as_i32().clamp(0, 255) as u8),+ ElementType::Int8+ | ElementType::Uint8+ | ElementType::Int16+ | ElementType::Uint16+ | ElementType::Int32+ | ElementType::Uint32+ if value.is_int32() =>+ {+ u64::from(value.as_i32() as u32)+ }+ _ => number_to_element_bits(element_type, value.to_double(vm).must()),};let mut raw_bytes = little_endian_bytes.to_le_bytes();let element_size = element_type.size();diff --git a/Libraries/LibJS/Rust/src/runtime/typed_array.rs b/Libraries/LibJS/Rust/src/runtime/typed_array.rsindex a36ebf509bd..bd608e1b658 100644--- a/Libraries/LibJS/Rust/src/runtime/typed_array.rs+++ b/Libraries/LibJS/Rust/src/runtime/typed_array.rs@@ -1255,7 +1255,21 @@ fn initialize_typed_array_from_typed_array(// e. Let count be elementLength.// f. Repeat, while count > 0,- for _ in 0..element_length {+ // OPTIMIZATION: The new buffer is not shared, so a source buffer that is not shared either converts in one pass.+ let element_count = if source_data.is_shared_array_buffer() {+ element_length+ } else {+ source_data.convert_elements_to(+ &data,+ source_byte_offset as usize,+ source_array.kind().element_type(),+ 0,+ typed_array.kind().element_type(),+ element_length as usize,+ );+ 0+ };+ for _ in 0..element_count {// i. Let value be GetValueFromBuffer(srcData, srcByteIndex, srcType, true, unordered).let value = source_array.get_value_from_buffer(vm, source_byte_index as usize, Order::Unordered);diff --git a/Libraries/LibJS/Rust/src/runtime/typed_array_prototype.rs b/Libraries/LibJS/Rust/src/runtime/typed_array_prototype.rsindex dc378782190..cda4d9d577a 100644--- a/Libraries/LibJS/Rust/src/runtime/typed_array_prototype.rs+++ b/Libraries/LibJS/Rust/src/runtime/typed_array_prototype.rs@@ -435,6 +435,19 @@ fn set_typed_array_from_typed_array(}// 22. Else,else {+ // OPTIMIZATION: Buffers that are not shared convert in one pass. (Step 17 above cloned sourceBuffer if it was+ // targetBuffer, so the two are different buffers here.)+ if !source_buffer.is_shared_array_buffer() && !target_buffer.is_shared_array_buffer() {+ source_buffer.convert_elements_to(+ &target_buffer,+ source_byte_index,+ source_type,+ target_byte_index,+ target.kind().element_type(),+ source_length as usize,+ );+ target_byte_index = limit;+ }// a. Repeat, while targetByteIndex < limit,while target_byte_index < limit {// i. Let value be GetValueFromBuffer(sourceBuffer, sourceByteIndex, sourceType, true, unordered).diff --git a/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-element-conversion.js b/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-element-conversion.jsnew file mode 100644index 00000000000..a4c32a9544d--- /dev/null+++ b/Tests/LibJS/Runtime/builtins/TypedArray/typed-array-element-conversion.js@@ -0,0 +1,163 @@+const NUMBER_TYPED_ARRAYS = [+ Uint8Array,+ Uint8ClampedArray,+ Uint16Array,+ Uint32Array,+ Int8Array,+ Int16Array,+ Int32Array,+ Float16Array,+ Float32Array,+ Float64Array,+];++const NUMBERS = [+ 0,+ -0,+ 1,+ -1,+ 0.5,+ 1.5,+ 2.5,+ -2.5,+ 127,+ 128,+ 255,+ 255.5,+ 256,+ -129,+ 32767,+ 32768,+ 65535,+ 65536,+ 2 ** 31,+ -(2 ** 31),+ 2 ** 32 - 1,+ 2 ** 32,+ 1 + 2 ** -11,+ 1 + 3 * 2 ** -11,+ 65520,+ 1e300,+ -1e300,+ Infinity,+ -Infinity,+ NaN,+ 1e-8,+];++// Elements that convert through a SharedArrayBuffer take the generic element-by-element path.+function sharedCopyOf(source) {+ const copy = new source.constructor(new SharedArrayBuffer(source.byteLength));+ copy.set(source);+ return copy;+}++function expectSameElements(actual, expected) {+ expect(actual.length).toBe(expected.length);+ for (let i = 0; i < expected.length; ++i) expect(Object.is(actual[i], expected[i])).toBeTrue();+}++describe("normal behavior", () => {+ test("converting between Number element types", () => {+ for (const SourceType of NUMBER_TYPED_ARRAYS) {+ const source = new SourceType(NUMBERS);+ for (const TargetType of NUMBER_TYPED_ARRAYS) {+ const expected = new TargetType(new SharedArrayBuffer(source.length * TargetType.BYTES_PER_ELEMENT));+ expected.set(sharedCopyOf(source));++ expectSameElements(new TargetType(source), expected);++ const target = new TargetType(source.length + 2);+ target.set(source, 1);+ expect(target[0]).toBe(0);+ expectSameElements(target.subarray(1, source.length + 1), expected);+ expect(target[source.length + 1]).toBe(0);+ }+ }+ });++ test("storing int32 values", () => {+ const values = [+ 0,+ 1,+ -1,+ 127,+ 128,+ -128,+ -129,+ 255,+ 256,+ 300,+ 32767,+ 32768,+ -32769,+ 65535,+ 65536,+ 2 ** 31 - 1,+ -(2 ** 31),+ ];+ expectSameElements(new Int8Array(values), [0, 1, -1, 127, -128, -128, 127, -1, 0, 44, -1, 0, -1, -1, 0, -1, 0]);+ expectSameElements(+ new Uint8Array(values),+ [0, 1, 255, 127, 128, 128, 127, 255, 0, 44, 255, 0, 255, 255, 0, 255, 0]+ );+ expectSameElements(+ new Uint8ClampedArray(values),+ [0, 1, 0, 127, 128, 0, 0, 255, 255, 255, 255, 255, 0, 255, 255, 255, 0]+ );+ expectSameElements(+ new Int16Array(values),+ [0, 1, -1, 127, 128, -128, -129, 255, 256, 300, 32767, -32768, 32767, -1, 0, -1, 0]+ );+ expectSameElements(+ new Uint16Array(values),+ [0, 1, 65535, 127, 128, 65408, 65407, 255, 256, 300, 32767, 32768, 32767, 65535, 0, 65535, 0]+ );+ expectSameElements(new Uint32Array([-1, -(2 ** 31), 2 ** 31 - 1]), [2 ** 32 - 1, 2 ** 31, 2 ** 31 - 1]);+ expectSameElements(new Int32Array([-1, -(2 ** 31), 2 ** 31 - 1]), [-1, -(2 ** 31), 2 ** 31 - 1]);+ });++ test("Uint8Clamped rounds half to even", () => {+ const source = new Float64Array([-1, 0.5, 1.5, 2.5, 254.5, 255.5, 300, NaN]);+ expectSameElements(new Uint8ClampedArray(source), [0, 0, 2, 2, 254, 255, 255, 0]);+ });++ test("Float16 rounds to nearest, ties to even", () => {+ const source = new Float64Array([1 + 2 ** -10, 1 + 2 ** -11, 1 + 3 * 2 ** -11, 65519, 65520, 2 ** -25]);+ expectSameElements(new Float16Array(source), [1 + 2 ** -10, 1, 1 + 2 ** -9, 65504, Infinity, 0]);+ });++ test("NaN elements become the canonical NaN", () => {+ const source = new Float64Array(2);+ const sourceBits = new Uint32Array(source.buffer);+ sourceBits.set([0x1234, 0x7ff01234, 0x5678, 0xfff85678]);++ const float32 = new Float32Array(source);+ expectSameElements(new Uint32Array(float32.buffer), [0x7fc00000, 0x7fc00000]);++ const float16 = new Float16Array(2);+ float16.set(source);+ expectSameElements(new Uint16Array(float16.buffer), [0x7e00, 0x7e00]);++ const float64 = new Float64Array(new Float32Array(new Uint32Array([0xff812345]).buffer));+ expectSameElements(new Uint32Array(float64.buffer), [0, 0x7ff80000]);+ });++ test("converting between BigInt element types", () => {+ const values = [0n, 1n, -1n, 2n ** 63n - 1n, -(2n ** 63n), 12345678901234567n];+ const unsigned = new BigUint64Array(new BigInt64Array(values));+ expectSameElements(unsigned, [0n, 1n, 2n ** 64n - 1n, 2n ** 63n - 1n, 2n ** 63n, 12345678901234567n]);++ const signed = new BigInt64Array(values.length + 1);+ signed.set(unsigned, 1);+ expectSameElements(signed, [0n, ...values]);+ });++ test("converting between views of the same buffer", () => {+ const buffer = new ArrayBuffer(16);+ const bytes = new Uint8Array(buffer);+ bytes.set([1, 2, 3, 4, 5, 6, 7, 8]);+ new Uint16Array(buffer).set(bytes.subarray(0, 4));+ expectSameElements(bytes.subarray(0, 8), [1, 0, 2, 0, 3, 0, 4, 0]);+ });+});