|
| 1 | +function shouldBe(actual, expected) { |
| 2 | + if (actual !== expected) |
| 3 | + throw new Error(`bad value: ${actual}, expected: ${expected}`); |
| 4 | +} |
| 5 | + |
| 6 | +// Source is a fixed-length view on a resizable ArrayBuffer. Shrinking the |
| 7 | +// buffer inside mapFn makes the view out-of-bounds without detaching it. |
| 8 | +// TypedArray.from must stop writing without throwing. |
| 9 | +function testSourceShrunkOutOfBounds() { |
| 10 | + const rab = new ArrayBuffer(32, { maxByteLength: 64 }); |
| 11 | + const source = new Int32Array(rab, 0, 8); |
| 12 | + for (let i = 0; i < 8; i++) |
| 13 | + source[i] = i + 1; |
| 14 | + source[Symbol.iterator] = null; |
| 15 | + |
| 16 | + let calls = 0; |
| 17 | + const result = Int32Array.from(source, (value, k) => { |
| 18 | + calls++; |
| 19 | + if (k === 4) |
| 20 | + rab.resize(16); |
| 21 | + return value; |
| 22 | + }); |
| 23 | + shouldBe(calls, 5); |
| 24 | + shouldBe(result.length, 8); |
| 25 | + shouldBe(result[4], 5); |
| 26 | + shouldBe(result[5], 0); |
| 27 | +} |
| 28 | + |
| 29 | +// Result is a fixed-length view on a resizable ArrayBuffer. Shrinking the |
| 30 | +// buffer inside mapFn makes the result out-of-bounds without detaching it. |
| 31 | +function testResultShrunkOutOfBounds() { |
| 32 | + let rab; |
| 33 | + class FixedLengthOnResizable extends Int32Array { |
| 34 | + constructor(length) { |
| 35 | + rab = new ArrayBuffer(4 * length, { maxByteLength: 8 * length }); |
| 36 | + super(rab, 0, length); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + let calls = 0; |
| 41 | + const result = FixedLengthOnResizable.from({ length: 8 }, (value, k) => { |
| 42 | + calls++; |
| 43 | + if (k === 2) |
| 44 | + rab.resize(4); |
| 45 | + return k; |
| 46 | + }); |
| 47 | + shouldBe(calls, 3); |
| 48 | +} |
| 49 | + |
| 50 | +// Result's buffer is detached by transfer() inside mapFn. |
| 51 | +function testResultDetached() { |
| 52 | + let buffer; |
| 53 | + class ViewOnTransferableBuffer extends Int32Array { |
| 54 | + constructor(length) { |
| 55 | + buffer = new ArrayBuffer(4 * length); |
| 56 | + super(buffer); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + let calls = 0; |
| 61 | + const result = ViewOnTransferableBuffer.from({ length: 8 }, (value, k) => { |
| 62 | + calls++; |
| 63 | + if (k === 2) |
| 64 | + buffer.transfer(); |
| 65 | + return k; |
| 66 | + }); |
| 67 | + shouldBe(calls, 3); |
| 68 | +} |
| 69 | + |
| 70 | +for (let i = 0; i < testLoopCount; i++) { |
| 71 | + testSourceShrunkOutOfBounds(); |
| 72 | + testResultShrunkOutOfBounds(); |
| 73 | + testResultDetached(); |
| 74 | +} |
0 commit comments