From 0b2e54ab7e4b61b4b446b0704f3bcb8b43731849 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sat, 14 Nov 2026 21:12:13 +0100 Subject: [PATCH] perf: packed arrays write through the leaf cache add(), increment() and set() used to walk the set trees for every byte they touched (getPackedIndex with insertAsNeeded), and only refreshed the leaf cache afterwards. They now take the leaf of the cached group directly and descend only for sets the cache has no leaf for, so sequential writes (histogram add, decoding, recordValue runs) mostly skip the descents. For the cached group, leafIndexBySet[0 .. knownSets) holds a leaf or NO_LEAF; sets from knownSets upwards are not looked up yet. get(), add() and set() resolve sets from byte 0 upwards without skipping one, so the known sets always form a prefix and evicting a group is a single knownSets = 0 instead of a reset of every entry. A miss, the common case for random recordValue such as latency recordings, therefore costs no more than before the cache: a write looks up only the sets it touches, get() resolves the remaining ones on demand. The write fast path skips getPackedIndex(), which held the only virtualLength check of the packed path, so a cache hit now checks the bound in cacheGroupOf(); a miss leaves it to getPackedIndex(), called for set 0 by every access after a miss. Correctness rests on the same invariants as the read cache: a leaf never moves once created (entries are only appended, resizeArray copies them in place), every write that creates a leaf records it so a known NO_LEAF is always current, and anything rebuilding the context invalidates the cache. The unpacked fallback is unchanged: the fast path only runs on a packed context, and unpack() is still reached from the inserting descents. Both the TypeScript and the AssemblyScript implementations change the same way, with property-based (fast-check) and as-test cases covering interleaved get/add/set/increment within a group, carries across cached and uncached sets, sets to smaller values, out-of-range indexes in a cached group, and the unpacked fallback after cached writes. Co-Authored-By: Claude Fable 5.1 Co-Authored-By: Claude Opus 5.5 --- assembly/__tests__/PackedArrayAccess.test.ts | 62 ++++++ assembly/packedarray/PackedArray.ts | 187 ++++++++++++------- src/packedarray/PackedArray.fc.spec.ts | 110 ++++++++++- src/packedarray/PackedArray.spec.ts | 15 ++ src/packedarray/PackedArray.ts | 180 +++++++++++------- 5 files changed, 409 insertions(+), 145 deletions(-) diff --git a/assembly/__tests__/PackedArrayAccess.test.ts b/assembly/__tests__/PackedArrayAccess.test.ts index 31c2333..911b34a 100644 --- a/assembly/__tests__/PackedArrayAccess.test.ts +++ b/assembly/__tests__/PackedArrayAccess.test.ts @@ -133,6 +133,68 @@ describe("Packed Array leaf cache", () => { expect(mismatches(packed, model)).equal(0); }); + test("writes within a group see each other without reads in between", () => { + // Writes alone cache their group, so the leaves looked up by one write + // serve the next writes of the group, including sets never looked up yet. + const packed = new PackedArray(64); + packed.add(24, 1); // caches group 3, set 0 only + packed.add(25, 0x200); // inserts set 1 while group 3 is cached + packed.increment(25); + packed.set(26, 0x030201); // inserts set 2 + packed.set(24, 0x7f); // set 0 known, higher sets looked up: no leaf yet for set 3 + expect(packed.get(24)).equal(0x7f); + expect(packed.get(25)).equal(0x201); + expect(packed.get(26)).equal(0x030201); + expect(packed.get(27)).equal(0); + }); + + test("carries propagate through cached and uncached sets", () => { + const packed = new PackedArray(64); + packed.set(40, 0xffff); // sets 0 and 1 + expect(packed.get(40)).equal(0xffff); + packed.add(41, 1); // cached group 5, set 0 known + packed.increment(40); // carries into set 1 (cached) then inserts set 2 + expect(packed.get(40)).equal(0x10000); + packed.add(40, 0xffffffffffff0000); // carries up to the top set + expect(packed.get(40)).equal(0); + expect(packed.get(41)).equal(1); + }); + + test("set to a smaller value through the cache clears the higher bytes", () => { + const packed = new PackedArray(64); + packed.set(50, 0x01020304); + packed.set(51, 0x05); // group 6 cached by the write above + packed.set(50, 0x0102); // sets 2 and 3 are cached leaves, zeroed + expect(packed.get(50)).equal(0x0102); + packed.set(50, 0); + expect(packed.get(50)).equal(0); + packed.set(52, 0); // no leaf created for a zero at an unknown set + expect(packed.get(52)).equal(0); + expect(packed.get(51)).equal(5); + }); + + test("cached writes keep their values when the packed storage fills up", () => { + const length = 5000; + const packed = new PackedArray(length); + const model = new StaticArray(length); + for (let i = 0; i < length; i++) { + // the cached group gets extra writes before the unpacking one + const v = u64.MAX_VALUE - i; + packed.add(i, v); + model[i] += v; + const neighbour = i & ~7; + packed.add(neighbour, 1); + model[neighbour] += 1; + } + expect(mismatches(packed, model)).equal(0); + // and the array keeps working once unpacked + packed.set(10, 42); + model[10] = 42; + packed.increment(11); + model[11] += 1; + expect(mismatches(packed, model)).equal(0); + }); + test("physical array growth during a cached group keeps the cache valid", () => { // Small initial capacity so inserts trigger resizeArray() repeatedly. const packed = new PackedArray(8192, 16); diff --git a/assembly/packedarray/PackedArray.ts b/assembly/packedarray/PackedArray.ts index fd1ae99..0afb704 100644 --- a/assembly/packedarray/PackedArray.ts +++ b/assembly/packedarray/PackedArray.ts @@ -12,7 +12,9 @@ import { } from "./PackedArrayContext"; const NUMBER_OF_SETS: i32 = 8; -const NO_LEAF: i32 = -1; +// Leaf cache entry states, besides a leaf long index (>= 0) +const NO_LEAF: i32 = -1; // the set has no leaf for the cached group +const UNKNOWN_LEAF: i32 = -2; // the set is beyond knownSets (not looked up yet) /** * A Packed array of signed 64 bit values, and supports {@link #get get()}, {@link #set set()}, @@ -30,18 +32,28 @@ export class PackedArray { private arrayContext: PackedArrayContext; - // Leaf cache for sequential reads. + // Leaf cache for sequential reads and writes. // // The 8 virtual indexes of a group (index >> 3) share one leaf per byte set, // so a scan over consecutive indexes would otherwise repeat the same set-tree - // walks 8 times. leafIndexBySet remembers, for the group last read, the long - // index of each set's leaf (NO_LEAF when the set has no entry for that - // group). set() and add() record the leaves they insert for the cached group, - // and anything that rebuilds the context invalidates the cache. + // walks 8 times. For the group last accessed, leafIndexBySet[0 .. knownSets) + // holds the long index of each set's leaf, or NO_LEAF when the set has no + // entry for that group; sets from knownSets upwards have not been looked up + // yet (writes only walk the sets they touch), whatever leafIndexBySet holds + // there. The known sets always form a prefix because get(), add() and set() + // resolve sets from byte 0 upwards and never skip one, so evicting a group + // is a single knownSets = 0 rather than a reset of every entry, which keeps + // the miss path (random recordValue) as cheap as before the cache. A leaf + // never moves once created, so a cached leaf index stays valid for the + // lifetime of the context, and every write that creates a leaf records it, + // so a known NO_LEAF entry is always current. Any access to another group + // evicts the cached one, writes included. Anything that rebuilds the context + // invalidates the cache. private cachedGroup: i32 = -1; + private knownSets: i32 = 0; private leafIndexBySet: StaticArray = new StaticArray( NUMBER_OF_SETS - ); + ).fill(NO_LEAF); constructor( virtualLength: i32, @@ -60,6 +72,7 @@ export class PackedArray { public setVirtualLength(newVirtualArrayLength: i32): void { this.cachedGroup = -1; + this.knownSets = 0; if (newVirtualArrayLength < this.length()) { throw new Error( "Cannot set virtual length, as requested length " + @@ -108,16 +121,29 @@ export class PackedArray { return arrayContext.getAtUnpackedIndex(index); } // Context is packed: - if (index >> 3 != this.cachedGroup) { - this.fillLeafCache(index); - } - const byteInLeaf = index & 0x7; + this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; + const byteInLeaf = index & 0x7; let value: u64 = 0; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - const leafIndex = unchecked(leafIndexBySet[byteNum]); - if (leafIndex == NO_LEAF) { - break; + let leafIndex = + byteNum < this.knownSets + ? unchecked(leafIndexBySet[byteNum]) + : UNKNOWN_LEAF; + if (leafIndex < 0) { + // Sets are populated from byte 0 upwards (see set() and add()), so once + // a set has no leaf for this group the higher sets have none either. + if (leafIndex == NO_LEAF) { + break; + } + const packedIndex = arrayContext.getPackedIndex(byteNum, index, false); + this.knownSets = byteNum + 1; + if (packedIndex < 0) { + unchecked((leafIndexBySet[byteNum] = NO_LEAF)); + break; + } + leafIndex = packedIndex >> 3; + unchecked((leafIndexBySet[byteNum] = leafIndex)); } value |= (arrayContext.getAtByteIndex((leafIndex << 3) + byteInLeaf)) << @@ -127,33 +153,22 @@ export class PackedArray { } /** - * Walk the set trees once for the group of 8 indexes containing `index`, and - * remember the leaf of every set that has one. + * Make the group of 8 indexes containing `index` the cached one, its leaves + * to be looked up on demand. */ - private fillLeafCache(index: i32): void { - const arrayContext = this.arrayContext; - const leafIndexBySet = this.leafIndexBySet; - let byteNum = 0; - for (; byteNum < NUMBER_OF_SETS; byteNum++) { - const packedIndex = arrayContext.getPackedIndex(byteNum, index, false); - if (packedIndex < 0) { - break; - } - unchecked((leafIndexBySet[byteNum] = packedIndex >> 3)); - } - // Sets are populated from byte 0 upwards (see set() and add()), so once a - // set has no leaf for this group the higher sets have none either. - for (; byteNum < NUMBER_OF_SETS; byteNum++) { - unchecked((leafIndexBySet[byteNum] = NO_LEAF)); - } - this.cachedGroup = index >> 3; - } - - /** Keep the leaf cache coherent with a leaf just looked up with insertAsNeeded. */ @inline - private noteLeaf(index: i32, byteNum: i32, packedIndex: i32): void { - if (index >> 3 == this.cachedGroup) { - unchecked((this.leafIndexBySet[byteNum] = packedIndex >> 3)); + private cacheGroupOf(index: i32): void { + const group = index >> 3; + if (group != this.cachedGroup) { + // No set is known after a miss, so every access walks set 0 first, and + // getPackedIndex() checks the virtualLength bound there. + this.cachedGroup = group; + this.knownSets = 0; + } else if (index >= this.arrayContext.getVirtualLength()) { + // A hit skips the walk, and the last group may be partly beyond the bound + throw new Error( + `Attempting access at index ${index}, beyond virtualLength ${this.arrayContext.getVirtualLength()}` + ); } } @@ -165,13 +180,6 @@ export class PackedArray { this.add(index, 1); } - private safeGetPackedIndexgetPackedIndex( - setNumber: i32, - virtualIndex: i32 - ): i32 { - return this.arrayContext.getPackedIndex(setNumber, virtualIndex, true); - } - /** * Add to a value at a virtual index in the array * @param index the virtual index of the value to be added to @@ -185,23 +193,37 @@ export class PackedArray { return; } // Context is packed: + this.cacheGroupOf(index); + const leafIndexBySet = this.leafIndexBySet; + const byteInLeaf = index & 0x7; let remainingValueToAdd = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - const packedIndex = this.safeGetPackedIndexgetPackedIndex(byteNum, index); - if (packedIndex < 0) { - // The packed storage is full, the lower bytes have already been added - this.unpack(); - this.arrayContext.addAndGetAtUnpackedIndex( - index, - remainingValueToAdd << (byteNum << 3) - ); - return; + let leafIndex = + byteNum < this.knownSets + ? unchecked(leafIndexBySet[byteNum]) + : UNKNOWN_LEAF; + if (leafIndex < 0) { + // Make sure byte is populated: + const packedIndex = arrayContext.getPackedIndex(byteNum, index, true); + if (packedIndex < 0) { + // The packed storage is full, the lower bytes have already been added + this.unpack(); + this.arrayContext.addAndGetAtUnpackedIndex( + index, + remainingValueToAdd << (byteNum << 3) + ); + return; + } + leafIndex = packedIndex >> 3; + unchecked((leafIndexBySet[byteNum] = leafIndex)); + // A known NO_LEAF is always the last known set (get() and a zero set() + // stop there), so this never shrinks the prefix. + this.knownSets = byteNum + 1; } - this.noteLeaf(index, byteNum, packedIndex); const byteToAdd = (remainingValueToAdd & 0xff); const afterAddByteValue = arrayContext.addAtByteIndex( - packedIndex, + (leafIndex << 3) + byteInLeaf, byteToAdd ); @@ -228,30 +250,50 @@ export class PackedArray { return; } // Context is packed: + this.cacheGroupOf(index); + const leafIndexBySet = this.leafIndexBySet; + const byteInLeaf = index & 0x7; let valueForNextLevels = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - if (valueForNextLevels == 0) { - // Special-case zeros to avoid inflating packed array for no reason - const packedIndex = arrayContext.getPackedIndex(byteNum, index, false); - if (packedIndex < 0) { - return; // no need to create entries for zero values if they don't already exist + let leafIndex = + byteNum < this.knownSets + ? unchecked(leafIndexBySet[byteNum]) + : UNKNOWN_LEAF; + if (leafIndex < 0) { + let packedIndex: i32; + if (valueForNextLevels == 0) { + // Special-case zeros to avoid inflating packed array for no reason + if (leafIndex == NO_LEAF) { + return; // no need to create entries for zero values if they don't already exist + } + packedIndex = arrayContext.getPackedIndex(byteNum, index, false); + if (packedIndex < 0) { + unchecked((leafIndexBySet[byteNum] = NO_LEAF)); + this.knownSets = byteNum + 1; + return; + } + } else { + // Make sure byte is populated: + packedIndex = arrayContext.getPackedIndex(byteNum, index, true); + if (packedIndex < 0) { + // The packed storage is full + this.unpack(); + this.arrayContext.setAtUnpackedIndex(index, value); + return; + } } + leafIndex = packedIndex >> 3; + unchecked((leafIndexBySet[byteNum] = leafIndex)); + // A known NO_LEAF is always the last known set (get() and a zero set() + // stop there), so this never shrinks the prefix. + this.knownSets = byteNum + 1; } - // Make sure byte is populated: - const packedIndex = arrayContext.getPackedIndex(byteNum, index, true); - if (packedIndex < 0) { - // The packed storage is full - this.unpack(); - this.arrayContext.setAtUnpackedIndex(index, value); - return; - } - this.noteLeaf(index, byteNum, packedIndex); // Determine value to write, and prepare for next levels const byteToWrite: u8 = (valueForNextLevels & 0xff); valueForNextLevels = valueForNextLevels >> 8; - arrayContext.setAtByteIndex(packedIndex, byteToWrite); + arrayContext.setAtByteIndex((leafIndex << 3) + byteInLeaf, byteToWrite); } } @@ -293,6 +335,7 @@ export class PackedArray { */ public clear(): void { this.cachedGroup = -1; + this.knownSets = 0; this.arrayContext.clear(); } diff --git a/src/packedarray/PackedArray.fc.spec.ts b/src/packedarray/PackedArray.fc.spec.ts index 7abf2f8..2328e90 100644 --- a/src/packedarray/PackedArray.fc.spec.ts +++ b/src/packedarray/PackedArray.fc.spec.ts @@ -39,5 +39,113 @@ describe("Packed array", () => { }); }); +describe("Packed array leaf cache", () => { + it("should match a plain array under interleaved operations within a few groups", () => { + // 4 groups of 8 indexes: most operations hit the cached group, with + // writes touching sets the cache has not looked up yet, carries across + // sets, and sets to smaller values (including 0) clearing higher bytes + const SIZE = 32; + fc.assert( + fc.property(arbOperations(SIZE), (operations) => { + const packedArray = new PackedArray(SIZE); + const model = new Array(SIZE).fill(0); + for (const operation of operations) { + const { index } = operation; + switch (operation.type) { + case "add": + packedArray.add(index, operation.value); + model[index] += operation.value; + break; + case "increment": + packedArray.increment(index); + model[index] += 1; + break; + case "set": + packedArray.set(index, operation.value); + model[index] = operation.value; + break; + case "get": + if (packedArray.get(index) !== model[index]) { + return false; + } + break; + } + } + return model.every((value, index) => packedArray.get(index) === value); + }), + runnerOptions + ); + }); + + it("should keep values once cached writes fill up the packed storage", () => { + // 7 byte values at every index need far more storage than the + // 16 bit indexes of a packed context can address + const SIZE = 5000; + fc.assert( + fc.property(arbOperations(SIZE), (operations) => { + const packedArray = new PackedArray(SIZE); + const model = new Array(SIZE).fill(0); + for (let index = 0; index < SIZE; index++) { + // cached write (same group as the previous index) when the packed + // storage becomes full + const value = Number.MAX_SAFE_INTEGER - index; + packedArray.add(index, value); + model[index] += value; + for (const operation of operations) { + if (operation.index >> 3 !== index >> 3) { + continue; + } + if (operation.type === "set") { + packedArray.set(operation.index, operation.value); + model[operation.index] = operation.value; + } else if ( + operation.type === "add" && + model[operation.index] + operation.value <= + Number.MAX_SAFE_INTEGER + ) { + packedArray.add(operation.index, operation.value); + model[operation.index] += operation.value; + } + } + } + return model.every((value, index) => packedArray.get(index) === value); + }), + { ...runnerOptions, numRuns: runFromStryker ? 2 : 20 } + ); + }); +}); + const arbData = (size: number) => - fc.array(fc.tuple(fc.integer({ min: 1, max: size }), fc.integer({ min: 1, max: 100000000 })), { minLength: 1, maxLength: size }); + fc.array( + fc.tuple( + fc.integer({ min: 1, max: size }), + fc.integer({ min: 1, max: 100000000 }) + ), + { minLength: 1, maxLength: size } + ); + +const arbOperations = (size: number) => { + const arbIndex = fc.integer({ min: 0, max: size - 1 }); + // up to 5 bytes, so that carries and sets to smaller values span several sets + const arbValue = fc.oneof( + fc.integer({ min: 0, max: 300 }), + fc.integer({ min: 0, max: 2 ** 40 }) + ); + return fc.array( + fc.oneof( + fc.record({ + type: fc.constant("add" as const), + index: arbIndex, + value: arbValue, + }), + fc.record({ type: fc.constant("increment" as const), index: arbIndex }), + fc.record({ + type: fc.constant("set" as const), + index: arbIndex, + value: arbValue, + }), + fc.record({ type: fc.constant("get" as const), index: arbIndex }) + ), + { minLength: 1, maxLength: 200 } + ); +}; diff --git a/src/packedarray/PackedArray.spec.ts b/src/packedarray/PackedArray.spec.ts index 2489a7b..5379646 100644 --- a/src/packedarray/PackedArray.spec.ts +++ b/src/packedarray/PackedArray.spec.ts @@ -280,4 +280,19 @@ describe("Packed array leaf cache", () => { array.clear(); expect(array.get(3)).toBe(0); }); + + it("Should reject indexes beyond the virtual length in a cached group", () => { + // given a 30-long array whose last group (indexes 24..31) is in the leaf cache + const array = new PackedArray(30); + array.add(24, 0x1ff); + // then indexes 30 and 31 belong to the cached group but not to the array + expect(() => array.add(31, 5)).toThrow(/beyond virtualLength 30/); + expect(() => array.set(31, 7)).toThrow(/beyond virtualLength 30/); + expect(() => array.increment(30)).toThrow(/beyond virtualLength 30/); + expect(() => array.get(31)).toThrow(/beyond virtualLength 30/); + expect(() => array.get(30)).toThrow(/beyond virtualLength 30/); + // and in-range accesses are unaffected + expect(array.get(24)).toBe(0x1ff); + expect(array.get(29)).toBe(0); + }); }); diff --git a/src/packedarray/PackedArray.ts b/src/packedarray/PackedArray.ts index 8ab8947..631edcb 100644 --- a/src/packedarray/PackedArray.ts +++ b/src/packedarray/PackedArray.ts @@ -11,7 +11,9 @@ import { } from "./PackedArrayContext"; const NUMBER_OF_SETS = 8; -const NO_LEAF = -1; +// Leaf cache entry states, besides a leaf long index (>= 0) +const NO_LEAF = -1; // the set has no leaf for the cached group +const UNKNOWN_LEAF = -2; // the set is beyond knownSets (not looked up yet) const { floor } = Math; // 256^byteNum, the weight of each set's byte in a 64 bit value const BYTE_WEIGHTS = [0, 1, 2, 3, 4, 5, 6, 7].map((n) => 256 ** n); @@ -30,15 +32,25 @@ const BYTE_WEIGHTS = [0, 1, 2, 3, 4, 5, 6, 7].map((n) => 256 ** n); export class PackedArray { private arrayContext: PackedArrayContext; - // Leaf cache for sequential reads. + // Leaf cache for sequential reads and writes. // // The 8 virtual indexes of a group (index >> 3) share one leaf per byte set, // so a scan over consecutive indexes would otherwise repeat the same set-tree - // walks 8 times. leafIndexBySet remembers, for the group last read, the long - // index of each set's leaf (NO_LEAF when the set has no entry for that - // group). set() and add() record the leaves they insert for the cached group, - // and anything that rebuilds the context invalidates the cache. + // walks 8 times. For the group last accessed, leafIndexBySet[0 .. knownSets) + // holds the long index of each set's leaf, or NO_LEAF when the set has no + // entry for that group; sets from knownSets upwards have not been looked up + // yet (writes only walk the sets they touch), whatever leafIndexBySet holds + // there. The known sets always form a prefix because get(), add() and set() + // resolve sets from byte 0 upwards and never skip one, so evicting a group + // is a single knownSets = 0 rather than a reset of every entry, which keeps + // the miss path (random recordValue) as cheap as before the cache. A leaf + // never moves once created, so a cached leaf index stays valid for the + // lifetime of the context, and every write that creates a leaf records it, + // so a known NO_LEAF entry is always current. Any access to another group + // evicts the cached one, writes included. Anything that rebuilds the context + // invalidates the cache. private cachedGroup = -1; + private knownSets = 0; private leafIndexBySet: number[] = new Array(NUMBER_OF_SETS).fill(NO_LEAF); constructor( @@ -53,6 +65,7 @@ export class PackedArray { public setVirtualLength(newVirtualArrayLength: number) { this.cachedGroup = -1; + this.knownSets = 0; if (newVirtualArrayLength < this.length()) { throw new Error( "Cannot set virtual length, as requested length " + @@ -93,17 +106,27 @@ export class PackedArray { return arrayContext.getAtUnpackedIndex(index); } // Context is packed: - const group = floor(index / 8); - if (group !== this.cachedGroup) { - this.fillLeafCache(index, group); - } - const byteInLeaf = index & 0x7; + this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; + const byteInLeaf = index & 0x7; let value = 0; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - const leafIndex = leafIndexBySet[byteNum]; - if (leafIndex === NO_LEAF) { - break; + let leafIndex = + byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; + if (leafIndex < 0) { + // Sets are populated from byte 0 upwards (see set() and add()), so once + // a set has no leaf for this group the higher sets have none either. + if (leafIndex === NO_LEAF) { + break; + } + const packedIndex = arrayContext.getPackedIndex(byteNum, index, false); + this.knownSets = byteNum + 1; + if (packedIndex < 0) { + leafIndexBySet[byteNum] = NO_LEAF; + break; + } + leafIndex = packedIndex >> 3; + leafIndexBySet[byteNum] = leafIndex; } value += arrayContext.getAtByteIndex(leafIndex * 8 + byteInLeaf) * @@ -113,32 +136,21 @@ export class PackedArray { } /** - * Walk the set trees once for the group of 8 indexes containing `index`, and - * remember the leaf of every set that has one. + * Make the group of 8 indexes containing `index` the cached one, its leaves + * to be looked up on demand. */ - private fillLeafCache(index: number, group: number) { - const arrayContext = this.arrayContext; - const leafIndexBySet = this.leafIndexBySet; - let byteNum = 0; - for (; byteNum < NUMBER_OF_SETS; byteNum++) { - const packedIndex = arrayContext.getPackedIndex(byteNum, index, false); - if (packedIndex < 0) { - break; - } - leafIndexBySet[byteNum] = packedIndex >> 3; - } - // Sets are populated from byte 0 upwards (see set() and add()), so once a - // set has no leaf for this group the higher sets have none either. - for (; byteNum < NUMBER_OF_SETS; byteNum++) { - leafIndexBySet[byteNum] = NO_LEAF; - } - this.cachedGroup = group; - } - - /** Keep the leaf cache coherent with a leaf just looked up with insertAsNeeded. */ - private noteLeaf(index: number, byteNum: number, packedIndex: number) { - if (floor(index / 8) === this.cachedGroup) { - this.leafIndexBySet[byteNum] = packedIndex >> 3; + private cacheGroupOf(index: number) { + const group = floor(index / 8); + if (group !== this.cachedGroup) { + // No set is known after a miss, so every access walks set 0 first, and + // getPackedIndex() checks the virtualLength bound there. + this.cachedGroup = group; + this.knownSets = 0; + } else if (index >= this.arrayContext.getVirtualLength()) { + // A hit skips the walk, and the last group may be partly beyond the bound + throw new Error( + `Attempting access at index ${index}, beyond virtualLength ${this.arrayContext.getVirtualLength()}` + ); } } @@ -150,13 +162,6 @@ export class PackedArray { this.add(index, 1); } - private safeGetPackedIndexgetPackedIndex( - setNumber: number, - virtualIndex: number - ) { - return this.arrayContext.getPackedIndex(setNumber, virtualIndex, true); - } - /** * Add to a value at a virtual index in the array * @param index the virtual index of the value to be added to @@ -170,24 +175,36 @@ export class PackedArray { return; } // Context is packed: + this.cacheGroupOf(index); + const leafIndexBySet = this.leafIndexBySet; + const byteInLeaf = index & 0x7; let remainingValueToAdd = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - const packedIndex = this.safeGetPackedIndexgetPackedIndex(byteNum, index); - if (packedIndex < 0) { - // The packed storage is full, the lower bytes have already been added - this.unpack(); - this.arrayContext.addAndGetAtUnpackedIndex( - index, - remainingValueToAdd * BYTE_WEIGHTS[byteNum] - ); - return; + let leafIndex = + byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; + if (leafIndex < 0) { + // Make sure byte is populated: + const packedIndex = arrayContext.getPackedIndex(byteNum, index, true); + if (packedIndex < 0) { + // The packed storage is full, the lower bytes have already been added + this.unpack(); + this.arrayContext.addAndGetAtUnpackedIndex( + index, + remainingValueToAdd * BYTE_WEIGHTS[byteNum] + ); + return; + } + leafIndex = packedIndex >> 3; + leafIndexBySet[byteNum] = leafIndex; + // A known NO_LEAF is always the last known set (get() and a zero set() + // stop there), so this never shrinks the prefix. + this.knownSets = byteNum + 1; } - this.noteLeaf(index, byteNum, packedIndex); // The low byte survives the int32 conversion, even above 2^32 const byteToAdd = remainingValueToAdd & 0xff; const afterAddByteValue = arrayContext.addAtByteIndex( - packedIndex, + leafIndex * 8 + byteInLeaf, byteToAdd ); @@ -214,30 +231,48 @@ export class PackedArray { return; } // Context is packed: + this.cacheGroupOf(index); + const leafIndexBySet = this.leafIndexBySet; + const byteInLeaf = index & 0x7; let valueForNextLevels = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - if (valueForNextLevels === 0) { - // Special-case zeros to avoid inflating packed array for no reason - const packedIndex = arrayContext.getPackedIndex(byteNum, index, false); - if (packedIndex < 0) { - return; // no need to create entries for zero values if they don't already exist + let leafIndex = + byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; + if (leafIndex < 0) { + let packedIndex: number; + if (valueForNextLevels === 0) { + // Special-case zeros to avoid inflating packed array for no reason + if (leafIndex === NO_LEAF) { + return; // no need to create entries for zero values if they don't already exist + } + packedIndex = arrayContext.getPackedIndex(byteNum, index, false); + if (packedIndex < 0) { + leafIndexBySet[byteNum] = NO_LEAF; + this.knownSets = byteNum + 1; + return; + } + } else { + // Make sure byte is populated: + packedIndex = arrayContext.getPackedIndex(byteNum, index, true); + if (packedIndex < 0) { + // The packed storage is full + this.unpack(); + this.arrayContext.setAtUnpackedIndex(index, value); + return; + } } + leafIndex = packedIndex >> 3; + leafIndexBySet[byteNum] = leafIndex; + // A known NO_LEAF is always the last known set (get() and a zero set() + // stop there), so this never shrinks the prefix. + this.knownSets = byteNum + 1; } - // Make sure byte is populated: - const packedIndex = arrayContext.getPackedIndex(byteNum, index, true); - if (packedIndex < 0) { - // The packed storage is full - this.unpack(); - this.arrayContext.setAtUnpackedIndex(index, value); - return; - } - this.noteLeaf(index, byteNum, packedIndex); // Determine value to write, and prepare for next levels const byteToWrite = valueForNextLevels & 0xff; valueForNextLevels = floor(valueForNextLevels / 256); - arrayContext.setAtByteIndex(packedIndex, byteToWrite); + arrayContext.setAtByteIndex(leafIndex * 8 + byteInLeaf, byteToWrite); } } @@ -274,6 +309,7 @@ export class PackedArray { */ public clear() { this.cachedGroup = -1; + this.knownSets = 0; this.arrayContext.clear(); }