Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache n children #317

Merged
merged 4 commits into from
May 29, 2024
Merged
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
37 changes: 24 additions & 13 deletions src/btree/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export class BTreeNode {
private readonly tree: RangeResolver;
private readonly pageFieldWidth: number;

private readonly childrenCache: (Promise<BTreeNode> | null)[];

constructor(
keys: ReferencedValue[],
leafPointers: MemoryPointer[],
Expand All @@ -41,6 +43,7 @@ export class BTreeNode {
this.pageFieldType = pageFieldType;
this.tree = tree;
this.pageFieldWidth = pageFieldWidth;
this.childrenCache = new Array(this.numPointers()).fill(null);
}

leaf(): boolean {
Expand All @@ -62,23 +65,31 @@ export class BTreeNode {
return this.internalPointers.length + this.leafPointers.length;
}

async child(index: number) {
const childPointer = this.pointer(index);
async child(index: number): Promise<BTreeNode> {
if (!this.childrenCache[index]) {
const childPointer = this.pointer(index);

this.childrenCache[index] = BTreeNode.fromMemoryPointer(
childPointer,
this.tree,
this.dataFileResolver,
this.fileFormat,
this.pageFieldType,
this.pageFieldWidth,
).then(({ node, bytesRead }) => {
if (!bytesRead) {
throw new Error("bytes read do not line up");
}

const { node, bytesRead } = await BTreeNode.fromMemoryPointer(
childPointer,
this.tree,
this.dataFileResolver,
this.fileFormat,
this.pageFieldType,
this.pageFieldWidth,
);
return node;
});
}

if (!bytesRead) {
throw new Error("bytes read do not line up");
if (!this.childrenCache[index]) {
throw new Error(`children cache at ${index} is null`);
}

return node;
return await this.childrenCache[index]!!;
}

async unmarshalBinary(buffer: ArrayBuffer, pageFieldWidth: number) {
Expand Down
Loading