cx_tree_add_iter() - optimize check for empty trees feature/tree_add

Tue, 20 Aug 2024 12:39:35 +0200

author
Mike Becker <universe@uap-core.de>
date
Tue, 20 Aug 2024 12:39:35 +0200
branch
feature/tree_add
changeset 868
56a908924510
parent 867
471c714d5b6f
child 869
9e7f0db6a725

cx_tree_add_iter() - optimize check for empty trees

relates to #390

src/tree.c file | annotate | diff | comparison | revisions
--- a/src/tree.c	Tue Aug 20 11:02:54 2024 +0200
+++ b/src/tree.c	Tue Aug 20 12:39:35 2024 +0200
@@ -531,27 +531,31 @@
         ptrdiff_t loc_prev,
         ptrdiff_t loc_next
 ) {
+    // iter not valid? cancel...
+    if (!iter->valid(iter)) return 0;
+
     size_t processed = 0;
     void *current_node = *root;
+    void *elem;
+
+    // if there is no root, yet - process the first node from the iter
+    // as the new root node
+    if (current_node == NULL) {
+        elem = *(void **) (iter->current(iter));
+        // no node in tree, yet - add a new one
+        current_node = cfunc(elem, NULL, cdata);
+        // node creation failed - stop processing
+        if (current_node == NULL) return 0;
+        cx_tree_zero_pointers(current_node, cx_tree_ptr_locations);
+        *root = current_node;
+        processed++;
+        iter->next(iter);
+    }
+
     for (void **eptr;
          iter->valid(iter) && (eptr = iter->current(iter)) != NULL;
          iter->next(iter)) {
-        void *elem = *eptr;
-
-        if (current_node == NULL) {
-            // no node in tree, yet - add a new one
-            current_node = cfunc(elem, NULL, cdata);
-            // node creation failed - stop processing
-            if (current_node == NULL) {
-                // but honestly... nothing should have been processed
-                assert(processed == 0);
-                return 0;
-            }
-            cx_tree_zero_pointers(current_node, cx_tree_ptr_locations);
-            *root = current_node;
-            processed++;
-            continue;
-        }
+        elem = *eptr;
 
         // start searching from current node
         void *match;

mercurial