[libcxx-commits] [libcxx] [libc++] Document how __tree is layed out and how we iterate through it (PR #152453)

via libcxx-commits libcxx-commits at lists.llvm.org
Thu Aug 7 01:33:25 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libcxx

Author: Nikolas Klauser (philnik777)

<details>
<summary>Changes</summary>



---
Full diff: https://github.com/llvm/llvm-project/pull/152453.diff


1 Files Affected:

- (modified) libcxx/include/__tree (+26) 


``````````diff
diff --git a/libcxx/include/__tree b/libcxx/include/__tree
index 3dd5ae585e1db..80ad56e5e7805 100644
--- a/libcxx/include/__tree
+++ b/libcxx/include/__tree
@@ -49,6 +49,27 @@
 _LIBCPP_PUSH_MACROS
 #include <__undef_macros>
 
+// __tree is a red-black-tree implementation used for the associative containers (i.e. (multi)map/set). To allow for
+// constant time lookup, it stores
+// - (1) a pointer to the node with the smallest (i.e. leftmost) element, namely __begin_node_
+// - (2) the number of nodes in the tree, namely __size_
+//
+// A pointer to the root of the tree is stored in the __end_node_.
+// A tree looks like this in memory:
+//
+//      __end_node_
+//           |
+//          root
+//         /    \
+//       l1       r1
+//      /  \     /  \
+//    ...  ... ...  ...
+//
+// All nodes except __end_node_ have a __left_ and __right_ pointer as well as a __parent_ pointer.
+// __end_node_ only contains a __left_ pointer, which point to the root of the tree.
+// This layout allows for iteration through the tree without a need for special handling of the end node. See
+// __tree_next_iter and __tree_prev_iter for more details.
+
 _LIBCPP_BEGIN_NAMESPACE_STD
 
 template <class _Tp, class _Compare, class _Allocator>
@@ -183,6 +204,11 @@ _LIBCPP_HIDE_FROM_ABI _NodePtr __tree_next(_NodePtr __x) _NOEXCEPT {
   return __x->__parent_unsafe();
 }
 
+// __tree_next_iter and __tree_prev_iter implement iteration through the tree. The order is as follows:
+// left sub-tree -> node -> right sub-tree. When the right-most node of a sub-tree is reached, we walk up the tree until
+// we find a node where we were in the left sub-tree. We are _always_ in a left sub-tree, since the __end_node_ points
+// to the actual root of the tree through a __left_ pointer. incrementing the end() pointer is UB, so we can assume that
+// never happens.
 template <class _EndNodePtr, class _NodePtr>
 inline _LIBCPP_HIDE_FROM_ABI _EndNodePtr __tree_next_iter(_NodePtr __x) _NOEXCEPT {
   _LIBCPP_ASSERT_INTERNAL(__x != nullptr, "node shouldn't be null");

``````````

</details>


https://github.com/llvm/llvm-project/pull/152453


More information about the libcxx-commits mailing list