public static void PruneNode <T>(IMerkleTreePruningCursor <T> cursor, int index) where T : IMerkleTreeNode <T> { if (!cursor.TryMoveToIndex(index)) { return; } var node = cursor.ReadNode(); if (node.Depth != 0) { return; } if (!node.Pruned) { node = node.AsPruned(); cursor.WriteNode(node); } bool didWork; do { didWork = false; if (node.IsLeft()) { if (cursor.TryMoveRight()) { var rightNode = cursor.ReadNode(); if (node.Pruned && rightNode.Pruned && node.Depth == rightNode.Depth) { var newNode = node.PairWith(rightNode); cursor.DeleteNode(); //TODO cursor.MoveLeft(); cursor.WriteNode(newNode); node = newNode; didWork = true; } } else { if (node.Index != 0 && node.Pruned) { var newNode = node.PairWithSelf(); //cursor.MoveLeft(); cursor.WriteNode(newNode); node = newNode; didWork = true; } } } else { if (cursor.TryMoveLeft()) { var leftNode = cursor.ReadNode(); if (node.Pruned && leftNode.Pruned && node.Depth == leftNode.Depth) { var newNode = leftNode.PairWith(node); cursor.WriteNode(newNode); cursor.MoveRight(); cursor.DeleteNode(); //TODO cursor.MoveLeft(); node = newNode; didWork = true; } } } }while (didWork); }
public void MoveToIndex(int index, Dictionary <int, int?> indicesToLeft, Dictionary <int, int?> indicesToRight) { if (currentIndex == -1) { pruningCursor.MoveToIndex(index); currentIndex = index; return; } if (currentIndex > index) { int?leftIndex; while (indicesToLeft.TryGetValue(currentIndex, out leftIndex)) { if (!leftIndex.HasValue) { throw new InvalidOperationException(); } pruningCursor.MoveLeft(); currentIndex = leftIndex.Value; if (currentIndex == index) { return; } else if (currentIndex < index) { break; } } } else if (currentIndex < index) { int?rightIndex; while (indicesToRight.TryGetValue(currentIndex, out rightIndex)) { if (!rightIndex.HasValue) { throw new InvalidOperationException(); } pruningCursor.MoveRight(); currentIndex = rightIndex.Value; if (currentIndex == index) { return; } else if (currentIndex > index) { break; } } } if (currentIndex != index) { pruningCursor.MoveToIndex(index); currentIndex = index; } Debug.Assert(pruningCursor.ReadNode().Index == index); }