diff -r 7c15fea5cbea -r 1ce90ab4fab9 src/tree.c --- a/src/tree.c Mon Feb 19 22:12:13 2024 +0100 +++ b/src/tree.c Wed Feb 21 18:32:38 2024 +0100 @@ -182,40 +182,58 @@ off_t const loc_children = iter->loc_children; // TODO: support mutating iterator - // TODO: support visit_on_exit - void *children = tree_children(iter->node); + void *children; + + // check if we are currently exiting or entering nodes + if (iter->exiting) { + children = NULL; + } else { + children = tree_children(iter->node); + } + if (children == NULL) { // search for the next node - void *current = iter->node; - do { - // check if there is a sibling - void *next = tree_next(current); - if (next == NULL) { - // no sibling, check again for parent node - --iter->depth; - if (iter->depth == 0) { + void *next; + cx_tree_iter_search_next: + // check if there is a sibling + next = tree_next(iter->node); + if (next == NULL) { + // no sibling, we are done with this node and exit + if (iter->visit_on_exit && !iter->exiting) { + // iter is supposed to visit the node again + iter->exiting = true; + } else { + iter->exiting = false; + if (iter->depth == 1) { // there is no parent - we have iterated the entire tree // invalidate the iterator and free the node stack iter->node = NULL; - current = NULL; - iter->stack_capacity = 0; + iter->stack_capacity = iter->depth = 0; free(iter->stack); iter->stack = NULL; } else { // the parent node can be obtained from the top of stack // this way we can avoid the loc_parent in the iterator - current = iter->stack[iter->depth - 1]; + iter->depth--; + iter->node = iter->stack[iter->depth - 1]; + // retry with the parent node to find a sibling + goto cx_tree_iter_search_next; } + } + } else { + if (iter->visit_on_exit && !iter->exiting) { + // iter is supposed to visit the node again + iter->exiting = true; } else { - // move to the sibling and break the loop - current = NULL; + iter->exiting = false; + // move to the sibling iter->counter++; iter->node = next; // new top of stack is the sibling iter->stack[iter->depth - 1] = next; } - } while (current != NULL); + } } else { // node has children, push the first child onto the stack and enter it cx_array_simple_add(iter->stack, children);