Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tree_allocation_test.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
45#include <gtest/gtest.h>
46
47#include <tpl_avl.H>
48#include <tpl_avlRk.H>
49#include <tpl_rb_tree.H>
50#include <tpl_rbRk.H>
51#include <tpl_hRbTree.H>
52#include <tpl_hRbTreeRk.H>
53#include <tpl_treap.H>
54#include <tpl_rand_tree.H>
55#include <tpl_splay_tree.H>
56#include <tpl_binNodeUtils.H>
57#include <tpl_dynBinHeap.H>
58#include <tpl_dynSetTree.H>
59#include <tpl_dynMapTree.H>
60#include <ah-zip.H>
61#include <ahFunctional.H>
62
63#include <cstdlib>
64#include <memory>
65#include <new>
66#include <type_traits>
67#include <utility>
68#include <vector>
69
70using namespace Aleph;
71
72#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) \
73 || defined(__SANITIZE_HWADDRESS__)
74# define COUNT_ALLOCATIONS 0
75#elif defined(__has_feature)
76# if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) \
77 || __has_feature(memory_sanitizer) || __has_feature(hwaddress_sanitizer)
78# define COUNT_ALLOCATIONS 0
79# endif
80#endif
81#ifndef COUNT_ALLOCATIONS
82# define COUNT_ALLOCATIONS 1
83#endif
84
85// Skip a test that counts allocations when they cannot be counted.
86#define SKIP_UNLESS_COUNTING_ALLOCATIONS() \
87 if (not COUNT_ALLOCATIONS) \
88 GTEST_SKIP() << "a sanitizer provides the allocation functions"
89
90#if defined(__GNUC__) || defined(__clang__)
91# define ALEPH_TEST_NOINLINE [[gnu::noinline]]
92#else
93# define ALEPH_TEST_NOINLINE
94#endif
95
96namespace
97{
98 // Calls to the global operator new. Replacing it in this translation unit
99 // replaces it for the whole program; only the deltas matter. Every variant
100 // is replaced, so that all the memory comes from malloc() and goes to
101 // free(). The helpers are not inlined, so that the compiler does not pair
102 // malloc() and free() with the operators and warn about a mismatch.
103 long allocations = 0;
104
105 // While it is set, there is no memory: every allocation fails.
106 bool out_of_memory = false;
107
108#if COUNT_ALLOCATIONS
109 ALEPH_TEST_NOINLINE void *allocate(std::size_t size)
110 {
111 ++allocations;
112 if (out_of_memory)
113 throw std::bad_alloc();
114 if (void *p = std::malloc(size == 0 ? 1 : size))
115 return p;
116 throw std::bad_alloc();
117 }
118
119 ALEPH_TEST_NOINLINE void release(void *p) noexcept
120 {
121 std::free(p);
122 }
123#endif
124
125 template <class Action>
126 long allocations_of(Action action)
127 {
128 const long before = allocations;
129 action();
130 return allocations - before;
131 }
132
133 // Runs `action` without memory; what it throws goes on to the caller.
134 template <class Action>
135 void without_memory(Action action)
136 {
137 struct Guard
138 {
139 Guard() noexcept { out_of_memory = true; }
140 ~Guard() { out_of_memory = false; }
141 } guard;
142 action();
143 }
144}
145
146#if COUNT_ALLOCATIONS
147void *operator new(std::size_t size) { return allocate(size); }
148void *operator new[](std::size_t size) { return allocate(size); }
149
150void *operator new(std::size_t size, const std::nothrow_t &) noexcept
151{
152 try
153 {
154 return allocate(size);
155 }
156 catch (...)
157 {
158 return nullptr;
159 }
160}
161
162void *operator new[](std::size_t size, const std::nothrow_t &) noexcept
163{
164 try
165 {
166 return allocate(size);
167 }
168 catch (...)
169 {
170 return nullptr;
171 }
172}
173
174void operator delete(void *p) noexcept { release(p); }
175void operator delete[](void *p) noexcept { release(p); }
176void operator delete(void *p, std::size_t) noexcept { release(p); }
177void operator delete[](void *p, std::size_t) noexcept { release(p); }
178void operator delete(void *p, const std::nothrow_t &) noexcept { release(p); }
179void operator delete[](void *p, const std::nothrow_t &) noexcept { release(p); }
180#endif
181
182TEST(TreeAllocation, constructing_a_tree_does_not_allocate)
183{
185
186 EXPECT_EQ(allocations_of([] { Avl_Tree<int> t; (void) t; }), 0);
187 EXPECT_EQ(allocations_of([] { Avl_Tree_Rk<int> t; (void) t; }), 0);
188 EXPECT_EQ(allocations_of([] { Rb_Tree<int> t; (void) t; }), 0);
189 EXPECT_EQ(allocations_of([] { Rb_Tree_Rk<int> t; (void) t; }), 0);
190 EXPECT_EQ(allocations_of([] { HtdRbTree<int> t; (void) t; }), 0);
191 EXPECT_EQ(allocations_of([] { HtdRbTreeRk<int> t; (void) t; }), 0);
192 EXPECT_EQ(allocations_of([] { Treap<int> t; (void) t; }), 0);
193 EXPECT_EQ(allocations_of([] { Rand_Tree<int> t; (void) t; }), 0);
194 EXPECT_EQ(allocations_of([] { Splay_Tree<int> t; (void) t; }), 0);
195
196 EXPECT_EQ(allocations_of([] { DynSetTree<int> s; (void) s; }), 0);
197 EXPECT_EQ(allocations_of([] { DynSetTree<int, Rb_Tree> s; (void) s; }), 0);
198 EXPECT_EQ(allocations_of([] { DynSetTree<int, Avl_Tree_Rk> s; (void) s; }), 0);
199 EXPECT_EQ(allocations_of([] { DynSetTree<int, Rb_Tree_Rk> s; (void) s; }), 0);
200 EXPECT_EQ(allocations_of([] { DynMapTree<int, int> m; (void) m; }), 0);
201}
202
203TEST(TreeAllocation, moving_a_tree_does_not_allocate)
204{
206
208 for (int i = 0; i < 100; ++i)
209 m.insert(i, i);
210 EXPECT_EQ(allocations_of([&m]
211 {
212 DynMapTree<int, int> moved(std::move(m));
213 EXPECT_EQ(moved.size(), 100u);
214 }), 0);
215
217 for (int i = 0; i < 100; ++i)
218 s.insert(i);
219 EXPECT_EQ(allocations_of([&s]
220 {
221 DynSetTree<int, Rb_Tree_Rk> moved(std::move(s));
222 EXPECT_EQ(moved.size(), 100u);
223 }), 0);
224
225 EXPECT_EQ(allocations_of([] { Rb_Tree_Rk<int> t, moved(std::move(t)); (void) moved; }), 0);
226 EXPECT_EQ(allocations_of([] { HtdRbTree<int> t, moved(std::move(t)); (void) moved; }), 0);
227 EXPECT_EQ(allocations_of([] { HtdRbTreeRk<int> t, moved(std::move(t)); (void) moved; }), 0);
228}
229
230namespace
231{
232 // Inserting allocates the node and nothing else; removing allocates nothing.
233 template <class Set>
234 void check_insert_and_remove_allocate_only_the_node()
235 {
236 Set s;
237 for (int i = 0; i < 100; ++i)
238 s.insert(i);
239 EXPECT_EQ(allocations_of([&s] { s.insert(1000); }), 1);
240 EXPECT_EQ(allocations_of([&s] { s.remove(1000); }), 0);
241 EXPECT_EQ(allocations_of([&s] { s.remove(50); }), 0);
242 EXPECT_EQ(allocations_of([&s] { s.insert(50); }), 1);
243 EXPECT_EQ(s.size(), 100u);
244 }
245}
246
247TEST(TreeAllocation, insert_and_remove_allocate_only_the_node)
248{
250
251 check_insert_and_remove_allocate_only_the_node<DynSetTree<int, Avl_Tree>>();
252 check_insert_and_remove_allocate_only_the_node<DynSetTree<int, Avl_Tree_Rk>>();
253 check_insert_and_remove_allocate_only_the_node<DynSetTree<int, Rb_Tree>>();
254 check_insert_and_remove_allocate_only_the_node<DynSetTree<int, Rb_Tree_Rk>>();
255 check_insert_and_remove_allocate_only_the_node<DynSetTree<int, Treap>>();
256 check_insert_and_remove_allocate_only_the_node<DynSetTree<int, Rand_Tree>>();
257 check_insert_and_remove_allocate_only_the_node<DynSetTree<int, Splay_Tree>>();
258
259 // The trees with a head node, through their raw node interface.
260 using Htd = HtdRbTree<int>;
261 std::vector<std::unique_ptr<Htd::Node>> nodes; // outlives the tree
262 for (int i = 0; i < 100; ++i)
263 nodes.emplace_back(new Htd::Node(i));
264 Htd t;
265 for (auto & n : nodes)
266 (void) t.insert(n.get());
267 EXPECT_EQ(allocations_of([&t] { (void) t.remove(50); }), 0);
268 EXPECT_EQ(allocations_of([&t] { (void) t.remove(0); }), 0);
269}
270
271TEST(TreeAllocation, iterating_does_not_allocate)
272{
274
276 for (int i = 0; i < 100; ++i)
277 s.insert(i);
278 EXPECT_EQ(allocations_of([&s]
279 {
280 long sum = 0;
281 for (DynSetTree<int>::Iterator it(s); it.has_curr(); it.next_ne())
282 sum += it.get_curr();
283 EXPECT_EQ(sum, 4950);
284 DynSetTree<int>::Iterator it(s), copy(it); // copying and exchanging
285 it.next();
286 copy.swap(it);
287 EXPECT_EQ(copy.get_curr(), 1);
288 EXPECT_EQ(it.get_curr(), 0);
289 }), 0);
290
291 // A splay tree uses the generic node, whose height bound is the largest.
293 for (int i = 0; i < 100; ++i)
294 splay.insert(i);
295 EXPECT_EQ(allocations_of([&splay]
296 {
297 long sum = 0;
298 for (DynSetTree<int, Splay_Tree>::Iterator it(splay); it.has_curr(); it.next_ne())
299 sum += it.get_curr();
300 EXPECT_EQ(sum, 4950);
301 }), 0);
302
303 using Tree = Avl_Tree<int>;
304 std::vector<std::unique_ptr<Tree::Node>> nodes; // outlives the tree
305 for (int i = 0; i < 100; ++i)
306 nodes.emplace_back(new Tree::Node(i));
307 Tree t;
308 for (auto & n : nodes)
309 (void) t.insert(n.get());
310 EXPECT_EQ(allocations_of([&t]
311 {
312 long count = 0;
313 for (BinNodePrefixIterator<Tree::Node> it(t.getRoot()); it.has_curr(); it.next_ne())
314 ++count;
315 for (BinNodeInfixIterator<Tree::Node> it(t.getRoot()); it.has_curr(); it.next_ne())
316 ++count;
317 EXPECT_EQ(count, 200);
318 }), 0);
319
320 DynBinHeap<int> heap;
321 for (int i = 0; i < 100; ++i)
322 heap.insert(i);
323 EXPECT_EQ(allocations_of([&heap]
324 {
325 long count = 0;
326 for (DynBinHeap<int>::Iterator it(heap); it.has_curr(); it.next_ne())
327 ++count;
328 EXPECT_EQ(count, 100);
329 }), 0);
330}
331
332namespace
333{
334 // A tree whose inorder iterator needs `n - 1` pending nodes, and not when
335 // it is built but in its first next_ne(): the minimum is the root, the
336 // maximum is its right child, and all the other keys go down the left
337 // spine of the maximum.
338 DynSetTree<int, BinTree> deep_tree(int n)
339 {
341 tree.insert(0);
342 for (int i = n; i > 0; --i)
343 tree.insert(i);
344 return tree;
345 }
346}
347
348TEST(TreeAllocation, advancing_on_a_deep_tree_allocates)
349{
351
352 auto tree = deep_tree(1000);
354 EXPECT_EQ(it.get_curr(), 0);
355 EXPECT_GT(allocations_of([&it] { it.next_ne(); }), 0);
356 EXPECT_EQ(it.get_curr(), 1);
357}
358
359// Out of memory, next_ne() of the iterator of a deep tree throws bad_alloc.
360// The adaptors must let it through: with a noexcept next_ne() they would
361// end the program.
362TEST(TreeAllocation, adaptors_propagate_the_bad_alloc_of_a_deep_tree)
363{
365
366 auto tree = deep_tree(1000);
367 const DynList<int> list = range<int>(0, 1000);
368
369 {
371 EXPECT_THROW(without_memory([&it] { it.next_ne(); }), std::bad_alloc);
372 }
373 {
374 auto it = get_pair_it(tree, list);
375 EXPECT_THROW(without_memory([&it] { it.next_ne(); }), std::bad_alloc);
376 }
377 {
378 auto it = get_pair_it(list, tree);
379 EXPECT_THROW(without_memory([&it] { it.next_ne(); }), std::bad_alloc);
380 }
381 {
382 auto it = zip_it(tree, list);
383 EXPECT_THROW(without_memory([&it] { it.next_ne(); }), std::bad_alloc);
384 }
385 {
386 auto it = zip_it(list, tree);
387 EXPECT_THROW(without_memory([&it] { it.next_ne(); }), std::bad_alloc);
388 }
389 {
390 auto it = enum_zip_it(tree, list);
391 EXPECT_THROW(without_memory([&it] { it.next_ne(); }), std::bad_alloc);
392 }
393 {
394 auto it = enum_zip_it(list, tree);
395 EXPECT_THROW(without_memory([&it] { it.next_ne(); }), std::bad_alloc);
396 }
397
398 // With memory again, the same traversals reach the end.
399 size_t count = 0;
400 for (auto it = zip_it(tree, list); it.has_curr(); it.next_ne())
401 ++count;
402 EXPECT_EQ(count, 1001u);
403}
404
405TEST(TreeAllocation, noexcept_specifications_hold)
406{
407 static_assert(std::is_nothrow_default_constructible_v<Avl_Tree<int>>);
408 static_assert(std::is_nothrow_default_constructible_v<Avl_Tree_Rk<int>>);
409 static_assert(std::is_nothrow_default_constructible_v<Rb_Tree<int>>);
410 static_assert(std::is_nothrow_default_constructible_v<HtdRbTree<int>>);
411 static_assert(std::is_nothrow_default_constructible_v<HtdRbTreeRk<int>>);
412 static_assert(std::is_nothrow_move_constructible_v<Rb_Tree<int>>);
413 static_assert(std::is_nothrow_move_constructible_v<Rb_Tree_Rk<int>>);
414 static_assert(std::is_nothrow_move_constructible_v<HtdRbTree<int>>);
415 static_assert(std::is_nothrow_move_constructible_v<HtdRbTreeRk<int>>);
416 static_assert(std::is_nothrow_move_constructible_v<DynSetTree<int>>);
417 static_assert(std::is_nothrow_move_constructible_v<DynMapTree<int, int>>);
418 using Node = AvlNode<int>;
419 // The inorder iterator pushes the left spine when it is built, and both
420 // iterators push while they advance: past min(Node::MaxHeight, 128)
421 // pending nodes they move to the heap, so those operations may throw
422 // bad_alloc.
423 static_assert(not std::is_nothrow_constructible_v<BinNodeInfixIterator<Node>, Node *>);
424 static_assert(std::is_nothrow_constructible_v<BinNodePrefixIterator<Node>, Node *>);
425 static_assert(not noexcept(std::declval<BinNodeInfixIterator<Node> &>().next_ne()));
426 static_assert(not noexcept(std::declval<BinNodePrefixIterator<Node> &>().next_ne()));
427
428 // An adaptor advances with the specification of the iterators it holds.
429 using Tree_It = DynSetTree<int>::Iterator;
430 using List_It = DynList<int>::Iterator;
431 static_assert(noexcept(std::declval<Pair_Iterator<List_It> &>().next_ne()));
432 static_assert(not noexcept(std::declval<Pair_Iterator<Tree_It, List_It> &>().next_ne()));
433 static_assert(not noexcept(std::declval<Pair_Iterator<List_It, Tree_It> &>().next_ne()));
434 using List = DynList<int>;
435 using Tree = DynSetTree<int>;
436 static_assert(noexcept(std::declval<ZipIterator<List, List> &>().next_ne()));
437 static_assert(not noexcept(std::declval<ZipIterator<Tree, List> &>().next_ne()));
438 static_assert(not noexcept(std::declval<ZipIterator<List, Tree> &>().next_ne()));
439 static_assert(noexcept(std::declval<EnumZipIterator<List, List> &>().next_ne()));
440 static_assert(not noexcept(std::declval<EnumZipIterator<Tree, List> &>().next_ne()));
441 static_assert(not noexcept(std::declval<EnumZipIterator<List, Tree> &>().next_ne()));
442
443 // The inline stack of pending nodes stops at 128 entries: an iterator over
444 // the generic BinNode (MaxHeight 2048) must not carry 16 KiB again.
445 static_assert(sizeof(BinNodeInfixIterator<BinNode<int>>) <= 128 * sizeof(void *) + 64);
446 static_assert(sizeof(BinNodePrefixIterator<BinNode<int>>) <= 128 * sizeof(void *) + 64);
447}
Zip iterators and functional operations for multiple containers.
Functional programming utilities for Aleph-w containers.
WeightedDigraph::Node Node
Inorder iterator on the nodes of a binary tree.
bool has_curr() const noexcept
Return true the iterator has current node.
Preorder iterator on the nodes of a binary tree.
Node belonging to a double circular linked list with header node.
Definition tpl_dnode.H:106
Dynamic heap of elements of type T ordered by a comparison functor.
T & insert(const T &item)
Insert a copy of item into the heap.
Iterator on the items of list.
Definition htlist.H:1614
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
Generic key-value map implemented on top of a binary search tree.
Dynamic set backed by balanced binary search trees with automatic memory management.
const size_t & size() const
Returns the cardinality of the set.
Key * insert(const Key &key)
Inserts a key into the dynamic set.
bool has_curr() const noexcept
Hybrid top-down/bottom-up red-black tree with rank support.
Hybrid top-down/bottom-up red-black tree.
Definition tpl_hRbTree.H:86
Node * insert(Node *p) noexcept(nothrow_compare_v< Compare, Key >)
Insert a node into the tree.
Declare AvlNode type with 40-byte pool allocation.
Definition avlNode.H:98
Key * insert(const Key &key)
Inserts a key into the hash table (copy version).
Definition hashDry.H:507
Node for QuadTree spatial data structure.
Definition quadnode.H:95
QuadTree - Hierarchical spatial index for 2D points.
Definition quadtree.H:126
Point * insert(Node *&r, const Point &p)
Recursive insert helper.
Definition quadtree.H:281
#define TEST(name)
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
Main namespace for Aleph-w library functions.
ZipIterator< Cs... > zip_it(const Cs &...cs)
Alias for get_zip_it.
Definition ah-zip.H:359
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
EnumZipIterator< Cs... > enum_zip_it(const Cs &...cs)
Alias for get_enum_zip_it.
Definition ah-zip.H:1421
T * allocate(AhArenaAllocator &arena, Args &&... args)
Allocate and construct an object in an arena.
Definition ah-arena.H:478
auto get_pair_it(C1 &c1, C2 &c2)
Create a Pair_Iterator for two containers.
void next_ne() noexcept(noexcept(std::declval< Aleph::const_iterator_t< HeadC > & >().next_ne()) and noexcept(std::declval< ZipIterator< TailC... > & >().next_ne()))
Advance all underlying iterators (unchecked variant).
Definition ah-zip.H:252
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Ranked AVL tree with nodes without a virtual destructor.
Definition tpl_avlRk.H:1592
AVL binary search tree with nodes without a virtual destructor.
Definition tpl_avl.H:831
const Key & get_curr() const
Randomized binary search tree.
Red-Black binary search tree with nodes without virtual destructor and with subtree counters for sele...
Definition tpl_rbRk.H:1653
Red-black tree with nodes without virtual destructor.
Treap (a special type of randomized binary search tree) using nodes without virtual destructor.
Definition tpl_treap.H:797
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
AVL tree with rank (order statistics).
AVL tree implementation (height-balanced BST).
Utility functions for binary tree operations.
Dynamic binary heap with node-based storage.
Dynamic key-value map based on balanced binary search trees.
Dynamic set implementations based on balanced binary search trees.
Hybrid top-down/bottom-up red-black tree with rank support.
Hybrid top-down/bottom-up red-black tree implementation.
Randomized binary search tree.
Red-Black tree with rank (order statistics).
Red-Black tree implementation (bottom-up balancing).
Top-down splay tree implementation (without rank support).
Treap: randomized BST combining tree and heap properties.
#define ALEPH_TEST_NOINLINE
#define SKIP_UNLESS_COUNTING_ALLOCATIONS()