Add function for removing arbitrary nodes in binaryheap.
authorNathan Bossart <[email protected]>
Mon, 18 Sep 2023 21:06:08 +0000 (14:06 -0700)
committerNathan Bossart <[email protected]>
Mon, 18 Sep 2023 21:06:08 +0000 (14:06 -0700)
This commit introduces binaryheap_remove_node(), which can be used
to remove any node from a binary heap.  The implementation is
straightforward.  The target node is replaced with the last node in
the heap, and then we sift as needed to preserve the heap property.
This new function is intended for use in a follow-up commit that
will improve the performance of pg_restore.

Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/3612876.1689443232%40sss.pgh.pa.us

src/common/binaryheap.c
src/include/lib/binaryheap.h

index 39a8243a6d5a21df36d89a2da309341962d09709..19e095f1fb1c7a47db294fdcf5ab0d793eeb8858 100644 (file)
@@ -215,6 +215,35 @@ binaryheap_remove_first(binaryheap *heap)
    return result;
 }
 
+/*
+ * binaryheap_remove_node
+ *
+ * Removes the nth (zero based) node from the heap.  The caller must ensure
+ * that there are at least (n + 1) nodes in the heap.  O(log n) worst case.
+ */
+void
+binaryheap_remove_node(binaryheap *heap, int n)
+{
+   int         cmp;
+
+   Assert(!binaryheap_empty(heap) && heap->bh_has_heap_property);
+   Assert(n >= 0 && n < heap->bh_size);
+
+   /* compare last node to the one that is being removed */
+   cmp = heap->bh_compare(heap->bh_nodes[--heap->bh_size],
+                          heap->bh_nodes[n],
+                          heap->bh_arg);
+
+   /* remove the last node, placing it in the vacated entry */
+   heap->bh_nodes[n] = heap->bh_nodes[heap->bh_size];
+
+   /* sift as needed to preserve the heap property */
+   if (cmp > 0)
+       sift_up(heap, n);
+   else if (cmp < 0)
+       sift_down(heap, n);
+}
+
 /*
  * binaryheap_replace_first
  *
index 3647aeae657630b4d8b5b26f3ca7c63056c3b185..9525dcaec44eb3f6f8c9e137c710e950b53cf85c 100644 (file)
@@ -59,8 +59,11 @@ extern void binaryheap_build(binaryheap *heap);
 extern void binaryheap_add(binaryheap *heap, bh_node_type d);
 extern bh_node_type binaryheap_first(binaryheap *heap);
 extern bh_node_type binaryheap_remove_first(binaryheap *heap);
+extern void binaryheap_remove_node(binaryheap *heap, int n);
 extern void binaryheap_replace_first(binaryheap *heap, bh_node_type d);
 
 #define binaryheap_empty(h)            ((h)->bh_size == 0)
+#define binaryheap_size(h)         ((h)->bh_size)
+#define binaryheap_get_node(h, n)  ((h)->bh_nodes[n])
 
 #endif                         /* BINARYHEAP_H */