diff --git a/assembly/Histogram.ts b/assembly/Histogram.ts index e96d3aa..dd3e3d2 100644 --- a/assembly/Histogram.ts +++ b/assembly/Histogram.ts @@ -119,6 +119,45 @@ function laneSub(a: v128, b: v128): v128 { } } +/** + * Largest count a U-wide cell can hold. u64 cells never overflow in practice, so + * their checks are compiled out (guarded by sizeof() < 8 at each call site). + */ +// @ts-ignore: decorator +@inline +function countMax(): u64 { + return (1 << (sizeof() << 3)) - 1; +} + +// Aborts with the message (AssemblyScript's throw of an Error carries no message in the +// minimal runtime, so the JS wrapper would only see the location). + +/** Aborts for a count that would overflow a narrow U cell, naming the width. */ +function overflowAbort(count: u64): void { + abort(count.toString() + " would overflow " + (sizeof() << 3).toString() + "-bit integer count"); +} + +/** Aborts for a count that would underflow a narrow U cell, naming the width. */ +function underflowAbort(count: i64): void { + abort(count.toString() + " would underflow " + (sizeof() << 3).toString() + "-bit integer count"); +} + +/** Lane-wise unsigned a < b. u64 lanes flip the sign bit so the signed compare orders them unsigned. */ +// @ts-ignore: decorator +@inline +function laneLtU(a: v128, b: v128): v128 { + if (sizeof() == 1) { + return i8x16.lt_u(a, b); + } else if (sizeof() == 2) { + return i16x8.lt_u(a, b); + } else if (sizeof() == 4) { + return i32x4.lt_u(a, b); + } else { + const bias = i64x2.splat(i64.MIN_VALUE); + return i64x2.lt_s(v128.xor(a, bias), v128.xor(b, bias)); + } +} + export default class Histogram extends AbstractHistogramBase { // "Hot" accessed fields (used in the the value recording code path) are bunched here, such // that they will have a good chance of ending up in the same cache line as the totalCounts and @@ -582,6 +621,19 @@ export default class Histogram extends AbstractHistogramBase { return index == 0 ? this.lowestNonZeroCountsIndex() : index + 1; } + /** + * Entry point for count arguments that arrive as f64 (the JS boundary). A negative + * count is not representable in any U cell (and would saturate to 0 in the u64 cast, + * dropping the record silently), so it aborts for every width. + */ + recordCountAtValueFromF64(count: f64, value: f64): void { + if (count < 0) { + underflowAbort(count); + } + this.recordCountAtValue(count, value); + } + + // @ts-ignore: decorator @inline recordCountAtValue(count: u64, value: u64): void { const countsIndex = this.countsArrayIndex(value); @@ -870,18 +922,23 @@ export default class Histogram extends AbstractHistogramBase { return; } // @ts-ignore - const currentCount = unchecked(this.counts[index]); - const newCount = currentCount + 1; - if (newCount < 0) { - throw new Error( - newCount.toString() + " would overflow short integer count" - ); + const newCount = unchecked(this.counts[index]) + 1; + if (sizeof() < 8 && newCount > countMax()) { + overflowAbort(newCount); } // @ts-ignore - unchecked((this.counts[index] = newCount)); + unchecked((this.counts[index] = newCount)); } setCountAtIndex(index: i32, value: u64): void { + if (sizeof() < 8) { + if (value < 0) { + underflowAbort(value); + } + if (value > countMax()) { + overflowAbort(value); + } + } // @ts-ignore unchecked((this.counts[index] = value)); } @@ -895,13 +952,24 @@ export default class Histogram extends AbstractHistogramBase { return; } // @ts-ignore - const currentCount = unchecked(this.counts[index]); - const newCount = currentCount + value; - if (newCount < 0) { - throw newCount + " would overflow short integer count"; + const currentCount = unchecked(this.counts[index]); + if (value >= 0) { + const newCount = currentCount + value; + if (sizeof() < 8 && newCount > countMax()) { + overflowAbort(newCount); + } + // @ts-ignore + unchecked((this.counts[index] = newCount)); + } else { + // Negative values arrive as two's complement (subtract); the magnitude is their negation. + // A cell of U (u64 included) cannot go below zero, so the check applies to every width. + const decrement = (0) - value; + if (decrement > currentCount) { + underflowAbort(currentCount - decrement); + } + // @ts-ignore + unchecked((this.counts[index] = (currentCount - decrement))); } - // @ts-ignore - unchecked((this.counts[index] = newCount)); } incrementTotalCount(): void { @@ -988,8 +1056,15 @@ export default class Histogram extends AbstractHistogramBase { for (; i + step <= end; i += step) { const offset = i << alignof(); const other = v128.load(src + offset); + const current = v128.load(dst + offset); + const sum = laneAdd(current, other); + if (sizeof() < 8 && v128.any_true(laneLtU(sum, current))) { + // A lane would wrap: leave this block to the checked scalar loop below, + // which reports the exact cell and width. + break; + } acc = i64x2.add(acc, widenSum(other)); - v128.store(dst + offset, laneAdd(v128.load(dst + offset), other)); + v128.store(dst + offset, sum); } observedOtherTotalCount += horizontalSum(acc); } @@ -1176,8 +1251,13 @@ export default class Histogram extends AbstractHistogramBase { for (; i + step <= end; i += step) { const offset = i << alignof(); const other = v128.load(src + offset); + const current = v128.load(dst + offset); + if (v128.any_true(laneLtU(current, other))) { + // A lane would go negative: leave this block to the checked scalar loop below. + break; + } acc = i64x2.add(acc, widenSum(other)); - v128.store(dst + offset, laneSub(v128.load(dst + offset), other)); + v128.store(dst + offset, laneSub(current, other)); } observedOtherTotalCount += horizontalSum(acc); } diff --git a/assembly/__tests__/Histogram.test.ts b/assembly/__tests__/Histogram.test.ts index 0fa5d0d..a7eedb9 100644 --- a/assembly/__tests__/Histogram.test.ts +++ b/assembly/__tests__/Histogram.test.ts @@ -526,3 +526,47 @@ describe("Histogram scans bounded by recorded min and max", () => { ); }); }); + +describe("Histogram count range", () => { + // Overflow and underflow abort the module (AssemblyScript has no throw assertion here), + // so these cover the in-range boundaries; the throwing paths are covered by the + // WASM tests in src/Histogram.spec.ts. + test("should accept a count equal to the 8-bit maximum", () => { + // given + const histogram = new Histogram8(1, 9007199254740991, 3); + // when + histogram.setCountAtIndex(5, 255); + // then + expect(histogram.getCountAtIndex(5)).equal(255); + }); + + test("should add up to exactly the 16-bit maximum", () => { + // given + const histogram = new Histogram16(1, 1000000, 3); + histogram.setCountAtIndex(7, 65000); + // when + histogram.addToCountAtIndex(7, 535); + // then + expect(histogram.getCountAtIndex(7)).equal(65535); + }); + + test("should subtract down to exactly zero without wrapping", () => { + // given + const histogram = new Histogram32(1, 1000000, 3); + histogram.setCountAtIndex(9, 4294967295); + // when + histogram.addToCountAtIndex(9, 0 - 4294967295); + // then + expect(histogram.getCountAtIndex(9)).equal(0); + }); + + test("should subtract a 64-bit cell down to exactly zero", () => { + // given + const histogram = new Histogram64(1, 1000000, 3); + histogram.setCountAtIndex(9, 5); + // when + histogram.addToCountAtIndex(9, 0 - 5); + // then + expect(histogram.getCountAtIndex(9)).equal(0); + }); +}); diff --git a/assembly/index.ts b/assembly/index.ts index 7fa7047..2a58d00 100644 --- a/assembly/index.ts +++ b/assembly/index.ts @@ -140,7 +140,7 @@ class HistogramAdapter { } recordValueWithCount(value: f64, count: f64): void { - this._histogram.recordCountAtValue(count, value); + this._histogram.recordCountAtValueFromF64(count, value); } recordValueWithExpectedInterval( diff --git a/src/Histogram.spec.ts b/src/Histogram.spec.ts index 951f3a0..cb04cd6 100644 --- a/src/Histogram.spec.ts +++ b/src/Histogram.spec.ts @@ -835,3 +835,262 @@ describe("Histogram bucket boundaries near 2^53", () => { histogram.destroy(); }); }); + +describe("WASM histogram count range", () => { + beforeAll(initWebAssembly); + + [8, 16, 32].forEach((bits) => { + const max = Math.pow(2, bits) - 1; + const label = `${bits}-bit`; + + it(`should throw on recordValueWithCount past the ${label} maximum, leaving the histogram unchanged (WASM)`, () => { + // given + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, max); + const before = histogram.summary; + // when + const act = () => histogram.recordValueWithCount(42, 1); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); + expect(histogram.summary).toEqual(before); + expect(histogram.totalCount).toBe(max); + histogram.destroy(); + }); + + it(`should throw on add when the only cell to change would overflow ${label}, leaving the histogram unchanged (WASM)`, () => { + // given + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, max - 10); + other.recordValueWithCount(42, 11); + const before = histogram.summary; + // when + const act = () => histogram.add(other); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); + expect(histogram.summary).toEqual(before); + histogram.destroy(); + other.destroy(); + }); + + it(`should add up to exactly the ${label} maximum (WASM)`, () => { + // given + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, max - 10); + other.recordValueWithCount(42, 10); + // when + histogram.add(other); + // then + expect(histogram.totalCount).toBe(max); + histogram.destroy(); + other.destroy(); + }); + + it(`should throw on subtract when the only cell to change would underflow ${label}, leaving the histogram unchanged (WASM)`, () => { + // given + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, 5); + other.recordValueWithCount(42, 6); + const before = histogram.summary; + // when + const act = () => histogram.subtract(other); + // then + expect(act).toThrow(`would underflow ${bits}-bit integer count`); + expect(histogram.summary).toEqual(before); + histogram.destroy(); + other.destroy(); + }); + }); + + [8, 16, 32].forEach((bits) => { + it(`should throw on a negative recordValueWithCount on a ${bits}-bit WASM histogram instead of dropping it`, () => { + // given + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + // when + const act = () => histogram.recordValueWithCount(42, -1); + // then + expect(act).toThrow(`would underflow ${bits}-bit integer count`); + expect(histogram.totalCount).toBe(0); + histogram.destroy(); + }); + }); + + it("should throw on add at a later cell, leaving earlier cells applied and totalCount unchanged (8-bit WASM)", () => { + // given + const histogram = build({ + bitBucketSize: 8, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: 8, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, 255); + other.recordValueWithCount(1, 5); + other.recordValueWithCount(42, 1); + // when + const act = () => histogram.add(other); + // then + expect(act).toThrow("would overflow 8-bit integer count"); + // non-zero counts are [index, count, ...] pairs in index order: value 1 (5) then value 42 (255) + const counts = Array.from(histogram.getNonZeroCounts()).filter( + (_, i) => i % 2 === 1 + ); + expect(counts).toEqual([5, 255]); + expect(histogram.totalCount).toBe(255); + histogram.destroy(); + other.destroy(); + }); + + it("should throw on subtract when the 64-bit result would underflow, leaving the histogram unchanged (WASM)", () => { + // given + const histogram = build({ + bitBucketSize: 64, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: 64, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, 5); + other.recordValueWithCount(42, 6); + const before = histogram.summary; + // when + const act = () => histogram.subtract(other); + // then + expect(act).toThrow("would underflow 64-bit integer count"); + expect(histogram.summary).toEqual(before); + histogram.destroy(); + other.destroy(); + }); + + it("should throw on a negative recordValueWithCount on a 64-bit WASM histogram instead of dropping it", () => { + // given + const histogram = build({ + bitBucketSize: 64, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + // when + const act = () => histogram.recordValueWithCount(42, -3); + // then + expect(act).toThrow("would underflow 64-bit integer count"); + expect(histogram.totalCount).toBe(0); + histogram.destroy(); + }); + + it("should keep 64-bit WASM histograms unbounded by the 32-bit maximum", () => { + // given + const histogram = build({ + bitBucketSize: 64, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + // when + histogram.recordValueWithCount(42, 4294967295); + histogram.recordValueWithCount(42, 4294967295); + // then + expect(histogram.totalCount).toBe(8589934590); + histogram.destroy(); + }); +}); + +describe("WASM histogram add across a wide counts range", () => { + beforeAll(initWebAssembly); + + [8, 16, 32].forEach((bits) => { + const max = Math.pow(2, bits) - 1; + + it(`should throw on add when a cell in the middle of a vectorised block range would overflow ${bits}-bit (WASM)`, () => { + // given + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + for (let v = 1000; v < 200000; v += 997) { + other.recordValueWithCount(v, 1); + } + other.recordValueWithCount(100000, 1); + histogram.recordValueWithCount(100000, max); + // when + const act = () => histogram.add(other); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); + expect(histogram.totalCount).toBe(max); + histogram.destroy(); + other.destroy(); + }); + + it(`should add a wide range without overflow up to the ${bits}-bit maximum (WASM)`, () => { + // given + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + let expected = 0; + for (let v = 1000; v < 200000; v += 997) { + other.recordValueWithCount(v, 1); + expected++; + } + other.recordValueWithCount(100000, 1); + expected++; + histogram.recordValueWithCount(100000, max - 1); + // when + histogram.add(other); + // then + expect(histogram.totalCount).toBe(expected + max - 1); + histogram.destroy(); + other.destroy(); + }); + }); +}); diff --git a/src/TypedArrayHistogram.spec.ts b/src/TypedArrayHistogram.spec.ts index 99493df..e9bba8f 100644 --- a/src/TypedArrayHistogram.spec.ts +++ b/src/TypedArrayHistogram.spec.ts @@ -67,3 +67,185 @@ import Float64Histogram from "./Float64Histogram"; }); } ); + +describe("Typed array histogram count range", () => { + const cases = [ + { name: "8-bit", Histogram: Int8Histogram, max: 255, bits: 8 }, + { name: "16-bit", Histogram: Int16Histogram, max: 65535, bits: 16 }, + { name: "32-bit", Histogram: Int32Histogram, max: 4294967295, bits: 32 }, + ]; + + cases.forEach(({ name, Histogram, max, bits }) => { + describe(`${name} histogram`, () => { + it("should accept a count up to the storage maximum", () => { + // given + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + // when + histogram.recordValueWithCount(42, max); + // then + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( + max + ); + expect(histogram.totalCount).toBe(max); + }); + + it("should throw on recordValueWithCount past the storage maximum, leaving the histogram unchanged", () => { + // given + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, max); + // when + const act = () => histogram.recordValueWithCount(42, 1); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( + max + ); + expect(histogram.totalCount).toBe(max); + }); + + it("should throw on recordValue when the counter is already at the maximum", () => { + // given + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.setCountAtIndex(histogram.countsArrayIndex(42), max); + // when + const act = () => histogram.recordValue(42); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); + expect(histogram.totalCount).toBe(0); + }); + + it("should throw on addToCountAtIndex and setCountAtIndex past the maximum", () => { + // given + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + // when + const setAct = () => histogram.setCountAtIndex(5, max + 1); + // then + expect(setAct).toThrow("would overflow"); + // given + histogram.setCountAtIndex(5, max - 1); + // when + const addAct = () => histogram.addToCountAtIndex(5, 2); + // then + expect(addAct).toThrow(`would overflow ${bits}-bit integer count`); + expect(histogram.getCountAtIndex(5)).toBe(max - 1); + }); + + it("should throw on a negative count instead of wrapping", () => { + // given + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, 3); + // when + const act = () => histogram.recordValueWithCount(42, -4); + // then + expect(act).toThrow(`would underflow ${bits}-bit integer count`); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( + 3 + ); + expect(histogram.totalCount).toBe(3); + }); + + it("should throw on add when the only cell to change would overflow, leaving the histogram unchanged", () => { + // given + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, max - 10); + other.recordValueWithCount(42, 11); + const before = histogram.summary; + // when + const act = () => histogram.add(other); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); + expect(histogram.summary).toEqual(before); + expect(other.totalCount).toBe(11); + }); + + it("should add up to exactly the storage maximum", () => { + // given + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, max - 10); + other.recordValueWithCount(42, 10); + // when + histogram.add(other); + // then + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( + max + ); + expect(histogram.totalCount).toBe(max); + }); + + it("should throw on subtract when the only cell to change would underflow, leaving the histogram unchanged", () => { + // given + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, 5); + other.recordValueWithCount(42, 6); + const before = histogram.summary; + // when + const act = () => histogram.subtract(other); + // then + expect(act).toThrow(`would underflow ${bits}-bit integer count`); + expect(histogram.summary).toEqual(before); + }); + }); + }); + + describe("8-bit histogram with several cells changing", () => { + it("should throw on add at a later cell, leaving earlier cells applied and totalCount unchanged", () => { + // given + const histogram = new Int8Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const other = new Int8Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, 255); + other.recordValueWithCount(1, 5); + other.recordValueWithCount(42, 1); + // when + const act = () => histogram.add(other); + // then + expect(act).toThrow("would overflow 8-bit integer count"); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(1))).toBe(5); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( + 255 + ); + expect(histogram.totalCount).toBe(255); + }); + + it("should throw on subtract at a later cell, leaving earlier cells applied and totalCount unchanged", () => { + // given + const histogram = new Int8Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const other = new Int8Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(1, 10); + other.recordValueWithCount(1, 5); + other.recordValueWithCount(42, 1); + // when + const act = () => histogram.subtract(other); + // then + expect(act).toThrow("would underflow 8-bit integer count"); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(1))).toBe(5); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe(0); + expect(histogram.totalCount).toBe(10); + }); + + it("should leave highestTrackableValue unchanged when an auto-resizing histogram rejects the count", () => { + // given + const histogram = new Int8Histogram(1, 1000, 3); + histogram.autoResize = true; + const highestBefore = histogram.highestTrackableValue; + // when + const act = () => histogram.recordValueWithCount(1000000, 300); + // then + expect(act).toThrow("would overflow 8-bit integer count"); + expect(histogram.highestTrackableValue).toBe(highestBefore); + expect(histogram.totalCount).toBe(0); + }); + }); + + it("should keep Float64 histograms unbounded by the 32-bit maximum", () => { + // given + const histogram = new Float64Histogram(1, Number.MAX_SAFE_INTEGER, 3); + // when + histogram.recordValueWithCount(42, 4294967295); + histogram.recordValueWithCount(42, 4294967295); + // then + expect(histogram.totalCount).toBe(8589934590); + }); +}); diff --git a/src/TypedArrayHistogram.ts b/src/TypedArrayHistogram.ts index 64bbfae..c1c1974 100644 --- a/src/TypedArrayHistogram.ts +++ b/src/TypedArrayHistogram.ts @@ -17,6 +17,12 @@ type TypedArray = ArrayLike & { class TypedArrayHistogram extends JsHistogram { _counts: TypedArray; _totalCount: number; + // Counts are range-checked against the storage width: unsigned typed arrays + // would otherwise wrap silently (255 + 1 -> 0 in an 8-bit array). + // Float64 storage keeps the safe-integer range it always had. + private readonly countBits: number; + private readonly countMin: number; + private readonly countMax: number; constructor( private arrayCtr: new (size: number) => TypedArray, @@ -31,6 +37,14 @@ class TypedArrayHistogram extends JsHistogram { ); this._totalCount = 0; this._counts = new arrayCtr(this.countsArrayLength); + this.countBits = this._counts.BYTES_PER_ELEMENT * 8; + if (this.countBits < 64) { + this.countMin = 0; + this.countMax = Math.pow(2, this.countBits) - 1; + } else { + this.countMin = Number.MIN_SAFE_INTEGER; + this.countMax = Number.MAX_SAFE_INTEGER; + } } clearCounts() { @@ -49,34 +63,59 @@ class TypedArrayHistogram extends JsHistogram { return -1; } + // Checked before the base class resizes an auto-resizing histogram, so a rejected + // count leaves the histogram's range untouched. Only reached on the out-of-range path. + handleRecordException(count: number, value: number) { + if (count > this.countMax) { + this.throwCountOverflow(count); + } + if (count < this.countMin) { + this.throwCountUnderflow(count); + } + super.handleRecordException(count, value); + } + incrementCountAtIndex(index: number) { - const currentCount = this._counts[index]; - const newCount = currentCount + 1; - if (newCount < 0) { - throw newCount + " would overflow short integer count"; + const newCount = this._counts[index] + 1; + if (newCount > this.countMax) { + this.throwCountOverflow(newCount); } this._counts[index] = newCount; } addToCountAtIndex(index: number, value: number) { - const currentCount = this._counts[index]; - const newCount = currentCount + value; - if ( - newCount < Number.MIN_SAFE_INTEGER || - newCount > Number.MAX_SAFE_INTEGER - ) { - throw newCount + " would overflow integer count"; + const newCount = this._counts[index] + value; + if (newCount > this.countMax) { + this.throwCountOverflow(newCount); + } + if (newCount < this.countMin) { + this.throwCountUnderflow(newCount); } this._counts[index] = newCount; } setCountAtIndex(index: number, value: number) { - if (value < Number.MIN_SAFE_INTEGER || value > Number.MAX_SAFE_INTEGER) { - throw value + " would overflow integer count"; + if (value > this.countMax) { + this.throwCountOverflow(value); + } + if (value < this.countMin) { + this.throwCountUnderflow(value); } this._counts[index] = value; } + private throwCountOverflow(count: number): never { + throw new Error(`${count} would overflow ${this.countWidthLabel()} count`); + } + + private throwCountUnderflow(count: number): never { + throw new Error(`${count} would underflow ${this.countWidthLabel()} count`); + } + + private countWidthLabel() { + return this.countBits < 64 ? `${this.countBits}-bit integer` : "integer"; + } + resize(newHighestTrackableValue: number) { this.establishSize(newHighestTrackableValue); const newCounts = new this.arrayCtr(this.countsArrayLength); diff --git a/src/wasm/index.ts b/src/wasm/index.ts index 08d6bba..9410047 100644 --- a/src/wasm/index.ts +++ b/src/wasm/index.ts @@ -139,6 +139,14 @@ const wasmImports = { lineNumber: number, columnNumber: number ) { + // AssemblyScript aborts carry the message (e.g. "... would overflow 8-bit integer count"); + // optimized builds have no source positions, so the location is added only when present. + if (messagePtr) { + const location = lineNumber + ? ` (WebAssembly at ${lineNumber}:${columnNumber})` + : ""; + throw new Error(`${getString(messagePtr)}${location}`); + } throw new Error(`Abort in WebAssembly at ${lineNumber}:${columnNumber}`); }, },