[libc-commits] [libc] [libc][tsearch] add weak AVL tree for tsearch implementation (PR #172411)

Michael Jones via libc-commits libc-commits at lists.llvm.org
Wed Jan 14 16:36:56 PST 2026


================
@@ -0,0 +1,290 @@
+//===-- Unittests for WeakAVL ---------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/__support/weak_avl.h"
+#include "test/UnitTest/Test.h"
+
+using Node = LIBC_NAMESPACE::WeakAVLNode<int>;
+
+namespace {
+constexpr int TEST_SIZE = 128;
+// Validate weak-AVL rank-difference invariant assuming **pure insertion only**
+// (i.e. no erasure has occurred).
+//
+// NOTE: This validator is intentionally *not* correct after erase(), because
+// weak-AVL allows transient or permanent 2-2 configurations during deletion
+// fixup.
+bool validate_pure_insertion(const Node *node) {
+  if (!node)
+    return true;
+  bool left_2 = node->has_rank_diff_2(false);
+  bool right_2 = node->has_rank_diff_2(true);
+  return (!left_2 || !right_2) && validate_pure_insertion(node->get_left()) &&
+         validate_pure_insertion(node->get_right());
+}
+
+// Insert according to pattern `next(i)`
+using NextFn = int (*)(int);
+
+static Node *build_tree(NextFn next, int N, int (*compare)(int, int)) {
+  Node *root = nullptr;
+  for (int i = 0; i < N; ++i)
+    Node::find_or_insert(root, next(i), compare);
+  return root;
+}
+
+// Insertion patterns
+static int seq(int i) { return i; }
+
+static int rev(int i) {
+  constexpr int N = TEST_SIZE;
+  return N - 1 - i;
+}
+
+// Coprime stride permutation: i -> (i * X) % N
+static int stride(int i, int prime = 7919) {
+  constexpr int N = TEST_SIZE;
+  return (i * prime) % N;
+}
+
+// Thin wrappers to make test intent explicit.
+template <typename Compare>
+static Node *find(Node *root, int value, Compare &&comp) {
+  return Node::find(root, value, comp);
+}
+
+static void erase(Node *&root, Node *node) { Node::erase(root, node); }
+
+} // namespace
+
+TEST(LlvmLibcWeakAVLTest, SimpleInsertion) {
+  Node *root = nullptr;
+  auto compare = [](int a, int b) { return (a > b) - (a < b); };
----------------
michaelrj-google wrote:

given that compare is defined the same way in every test, it might make more sense to define it once above, then pass a pointer to that function.

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


More information about the libc-commits mailing list