From 692bfe4ace7089ade6bcbb69462381c13b346877 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 08:29:01 +0100 Subject: [PATCH] perf: 16 byte leaves for set 0 of the packed array Set 0 (the dense low byte) gets 16 byte leaves, so its set tree is one level shallower for some virtual lengths. Sets 1..7 keep 8 byte leaves. Each set has its own leaf shift and top level shift; the leaf cache stores long indexes as before. Encoded bytes do not change. The leaf cache keeps set 0's entry across the two 8 index groups of a 16 index block, so sequential scans walk set 0 once per block. Measured with src/bench/packed-leaves.bench.ts, master vs branch, three alternating runs each (hz = iterations per second, 200k records each): - record centre band: ~49.7 -> ~64.3 (about +29%) - record sparse tails: ~42.9 -> ~58.3 (about +36%) - sequential get, sparse (N=4096): ~12.8k -> ~18.6k (about +45%) - sequential get, centre (N=16384): ~6.4k -> ~8.0k (about +26%) Memory cost: isolated values reach the unpacked fallback later at virtual lengths 2^13..2^15 and sooner at 2^16 and 2^17 (about 16-18% fewer distinct values before fallback). Co-Authored-By: Claude Fable 5.1 --- .../__tests__/PackedArrayWideLeaves.test.ts | 135 +++++++++++++ assembly/packedarray/PackedArray.ts | 46 +++-- assembly/packedarray/PackedArrayContext.ts | 190 +++++++++++++----- src/PackedHistogram.encoding.spec.ts | 55 +++++ src/bench/packed-leaves.bench.ts | 61 ++++++ src/packedarray/PackedArray.ts | 55 ++--- .../PackedArray.wideLeaves.spec.ts | 173 ++++++++++++++++ src/packedarray/PackedArrayContext.ts | 165 +++++++++++---- 8 files changed, 739 insertions(+), 141 deletions(-) create mode 100644 assembly/__tests__/PackedArrayWideLeaves.test.ts create mode 100644 src/PackedHistogram.encoding.spec.ts create mode 100644 src/bench/packed-leaves.bench.ts create mode 100644 src/packedarray/PackedArray.wideLeaves.spec.ts diff --git a/assembly/__tests__/PackedArrayWideLeaves.test.ts b/assembly/__tests__/PackedArrayWideLeaves.test.ts new file mode 100644 index 0000000..2be7d51 --- /dev/null +++ b/assembly/__tests__/PackedArrayWideLeaves.test.ts @@ -0,0 +1,135 @@ +/* + * This is a AssemblyScript port of the original Java version, which was written by + * Gil Tene as described in + * https://github.com/HdrHistogram/HdrHistogram + * and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +import { describe, test, expect } from "assemblyscript-unittest-framework/assembly"; +import { PackedArray } from "../packedarray/PackedArray"; + +// Set 0 of a packed array uses 16 byte leaves: these tests cover the resize, sharing, +// fallback and random paths that the wider leaves change. +describe("Packed Array with 16 byte leaves for set 0", () => { + test("should keep values when a resize changes the depth of the set trees", () => { + // given: the set 0 tree gets one more level past 2^12, the others past 2^10 + const array = new PackedArray(1000, 16); + array.set(0, 1); + array.set(17, 300); + array.set(255, 70000); + array.set(700, 1099511627781); + array.set(999, 42); + + // when + array.setVirtualLength(8192); + array.set(8000, 5); + + // then + expect(array.get(0)).equal(1); + expect(array.get(17)).equal(300); + expect(array.get(255)).equal(70000); + expect(array.get(700)).equal(1099511627781); + expect(array.get(999)).equal(42); + expect(array.get(8000)).equal(5); + expect(array.get(4096)).equal(0); + }); + + test("should share one leaf between the indexes of a 16 index block", () => { + // given + const array = new PackedArray(1024, 16); + array.set(16, 1); + const physicalLength = array.getPhysicalLength(); + + // when: the other 15 indexes of the block are written, in both 8 index groups + for (let index = 17; index < 32; index++) { + array.set(index, index); + } + + // then + expect(array.getPhysicalLength()).equal(physicalLength); + expect(array.get(16)).equal(1); + for (let index = 17; index < 32; index++) { + expect(array.get(index)).equal(index); + } + }); + + test("should keep set 0 coherent when alternating between the two groups of a 16 index block", () => { + // given: group 0 is cached with no leaf, then group 1 of the same block gets one + const array = new PackedArray(1024, 16); + expect(array.get(3)).equal(0); + array.set(9, 5); + + // when / then: back to group 0 of the block, which now shares the leaf + expect(array.get(3)).equal(0); + expect(array.get(9)).equal(5); + array.add(2, 7); + expect(array.get(2)).equal(7); + expect(array.get(9)).equal(5); + array.set(1, 0); + expect(array.get(1)).equal(0); + }); + + test("should keep values once the packed storage falls back to unpacked", () => { + // given: isolated values, one leaf each, until the 16 bit addresses run out + const length: i32 = 1 << 16; + const array = new PackedArray(length, 16); + const plain = new Array(length); + for (let i = 0; i < length; i++) plain[i] = 0; + for (let i = 0; i < 20000 && array.getPhysicalLength() <= 8191; i++) { + const index = (i * 7919) % length; + array.add(index, (i + 1)); + plain[index] += (i + 1); + } + + // then + expect(array.getPhysicalLength() > 8191).equal(true); + for (let index = 0; index < length; index++) { + expect(array.get(index)).equal(plain[index]); + } + }); + + test("should match a plain array across the depth thresholds of the set trees", () => { + const lengths: i32[] = [1000, 4096, 4097, 8192, 8193, 40000]; + let seed: u32 = 2024; + for (let l = 0; l < lengths.length; l++) { + const length = lengths[l]; + // given + const array = new PackedArray(length, 16); + const plain = new Array(length); + for (let i = 0; i < length; i++) plain[i] = 0; + + // when: a hot band, isolated values, carries into the next sets + for (let k = 0; k < 20000; k++) { + seed = seed * 1664525 + 1013904223; + const hot = (seed >>> 8) % 2 == 0; + seed = seed * 1664525 + 1013904223; + const index = hot + ? min(length - 1, 100 + ((seed >>> 8) % 40)) + : ((seed >>> 8) % length); + seed = seed * 1664525 + 1013904223; + const value: u64 = (seed >>> 8) % 5 == 0 ? 250 + ((seed >>> 8) % 10) : 1; + array.add(index, value); + plain[index] += value; + } + + // then + for (let index = 0; index < length; index++) { + expect(array.get(index)).equal(plain[index]); + } + } + }); + + test("should print every byte of a 16 byte set 0 leaf", () => { + // given: index 15 is the last byte of the first set 0 leaf + const array = new PackedArray(16, 16); + array.set(15, 0xab); + + // when + const output = array.toString(); + + // then + expect(output.includes("Set 0: root")).equal(true); + expect(output.includes("0xab")).equal(true); + }); +}); diff --git a/assembly/packedarray/PackedArray.ts b/assembly/packedarray/PackedArray.ts index a80f0f6..b1d7ae7 100644 --- a/assembly/packedarray/PackedArray.ts +++ b/assembly/packedarray/PackedArray.ts @@ -9,6 +9,7 @@ import { PackedArrayContext, MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY, + LEAF_BYTE_MASK_BY_SET, } from "./PackedArrayContext"; const NUMBER_OF_SETS: i32 = 8; @@ -34,7 +35,8 @@ export class PackedArray { // Leaf cache for sequential reads and writes. // - // The 8 virtual indexes of a group (index >> 3) share one leaf per byte set, + // The 8 virtual indexes of a group (index >> 3) share one leaf per byte set + // (set 0 leaves are 16 bytes and cover two groups, the cache still holds one group), // so a scan over consecutive indexes would otherwise repeat the same set-tree // 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 @@ -87,9 +89,7 @@ export class PackedArray { return; } if ( - currentArrayContext.determineTopLevelShiftForVirtualLength( - newVirtualArrayLength - ) == currentArrayContext.getTopLevelShift() + currentArrayContext.hasTopLevelShiftsFor(newVirtualArrayLength) ) { // No changes to the array context contents is needed. Just change the virtual length. currentArrayContext.setVirtualLength(newVirtualArrayLength); @@ -123,9 +123,9 @@ export class PackedArray { // Context is packed: 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 byteInLeaf = index & LEAF_BYTE_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -142,7 +142,7 @@ export class PackedArray { unchecked((leafIndexBySet[byteNum] = NO_LEAF)); break; } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 3; unchecked((leafIndexBySet[byteNum] = leafIndex)); } value |= @@ -158,18 +158,20 @@ export class PackedArray { */ @inline 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 + // The last group may be partly beyond the bound, and a hit skips the walk + if (index >= this.arrayContext.getVirtualLength()) { throw new Error( `Attempting access at index ${index}, beyond virtualLength ${this.arrayContext.getVirtualLength()}` ); } + const group = index >> 3; + if (group != this.cachedGroup) { + // Set 0 leaves cover 16 indexes, two groups: its entry stays valid when the + // new group is in the same block. Any other set walks again. + this.knownSets = + group >> 1 == this.cachedGroup >> 1 ? min(this.knownSets, 1) : 0; + this.cachedGroup = group; + } } /** @@ -195,9 +197,9 @@ export class PackedArray { // 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 byteInLeaf = index & LEAF_BYTE_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -214,7 +216,7 @@ export class PackedArray { ); return; } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 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. @@ -252,9 +254,9 @@ export class PackedArray { // 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++) { + const byteInLeaf = index & LEAF_BYTE_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -282,7 +284,7 @@ export class PackedArray { return; } } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 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. @@ -300,8 +302,8 @@ export class PackedArray { /** * Lowest index >= fromIndex holding a non-zero value, or -1 when there is none. * - * On a packed context the set-0 tree is walked to skip the groups of 8 - * indexes that were never populated, so a scan over the whole array costs + * On a packed context the set-0 tree is walked to skip the groups of + * indexes (one set-0 leaf each) that were never populated, so a scan over the whole array costs * time proportional to the populated groups rather than to the virtual * length. An unpacked context is scanned linearly. */ @@ -322,8 +324,8 @@ export class PackedArray { if (index < 0) { return -1; } - // The leaf found only vouches for the group of 8 indexes holding index - const groupEnd = min((index | 0x7) + 1, length); + // The leaf found only vouches for the group of indexes sharing its set-0 leaf + const groupEnd = min((index | LEAF_BYTE_MASK_BY_SET[0]) + 1, length); for (; index < groupEnd; index++) { if (this.get(index) != 0) { return index; diff --git a/assembly/packedarray/PackedArrayContext.ts b/assembly/packedarray/PackedArrayContext.ts index 8e32fd8..19b75d9 100644 --- a/assembly/packedarray/PackedArrayContext.ts +++ b/assembly/packedarray/PackedArrayContext.ts @@ -30,7 +30,26 @@ export const MAX_SUPPORTED_PACKED_COUNTS_ARRAY_LENGTH: i32 = 8191; const SET_0_START_INDEX = 0; const NUMBER_OF_SETS = 8; - const LEAF_LEVEL_SHIFT = 3; + // A leaf of a set covers the 2^leafLevelShift virtual indexes sharing their high bits. + // Set 0 is the dense byte (most recorded values only use it), so its leaves are 16 bytes wide: + // the set tree is one level shallower for some virtual lengths. The other sets keep 8 bytes, + // as a populated leaf costs its whole width. + const LEAF_LEVEL_SHIFT: i32 = 3; + const SET_0_LEAF_LEVEL_SHIFT: i32 = 4; + export const LEAF_LEVEL_SHIFT_BY_SET: StaticArray = [ + SET_0_LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT + ]; + // Mask of the virtual index bits selecting the byte within a leaf, per set + export const LEAF_BYTE_MASK_BY_SET: StaticArray = [15, 7, 7, 7, 7, 7, 7, 7]; + // Length of a leaf in longs (8 bytes each), per set + const LEAF_LENGTH_IN_LONGS_BY_SET: StaticArray = [2, 1, 1, 1, 1, 1, 1, 1]; const NON_LEAF_ENTRY_SLOT_INDICATORS_OFFSET = 0; const NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS = 1; const PACKED_ARRAY_GROWTH_INCREMENT = 16; @@ -52,7 +71,10 @@ private dataStart: usize = 0; private populatedShortLength: i32 = 0; private virtualLength: i32; - private topLevelShift: i32 = i32.MAX_VALUE; // Make it non-sensical until properly initialized. + // Per set, make it non-sensical until properly initialized. + private topLevelShiftBySet: StaticArray = new StaticArray( + NUMBER_OF_SETS + ).fill(i32.MAX_VALUE); constructor(virtualLength: i32, initialPhysicalLength: i32) { this.physicalLength = ( @@ -245,18 +267,23 @@ return newEntryIndex; } - /** @return the long index of the new leaf, or -1 if the array is full */ - private newLeafEntry(): i32 { + /** + * @param lengthInLongs the length of the leaf, 1 for an 8 byte leaf + * @return the long index of the new leaf, or -1 if the array is full + */ + private newLeafEntry(lengthInLongs: i32): i32 { // Add entry at the end of the array: let newEntryIndex = this.getPopulatedLongLength(); - if (!this.expandArrayIfNeeded(1)) { + if (!this.expandArrayIfNeeded(lengthInLongs)) { return -1; } - this.setPopulatedLongLength(newEntryIndex + 1); - - this.setAtLongIndex(newEntryIndex, 0); - + this.setPopulatedLongLength(newEntryIndex + lengthInLongs); + + for (let i = 0; i < lengthInLongs; i++) { + this.setAtLongIndex(newEntryIndex + i, 0); + } + return newEntryIndex; } @@ -308,6 +335,7 @@ * @param insertedSlotIndex realtive [packed] index of slot being inserted into entry * @param insertedSlotMask mask value fo slot being inserted * @param nextLevelIsLeaf the level below this one is a leaf level + * @param leafLengthInLongs the length of the leaves, when the level below is a leaf level * @return the updated index of the entry, or -1 if the array is full (the entry is then left untouched) */ expandEntry( @@ -315,7 +343,8 @@ entryPointerIndex: i32, insertedSlotIndex: i32, insertedSlotMask: i32, - nextLevelIsLeaf: boolean + nextLevelIsLeaf: boolean, + leafLengthInLongs: i32 ): i32 { let packedSlotIndicators = (this.getAtShortIndex(existingEntryIndex)) & 0xffff; @@ -334,7 +363,7 @@ // Create new next-level entry to refer to from slot at this level: let indexOfNewNextLevelEntry = 0; if (nextLevelIsLeaf) { - indexOfNewNextLevelEntry = this.newLeafEntry(); // Establish long-index to new leaf entry + indexOfNewNextLevelEntry = this.newLeafEntry(leafLengthInLongs); // Establish long-index to new leaf entry if (indexOfNewNextLevelEntry < 0) { return -1; } @@ -435,12 +464,14 @@ } // Work down the levels of non-leaf entries: + const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; + const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[setNumber]; for ( - let indexShift = this.topLevelShift; - indexShift >= LEAF_LEVEL_SHIFT; + let indexShift = this.topLevelShiftBySet[setNumber]; + indexShift >= leafLevelShift; indexShift -= 4 ) { - const nextLevelIsLeaf = indexShift === LEAF_LEVEL_SHIFT; + const nextLevelIsLeaf = indexShift === leafLevelShift; // Target is a packedSlotIndicators entry const packedSlotIndicators = this.getPackedSlotIndicators(entryIndex); const slotBitNumber = (virtualIndex >>> indexShift) & 0xf; @@ -460,7 +491,8 @@ entryPointerIndex, slotNumber, slotMask, - nextLevelIsLeaf + nextLevelIsLeaf, + leafLengthInLongs ); if (entryIndex < 0) { return -1; // The array is full, the index cannot be added @@ -476,13 +508,15 @@ // entryIndex is the long-index of a leaf entry that contains the value byte for the given set - const byteIndex = (entryIndex << 3) + (virtualIndex & 0x7); // Determine byte index offset within leaf entry + // Byte index offset within leaf entry, the leaf entry being the long index + const byteIndex = + (entryIndex << 3) + (virtualIndex & LEAF_BYTE_MASK_BY_SET[setNumber]); return byteIndex; } /** - * Lowest virtual index >= fromIndex whose group of 8 indexes has a leaf in - * set 0, i.e. whose values may be non-zero. Groups without a leaf are all + * Lowest virtual index >= fromIndex whose group of indexes (the ones sharing + * a set-0 leaf) has a leaf in set 0, i.e. whose values may be non-zero. Groups without a leaf are all * zeros and are skipped by descending only into the populated slots of * the set-0 tree, so the walk costs time proportional to the populated * groups rather than to the virtual length. @@ -506,7 +540,7 @@ } return this.nextIndexWithLeafBelow( rootEntryIndex, - this.topLevelShift, + this.topLevelShiftBySet[0], fromIndex ); } @@ -524,7 +558,7 @@ const packedSlotIndicators = this.getPackedSlotIndicators(entryIndex); // The indexes covered by this entry share the bits above the ones its slots decode const entryBase = fromIndex & ~((1 << (indexShift + 4)) - 1); - const nextLevelIsLeaf = indexShift == LEAF_LEVEL_SHIFT; + const nextLevelIsLeaf = indexShift == LEAF_LEVEL_SHIFT_BY_SET[0]; for ( let slotBitNumber = (fromIndex >>> indexShift) & 0xf; slotBitNumber < 16; @@ -558,14 +592,35 @@ return -1; } - determineTopLevelShiftForVirtualLength(virtualLength: i32): i32 { + /** + * The top level shift of the set tree of the given set, for a virtual length: the levels of + * non-leaf entries are at shifts leafLevelShift, leafLevelShift + 4, ..., top, and the top + * level must cover the most significant bit of the virtual length, with at least two levels. + */ + determineTopLevelShiftForVirtualLength( + virtualLength: i32, + setNumber: i32 = 1 + ): i32 { + const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; const sizeMagnitude = ceil(Math.log2(virtualLength)); - const eightsSizeMagnitude = sizeMagnitude - 3; - let multipleOfFourSizeMagnitude = - ceil(eightsSizeMagnitude / 4.0) * 4; - multipleOfFourSizeMagnitude = max(multipleOfFourSizeMagnitude, 8); - const topLevelShiftNeeded = multipleOfFourSizeMagnitude - 4 + 3; - return topLevelShiftNeeded; + const levelsAboveTheFirst = max( + ceil((sizeMagnitude - leafLevelShift - 4) / 4.0), + 1 + ); + return leafLevelShift + 4 * levelsAboveTheFirst; + } + + /** @return whether the set trees of this context are laid out for the given virtual length */ + hasTopLevelShiftsFor(virtualLength: i32): boolean { + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + if ( + this.determineTopLevelShiftForVirtualLength(virtualLength, setNumber) !== + this.topLevelShiftBySet[setNumber] + ) { + return false; + } + } + return true; } setVirtualLength(virtualLength: i32): void { @@ -574,15 +629,15 @@ "Should never be adjusting the virtual size of a non-packed context" ); } - this.topLevelShift = this.determineTopLevelShiftForVirtualLength( - virtualLength - ); + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + this.topLevelShiftBySet[setNumber] = this.determineTopLevelShiftForVirtualLength( + virtualLength, + setNumber + ); + } this.virtualLength = virtualLength; } - getTopLevelShift(): i32 { - return this.topLevelShift; - } // // ## ## ######## ####### ######## ## ## ## ### ######## ######## @@ -609,11 +664,18 @@ throw new Error("Cannot populate array of smaller virtual length"); } - for (let i = 0; i < NUMBER_OF_SETS; i++) { - const otherEntryIndex = other.getAtShortIndex(SET_0_START_INDEX + i); + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + const otherEntryIndex = other.getAtShortIndex( + SET_0_START_INDEX + setNumber + ); if (otherEntryIndex == 0) continue; // No tree to duplicate - let entryIndexPointer = SET_0_START_INDEX + i; - for (let i = this.topLevelShift; i > other.topLevelShift; i -= 4) { + let entryIndexPointer = SET_0_START_INDEX + setNumber; + const otherTopLevelShift = other.topLevelShiftBySet[setNumber]; + for ( + let i = this.topLevelShiftBySet[setNumber]; + i > otherTopLevelShift; + i -= 4 + ) { // for each inserted level: // Allocate entry in other: const sizeOfEntry = NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + 1; @@ -630,7 +692,8 @@ other, otherEntryIndex, entryIndexPointer, - other.topLevelShift + otherTopLevelShift, + setNumber ); } } @@ -639,9 +702,12 @@ other: PackedArrayContext, otherLevelEntryIndex: i32, levelEntryIndexPointer: i32, - otherIndexShift: i32 + otherIndexShift: i32, + setNumber: i32 ): void { - const nextLevelIsLeaf = otherIndexShift == LEAF_LEVEL_SHIFT; + const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; + const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[setNumber]; + const nextLevelIsLeaf = otherIndexShift == leafLevelShift; const packedSlotIndicators = other.getPackedSlotIndicators( otherLevelEntryIndex ); @@ -658,7 +724,7 @@ for (let i: u8 = 0; i < numberOfSlots; i++) { if (nextLevelIsLeaf) { // Make leaf in other: - const leafEntryIndex = this.newLeafEntry(); + const leafEntryIndex = this.newLeafEntry(leafLengthInLongs); this.setIndexAtEntrySlot(entryIndex, i, leafEntryIndex); @@ -668,8 +734,10 @@ otherLevelEntryIndex, i ); - this.longArray[leafEntryIndex] = - other.longArray[otherNextLevelEntryIndex]; + for (let longNum = 0; longNum < leafLengthInLongs; longNum++) { + this.longArray[leafEntryIndex + longNum] = + other.longArray[otherNextLevelEntryIndex + longNum]; + } } else { const otherNextLevelEntryIndex = other.getIndexAtEntrySlot( otherLevelEntryIndex, @@ -679,7 +747,8 @@ other, otherNextLevelEntryIndex, entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + i, - otherIndexShift - 4 + otherIndexShift - 4, + setNumber ); } } @@ -722,7 +791,8 @@ private nonLeafEntryToString( entryIndex: i32, indexShift: i32, - indentLevel: i32 + indentLevel: i32, + leafLevelShift: i32 ): string { let output = ""; for (let i = 0; i < indentLevel; i++) { @@ -742,16 +812,21 @@ } } output += " ] (indexShift = " + indexShift.toString() + ")\n"; - const nextLevelIsLeaf = indexShift == LEAF_LEVEL_SHIFT; + const nextLevelIsLeaf = indexShift == leafLevelShift; for (let i: u8 = 0; i < numberOfslotsInEntry; i++) { const nextLevelEntryIndex = this.getIndexAtEntrySlot(entryIndex, i); if (nextLevelIsLeaf) { - output += this.leafEntryToString(nextLevelEntryIndex, indentLevel + 4); + output += this.leafEntryToString( + nextLevelEntryIndex, + indentLevel + 4, + leafLevelShift + ); } else { output += this.nonLeafEntryToString( nextLevelEntryIndex, indexShift - 4, - indentLevel + 4 + indentLevel + 4, + leafLevelShift ); } } @@ -759,14 +834,20 @@ return output; } - private leafEntryToString(entryIndex: i32, indentLevel: i32): string { + private leafEntryToString( + entryIndex: i32, + indentLevel: i32, + leafLevelShift: i32 + ): string { let output = ""; for (let i = 0; i < indentLevel; i++) { output += " "; } - + output += "Leaf bytes : "; - for (let i = 0; i < 8; i++) { + // 16 bytes for a set 0 leaf, 8 for the other sets + const leafLengthInBytes = 1 << leafLevelShift; + for (let i = 0; i < leafLengthInBytes; i++) { output += "0x" + toHex(this.byteArray[entryIndex * 8 + i]) + " "; } output += "\n"; @@ -789,7 +870,12 @@ entryIndex.toString() + " \n"; if (entryIndex == 0) continue; - output += this.nonLeafEntryToString(entryIndex, this.topLevelShift, 4); + output += this.nonLeafEntryToString( + entryIndex, + this.topLevelShiftBySet[setNumber], + 4, + LEAF_LEVEL_SHIFT_BY_SET[setNumber] + ); } //output += recordedValuesToString(); return output; diff --git a/src/PackedHistogram.encoding.spec.ts b/src/PackedHistogram.encoding.spec.ts new file mode 100644 index 0000000..59c5012 --- /dev/null +++ b/src/PackedHistogram.encoding.spec.ts @@ -0,0 +1,55 @@ +import Histogram from "./PackedHistogram"; +import { Int32Histogram } from "./index"; +import { encodeIntoCompressedBase64 } from "./encoding"; +import { initWebAssembly } from "./wasm"; + +beforeAll(() => initWebAssembly()); + +// Records the same counts in a packed histogram and in its Int32 twin: a contiguous band of +// latencies in the centre, and isolated values across the tails. +const recordBoth = () => { + const packed = new Histogram(1, 3_600_000_000, 3); + const int32 = new Int32Histogram(1, 3_600_000_000, 3); + let seed = 99; + const rand = () => { + seed = (seed * 1664525 + 1013904223) >>> 0; + return seed / 0x100000000; + }; + for (let k = 0; k < 20000; k++) { + const value = + rand() < 0.7 + ? 1_000_000 + Math.floor(rand() * 5000) + : Math.floor(rand() * 3_600_000_000); + const count = 1 + Math.floor(rand() * 300); + packed.recordValueWithCount(value, count); + int32.recordValueWithCount(value, count); + } + return { packed, int32 }; +}; + +describe("Packed histogram cross-check against Int32 histogram", () => { + it("should encode the same bytes as the Int32 histogram with the same counts", async () => { + // given + const { packed, int32 } = recordBoth(); + + // when + const packedEncoded = await encodeIntoCompressedBase64(packed); + const int32Encoded = await encodeIntoCompressedBase64(int32); + + // then + expect(packed.totalCount).toBe(int32.totalCount); + expect(packedEncoded).toBe(int32Encoded); + }); + + it("should report the same percentiles as the Int32 histogram", () => { + // given + const { packed, int32 } = recordBoth(); + + // then + for (const percentile of [1, 50, 90, 99, 99.99]) { + expect(packed.getValueAtPercentile(percentile)).toBe( + int32.getValueAtPercentile(percentile) + ); + } + }); +}); diff --git a/src/bench/packed-leaves.bench.ts b/src/bench/packed-leaves.bench.ts new file mode 100644 index 0000000..48eea26 --- /dev/null +++ b/src/bench/packed-leaves.bench.ts @@ -0,0 +1,61 @@ +import { test } from "vitest"; +import { PackedArray } from "../packedarray/PackedArray"; + +// Packed array recording and scanning, on the same seeded inputs on every branch. +// Run it on master and on the branch to compare: only the packedarray sources differ. + +// Seeded PRNG so every run and every branch sees the same indexes +const seeded = (seed: number) => () => { + seed = (seed * 1664525 + 1013904223) >>> 0; + return seed / 0x100000000; +}; + +// Sizes chosen so that neither workload falls back to unpacked storage +const N_CENTRE = 1 << 14; +const N_SPARSE = 1 << 12; +const OPS = 200_000; +const rand = seeded(42); +// contiguous latencies in the centre: a band of 512 indexes +const centre = Array.from( + { length: OPS }, + () => N_CENTRE / 2 - 256 + Math.floor(rand() * 512) +); +// isolated values across the whole range (tails and sparse) +const sparse = Array.from({ length: OPS }, () => Math.floor(rand() * N_SPARSE)); +const counts = Array.from({ length: OPS }, () => 1 + Math.floor(rand() * 3)); + +const filled = (n: number, indexes: number[]) => { + const array = new PackedArray(n, 16); + for (let i = 0; i < indexes.length; i++) array.add(indexes[i], counts[i]); + return array; +}; +const centreFilled = filled(N_CENTRE, centre); +const sparseFilled = filled(N_SPARSE, sparse); + +test("Packed array recording", async ({ bench }) => { + await bench.compare( + bench("record centre band", () => { + const array = new PackedArray(N_CENTRE, 16); + for (let i = 0; i < OPS; i++) array.add(centre[i], counts[i]); + }), + bench("record sparse tails", () => { + const array = new PackedArray(N_SPARSE, 16); + for (let i = 0; i < OPS; i++) array.add(sparse[i], counts[i]); + }) + ); +}); + +test("Packed array scans", async ({ bench }) => { + await bench.compare( + bench("sequential get, centre-filled", () => { + let sum = 0; + for (let i = 0; i < N_CENTRE; i++) sum += centreFilled.get(i); + return sum; + }), + bench("sequential get, sparse-filled", () => { + let sum = 0; + for (let i = 0; i < N_SPARSE; i++) sum += sparseFilled.get(i); + return sum; + }) + ); +}); diff --git a/src/packedarray/PackedArray.ts b/src/packedarray/PackedArray.ts index 8d2b63d..cb79435 100644 --- a/src/packedarray/PackedArray.ts +++ b/src/packedarray/PackedArray.ts @@ -8,13 +8,16 @@ import { PackedArrayContext, MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY, + LEAF_BYTE_MASK_BY_SET, } from "./PackedArrayContext"; const NUMBER_OF_SETS = 8; +// Read once: the hot loops below index a module-local array, not an import binding +const BYTE_IN_LEAF_MASK_BY_SET = LEAF_BYTE_MASK_BY_SET; // 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; +const { floor, min } = 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); @@ -34,7 +37,8 @@ export class PackedArray { // Leaf cache for sequential reads and writes. // - // The 8 virtual indexes of a group (index >> 3) share one leaf per byte set, + // The 8 virtual indexes of a group (index >> 3) share one leaf per byte set + // (set 0 leaves are 16 bytes and cover two groups, the cache still holds one group), // so a scan over consecutive indexes would otherwise repeat the same set-tree // 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 @@ -79,11 +83,7 @@ export class PackedArray { this.unpack(newVirtualArrayLength); return; } - if ( - currentArrayContext.determineTopLevelShiftForVirtualLength( - newVirtualArrayLength - ) == currentArrayContext.getTopLevelShift() - ) { + if (currentArrayContext.hasTopLevelShiftsFor(newVirtualArrayLength)) { // No changes to the array context contents is needed. Just change the virtual length. currentArrayContext.setVirtualLength(newVirtualArrayLength); return; @@ -108,9 +108,9 @@ export class PackedArray { // Context is packed: this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; - const byteInLeaf = index & 0x7; let value = 0; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { + const byteInLeaf = index & BYTE_IN_LEAF_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -125,7 +125,7 @@ export class PackedArray { leafIndexBySet[byteNum] = NO_LEAF; break; } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 3; leafIndexBySet[byteNum] = leafIndex; } value += @@ -140,18 +140,20 @@ export class PackedArray { * to be looked up on demand. */ 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 + // The last group may be partly beyond the bound, and a hit skips the walk + if (index >= this.arrayContext.getVirtualLength()) { throw new Error( `Attempting access at index ${index}, beyond virtualLength ${this.arrayContext.getVirtualLength()}` ); } + const group = floor(index / 8); + if (group !== this.cachedGroup) { + // Set 0 leaves cover 16 indexes, two groups: its entry stays valid when the + // new group is in the same block. Any other set walks again. + this.knownSets = + group >> 1 === this.cachedGroup >> 1 ? min(this.knownSets, 1) : 0; + this.cachedGroup = group; + } } /** @@ -177,9 +179,9 @@ export class PackedArray { // 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 byteInLeaf = index & BYTE_IN_LEAF_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -194,7 +196,7 @@ export class PackedArray { ); return; } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 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. @@ -233,9 +235,9 @@ export class PackedArray { // 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++) { + const byteInLeaf = index & BYTE_IN_LEAF_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -261,7 +263,7 @@ export class PackedArray { return; } } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 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. @@ -279,8 +281,8 @@ export class PackedArray { /** * Lowest index >= fromIndex holding a non-zero value, or -1 when there is none. * - * On a packed context the set-0 tree is walked to skip the groups of 8 - * indexes that were never populated, so a scan over the whole array costs + * On a packed context the set-0 tree is walked to skip the groups of + * indexes (one set-0 leaf each) that were never populated, so a scan over the whole array costs * time proportional to the populated groups rather than to the virtual * length. An unpacked context is scanned linearly. */ @@ -301,8 +303,11 @@ export class PackedArray { if (index < 0) { return -1; } - // The leaf found only vouches for the group of 8 indexes holding index - const groupEnd = Math.min((index | 0x7) + 1, length); + // The leaf found only vouches for the group of indexes sharing its set-0 leaf + const groupEnd = Math.min( + (index | BYTE_IN_LEAF_MASK_BY_SET[0]) + 1, + length + ); for (; index < groupEnd; index++) { if (this.get(index) !== 0) { return index; diff --git a/src/packedarray/PackedArray.wideLeaves.spec.ts b/src/packedarray/PackedArray.wideLeaves.spec.ts new file mode 100644 index 0000000..d533ae1 --- /dev/null +++ b/src/packedarray/PackedArray.wideLeaves.spec.ts @@ -0,0 +1,173 @@ +import { PackedArray } from "./PackedArray"; + +// Set 0 of a packed array uses 16 byte leaves: these tests cover the resize, sharing, +// fallback and iteration paths that the wider leaves change. +describe("Packed array with 16 byte leaves for set 0", () => { + // Deterministic PRNG, so that failures reproduce + const seeded = (seed: number) => () => { + seed = (seed * 1664525 + 1013904223) >>> 0; + return seed / 0x100000000; + }; + + it("should keep values when a resize changes the depth of the set trees", () => { + // given: the set 0 tree gets one more level past 2^12, the others past 2^10 + const array = new PackedArray(1000, 16); + const values = new Map([ + [0, 1], + [17, 300], + [255, 70000], + [700, 2 ** 40 + 5], + [999, 42], + ]); + values.forEach((value, index) => array.set(index, value)); + + // when + array.setVirtualLength(8192); + array.set(8000, 5); + + // then + values.forEach((value, index) => expect(array.get(index)).toBe(value)); + expect(array.get(8000)).toBe(5); + expect(array.get(4096)).toBe(0); + }); + + it("should share one leaf between the indexes of a 16 index block", () => { + // given + const array = new PackedArray(1024, 16); + array.set(16, 1); + const physicalLength = array.getPhysicalLength(); + + // when: the other 15 indexes of the block are written, in both 8 index groups + for (let index = 17; index < 32; index++) { + array.set(index, index); + } + + // then + expect(array.getPhysicalLength()).toBe(physicalLength); + expect(array.get(16)).toBe(1); + for (let index = 17; index < 32; index++) { + expect(array.get(index)).toBe(index); + } + }); + + it("should not allocate leaves when setting zeros", () => { + // given + const array = new PackedArray(1 << 12, 16); + const physicalLength = array.getPhysicalLength(); + + // when + for (let index = 0; index < 1 << 12; index++) { + array.set(index, 0); + } + + // then + expect(array.getPhysicalLength()).toBe(physicalLength); + expect(array.get(1234)).toBe(0); + }); + + it("should iterate over the non zero values of a sparse array", () => { + // given + const array = new PackedArray(1 << 12, 16); + const expected = [3, 16, 31, 32, 1000, 1015, 4095]; + expected.forEach((index) => array.increment(index)); + + // when + const nonZero: number[] = []; + for (let index = 0; index < array.length(); index++) { + if (array.get(index) !== 0) { + nonZero.push(index); + } + } + + // then + expect(nonZero).toEqual(expected); + }); + + it("should keep values once the packed storage falls back to unpacked", () => { + // given: isolated values, one leaf each, until the 16 bit addresses run out + const length = 1 << 16; + const array = new PackedArray(length, 16); + const values = new Map(); + for (let i = 0; i < 20000 && array.getPhysicalLength() <= 8191; i++) { + const index = (i * 7919) % length; + array.add(index, i + 1); + values.set(index, (values.get(index) ?? 0) + i + 1); + } + + // then + expect(array.getPhysicalLength()).toBeGreaterThan(8191); + values.forEach((value, index) => expect(array.get(index)).toBe(value)); + }); + + it("should keep set 0 coherent when alternating between the two groups of a 16 index block", () => { + // given: group 0 is cached with no leaf, then group 1 of the same block gets one + const array = new PackedArray(1024, 16); + expect(array.get(3)).toBe(0); + array.set(9, 5); + + // when / then: back to group 0 of the block, which now shares the leaf + expect(array.get(3)).toBe(0); + expect(array.get(9)).toBe(5); + array.add(2, 7); + expect(array.get(2)).toBe(7); + expect(array.get(9)).toBe(5); + array.set(1, 0); + expect(array.get(1)).toBe(0); + }); + + it("should match a plain array on random operations within a 16 index block", () => { + const rand = seeded(77); + for (let round = 0; round < 50; round++) { + // given: a small range, where most accesses switch between the two groups + const length = 64; + const array = new PackedArray(length, 16); + const plain = new Float64Array(length); + for (let k = 0; k < 2000; k++) { + const index = Math.floor(rand() * length); + const op = rand(); + if (op < 0.4) { + const value = 1 + Math.floor(rand() * 300); + array.add(index, value); + plain[index] += value; + } else if (op < 0.5) { + array.set(index, 0); + plain[index] = 0; + } else { + expect(array.get(index)).toBe(plain[index]); + } + } + for (let index = 0; index < length; index++) { + expect(array.get(index)).toBe(plain[index]); + } + } + }); + + it("should match a plain array across the depth thresholds of the set trees", () => { + const rand = seeded(2024); + for (const length of [1000, 4096, 4097, 8192, 8193, 40000]) { + // given + const array = new PackedArray(length, 16); + const plain = new Float64Array(length); + + // when: a hot band, isolated values, carries into the next sets + for (let k = 0; k < 20000; k++) { + const index = + rand() < 0.5 + ? Math.min(length - 1, 100 + Math.floor(rand() * 40)) + : Math.floor(rand() * length); + const value = rand() < 0.2 ? 250 + Math.floor(rand() * 10) : 1; + array.add(index, value); + plain[index] += value; + } + + // then + for (let index = 0; index < length; index++) { + if (array.get(index) !== plain[index]) { + throw new Error( + `length ${length}: index ${index} is ${array.get(index)}, expected ${plain[index]}` + ); + } + } + } + }); +}); diff --git a/src/packedarray/PackedArrayContext.ts b/src/packedarray/PackedArrayContext.ts index 6330b23..4ac16b9 100644 --- a/src/packedarray/PackedArrayContext.ts +++ b/src/packedarray/PackedArrayContext.ts @@ -30,7 +30,30 @@ export const MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY = 16; export const MAX_SUPPORTED_PACKED_COUNTS_ARRAY_LENGTH = 8191; const SET_0_START_INDEX = 0; const NUMBER_OF_SETS = 8; +// A leaf of a set covers the 2^leafLevelShift virtual indexes sharing their high bits. +// Set 0 is the dense byte (most recorded values only use it), so its leaves are 16 bytes wide: +// the set tree is one level shallower for some virtual lengths. The other sets keep 8 bytes, +// as a populated leaf costs its whole width. const LEAF_LEVEL_SHIFT = 3; +const SET_0_LEAF_LEVEL_SHIFT = 4; +export const LEAF_LEVEL_SHIFT_BY_SET = [ + SET_0_LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, +]; +// Mask of the virtual index bits selecting the byte within a leaf, per set +export const LEAF_BYTE_MASK_BY_SET = LEAF_LEVEL_SHIFT_BY_SET.map( + (leafLevelShift) => (1 << leafLevelShift) - 1 +); +// Length of a leaf in longs (8 bytes each), per set +const LEAF_LENGTH_IN_LONGS_BY_SET = LEAF_LEVEL_SHIFT_BY_SET.map( + (leafLevelShift) => 1 << (leafLevelShift - LEAF_LEVEL_SHIFT) +); const NON_LEAF_ENTRY_SLOT_INDICATORS_OFFSET = 0; const NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS = 1; const PACKED_ARRAY_GROWTH_INCREMENT = 16; @@ -63,7 +86,10 @@ export class PackedArrayContext { private longArray: Float64Array; private populatedShortLength: number = 0; private virtualLength: number; - private topLevelShift: number = Number.MAX_VALUE; // Make it non-sensical until properly initialized. + // Per set, make it non-sensical until properly initialized. + private topLevelShiftBySet: number[] = new Array(NUMBER_OF_SETS).fill( + Number.MAX_VALUE + ); constructor(virtualLength: number, initialPhysicalLength: number) { this.physicalLength = Math.max( @@ -247,17 +273,22 @@ export class PackedArrayContext { return newEntryIndex; } - /** @return the long index of the new leaf, or -1 if the array is full */ - private newLeafEntry() { + /** + * @param lengthInLongs the length of the leaf, 1 for an 8 byte leaf + * @return the long index of the new leaf, or -1 if the array is full + */ + private newLeafEntry(lengthInLongs: number) { // Add entry at the end of the array: const newEntryIndex = this.getPopulatedLongLength(); - if (!this.expandArrayIfNeeded(1)) { + if (!this.expandArrayIfNeeded(lengthInLongs)) { return -1; } - this.setPopulatedLongLength(newEntryIndex + 1); + this.setPopulatedLongLength(newEntryIndex + lengthInLongs); - this.setAtLongIndex(newEntryIndex, 0); + for (let i = 0; i < lengthInLongs; i++) { + this.setAtLongIndex(newEntryIndex + i, 0); + } return newEntryIndex; } @@ -305,6 +336,7 @@ export class PackedArrayContext { * @param insertedSlotIndex realtive [packed] index of slot being inserted into entry * @param insertedSlotMask mask value fo slot being inserted * @param nextLevelIsLeaf the level below this one is a leaf level + * @param leafLengthInLongs the length of the leaves, when the level below is a leaf level * @return the updated index of the entry, or -1 if the array is full (the entry is then left untouched) */ expandEntry( @@ -312,7 +344,8 @@ export class PackedArrayContext { entryPointerIndex: number, insertedSlotIndex: number, insertedSlotMask: number, - nextLevelIsLeaf: boolean + nextLevelIsLeaf: boolean, + leafLengthInLongs: number ): number { let packedSlotIndicators = this.getAtShortIndex(existingEntryIndex) & 0xffff; @@ -331,7 +364,7 @@ export class PackedArrayContext { // Create new next-level entry to refer to from slot at this level: let indexOfNewNextLevelEntry = 0; if (nextLevelIsLeaf) { - indexOfNewNextLevelEntry = this.newLeafEntry(); // Establish long-index to new leaf entry + indexOfNewNextLevelEntry = this.newLeafEntry(leafLengthInLongs); // Establish long-index to new leaf entry if (indexOfNewNextLevelEntry < 0) { return -1; } @@ -432,12 +465,14 @@ export class PackedArrayContext { } // Work down the levels of non-leaf entries: + const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; + const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[setNumber]; for ( - let indexShift = this.topLevelShift; - indexShift >= LEAF_LEVEL_SHIFT; + let indexShift = this.topLevelShiftBySet[setNumber]; + indexShift >= leafLevelShift; indexShift -= 4 ) { - const nextLevelIsLeaf = indexShift === LEAF_LEVEL_SHIFT; + const nextLevelIsLeaf = indexShift === leafLevelShift; // Target is a packedSlotIndicators entry const packedSlotIndicators = this.getPackedSlotIndicators(entryIndex); const slotBitNumber = (virtualIndex >>> indexShift) & 0xf; @@ -457,7 +492,8 @@ export class PackedArrayContext { entryPointerIndex, slotNumber, slotMask, - nextLevelIsLeaf + nextLevelIsLeaf, + leafLengthInLongs ); if (entryIndex < 0) { return -1; // The array is full, the index cannot be added @@ -473,13 +509,15 @@ export class PackedArrayContext { // entryIndex is the long-index of a leaf entry that contains the value byte for the given set - const byteIndex = (entryIndex << 3) + (virtualIndex & 0x7); // Determine byte index offset within leaf entry + // Byte index offset within leaf entry. The leaf entry is the long index + const byteIndex = + (entryIndex << 3) + (virtualIndex & LEAF_BYTE_MASK_BY_SET[setNumber]); return byteIndex; } /** - * Lowest virtual index >= fromIndex whose group of 8 indexes has a leaf in - * set 0, i.e. whose values may be non-zero. Groups without a leaf are all + * Lowest virtual index >= fromIndex whose group of indexes (the ones sharing + * a set-0 leaf) has a leaf in set 0, i.e. whose values may be non-zero. Groups without a leaf are all * zeros and are skipped by descending only into the populated slots of * the set-0 tree, so the walk costs time proportional to the populated * groups rather than to the virtual length. @@ -503,7 +541,7 @@ export class PackedArrayContext { } return this.nextIndexWithLeafBelow( rootEntryIndex, - this.topLevelShift, + this.topLevelShiftBySet[0], fromIndex ); } @@ -521,7 +559,7 @@ export class PackedArrayContext { const packedSlotIndicators = this.getPackedSlotIndicators(entryIndex); // The indexes covered by this entry share the bits above the ones its slots decode const entryBase = fromIndex & ~((1 << (indexShift + 4)) - 1); - const nextLevelIsLeaf = indexShift === LEAF_LEVEL_SHIFT; + const nextLevelIsLeaf = indexShift === LEAF_LEVEL_SHIFT_BY_SET[0]; for ( let slotBitNumber = (fromIndex >>> indexShift) & 0xf; slotBitNumber < 16; @@ -553,13 +591,22 @@ export class PackedArrayContext { return -1; } - determineTopLevelShiftForVirtualLength(virtualLength: number) { + /** + * The top level shift of the set tree of the given set, for a virtual length: the levels of + * non-leaf entries are at shifts leafLevelShift, leafLevelShift + 4, ..., top, and the top + * level must cover the most significant bit of the virtual length, with at least two levels. + */ + determineTopLevelShiftForVirtualLength( + virtualLength: number, + setNumber: number = 1 + ) { + const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; const sizeMagnitude = ceil(log2(virtualLength)); - const eightsSizeMagnitude = sizeMagnitude - 3; - let multipleOfFourSizeMagnitude = ceil(eightsSizeMagnitude / 4) * 4; - multipleOfFourSizeMagnitude = max(multipleOfFourSizeMagnitude, 8); - const topLevelShiftNeeded = multipleOfFourSizeMagnitude - 4 + 3; - return topLevelShiftNeeded; + const levelsAboveTheFirst = max( + ceil((sizeMagnitude - leafLevelShift - 4) / 4), + 1 + ); + return leafLevelShift + 4 * levelsAboveTheFirst; } setVirtualLength(virtualLength: number) { @@ -568,13 +615,26 @@ export class PackedArrayContext { "Should never be adjusting the virtual size of a non-packed context" ); } - this.topLevelShift = - this.determineTopLevelShiftForVirtualLength(virtualLength); + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + this.topLevelShiftBySet[setNumber] = + this.determineTopLevelShiftForVirtualLength(virtualLength, setNumber); + } this.virtualLength = virtualLength; } - getTopLevelShift() { - return this.topLevelShift; + /** @return whether the set trees of this context are laid out for the given virtual length */ + hasTopLevelShiftsFor(virtualLength: number) { + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + if ( + this.determineTopLevelShiftForVirtualLength( + virtualLength, + setNumber + ) !== this.topLevelShiftBySet[setNumber] + ) { + return false; + } + } + return true; } // @@ -602,11 +662,18 @@ export class PackedArrayContext { throw new Error("Cannot populate array of smaller virtual length"); } - for (let i = 0; i < NUMBER_OF_SETS; i++) { - const otherEntryIndex = other.getAtShortIndex(SET_0_START_INDEX + i); + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + const otherEntryIndex = other.getAtShortIndex( + SET_0_START_INDEX + setNumber + ); if (otherEntryIndex == 0) continue; // No tree to duplicate - let entryIndexPointer = SET_0_START_INDEX + i; - for (let i = this.topLevelShift; i > other.topLevelShift; i -= 4) { + let entryIndexPointer = SET_0_START_INDEX + setNumber; + const otherTopLevelShift = other.topLevelShiftBySet[setNumber]; + for ( + let i = this.topLevelShiftBySet[setNumber]; + i > otherTopLevelShift; + i -= 4 + ) { // for each inserted level: // Allocate entry in other: const sizeOfEntry = NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + 1; @@ -623,7 +690,8 @@ export class PackedArrayContext { other, otherEntryIndex, entryIndexPointer, - other.topLevelShift + otherTopLevelShift, + setNumber ); } } @@ -632,9 +700,12 @@ export class PackedArrayContext { other: PackedArrayContext, otherLevelEntryIndex: number, levelEntryIndexPointer: number, - otherIndexShift: number + otherIndexShift: number, + setNumber: number ) { - const nextLevelIsLeaf = otherIndexShift == LEAF_LEVEL_SHIFT; + const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; + const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[setNumber]; + const nextLevelIsLeaf = otherIndexShift == leafLevelShift; const packedSlotIndicators = other.getPackedSlotIndicators(otherLevelEntryIndex); const numberOfSlots = bitCount(packedSlotIndicators); @@ -650,7 +721,7 @@ export class PackedArrayContext { for (let i = 0; i < numberOfSlots; i++) { if (nextLevelIsLeaf) { // Make leaf in other: - const leafEntryIndex = this.newLeafEntry(); + const leafEntryIndex = this.newLeafEntry(leafLengthInLongs); this.setIndexAtEntrySlot(entryIndex, i, leafEntryIndex); @@ -660,8 +731,10 @@ export class PackedArrayContext { otherLevelEntryIndex, i ); - this.longArray[leafEntryIndex] = - other.longArray[otherNextLevelEntryIndex]; + for (let longNum = 0; longNum < leafLengthInLongs; longNum++) { + this.longArray[leafEntryIndex + longNum] = + other.longArray[otherNextLevelEntryIndex + longNum]; + } } else { const otherNextLevelEntryIndex = other.getIndexAtEntrySlot( otherLevelEntryIndex, @@ -671,7 +744,8 @@ export class PackedArrayContext { other, otherNextLevelEntryIndex, entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + i, - otherIndexShift - 4 + otherIndexShift - 4, + setNumber ); } } @@ -712,7 +786,8 @@ export class PackedArrayContext { private nonLeafEntryToString( entryIndex: number, indexShift: number, - indentLevel: number + indentLevel: number, + leafLevelShift: number ) { let output = ""; for (let i = 0; i < indentLevel; i++) { @@ -732,7 +807,7 @@ export class PackedArrayContext { } } output += ` ] (indexShift = ${indexShift})\n`; - const nextLevelIsLeaf = indexShift == LEAF_LEVEL_SHIFT; + const nextLevelIsLeaf = indexShift == leafLevelShift; for (let i = 0; i < numberOfslotsInEntry; i++) { const nextLevelEntryIndex = this.getIndexAtEntrySlot(entryIndex, i); if (nextLevelIsLeaf) { @@ -744,7 +819,8 @@ export class PackedArrayContext { output += this.nonLeafEntryToString( nextLevelEntryIndex, indexShift - 4, - indentLevel + 4 + indentLevel + 4, + leafLevelShift ); } } @@ -782,7 +858,12 @@ export class PackedArrayContext { const entryIndex = this.getIndexAtShortIndex(entryPointerIndex); output += `Set ${setNumber}: root = ${entryIndex} \n`; if (entryIndex == 0) continue; - output += this.nonLeafEntryToString(entryIndex, this.topLevelShift, 4); + output += this.nonLeafEntryToString( + entryIndex, + this.topLevelShiftBySet[setNumber], + 4, + LEAF_LEVEL_SHIFT_BY_SET[setNumber] + ); } catch (ex) { output += `Exception thrown in set ${setNumber}%d\n`; }