LibJS: Fix indexed access of TypedArray with byte offset

By doing the offset calculation in {get,put}_by_index() we would
delegate these operations to Object for any index >= (array length -
byte offset). By doing the offset calculation in data() instead, we can
just use the unaltered property index for indexing the returned Span.
In other words: data()[0] now returns the same value as indexing the
TypedArray at index 0 in JS.

This also fixes a bug in the js REPL which would not consider the byte
offset and subsequently access the underlying ArrayBuffer data with a
wrong index.
This commit is contained in:
Linus Groh 2021-05-21 19:29:05 +01:00
parent 9003dd907e
commit 3a4cbbf01c
Notes: sideshowbarker 2024-07-18 17:36:56 +09:00

View File

@ -51,7 +51,6 @@ class TypedArray : public TypedArrayBase {
public:
virtual bool put_by_index(u32 property_index, Value value) override
{
property_index += m_byte_offset / sizeof(T);
if (property_index >= m_array_length)
return Base::put_by_index(property_index, value);
@ -73,7 +72,6 @@ public:
virtual Value get_by_index(u32 property_index) const override
{
property_index += m_byte_offset / sizeof(T);
if (property_index >= m_array_length)
return Base::get_by_index(property_index);
@ -98,11 +96,11 @@ public:
Span<const T> data() const
{
return { reinterpret_cast<const T*>(m_viewed_array_buffer->buffer().data()), m_array_length };
return { reinterpret_cast<const T*>(m_viewed_array_buffer->buffer().data() + m_byte_offset), m_array_length };
}
Span<T> data()
{
return { reinterpret_cast<T*>(m_viewed_array_buffer->buffer().data()), m_array_length };
return { reinterpret_cast<T*>(m_viewed_array_buffer->buffer().data() + m_byte_offset), m_array_length };
}
virtual size_t element_size() const override { return sizeof(T); };