Skip to content

Commit cf18d89

Browse files
committed
Fixed exporting of typed arrays and DataView into []byte so that it respects the offset and length.
1 parent 58d95d8 commit cf18d89

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

builtin_typedarrays_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package goja
22

33
import (
4+
"bytes"
45
"testing"
56
)
67

@@ -324,3 +325,45 @@ func TestTypedArrayDeleteUnconfigurable(t *testing.T) {
324325

325326
testScript(SCRIPT, _undefined, t)
326327
}
328+
329+
func TestTypedArrayExportToBytes(t *testing.T) {
330+
const SCRIPT = `
331+
const arr = new Uint16Array(10);
332+
arr[2] = 0xFFFF; // make sure it's not affected by the platform endianness
333+
arr.subarray(2, 4);
334+
`
335+
vm := New()
336+
v, err := vm.RunString(SCRIPT)
337+
if err != nil {
338+
t.Fatal(err)
339+
}
340+
var b []byte
341+
err = vm.ExportTo(v, &b)
342+
if err != nil {
343+
t.Fatal(err)
344+
}
345+
if !bytes.Equal(b, []byte{0xFF, 0xFF, 0, 0}) {
346+
t.Fatal("unexpected value", b)
347+
}
348+
}
349+
350+
func TestDataViewExportToBytes(t *testing.T) {
351+
const SCRIPT = `
352+
const arr = new Uint16Array(10);
353+
arr[2] = 0xFFFF;
354+
new DataView(arr.buffer, 4, 4);
355+
`
356+
vm := New()
357+
v, err := vm.RunString(SCRIPT)
358+
if err != nil {
359+
t.Fatal(err)
360+
}
361+
var b []byte
362+
err = vm.ExportTo(v, &b)
363+
if err != nil {
364+
t.Fatal(err)
365+
}
366+
if !bytes.Equal(b, []byte{0xFF, 0xFF, 0, 0}) {
367+
t.Fatal("unexpected value", b)
368+
}
369+
}

typedarrays.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -994,7 +994,7 @@ func (a *typedArrayObject) iterateStringKeys() iterNextFunc {
994994

995995
func (a *typedArrayObject) exportToArrayOrSlice(dst reflect.Value, typ reflect.Type, ctx *objectExportCtx) error {
996996
if typ == typeBytes {
997-
dst.Set(reflect.ValueOf(a.viewedArrayBuf.data))
997+
dst.Set(reflect.ValueOf(a.viewedArrayBuf.data[a.offset*a.elemSize : (a.offset+a.length)*a.elemSize]))
998998
return nil
999999
}
10001000
return a.baseObject.exportToArrayOrSlice(dst, typ, ctx)
@@ -1010,7 +1010,7 @@ func (a *typedArrayObject) exportType() reflect.Type {
10101010

10111011
func (o *dataViewObject) exportToArrayOrSlice(dst reflect.Value, typ reflect.Type, ctx *objectExportCtx) error {
10121012
if typ == typeBytes {
1013-
dst.Set(reflect.ValueOf(o.viewedArrayBuf.data))
1013+
dst.Set(reflect.ValueOf(o.viewedArrayBuf.data[o.byteOffset : o.byteOffset+o.byteLen]))
10141014
return nil
10151015
}
10161016
return o.baseObject.exportToArrayOrSlice(dst, typ, ctx)

0 commit comments

Comments
 (0)