Correct TypedArray#byteOffset handling and fix TypedArray#subarray (#328)

This commit is contained in:
Max Graey
2018-11-09 00:19:41 +02:00
committed by Daniel Wirtz
parent 2ecec660d2
commit d93ca84aed
5 changed files with 362 additions and 419 deletions

View File

@ -32,15 +32,13 @@ export abstract class TypedArray<T,V> {
@inline
get length(): i32 {
return (this.byteLength - this.byteOffset) >> alignof<T>();
return this.byteLength >>> alignof<T>();
}
@operator("[]")
protected __get(index: i32): T {
var byteOffset = this.byteOffset;
var elementLength = (this.byteLength - byteOffset) >>> alignof<T>();
if (<u32>index >= <u32>elementLength) throw new Error("Index out of bounds");
return loadUnsafeWithOffset<T,T>(this.buffer, index, byteOffset);
if (<u32>index >= <u32>(this.byteLength >>> alignof<T>())) throw new Error("Index out of bounds");
return loadUnsafeWithOffset<T,T>(this.buffer, index, this.byteOffset);
}
@inline @operator("{}")
@ -50,10 +48,8 @@ export abstract class TypedArray<T,V> {
@operator("[]=")
protected __set(index: i32, value: V): void {
var byteOffset = this.byteOffset;
var elementLength = (this.byteLength - byteOffset) >>> alignof<T>();
if (<u32>index >= <u32>elementLength) throw new Error("Index out of bounds");
storeUnsafeWithOffset<T,V>(this.buffer, index, value, byteOffset);
if (<u32>index >= <u32>(this.byteLength >>> alignof<T>())) throw new Error("Index out of bounds");
storeUnsafeWithOffset<T,V>(this.buffer, index, value, this.byteOffset);
}
@inline @operator("{}=")
@ -95,7 +91,7 @@ export abstract class TypedArray<T,V> {
var slice = memory.allocate(offsetof<this>());
store<usize>(slice, this.buffer, offsetof<this>("buffer"));
store<i32>(slice, begin << alignof<T>(), offsetof<this>("byteOffset"));
store<i32>(slice, end << alignof<T>(), offsetof<this>("byteLength"));
store<i32>(slice, (end - begin) << alignof<T>(), offsetof<this>("byteLength"));
return changetype<this>(slice);
}

View File

@ -21,7 +21,7 @@ export class Uint8Array extends TypedArray<u8,u32> {
export class Uint8ClampedArray extends TypedArray<u8,u32> {
static readonly BYTES_PER_ELEMENT: usize = sizeof<u8>();
@operator("[]=")
@inline @operator("[]=")
protected __set(index: i32, value: i32): void {
super.__set(index, max(min(value, 255), 0));
}