/** * TreeIterator implements iteration over an ImmutableTree. * Uses delayed node traversal with a stack-based approach. * * Corresponds to Go's Iterator in iterator.go */ import type { ImmutableTree, } from "../immutable-tree.js"; import type { Node, } from "../node.js"; import { compareBytes, } from "../utils/bytes.js"; /** * Delayed node represents a node that may need to be expanded. * When delayed is true, the node's children should be traversed. * When delayed is false, the node can be immediately returned. */ interface DelayedNode { node: Node delayed: boolean } /** * Traversal manages the stack-based depth-first traversal of the tree. */ class Traversal { private readonly tree: ImmutableTree; private start: Uint8Array | null; private end: Uint8Array | null; private readonly ascending: boolean; private readonly inclusive: boolean; private readonly delayedNodes: DelayedNode[]; constructor( tree: ImmutableTree, start: Uint8Array | null, end: Uint8Array | null, ascending: boolean, inclusive: boolean, initialNode: Node, ) { this.tree = tree; this.start = start; this.end = end; this.ascending = ascending; this.inclusive = inclusive; this.delayedNodes = [ { node: initialNode, delayed: true, }, ]; } /** * Gets the next node in the traversal. * Returns null when traversal is complete. */ async next(): Promise { // End of traversal if (this.delayedNodes.length === 0) { return null; } const delayedNode = this.delayedNodes.pop()!; const { node, delayed, } = delayedNode; // Already expanded, immediately return if (!delayed || node === null) { return node; } // All nodes in the tree should have keys if (node.key === null) { throw new Error("Iterator encountered node without key"); } // Check if node is within range let afterStart: boolean; let startOrAfter: boolean; if (this.start === null) { afterStart = true; startOrAfter = true; } else { const cmp = compareBytes(this.start, node.key); afterStart = cmp < 0; startOrAfter = afterStart || cmp === 0; } let beforeEnd: boolean; let withinEnd: boolean; if (this.end === null) { beforeEnd = true; withinEnd = true; } else { const cmp = compareBytes(node.key, this.end); beforeEnd = cmp < 0; withinEnd = this.inclusive ? (beforeEnd || cmp === 0) : beforeEnd; } // If node is a branch node, traverse children if (!node.isLeaf()) { // Ascending: left first, then right if (this.ascending) { // Push right child (will be processed after left) if (withinEnd) { const rightNode = await node.getRightNode(this.tree.ndb); if (rightNode) { this.delayedNodes.push({ node: rightNode, delayed: true, }); } } // Push left child (will be processed first) if (afterStart) { const leftNode = await node.getLeftNode(this.tree.ndb); if (leftNode) { this.delayedNodes.push({ node: leftNode, delayed: true, }); } } } // Descending: right first, then left else { // Push left child (will be processed after right) if (afterStart) { const leftNode = await node.getLeftNode(this.tree.ndb); if (leftNode) { this.delayedNodes.push({ node: leftNode, delayed: true, }); } } // Push right child (will be processed first) if (withinEnd) { const rightNode = await node.getRightNode(this.tree.ndb); if (rightNode) { this.delayedNodes.push({ node: rightNode, delayed: true, }); } } } } // If node is a leaf and within range, return it // If node is a branch, skip it (we only want leaves) if (node.isLeaf() && startOrAfter && withinEnd) { return node; } // Continue traversing return this.next(); } } /** * TreeIterator iterates over key-value pairs in an ImmutableTree. * * Usage: * ```typescript * const iter = new TreeIterator(tree, start, end, true); * while (iter.valid()) { * console.log(iter.key(), iter.value()); * await iter.next(); * } * iter.close(); * ``` */ export class TreeIterator { private readonly tree: ImmutableTree; private readonly start: Uint8Array | null; private readonly end: Uint8Array | null; private readonly ascending: boolean; private readonly inclusive: boolean; private currentKey: Uint8Array | null = null; private currentValue: Uint8Array | null = null; private currentVersion: bigint | null = null; private isValid = false; private traversal: Traversal | null = null; /** * Creates a new TreeIterator. * The iterator is positioned before the first element. * Call next() to move to the first element. * * @param tree - The immutable tree to iterate over * @param start - Start key (null for beginning) * @param end - End key (null for no limit) * @param ascending - True for ascending order, false for descending * @param inclusive - True to include end key, false to exclude */ constructor( tree: ImmutableTree, start: Uint8Array | null = null, end: Uint8Array | null = null, ascending = true, inclusive = false, ) { this.tree = tree; this.start = start; this.end = end; this.ascending = ascending; this.inclusive = inclusive; // Initialize traversal if tree has a root const root = tree.getRoot(); if (root) { this.isValid = true; this.traversal = new Traversal( tree, start, end, ascending, inclusive, root, ); } else { // Empty tree this.isValid = false; } } /** * Checks if the iterator is currently valid. * Returns false when iteration is complete or tree is empty. */ valid(): boolean { return this.isValid; } /** * Gets the current key. * Only valid when valid() returns true. */ key(): Uint8Array { if (!this.isValid || this.currentKey === null) { throw new Error("Iterator is not valid"); } return this.currentKey; } /** * Gets the current value. * Only valid when valid() returns true. */ value(): Uint8Array { if (!this.isValid || this.currentValue === null) { throw new Error("Iterator is not valid"); } return this.currentValue; } /** * Gets the current node's version. * Only valid when valid() returns true. */ version(): bigint { if (!this.isValid || this.currentVersion === null) { throw new Error("Iterator is not valid"); } return this.currentVersion; } /** * Advances the iterator to the next key-value pair. * After the last element, valid() will return false. */ async next(): Promise { if (!this.traversal) { this.isValid = false; return; } const node = await this.traversal.next(); if (node === null) { this.isValid = false; this.currentKey = null; this.currentValue = null; this.currentVersion = null; this.traversal = null; return; } // Only leaf nodes have values if (node.isLeaf()) { this.currentKey = node.key; this.currentValue = node.value; this.currentVersion = node.nodeKey?.version ?? null; } else { // Branch node, continue to next await this.next(); } } /** * Closes the iterator and releases resources. * The iterator becomes invalid after calling close(). */ close(): void { this.isValid = false; this.currentKey = null; this.currentValue = null; this.currentVersion = null; this.traversal = null; } /** * Gets the iteration domain (start and end keys). */ domain(): [Uint8Array | null, Uint8Array | null] { return [this.start, this.end]; } }