aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLars Knoll <lars.knoll@digia.com>2014-09-11 15:37:31 +0200
committerSimon Hausmann <simon.hausmann@digia.com>2014-10-29 09:07:36 +0100
commita3a44fc16417edfe09fca757f4ab1fb8fdaff00d (patch)
treecce2b9d011b1e70736af2dab901247d9dcb2244e
parent868478e92afaa9d0823f3a65ff3d7b44216087ea (diff)
Basic support for typed arrays
This implements most of the spec required for the Khronos typed array specification. It tries to follow ECMAScript 6 as closely as possible, but currently only implements a subset of the ECMAScript 6 specification. Addes a test script in tests/manual/v4 to test our implementation. Change-Id: I8ec63869500358e088b73240e1f37120ae3cf59a Reviewed-by: Simon Hausmann <simon.hausmann@digia.com>
-rw-r--r--src/qml/jsruntime/jsruntime.pri2
-rw-r--r--src/qml/jsruntime/qv4arraybuffer.cpp2
-rw-r--r--src/qml/jsruntime/qv4engine.cpp14
-rw-r--r--src/qml/jsruntime/qv4engine_p.h3
-rw-r--r--src/qml/jsruntime/qv4managed_p.h10
-rw-r--r--src/qml/jsruntime/qv4typedarray.cpp571
-rw-r--r--src/qml/jsruntime/qv4typedarray_p.h133
-rw-r--r--tests/auto/qml/qjsengine/tst_qjsengine.cpp9
-rw-r--r--tests/manual/v4/typedarray.js13
-rw-r--r--tests/manual/v4/typedarrays.js738
10 files changed, 1490 insertions, 5 deletions
diff --git a/src/qml/jsruntime/jsruntime.pri b/src/qml/jsruntime/jsruntime.pri
index 3914537a19..ef44ca6f4d 100644
--- a/src/qml/jsruntime/jsruntime.pri
+++ b/src/qml/jsruntime/jsruntime.pri
@@ -44,6 +44,7 @@ SOURCES += \
$$PWD/qv4vme_moth.cpp \
$$PWD/qv4profiling.cpp \
$$PWD/qv4arraybuffer.cpp \
+ $$PWD/qv4typedarray.cpp \
$$PWD/qv4dataview.cpp
HEADERS += \
@@ -93,6 +94,7 @@ HEADERS += \
$$PWD/qv4vme_moth_p.h \
$$PWD/qv4profiling_p.h \
$$PWD/qv4arraybuffer_p.h \
+ $$PWD/qv4typedarray_p.h \
$$PWD/qv4dataview_p.h
}
diff --git a/src/qml/jsruntime/qv4arraybuffer.cpp b/src/qml/jsruntime/qv4arraybuffer.cpp
index 9d24044d7c..c97b16a255 100644
--- a/src/qml/jsruntime/qv4arraybuffer.cpp
+++ b/src/qml/jsruntime/qv4arraybuffer.cpp
@@ -59,6 +59,8 @@ ReturnedValue ArrayBufferCtor::construct(Managed *m, CallData *callData)
return v4->currentContext()->throwRangeError(QLatin1String("ArrayBuffer constructor: invalid length"));
Scoped<ArrayBuffer> a(scope, v4->memoryManager->alloc<ArrayBuffer>(v4, len));
+ if (scope.engine->hasException)
+ return Encode::undefined();
return a.asReturnedValue();
}
diff --git a/src/qml/jsruntime/qv4engine.cpp b/src/qml/jsruntime/qv4engine.cpp
index 454928252f..057f692bf9 100644
--- a/src/qml/jsruntime/qv4engine.cpp
+++ b/src/qml/jsruntime/qv4engine.cpp
@@ -63,6 +63,7 @@
#include "qv4memberdata_p.h"
#include "qv4arraybuffer_p.h"
#include "qv4dataview_p.h"
+#include "qv4typedarray_p.h"
#include <QtCore/QTextStream>
#include <QDateTime>
@@ -381,6 +382,13 @@ ExecutionEngine::ExecutionEngine(EvalISelFactory *factory)
dataViewPrototype->init(this, dataViewCtor.asObject());
dataViewClass = InternalClass::create(this, DataView::staticVTable(), dataViewPrototype);
+ for (int i = 0; i < TypedArray::NTypes; ++i) {
+ typedArrayCtors[i] = memoryManager->alloc<TypedArrayCtor>(rootContext, TypedArray::Type(i));
+ Scoped<TypedArrayPrototype> typedArrayPrototype(scope, memoryManager->alloc<TypedArrayPrototype>(this, TypedArray::Type(i)));
+ typedArrayPrototype->init(this, static_cast<TypedArrayCtor *>(typedArrayCtors[i].asObject()));
+ typedArrayClasses[i] = InternalClass::create(this, TypedArray::staticVTable(), typedArrayPrototype);
+ }
+
//
// set up the global object
//
@@ -404,8 +412,12 @@ ExecutionEngine::ExecutionEngine(EvalISelFactory *factory)
globalObject->defineDefaultProperty(QStringLiteral("SyntaxError"), syntaxErrorCtor);
globalObject->defineDefaultProperty(QStringLiteral("TypeError"), typeErrorCtor);
globalObject->defineDefaultProperty(QStringLiteral("URIError"), uRIErrorCtor);
+
globalObject->defineDefaultProperty(QStringLiteral("ArrayBuffer"), arrayBufferCtor);
globalObject->defineDefaultProperty(QStringLiteral("DataView"), dataViewCtor);
+ ScopedString str(scope);
+ for (int i = 0; i < TypedArray::NTypes; ++i)
+ globalObject->defineDefaultProperty((str = typedArrayCtors[i].asFunctionObject()->name())->toQString(), typedArrayCtors[i]);
ScopedObject o(scope);
globalObject->defineDefaultProperty(QStringLiteral("Math"), (o = memoryManager->alloc<MathObject>(QV4::InternalClass::create(this, MathObject::staticVTable(), objectPrototype))));
globalObject->defineDefaultProperty(QStringLiteral("JSON"), (o = memoryManager->alloc<JsonObject>(QV4::InternalClass::create(this, JsonObject::staticVTable(), objectPrototype))));
@@ -928,6 +940,8 @@ void ExecutionEngine::markObjects()
uRIErrorCtor.mark(this);
arrayBufferCtor.mark(this);
dataViewCtor.mark(this);
+ for (int i = 0; i < TypedArray::NTypes; ++i)
+ typedArrayCtors[i].mark(this);
sequencePrototype.mark(this);
exceptionValue.mark(this);
diff --git a/src/qml/jsruntime/qv4engine_p.h b/src/qml/jsruntime/qv4engine_p.h
index ba96649ab9..c77c5b1ce1 100644
--- a/src/qml/jsruntime/qv4engine_p.h
+++ b/src/qml/jsruntime/qv4engine_p.h
@@ -191,6 +191,8 @@ public:
Value sequencePrototype;
Value arrayBufferCtor;
Value dataViewCtor;
+ enum { NTypedArrayTypes = 9 }; // avoid header dependency
+ Value typedArrayCtors[NTypedArrayTypes];
InternalClassPool *classPool;
InternalClass *emptyClass;
@@ -228,6 +230,7 @@ public:
InternalClass *arrayBufferClass;
InternalClass *dataViewClass;
+ InternalClass *typedArrayClasses[NTypedArrayTypes]; // TypedArray::NValues, avoid including the header here
EvalFunction *evalFunction;
FunctionObject *thrower;
diff --git a/src/qml/jsruntime/qv4managed_p.h b/src/qml/jsruntime/qv4managed_p.h
index ce0ee973e8..636c89c5e4 100644
--- a/src/qml/jsruntime/qv4managed_p.h
+++ b/src/qml/jsruntime/qv4managed_p.h
@@ -45,7 +45,7 @@ QT_BEGIN_NAMESPACE
namespace QV4 {
#define Q_MANAGED_CHECK \
- template <typename T> inline void qt_check_for_QMANAGED_macro(const T *_q_argument) const \
+ template <typename _T> inline void qt_check_for_QMANAGED_macro(const _T *_q_argument) const \
{ int i = qYouForgotTheQ_MANAGED_Macro(this, _q_argument); i = i + 1; }
template <typename T>
@@ -66,8 +66,8 @@ inline void qYouForgotTheQ_MANAGED_Macro(T1, T2) {}
typedef superClass SuperClass; \
static const QV4::ManagedVTable static_vtbl; \
static inline const QV4::ManagedVTable *staticVTable() { return &static_vtbl; } \
- template <typename T> \
- QV4::Returned<T> *asReturned() { return QV4::Returned<T>::create(this); } \
+ template <typename _T> \
+ QV4::Returned<_T> *asReturned() { return QV4::Returned<_T>::create(this); } \
V4_MANAGED_SIZE_TEST \
const Data *d() const { return &static_cast<const Data &>(Managed::data); } \
Data *d() { return &static_cast<Data &>(Managed::data); }
@@ -78,8 +78,8 @@ inline void qYouForgotTheQ_MANAGED_Macro(T1, T2) {}
typedef superClass SuperClass; \
static const QV4::ObjectVTable static_vtbl; \
static inline const QV4::ManagedVTable *staticVTable() { return &static_vtbl.managedVTable; } \
- template <typename T> \
- QV4::Returned<T> *asReturned() { return QV4::Returned<T>::create(this); } \
+ template <typename _T> \
+ QV4::Returned<_T> *asReturned() { return QV4::Returned<_T>::create(this); } \
V4_MANAGED_SIZE_TEST \
const Data *d() const { return &static_cast<const Data &>(Managed::data); } \
Data *d() { return &static_cast<Data &>(Managed::data); }
diff --git a/src/qml/jsruntime/qv4typedarray.cpp b/src/qml/jsruntime/qv4typedarray.cpp
new file mode 100644
index 0000000000..08d272862b
--- /dev/null
+++ b/src/qml/jsruntime/qv4typedarray.cpp
@@ -0,0 +1,571 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtQml module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+#include "qv4typedarray_p.h"
+#include "qv4arraybuffer_p.h"
+
+using namespace QV4;
+
+DEFINE_OBJECT_VTABLE(TypedArrayCtor);
+DEFINE_OBJECT_VTABLE(TypedArrayPrototype);
+DEFINE_OBJECT_VTABLE(TypedArray);
+
+Q_STATIC_ASSERT((int)ExecutionEngine::NTypedArrayTypes == (int)TypedArray::NTypes);
+
+ReturnedValue Int8ArrayRead(const char *data, int index)
+{
+ return Encode((int)(signed char)data[index]);
+}
+
+void Int8ArrayWrite(ExecutionEngine *e, char *data, int index, ValueRef value)
+{
+ signed char v = (signed char)value->toUInt32();
+ if (e->hasException)
+ return;
+ data[index] = v;
+}
+
+ReturnedValue UInt8ArrayRead(const char *data, int index)
+{
+ return Encode((int)(unsigned char)data[index]);
+}
+
+void UInt8ArrayWrite(ExecutionEngine *e, char *data, int index, ValueRef value)
+{
+ unsigned char v = (unsigned char)value->toUInt32();
+ if (e->hasException)
+ return;
+ data[index] = v;
+}
+
+void UInt8ClampedArrayWrite(ExecutionEngine *e, char *data, int index, ValueRef value)
+{
+ if (value->isInteger()) {
+ data[index] = (char)(unsigned char)qBound(0, value->integerValue(), 255);
+ return;
+ }
+ double d = value->toNumber();
+ if (e->hasException)
+ return;
+ // ### is there a way to optimise this?
+ if (d <= 0 || std::isnan(d)) {
+ data[index] = 0;
+ return;
+ }
+ if (d >= 255) {
+ data[index] = 255;
+ return;
+ }
+ double f = floor(d);
+ if (f + 0.5 < d) {
+ data[index] = (unsigned char)(f + 1);
+ return;
+ }
+ if (d < f + 0.5) {
+ data[index] = (unsigned char)(f);
+ return;
+ }
+ if (int(f) % 2) {
+ // odd number
+ data[index] = (unsigned char)(f + 1);
+ return;
+ }
+ data[index] = (unsigned char)(f);
+}
+
+ReturnedValue Int16ArrayRead(const char *data, int index)
+{
+ return Encode((int)*(short *)(data + index));
+}
+
+void Int16ArrayWrite(ExecutionEngine *e, char *data, int index, ValueRef value)
+{
+ short v = (short)value->toInt32();
+ if (e->hasException)
+ return;
+ *(short *)(data + index) = v;
+}
+
+ReturnedValue UInt16ArrayRead(const char *data, int index)
+{
+ return Encode((int)*(unsigned short *)(data + index));
+}
+
+void UInt16ArrayWrite(ExecutionEngine *e, char *data, int index, ValueRef value)
+{
+ unsigned short v = (unsigned short)value->toInt32();
+ if (e->hasException)
+ return;
+ *(unsigned short *)(data + index) = v;
+}
+
+ReturnedValue Int32ArrayRead(const char *data, int index)
+{
+ return Encode(*(int *)(data + index));
+}
+
+void Int32ArrayWrite(ExecutionEngine *e, char *data, int index, ValueRef value)
+{
+ int v = (int)value->toInt32();
+ if (e->hasException)
+ return;
+ *(int *)(data + index) = v;
+}
+
+ReturnedValue UInt32ArrayRead(const char *data, int index)
+{
+ return Encode(*(unsigned int *)(data + index));
+}
+
+void UInt32ArrayWrite(ExecutionEngine *e, char *data, int index, ValueRef value)
+{
+ unsigned int v = (unsigned int)value->toUInt32();
+ if (e->hasException)
+ return;
+ *(unsigned int *)(data + index) = v;
+}
+
+ReturnedValue Float32ArrayRead(const char *data, int index)
+{
+ return Encode(*(float *)(data + index));
+}
+
+void Float32ArrayWrite(ExecutionEngine *e, char *data, int index, ValueRef value)
+{
+ float v = value->toNumber();
+ if (e->hasException)
+ return;
+ *(float *)(data + index) = v;
+}
+
+ReturnedValue Float64ArrayRead(const char *data, int index)
+{
+ return Encode(*(double *)(data + index));
+}
+
+void Float64ArrayWrite(ExecutionEngine *e, char *data, int index, ValueRef value)
+{
+ double v = value->toNumber();
+ if (e->hasException)
+ return;
+ *(double *)(data + index) = v;
+}
+
+const TypedArrayOperations operations[TypedArray::NTypes] = {
+ { 1, "Int8Array", Int8ArrayRead, Int8ArrayWrite },
+ { 1, "Uint8Array", UInt8ArrayRead, UInt8ArrayWrite },
+ { 1, "Uint8ClampedArray", UInt8ArrayRead, UInt8ClampedArrayWrite },
+ { 2, "Int16Array", Int16ArrayRead, Int16ArrayWrite },
+ { 2, "Uint16Array", UInt16ArrayRead, UInt16ArrayWrite },
+ { 4, "Int32Array", Int32ArrayRead, Int32ArrayWrite },
+ { 4, "Uint32Array", UInt32ArrayRead, UInt32ArrayWrite },
+ { 4, "Float32Array", Float32ArrayRead, Float32ArrayWrite },
+ { 8, "Float64Array", Float64ArrayRead, Float64ArrayWrite },
+};
+
+
+TypedArrayCtor::Data::Data(ExecutionContext *scope, TypedArray::Type t)
+ : FunctionObject::Data(scope, QLatin1String(operations[t].name))
+ , type(t)
+{
+ setVTable(staticVTable());
+}
+
+ReturnedValue TypedArrayCtor::construct(Managed *m, CallData *callData)
+{
+ Scope scope(m->engine());
+ Scoped<TypedArrayCtor> that(scope, static_cast<TypedArrayCtor *>(m));
+
+ if (!callData->argc || !callData->args[0].isObject()) {
+ // ECMA 6 22.2.1.1
+ double l = callData->argc ? callData->args[0].toNumber() : 0;
+ if (scope.engine->hasException)
+ return Encode::undefined();
+ uint len = (uint)l;
+ if (l != len)
+ scope.engine->currentContext()->throwRangeError(QStringLiteral("Non integer length for typed array."));
+ uint byteLength = len * operations[that->d()->type].bytesPerElement;
+ Scoped<ArrayBuffer> buffer(scope, scope.engine->memoryManager->alloc<ArrayBuffer>(scope.engine, byteLength));
+ if (scope.engine->hasException)
+ return Encode::undefined();
+
+ Scoped<TypedArray > array(scope, scope.engine->memoryManager->alloc<TypedArray>(scope.engine, that->d()->type));
+ array->d()->buffer = buffer;
+ array->d()->byteLength = byteLength;
+ array->d()->byteOffset = 0;
+
+ return array.asReturnedValue();
+ }
+ Scoped<TypedArray> typedArray(scope, callData->argument(0));
+ if (!!typedArray) {
+ // ECMA 6 22.2.1.2
+ Scoped<ArrayBuffer> buffer(scope, typedArray->d()->buffer);
+ uint srcElementSize = typedArray->d()->type->bytesPerElement;
+ uint destElementSize = operations[that->d()->type].bytesPerElement;
+ uint byteLength = typedArray->d()->byteLength;
+ uint destByteLength = byteLength*destElementSize/srcElementSize;
+
+ Scoped<ArrayBuffer> newBuffer(scope, scope.engine->memoryManager->alloc<ArrayBuffer>(scope.engine, destByteLength));
+ if (scope.engine->hasException)
+ return Encode::undefined();
+
+ Scoped<TypedArray > array(scope, scope.engine->memoryManager->alloc<TypedArray>(scope.engine, that->d()->type));
+ array->d()->buffer = newBuffer;
+ array->d()->byteLength = destByteLength;
+ array->d()->byteOffset = 0;
+
+ const char *src = buffer->d()->data->data() + typedArray->d()->byteOffset;
+ char *dest = newBuffer->d()->data->data();
+
+ // check if src and new type have the same size. In that case we can simply memcpy the data
+ if (srcElementSize == destElementSize) {
+ memcpy(dest, src, byteLength);
+ } else {
+ // not same size, we need to loop
+ uint l = typedArray->length();
+ TypedArrayRead read = typedArray->d()->type->read;
+ TypedArrayWrite write =array->d()->type->write;
+ for (uint i = 0; i < l; ++i) {
+ Primitive val;
+ val.val = read(src, i*srcElementSize);
+ write(scope.engine, dest, i*destElementSize, val);
+ }
+ }
+
+ return array.asReturnedValue();
+ }
+ Scoped<ArrayBuffer> buffer(scope, callData->argument(0));
+ if (!!buffer) {
+ // ECMA 6 22.2.1.4
+
+ double dbyteOffset = callData->argc > 1 ? callData->args[1].toInteger() : 0;
+ uint byteOffset = (uint)dbyteOffset;
+ uint elementSize = operations[that->d()->type].bytesPerElement;
+ if (dbyteOffset < 0 || (byteOffset % elementSize) || dbyteOffset > buffer->byteLength())
+ return scope.engine->currentContext()->throwRangeError(QStringLiteral("new TypedArray: invalid byteOffset"));
+
+ uint byteLength;
+ if (callData->argc < 3 || callData->args[2].isUndefined()) {
+ byteLength = buffer->byteLength() - byteOffset;
+ if (buffer->byteLength() < byteOffset || byteLength % elementSize)
+ return scope.engine->currentContext()->throwRangeError(QStringLiteral("new TypedArray: invalid length"));
+ } else {
+ double l = qBound(0., callData->args[2].toInteger(), (double)UINT_MAX);
+ if (scope.engine->hasException)
+ return Encode::undefined();
+ l *= elementSize;
+ if (buffer->byteLength() - byteOffset < l)
+ return scope.engine->currentContext()->throwRangeError(QStringLiteral("new TypedArray: invalid length"));
+ byteLength = (uint)l;
+ }
+
+ Scoped<TypedArray > array(scope, scope.engine->memoryManager->alloc<TypedArray>(scope.engine, that->d()->type));
+ array->d()->buffer = buffer;
+ array->d()->byteLength = byteLength;
+ array->d()->byteOffset = byteOffset;
+ return array.asReturnedValue();
+ }
+
+ // ECMA 6 22.2.1.3
+
+ ScopedObject o(scope, callData->argument(0));
+ uint l = (uint) qBound(0., ScopedValue(scope, o->get(scope.engine->id_length))->toInteger(), (double)UINT_MAX);
+ if (scope.engine->hasException)
+ return scope.engine->currentContext()->throwTypeError();
+
+ uint elementSize = operations[that->d()->type].bytesPerElement;
+ Scoped<ArrayBuffer> newBuffer(scope, scope.engine->memoryManager->alloc<ArrayBuffer>(scope.engine, l * elementSize));
+ if (scope.engine->hasException)
+ return Encode::undefined();
+
+ Scoped<TypedArray > array(scope, scope.engine->memoryManager->alloc<TypedArray>(scope.engine, that->d()->type));
+ array->d()->buffer = newBuffer;
+ array->d()->byteLength = l * elementSize;
+ array->d()->byteOffset = 0;
+
+ uint idx = 0;
+ char *b = newBuffer->d()->data->data();
+ ScopedValue val(scope);
+ while (idx < l) {
+ val = o->getIndexed(idx);
+ array->d()->type->write(scope.engine, b, 0, val);
+ if (scope.engine->hasException)
+ return Encode::undefined();
+ ++idx;
+ b += elementSize;
+ }
+
+
+ return array.asReturnedValue();
+}
+
+ReturnedValue TypedArrayCtor::call(Managed *that, CallData *callData)
+{
+ return construct(that, callData);
+}
+
+TypedArray::Data::Data(ExecutionEngine *e, Type t)
+ : Object::Data(e->typedArrayClasses[t]),
+ type(operations + t)
+{
+}
+
+void TypedArray::markObjects(Managed *that, ExecutionEngine *e)
+{
+ static_cast<TypedArray *>(that)->d()->buffer->mark(e);
+}
+
+ReturnedValue TypedArray::getIndexed(Managed *m, uint index, bool *hasProperty)
+{
+ Scope scope(m->engine());
+ Scoped<TypedArray> a(scope, static_cast<TypedArray *>(m));
+
+ uint bytesPerElement = a->d()->type->bytesPerElement;
+ uint byteOffset = a->d()->byteOffset + index * bytesPerElement;
+ if (byteOffset + bytesPerElement > (uint)a->d()->buffer->byteLength()) {
+ if (hasProperty)
+ *hasProperty = false;
+ return Encode::undefined();
+ }
+ if (hasProperty)
+ *hasProperty = true;
+ return a->d()->type->read(a->d()->buffer->d()->data->data(), byteOffset);
+}
+
+void TypedArray::putIndexed(Managed *m, uint index, const ValueRef value)
+{
+ if (m->engine()->hasException)
+ return;
+
+ Scope scope(m->engine());
+ Scoped<TypedArray> a(scope, static_cast<TypedArray *>(m));
+
+ uint bytesPerElement = a->d()->type->bytesPerElement;
+ uint byteOffset = a->d()->byteOffset + index * bytesPerElement;
+ if (byteOffset + bytesPerElement > (uint)a->d()->buffer->byteLength())
+ goto reject;
+
+ a->d()->type->write(scope.engine, a->d()->buffer->d()->data->data(), byteOffset, value);
+ return;
+
+reject:
+ if (scope.engine->currentContext()->d()->strictMode)
+ scope.engine->currentContext()->throwTypeError();
+}
+
+void TypedArrayPrototype::init(ExecutionEngine *engine, TypedArrayCtor *ctor)
+{
+ Scope scope(engine);
+ ScopedObject o(scope);
+ ctor->defineReadonlyProperty(engine->id_length, Primitive::fromInt32(3));
+ ctor->defineReadonlyProperty(engine->id_prototype, (o = this));
+ ctor->defineReadonlyProperty(QStringLiteral("BYTES_PER_ELEMENT"), Primitive::fromInt32(operations[ctor->d()->type].bytesPerElement));
+ defineDefaultProperty(engine->id_constructor, (o = ctor));
+ defineAccessorProperty(QStringLiteral("buffer"), method_get_buffer, 0);
+ defineAccessorProperty(QStringLiteral("byteLength"), method_get_byteLength, 0);
+ defineAccessorProperty(QStringLiteral("byteOffset"), method_get_byteOffset, 0);
+ defineAccessorProperty(QStringLiteral("length"), method_get_length, 0);
+ defineReadonlyProperty(QStringLiteral("BYTES_PER_ELEMENT"), Primitive::fromInt32(operations[ctor->d()->type].bytesPerElement));
+
+ defineDefaultProperty(QStringLiteral("set"), method_set, 1);
+ defineDefaultProperty(QStringLiteral("subarray"), method_subarray, 0);
+}
+
+ReturnedValue TypedArrayPrototype::method_get_buffer(CallContext *ctx)
+{
+ Scope scope(ctx);
+ Scoped<TypedArray> v(scope, ctx->d()->callData->thisObject);
+ if (!v)
+ return ctx->throwTypeError();
+
+ return Encode(v->d()->buffer->asReturnedValue());
+}
+
+ReturnedValue TypedArrayPrototype::method_get_byteLength(CallContext *ctx)
+{
+ Scope scope(ctx);
+ Scoped<TypedArray> v(scope, ctx->d()->callData->thisObject);
+ if (!v)
+ return ctx->throwTypeError();
+
+ return Encode(v->d()->byteLength);
+}
+
+ReturnedValue TypedArrayPrototype::method_get_byteOffset(CallContext *ctx)
+{
+ Scope scope(ctx);
+ Scoped<TypedArray> v(scope, ctx->d()->callData->thisObject);
+ if (!v)
+ return ctx->throwTypeError();
+
+ return Encode(v->d()->byteOffset);
+}
+
+ReturnedValue TypedArrayPrototype::method_get_length(CallContext *ctx)
+{
+ Scope scope(ctx);
+ Scoped<TypedArray> v(scope, ctx->d()->callData->thisObject);
+ if (!v)
+ return ctx->throwTypeError();
+
+ return Encode(v->d()->byteLength/v->d()->type->bytesPerElement);
+}
+
+ReturnedValue TypedArrayPrototype::method_set(CallContext *ctx)
+{
+ Scope scope(ctx);
+ Scoped<TypedArray> a(scope, ctx->d()->callData->thisObject);
+ if (!a)
+ return ctx->throwTypeError();
+ Scoped<ArrayBuffer> buffer(scope, a->d()->buffer);
+ if (!buffer)
+ ctx->throwTypeError();
+
+ double doffset = ctx->d()->callData->argc >= 2 ? ctx->d()->callData->args[1].toInteger() : 0;
+ if (scope.engine->hasException)
+ return Encode::undefined();
+
+ if (doffset < 0 || doffset >= UINT_MAX)
+ return ctx->throwRangeError(QStringLiteral("TypedArray.set: out of range"));
+ uint offset = (uint)doffset;
+ uint elementSize = a->d()->type->bytesPerElement;
+
+ Scoped<TypedArray> srcTypedArray(scope, ctx->d()->callData->args[0]);
+ if (!srcTypedArray) {
+ // src is a regular object
+ ScopedObject o(scope, ctx->d()->callData->args[0].toObject(ctx));
+ if (scope.engine->hasException || !o)
+ return ctx->throwTypeError();
+
+ double len = ScopedValue(scope, o->get(scope.engine->id_length))->toNumber();
+ uint l = (uint)len;
+ if (scope.engine->hasException || l != len)
+ return ctx->throwTypeError();
+
+ if (offset + l > a->length())
+ return ctx->throwRangeError(QStringLiteral("TypedArray.set: out of range"));
+
+ uint idx = 0;
+ char *b = buffer->d()->data->data() + a->d()->byteOffset + offset*elementSize;
+ ScopedValue val(scope);
+ while (idx < l) {
+ val = o->getIndexed(idx);
+ a->d()->type->write(scope.engine, b, 0, val);
+ if (scope.engine->hasException)
+ return Encode::undefined();
+ ++idx;
+ b += elementSize;
+ }
+ return Encode::undefined();
+ }
+
+ // src is a typed array
+ Scoped<ArrayBuffer> srcBuffer(scope, srcTypedArray->d()->buffer);
+ if (!srcBuffer)
+ return ctx->throwTypeError();
+
+ uint l = srcTypedArray->length();
+ if (offset + l > a->length())
+ return ctx->throwRangeError(QStringLiteral("TypedArray.set: out of range"));
+
+ char *dest = buffer->d()->data->data() + a->d()->byteOffset + offset*elementSize;
+ const char *src = srcBuffer->d()->data->data() + srcTypedArray->d()->byteOffset;
+ if (srcTypedArray->d()->type == a->d()->type) {
+ // same type of typed arrays, use memmove (as srcbuffer and buffer could be the same)
+ memmove(dest, src, srcTypedArray->d()->byteLength);
+ return Encode::undefined();
+ }
+
+ char *srcCopy = 0;
+ if (buffer->d() == srcBuffer->d()) {
+ // same buffer, need to take a temporary copy, to not run into problems
+ srcCopy = new char[srcTypedArray->d()->byteLength];
+ memcpy(srcCopy, src, srcTypedArray->d()->byteLength);
+ src = srcCopy;
+ }
+
+ // typed arrays of different kind, need to manually loop
+ uint srcElementSize = srcTypedArray->d()->type->bytesPerElement;
+ TypedArrayRead read = srcTypedArray->d()->type->read;
+ TypedArrayWrite write = a->d()->type->write;
+ for (uint i = 0; i < l; ++i) {
+ Primitive val;
+ val.val = read(src, i*srcElementSize);
+ write(scope.engine, dest, i*elementSize, val);
+ }
+
+ if (srcCopy)
+ delete [] srcCopy;
+
+ return Encode::undefined();
+}
+
+ReturnedValue TypedArrayPrototype::method_subarray(CallContext *ctx)
+{
+ Scope scope(ctx);
+ Scoped<TypedArray> a(scope, ctx->d()->callData->thisObject);
+
+ if (!a)
+ return ctx->throwTypeError();
+
+ Scoped<ArrayBuffer> buffer(scope, a->d()->buffer);
+ if (!buffer)
+ return ctx->throwTypeError();
+
+ int len = a->length();
+ double b = ctx->d()->callData->argc > 0 ? ctx->d()->callData->args[0].toInteger() : 0;
+ if (b < 0)
+ b = len + b;
+ uint begin = (uint)qBound(0., b, (double)len);
+
+ double e = ctx->d()->callData->argc < 2 || ctx->d()->callData->args[1].isUndefined() ? len : ctx->d()->callData->args[1].toInteger();
+ if (e < 0)
+ e = len + e;
+ uint end = (uint)qBound(0., e, (double)len);
+ if (end < begin)
+ end = begin;
+
+ if (scope.engine->hasException)
+ return Encode::undefined();
+
+ int newLen = end - begin;
+
+ Scoped<FunctionObject> constructor(scope, a->get(scope.engine->id_constructor));
+ if (!constructor)
+ return ctx->throwTypeError();
+
+ ScopedCallData callData(scope, 3);
+ callData->args[0] = buffer;
+ callData->args[1] = Encode(a->d()->byteOffset + begin*a->d()->type->bytesPerElement);
+ callData->args[2] = Encode(newLen);
+ return constructor->construct(callData);
+}
diff --git a/src/qml/jsruntime/qv4typedarray_p.h b/src/qml/jsruntime/qv4typedarray_p.h
new file mode 100644
index 0000000000..deafb0eed8
--- /dev/null
+++ b/src/qml/jsruntime/qv4typedarray_p.h
@@ -0,0 +1,133 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtQml module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+#ifndef QV4TYPEDARRAY_H
+#define QV4TYPEDARRAY_H
+
+#include "qv4object_p.h"
+#include "qv4functionobject_p.h"
+
+QT_BEGIN_NAMESPACE
+
+namespace QV4 {
+
+struct ArrayBuffer;
+
+typedef ReturnedValue (*TypedArrayRead)(const char *data, int index);
+typedef void (*TypedArrayWrite)(ExecutionEngine *engine, char *data, int index, ValueRef value);
+
+struct TypedArrayOperations {
+ int bytesPerElement;
+ const char *name;
+ TypedArrayRead read;
+ TypedArrayWrite write;
+};
+
+struct TypedArray : Object
+{
+ enum Type {
+ Int8Array,
+ UInt8Array,
+ UInt8ClampedArray,
+ Int16Array,
+ UInt16Array,
+ Int32Array,
+ UInt32Array,
+ Float32Array,
+ Float64Array,
+ NTypes
+ };
+
+ struct Data : Object::Data {
+ Data(ExecutionEngine *e, Type t);
+
+ const TypedArrayOperations *type;
+ ArrayBuffer *buffer;
+ uint byteLength;
+ uint byteOffset;
+ };
+ V4_OBJECT(Object)
+
+ uint length() const {
+ return d()->byteLength/d()->type->bytesPerElement;
+ }
+
+
+ static void markObjects(Managed *that, ExecutionEngine *e);
+ static ReturnedValue getIndexed(Managed *m, uint index, bool *hasProperty);
+ static void putIndexed(Managed *m, uint index, const ValueRef value);
+};
+
+struct TypedArrayCtor: FunctionObject
+{
+ struct Data : FunctionObject::Data {
+ Data(ExecutionContext *scope, TypedArray::Type t);
+
+ TypedArray::Type type;
+ };
+
+ V4_OBJECT(FunctionObject)
+
+ static ReturnedValue construct(Managed *m, CallData *callData);
+ static ReturnedValue call(Managed *that, CallData *callData);
+};
+
+
+struct TypedArrayPrototype : Object
+{
+ struct Data : Object::Data {
+ Data(ExecutionEngine *e, TypedArray::Type t)
+ : Object::Data(e)
+ , type(t)
+ {
+ setVTable(staticVTable());
+ }
+ TypedArray::Type type;
+ };
+ V4_OBJECT(Object)
+
+ void init(ExecutionEngine *engine, TypedArrayCtor *ctor);
+
+ static ReturnedValue method_get_buffer(CallContext *ctx);
+ static ReturnedValue method_get_byteLength(CallContext *ctx);
+ static ReturnedValue method_get_byteOffset(CallContext *ctx);
+ static ReturnedValue method_get_length(CallContext *ctx);
+
+ static ReturnedValue method_set(CallContext *ctx);
+ static ReturnedValue method_subarray(CallContext *ctx);
+};
+
+} // namespace QV4
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/tests/auto/qml/qjsengine/tst_qjsengine.cpp b/tests/auto/qml/qjsengine/tst_qjsengine.cpp
index 74104169ed..2e7fe34796 100644
--- a/tests/auto/qml/qjsengine/tst_qjsengine.cpp
+++ b/tests/auto/qml/qjsengine/tst_qjsengine.cpp
@@ -805,6 +805,15 @@ void tst_QJSEngine::globalObjectProperties_enumerate()
<< "JSON"
<< "ArrayBuffer"
<< "DataView"
+ << "Int8Array"
+ << "Uint8Array"
+ << "Uint8ClampedArray"
+ << "Int16Array"
+ << "Uint16Array"
+ << "Int32Array"
+ << "Uint32Array"
+ << "Float32Array"
+ << "Float64Array"
;
QSet<QString> actualNames;
{
diff --git a/tests/manual/v4/typedarray.js b/tests/manual/v4/typedarray.js
new file mode 100644
index 0000000000..3a18531af8
--- /dev/null
+++ b/tests/manual/v4/typedarray.js
@@ -0,0 +1,13 @@
+var y = new Float32Array(3);
+y.set([1.3, 2.1, 3.5]);
+x = new Uint8ClampedArray(256);
+x.set([-3, 2.5, 3.5, 256]);
+x.set(y, 5);
+print(x.length, x.byteLength, x[0], x[1], x[2], x[3], x[5], x[6], x[7])
+x = new Int16Array(x);
+print(x.length, x.byteLength, x[0], x[1], x[2], x[3], x[5], x[6], x[7])
+x = x.subarray(1, 2);
+print(x)
+print(x.length, x.byteLength, x.byteOffset, x[0], x[1])//, x[2], x[3], x[5], x[6], x[7])
+x = new Int8Array([-1, 0, 3, 127, 255]);
+print(x.length, x.byteLength, x.byteOffset, x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7])
diff --git a/tests/manual/v4/typedarrays.js b/tests/manual/v4/typedarrays.js
new file mode 100644
index 0000000000..d7a863e573
--- /dev/null
+++ b/tests/manual/v4/typedarrays.js
@@ -0,0 +1,738 @@
+// Copyright 2013 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// ArrayBuffer
+
+function assertThrows(func, type) {
+ var ok = false;
+ try {
+ func()
+ } catch (e) {
+ if (type !== undefined)
+ ok = (typeof(e) == typeof(new type()))
+ else
+ ok = true
+ }
+ if (!ok)
+ throw "assertThrows failed"
+}
+
+function assertSame(a, b) {
+ if (a !== b)
+ throw "assertSame failed:" + a + "!==" + b
+}
+
+function assertTrue(b) {
+ if (!b)
+ throw "assertTrue failed:" + b
+}
+
+function assertEquals(a, b) {
+ if (isNaN(a) && isNaN(b))
+ return
+ if (a !== b)
+ throw "assertEquals failed:" + a + "!==" + b
+}
+
+function assertArrayEquals(a, b)
+{
+ if (a.length != b.length)
+ throw "assertArrayEquals failed:" + a + "!=" + b
+ var i;
+ for (i = 0; i < a.length; ++i)
+ assertEquals(a[i], b[i])
+}
+
+function TestByteLength(param, expectedByteLength) {
+ var ab = new ArrayBuffer(param);
+ assertSame(expectedByteLength, ab.byteLength);
+}
+
+function TestArrayBufferCreation() {
+ TestByteLength(1, 1);
+ TestByteLength(256, 256);
+ TestByteLength(2.567, 2);
+
+ TestByteLength("abc", 0);
+
+ TestByteLength(0, 0);
+
+ assertThrows(function() { new ArrayBuffer(-10); }, RangeError);
+ assertThrows(function() { new ArrayBuffer(-2.567); }, RangeError);
+
+/* TODO[dslomov]: Reenable the test
+ assertThrows(function() {
+ var ab1 = new ArrayBuffer(0xFFFFFFFFFFFF)
+ }, RangeError);
+*/
+
+ var ab = new ArrayBuffer();
+ assertSame(0, ab.byteLength);
+}
+
+TestArrayBufferCreation();
+
+function TestByteLengthNotWritable() {
+ var ab = new ArrayBuffer(1024);
+ assertSame(1024, ab.byteLength);
+
+ assertThrows(function() { "use strict"; ab.byteLength = 42; }, TypeError);
+}
+
+TestByteLengthNotWritable();
+
+function TestSlice(expectedResultLen, initialLen, start, end) {
+ var ab = new ArrayBuffer(initialLen);
+ var a1 = new Uint8Array(ab);
+ for (var i = 0; i < a1.length; i++) {
+ a1[i] = 0xCA;
+ }
+ var slice = ab.slice(start, end);
+ assertSame(expectedResultLen, slice.byteLength);
+ var a2 = new Uint8Array(slice);
+ for (var i = 0; i < a2.length; i++) {
+ assertSame(0xCA, a2[i]);
+ }
+}
+
+function TestArrayBufferSlice() {
+ var ab = new ArrayBuffer(1024);
+ var ab1 = ab.slice(512, 1024);
+ assertSame(512, ab1.byteLength);
+
+ TestSlice(512, 1024, 512, 1024);
+ TestSlice(512, 1024, 512);
+
+ TestSlice(0, 0, 1, 20);
+ TestSlice(100, 100, 0, 100);
+ TestSlice(100, 100, 0, 1000);
+
+ TestSlice(0, 100, 5, 1);
+
+ TestSlice(1, 100, -11, -10);
+ TestSlice(9, 100, -10, 99);
+ TestSlice(0, 100, -10, 80);
+ TestSlice(10, 100, 80, -10);
+
+ TestSlice(10, 100, 90, "100");
+ TestSlice(10, 100, "90", "100");
+
+ TestSlice(0, 100, 90, "abc");
+ TestSlice(10, 100, "abc", 10);
+
+ TestSlice(10, 100, 0.96, 10.96);
+ TestSlice(10, 100, 0.96, 10.01);
+ TestSlice(10, 100, 0.01, 10.01);
+ TestSlice(10, 100, 0.01, 10.96);
+
+ TestSlice(10, 100, 90);
+ TestSlice(10, 100, -10);
+}
+
+TestArrayBufferSlice();
+
+// Typed arrays
+
+function TestTypedArray(constr, elementSize, typicalElement) {
+ assertSame(elementSize, constr.BYTES_PER_ELEMENT);
+
+ var ab = new ArrayBuffer(256*elementSize);
+
+ var a0 = new constr(30);
+ assertTrue(ArrayBuffer.isView(a0));
+ assertSame(elementSize, a0.BYTES_PER_ELEMENT);
+ assertSame(30, a0.length);
+ assertSame(30*elementSize, a0.byteLength);
+ assertSame(0, a0.byteOffset);
+ assertSame(30*elementSize, a0.buffer.byteLength);
+
+ var aLen0 = new constr(0);
+ assertSame(elementSize, aLen0.BYTES_PER_ELEMENT);
+ assertSame(0, aLen0.length);
+ assertSame(0, aLen0.byteLength);
+ assertSame(0, aLen0.byteOffset);
+ assertSame(0, aLen0.buffer.byteLength);
+
+ var aOverBufferLen0 = new constr(ab, 128*elementSize, 0);
+ assertSame(ab, aOverBufferLen0.buffer);
+ assertSame(elementSize, aOverBufferLen0.BYTES_PER_ELEMENT);
+ assertSame(0, aOverBufferLen0.length);
+ assertSame(0, aOverBufferLen0.byteLength);
+ assertSame(128*elementSize, aOverBufferLen0.byteOffset);
+
+ var a1 = new constr(ab, 128*elementSize, 128);
+ assertSame(ab, a1.buffer);
+ assertSame(elementSize, a1.BYTES_PER_ELEMENT);
+ assertSame(128, a1.length);
+ assertSame(128*elementSize, a1.byteLength);
+ assertSame(128*elementSize, a1.byteOffset);
+
+
+ var a2 = new constr(ab, 64*elementSize, 128);
+ assertSame(ab, a2.buffer);
+ assertSame(elementSize, a2.BYTES_PER_ELEMENT);
+ assertSame(128, a2.length);
+ assertSame(128*elementSize, a2.byteLength);
+ assertSame(64*elementSize, a2.byteOffset);
+
+ var a3 = new constr(ab, 192*elementSize);
+ assertSame(ab, a3.buffer);
+ assertSame(64, a3.length);
+ assertSame(64*elementSize, a3.byteLength);
+ assertSame(192*elementSize, a3.byteOffset);
+
+ var a4 = new constr(ab);
+ assertSame(ab, a4.buffer);
+ assertSame(256, a4.length);
+ assertSame(256*elementSize, a4.byteLength);
+ assertSame(0, a4.byteOffset);
+
+
+ var i;
+ for (i = 0; i < 128; i++) {
+ a1[i] = typicalElement;
+ }
+
+ for (i = 0; i < 128; i++) {
+ assertSame(typicalElement, a1[i]);
+ }
+
+ for (i = 0; i < 64; i++) {
+ assertSame(0, a2[i]);
+ }
+
+ for (i = 64; i < 128; i++) {
+ assertSame(typicalElement, a2[i]);
+ }
+
+ for (i = 0; i < 64; i++) {
+ assertSame(typicalElement, a3[i]);
+ }
+
+ for (i = 0; i < 128; i++) {
+ assertSame(0, a4[i]);
+ }
+
+ for (i = 128; i < 256; i++) {
+ assertSame(typicalElement, a4[i]);
+ }
+
+ var aAtTheEnd = new constr(ab, 256*elementSize);
+ assertSame(elementSize, aAtTheEnd.BYTES_PER_ELEMENT);
+ assertSame(0, aAtTheEnd.length);
+ assertSame(0, aAtTheEnd.byteLength);
+ assertSame(256*elementSize, aAtTheEnd.byteOffset);
+
+ assertThrows(function () { new constr(ab, 257*elementSize); }, RangeError);
+ assertThrows(
+ function () { new constr(ab, 128*elementSize, 192); },
+ RangeError);
+
+ if (elementSize !== 1) {
+ assertThrows(function() { new constr(ab, 128*elementSize - 1, 10); },
+ RangeError);
+ var unalignedArrayBuffer = new ArrayBuffer(10*elementSize + 1);
+ var goodArray = new constr(unalignedArrayBuffer, 0, 10);
+ assertSame(10, goodArray.length);
+ assertSame(10*elementSize, goodArray.byteLength);
+ assertThrows(function() { new constr(unalignedArrayBuffer)}, RangeError);
+ assertThrows(function() { new constr(unalignedArrayBuffer, 5*elementSize)},
+ RangeError);
+ }
+
+ var aFromString = new constr("30");
+ assertSame(elementSize, aFromString.BYTES_PER_ELEMENT);
+ assertSame(30, aFromString.length);
+ assertSame(30*elementSize, aFromString.byteLength);
+ assertSame(0, aFromString.byteOffset);
+ assertSame(30*elementSize, aFromString.buffer.byteLength);
+
+ var jsArray = [];
+ for (i = 0; i < 30; i++) {
+ jsArray.push(typicalElement);
+ }
+ var aFromArray = new constr(jsArray);
+ assertSame(elementSize, aFromArray.BYTES_PER_ELEMENT);
+ assertSame(30, aFromArray.length);
+ assertSame(30*elementSize, aFromArray.byteLength);
+ assertSame(0, aFromArray.byteOffset);
+ assertSame(30*elementSize, aFromArray.buffer.byteLength);
+ for (i = 0; i < 30; i++) {
+ assertSame(typicalElement, aFromArray[i]);
+ }
+
+ var abLen0 = new ArrayBuffer(0);
+ var aOverAbLen0 = new constr(abLen0);
+ assertSame(abLen0, aOverAbLen0.buffer);
+ assertSame(elementSize, aOverAbLen0.BYTES_PER_ELEMENT);
+ assertSame(0, aOverAbLen0.length);
+ assertSame(0, aOverAbLen0.byteLength);
+ assertSame(0, aOverAbLen0.byteOffset);
+
+ var aNoParam = new constr();
+ assertSame(elementSize, aNoParam.BYTES_PER_ELEMENT);
+ assertSame(0, aNoParam.length);
+ assertSame(0, aNoParam.byteLength);
+ assertSame(0, aNoParam.byteOffset);
+}
+
+TestTypedArray(Uint8Array, 1, 0xFF);
+TestTypedArray(Int8Array, 1, -0x7F);
+TestTypedArray(Uint16Array, 2, 0xFFFF);
+TestTypedArray(Int16Array, 2, -0x7FFF);
+TestTypedArray(Uint32Array, 4, 0xFFFFFFFF);
+TestTypedArray(Int32Array, 4, -0x7FFFFFFF);
+TestTypedArray(Float32Array, 4, 0.5);
+TestTypedArray(Float64Array, 8, 0.5);
+TestTypedArray(Uint8ClampedArray, 1, 0xFF);
+
+function SubarrayTestCase(constructor, item, expectedResultLen, expectedStartIndex,
+ initialLen, start, end) {
+ var a = new constructor(initialLen);
+ var s = a.subarray(start, end);
+ assertSame(constructor, s.constructor);
+ assertSame(expectedResultLen, s.length);
+ if (s.length > 0) {
+ s[0] = item;
+ assertSame(item, a[expectedStartIndex]);
+ }
+}
+
+function TestSubArray(constructor, item) {
+ SubarrayTestCase(constructor, item, 512, 512, 1024, 512, 1024);
+ SubarrayTestCase(constructor, item, 512, 512, 1024, 512);
+
+ SubarrayTestCase(constructor, item, 0, undefined, 0, 1, 20);
+ SubarrayTestCase(constructor, item, 100, 0, 100, 0, 100);
+ SubarrayTestCase(constructor, item, 100, 0, 100, 0, 1000);
+ SubarrayTestCase(constructor, item, 0, undefined, 100, 5, 1);
+
+ SubarrayTestCase(constructor, item, 1, 89, 100, -11, -10);
+ SubarrayTestCase(constructor, item, 9, 90, 100, -10, 99);
+ SubarrayTestCase(constructor, item, 0, undefined, 100, -10, 80);
+ SubarrayTestCase(constructor, item, 10,80, 100, 80, -10);
+
+ SubarrayTestCase(constructor, item, 10,90, 100, 90, "100");
+ SubarrayTestCase(constructor, item, 10,90, 100, "90", "100");
+
+ SubarrayTestCase(constructor, item, 0, undefined, 100, 90, "abc");
+ SubarrayTestCase(constructor, item, 10,0, 100, "abc", 10);
+
+ SubarrayTestCase(constructor, item, 10,0, 100, 0.96, 10.96);
+ SubarrayTestCase(constructor, item, 10,0, 100, 0.96, 10.01);
+ SubarrayTestCase(constructor, item, 10,0, 100, 0.01, 10.01);
+ SubarrayTestCase(constructor, item, 10,0, 100, 0.01, 10.96);
+
+
+ SubarrayTestCase(constructor, item, 10,90, 100, 90);
+ SubarrayTestCase(constructor, item, 10,90, 100, -10);
+
+ var method = constructor.prototype.subarray;
+ method.call(new constructor(100), 0, 100);
+ var o = {};
+ assertThrows(function() { method.call(o, 0, 100); }, TypeError);
+}
+
+TestSubArray(Uint8Array, 0xFF);
+TestSubArray(Int8Array, -0x7F);
+TestSubArray(Uint16Array, 0xFFFF);
+TestSubArray(Int16Array, -0x7FFF);
+TestSubArray(Uint32Array, 0xFFFFFFFF);
+TestSubArray(Int32Array, -0x7FFFFFFF);
+TestSubArray(Float32Array, 0.5);
+TestSubArray(Float64Array, 0.5);
+TestSubArray(Uint8ClampedArray, 0xFF);
+
+function TestTypedArrayOutOfRange(constructor, value, result) {
+ var a = new constructor(1);
+ a[0] = value;
+ assertSame(result, a[0]);
+}
+
+TestTypedArrayOutOfRange(Uint8Array, 0x1FA, 0xFA);
+TestTypedArrayOutOfRange(Uint8Array, -1, 0xFF);
+
+TestTypedArrayOutOfRange(Int8Array, 0x1FA, 0x7A - 0x80);
+
+TestTypedArrayOutOfRange(Uint16Array, 0x1FFFA, 0xFFFA);
+TestTypedArrayOutOfRange(Uint16Array, -1, 0xFFFF);
+TestTypedArrayOutOfRange(Int16Array, 0x1FFFA, 0x7FFA - 0x8000);
+
+TestTypedArrayOutOfRange(Uint32Array, 0x1FFFFFFFA, 0xFFFFFFFA);
+TestTypedArrayOutOfRange(Uint32Array, -1, 0xFFFFFFFF);
+TestTypedArrayOutOfRange(Int32Array, 0x1FFFFFFFA, 0x7FFFFFFA - 0x80000000);
+
+TestTypedArrayOutOfRange(Uint8ClampedArray, 0x1FA, 0xFF);
+TestTypedArrayOutOfRange(Uint8ClampedArray, -1, 0);
+
+var typedArrayConstructors = [
+ Uint8Array,
+ Int8Array,
+ Uint16Array,
+ Int16Array,
+ Uint32Array,
+ Int32Array,
+ Uint8ClampedArray,
+ Float32Array,
+ Float64Array];
+
+function TestPropertyTypeChecks(constructor) {
+ function CheckProperty(name) {
+ var d = Object.getOwnPropertyDescriptor(constructor.prototype, name);
+ var o = {};
+ assertThrows(function() {d.get.call(o);}, TypeError);
+ for (var i = 0; i < typedArrayConstructors.length; i++) {
+ var ctor = typedArrayConstructors[i];
+ var a = new ctor(10);
+ /* Lars: According to my interpretation of ecma6 the test below is wrong. The accessors for the buffer etc. properties
+ do not check for type matching, are the same for all typed arrays. According to the spec they only check that the
+ object has a [[ViewedArrayBuffer]] internal property which they all have.
+
+ if (ctor === constructor) {
+ d.get.call(a); // shouldn't throw
+ } else {
+ assertThrows(function() {d.get.call(a);}, TypeError);
+ }
+
+ the below is IMO correct:
+ */
+ d.get.call(a); // shouldn't throw
+ assertThrows(function() {d.get.call({});}, TypeError); // throw on objects that aren't Typed Arrays
+ }
+ }
+
+ CheckProperty("buffer");
+ CheckProperty("byteOffset");
+ CheckProperty("byteLength");
+ CheckProperty("length");
+}
+
+for(i = 0; i < typedArrayConstructors.length; i++) {
+ TestPropertyTypeChecks(typedArrayConstructors[i]);
+}
+
+
+function TestTypedArraySet() {
+ // Test array.set in different combinations.
+
+ function assertArrayPrefix(expected, array) {
+ for (var i = 0; i < expected.length; ++i) {
+ assertEquals(expected[i], array[i]);
+ }
+ }
+
+ var a11 = new Int16Array([1, 2, 3, 4, 0, -1])
+ var a12 = new Uint16Array(15)
+ a12.set(a11, 3)
+ assertArrayPrefix([0, 0, 0, 1, 2, 3, 4, 0, 0xffff, 0, 0], a12)
+ assertThrows(function(){ a11.set(a12) })
+
+ var a21 = [1, undefined, 10, NaN, 0, -1, {valueOf: function() {return 3}}]
+ var a22 = new Int32Array(12)
+ a22.set(a21, 2)
+ assertArrayPrefix([0, 0, 1, 0, 10, 0, 0, -1, 3, 0], a22)
+
+ var a31 = new Float32Array([2, 4, 6, 8, 11, NaN, 1/0, -3])
+ var a32 = a31.subarray(2, 6)
+ a31.set(a32, 4)
+ assertArrayPrefix([2, 4, 6, 8, 6, 8, 11, NaN], a31)
+ assertArrayPrefix([6, 8, 6, 8], a32)
+
+ var a4 = new Uint8ClampedArray([3,2,5,6])
+ a4.set(a4)
+ assertArrayPrefix([3, 2, 5, 6], a4)
+
+ // Cases with overlapping backing store but different element sizes.
+ var b = new ArrayBuffer(4)
+ var a5 = new Int16Array(b)
+ var a50 = new Int8Array(b)
+ var a51 = new Int8Array(b, 0, 2)
+ var a52 = new Int8Array(b, 1, 2)
+ var a53 = new Int8Array(b, 2, 2)
+
+ a5.set([0x5050, 0x0a0a])
+ assertArrayPrefix([0x50, 0x50, 0x0a, 0x0a], a50)
+ assertArrayPrefix([0x50, 0x50], a51)
+ assertArrayPrefix([0x50, 0x0a], a52)
+ assertArrayPrefix([0x0a, 0x0a], a53)
+
+ a50.set([0x50, 0x50, 0x0a, 0x0a])
+ a51.set(a5)
+ assertArrayPrefix([0x50, 0x0a, 0x0a, 0x0a], a50)
+
+ a50.set([0x50, 0x50, 0x0a, 0x0a])
+ a52.set(a5)
+ assertArrayPrefix([0x50, 0x50, 0x0a, 0x0a], a50)
+
+ a50.set([0x50, 0x50, 0x0a, 0x0a])
+ a53.set(a5)
+ assertArrayPrefix([0x50, 0x50, 0x50, 0x0a], a50)
+
+ a50.set([0x50, 0x51, 0x0a, 0x0b])
+ a5.set(a51)
+ assertArrayPrefix([0x0050, 0x0051], a5)
+
+ a50.set([0x50, 0x51, 0x0a, 0x0b])
+ a5.set(a52)
+ assertArrayPrefix([0x0051, 0x000a], a5)
+
+ a50.set([0x50, 0x51, 0x0a, 0x0b])
+ a5.set(a53)
+ assertArrayPrefix([0x000a, 0x000b], a5)
+
+ // Mixed types of same size.
+ var a61 = new Float32Array([1.2, 12.3])
+ var a62 = new Int32Array(2)
+ a62.set(a61)
+ assertArrayPrefix([1, 12], a62)
+ a61.set(a62)
+ assertArrayPrefix([1, 12], a61)
+
+ // Invalid source
+ var a = new Uint16Array(50);
+ var expected = [];
+ for (i = 0; i < 50; i++) {
+ a[i] = i;
+ expected.push(i);
+ }
+ /* Lars: Also here the test is wrong. According to ecma 6 this should throw:
+ a.set({});
+
+ but a.set([]) shouldn't
+ */
+ assertThrows(function() { a.set({}) }, TypeError)
+ a.set([])
+ assertArrayPrefix(expected, a);
+ assertThrows(function() { a.set.call({}) }, TypeError);
+ assertThrows(function() { a.set.call([]) }, TypeError);
+
+ assertThrows(function() { a.set(0); }, TypeError);
+ assertThrows(function() { a.set(0, 1); }, TypeError);
+}
+
+TestTypedArraySet();
+
+function TestTypedArraysWithIllegalIndices() {
+ var a = new Int32Array(100);
+
+ a[-10] = 10;
+ assertEquals(undefined, a[-10]);
+ a["-10"] = 10;
+ assertEquals(undefined, a["-10"]);
+
+ var s = " -10";
+ a[s] = 10;
+ assertEquals(10, a[s]);
+ var s1 = " -10 ";
+ a[s] = 10;
+ assertEquals(10, a[s]);
+
+ a["-1e2"] = 10;
+ assertEquals(10, a["-1e2"]);
+ assertEquals(undefined, a[-1e2]);
+
+ /* Chromium bug: 424619
+ * a[-Infinity] = 50;
+ * assertEquals(undefined, a[-Infinity]);
+ */
+ a[1.5] = 10;
+ assertEquals(undefined, a[1.5]);
+ var nan = Math.sqrt(-1);
+ a[nan] = 5;
+ assertEquals(5, a[nan]);
+
+ var x = 0;
+ var y = -0;
+ assertEquals(Infinity, 1/x);
+ assertEquals(-Infinity, 1/y);
+ a[x] = 5;
+ a[y] = 27;
+ assertEquals(27, a[x]);
+ assertEquals(27, a[y]);
+}
+
+// Lars: I can't find anything in the spec that should prevent indices that are not array indices from working as usual.
+// So I don't see why the test is as it is.
+//TestTypedArraysWithIllegalIndices();
+
+function TestTypedArraysWithIllegalIndicesStrict() {
+ 'use strict';
+ var a = new Int32Array(100);
+
+ a[-10] = 10;
+ assertEquals(undefined, a[-10]);
+ a["-10"] = 10;
+ assertEquals(undefined, a["-10"]);
+
+ var s = " -10";
+ a[s] = 10;
+ assertEquals(10, a[s]);
+ var s1 = " -10 ";
+ a[s] = 10;
+ assertEquals(10, a[s]);
+
+ a["-1e2"] = 10;
+ assertEquals(10, a["-1e2"]);
+ assertEquals(undefined, a[-1e2]);
+
+ /* Chromium bug: 424619
+ * a[-Infinity] = 50;
+ * assertEquals(undefined, a[-Infinity]);
+ */
+ a[1.5] = 10;
+ assertEquals(undefined, a[1.5]);
+ var nan = Math.sqrt(-1);
+ a[nan] = 5;
+ assertEquals(5, a[nan]);
+
+ var x = 0;
+ var y = -0;
+ assertEquals(Infinity, 1/x);
+ assertEquals(-Infinity, 1/y);
+ a[x] = 5;
+ a[y] = 27;
+ assertEquals(27, a[x]);
+ assertEquals(27, a[y]);
+}
+
+// Lars: See above
+//TestTypedArraysWithIllegalIndicesStrict();
+
+// DataView
+function TestDataViewConstructor() {
+ var ab = new ArrayBuffer(256);
+
+ var d1 = new DataView(ab, 1, 255);
+ assertTrue(ArrayBuffer.isView(d1));
+ assertSame(ab, d1.buffer);
+ assertSame(1, d1.byteOffset);
+ assertSame(255, d1.byteLength);
+
+ var d2 = new DataView(ab, 2);
+ assertSame(ab, d2.buffer);
+ assertSame(2, d2.byteOffset);
+ assertSame(254, d2.byteLength);
+
+ var d3 = new DataView(ab);
+ assertSame(ab, d3.buffer);
+ assertSame(0, d3.byteOffset);
+ assertSame(256, d3.byteLength);
+
+ var d3a = new DataView(ab, 1, 0);
+ assertSame(ab, d3a.buffer);
+ assertSame(1, d3a.byteOffset);
+ assertSame(0, d3a.byteLength);
+
+ var d3b = new DataView(ab, 256, 0);
+ assertSame(ab, d3b.buffer);
+ assertSame(256, d3b.byteOffset);
+ assertSame(0, d3b.byteLength);
+
+ var d3c = new DataView(ab, 256);
+ assertSame(ab, d3c.buffer);
+ assertSame(256, d3c.byteOffset);
+ assertSame(0, d3c.byteLength);
+
+ /* This is wrong according to ecma 6 and should throw:
+
+ var d4 = new DataView(ab, 1, 3.1415926);
+ assertSame(ab, d4.buffer);
+ assertSame(1, d4.byteOffset);
+ assertSame(3, d4.byteLength);
+ */
+ assertThrows(function() { new DataView(ab, 3.1415926); }, RangeError);
+
+ // error cases
+ assertThrows(function() { new DataView(ab, -1); }, RangeError);
+ assertThrows(function() { new DataView(ab, 1, -1); }, RangeError);
+ assertThrows(function() { new DataView(); }, TypeError);
+ assertThrows(function() { new DataView([]); }, TypeError);
+ assertThrows(function() { new DataView(ab, 257); }, RangeError);
+ assertThrows(function() { new DataView(ab, 1, 1024); }, RangeError);
+}
+
+TestDataViewConstructor();
+
+function TestDataViewPropertyTypeChecks() {
+ var a = new DataView(new ArrayBuffer(10));
+ function CheckProperty(name) {
+ var d = Object.getOwnPropertyDescriptor(DataView.prototype, name);
+ var o = {}
+ assertThrows(function() {d.get.call(o);}, TypeError);
+ d.get.call(a); // shouldn't throw
+ }
+
+ CheckProperty("buffer");
+ CheckProperty("byteOffset");
+ CheckProperty("byteLength");
+}
+
+
+TestDataViewPropertyTypeChecks();
+
+// General tests for properties
+
+// Test property attribute [[Enumerable]]
+function TestEnumerable(func, obj) {
+ function props(x) {
+ var array = [];
+ for (var p in x) array.push(p);
+ return array.sort();
+ }
+ assertArrayEquals([], props(func));
+ assertArrayEquals([], props(func.prototype));
+ if (obj)
+ assertArrayEquals([], props(obj));
+}
+TestEnumerable(ArrayBuffer, new ArrayBuffer());
+for(i = 0; i < typedArrayConstructors.length; i++) {
+ TestEnumerable(typedArrayConstructors[i]);
+}
+TestEnumerable(DataView, new DataView(new ArrayBuffer()));
+
+// Test arbitrary properties on ArrayBuffer
+function TestArbitrary(m) {
+ function TestProperty(map, property, value) {
+ map[property] = value;
+ assertEquals(value, map[property]);
+ }
+ for (var i = 0; i < 20; i++) {
+ TestProperty(m, 'key' + i, 'val' + i);
+ TestProperty(m, 'foo' + i, 'bar' + i);
+ }
+}
+TestArbitrary(new ArrayBuffer(256));
+for(i = 0; i < typedArrayConstructors.length; i++) {
+ TestArbitrary(new typedArrayConstructors[i](10));
+}
+TestArbitrary(new DataView(new ArrayBuffer(256)));
+
+/* Lars: Not sure this is correct, as ECMA6 seems to allow calling the constructors as functions.
+ */
+// Test direct constructor call
+//assertThrows(function() { ArrayBuffer(); }, TypeError);
+//assertThrows(function() { DataView(new ArrayBuffer()); }, TypeError);