Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions assembly/__tests__/PackedArrayWideLeaves.test.ts
Original file line number Diff line number Diff line change
@@ -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, <u64>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(<u64>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<u64>(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, <u64>(i + 1));
plain[index] += <u64>(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<u64>(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 + <i32>((seed >>> 8) % 40))
: <i32>((seed >>> 8) % <u32>length);
seed = seed * 1664525 + 1013904223;
const value: u64 = (seed >>> 8) % 5 == 0 ? 250 + <u64>((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);
});
});
46 changes: 24 additions & 22 deletions assembly/packedarray/PackedArray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import {
PackedArrayContext,
MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY,
LEAF_BYTE_MASK_BY_SET,
} from "./PackedArrayContext";

const NUMBER_OF_SETS: i32 = 8;
Expand All @@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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])
Expand All @@ -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 |=
Expand All @@ -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;
}
}

/**
Expand All @@ -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])
Expand All @@ -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.
Expand Down Expand Up @@ -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])
Expand Down Expand Up @@ -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.
Expand All @@ -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.
*/
Expand All @@ -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<i32>((index | 0x7) + 1, length);
// The leaf found only vouches for the group of indexes sharing its set-0 leaf
const groupEnd = min<i32>((index | LEAF_BYTE_MASK_BY_SET[0]) + 1, length);
for (; index < groupEnd; index++) {
if (this.get(index) != 0) {
return index;
Expand Down
Loading
Loading