Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
noexcept_allocation_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
37// A function that is noexcept and allocates ends the program when there is
38// no memory, where it should throw std::bad_alloc. The moves of several
39// containers did: they built something for the container that they moved
40// from, as the lists of a hash table of its capacity, the array of a
41// FixedQueue of the default one, or a header node, whose item is built by
42// default; and the hash functions of the maps were a std::bind, which a
43// std::function keeps in the heap and copies there.
44//
45// These tests build, move, move assign and swap each container, with
46// three kinds of item, and count the allocations of what is noexcept:
47// there must be none. The items are an int; one whose default
48// construction allocates and whose move does not; and one that, besides,
49// has no move, as a class of before C++11 with a copy written by hand, so
50// that moving it copies it, which allocates. And the container that was
51// moved from must take items again, unless it is one of a fixed capacity,
52// which a move leaves without array.
53//
54// The allocations are those of operator new, which allocation_failure.H
55// replaces. Those of malloc() are not counted: the directory of a
56// DynArray, which it makes when it first writes, and no more when it is
57// built, so that the move of a DynSetLinHash, which builds a linear table,
58// takes none. The last test looks at the heap of malloc(), where it can
59// be seen. The generator of random numbers of Treap, Treap_Rk and
60// Rand_Tree is inside the tree, and takes memory of malloc() only when it
61// is asked for the Mersenne Twister: random_structures_test looks at the
62// heap of malloc() when each randomized structure is built and moved.
63
64#include <gtest/gtest.h>
65
66#include "allocation_failure.H"
67
68#include <ah-mapping.H>
69#include <bitArray.H>
70#include <htlist.H>
71#include <tpl_array.H>
72#include <tpl_arrayHeap.H>
73#include <tpl_arrayQueue.H>
74#include <tpl_arrayStack.H>
75#include <tpl_avl.H>
76#include <tpl_avlRk.H>
77#include <tpl_binTree.H>
78#include <tpl_dynArray.H>
79#include <tpl_dynArrayHeap.H>
80#include <tpl_dynBinHeap.H>
81#include <tpl_dynDlist.H>
82#include <tpl_dynLhash.H>
83#include <tpl_dynListQueue.H>
84#include <tpl_dynListStack.H>
85#include <tpl_dynMapOhash.H>
86#include <tpl_dynMapTree.H>
87#include <tpl_dynMat.H>
88#include <tpl_dynSetHash.H>
89#include <tpl_dynSetTree.H>
90#include <tpl_dynSkipList.H>
91#include <tpl_flat_map.H>
92#include <tpl_flat_set.H>
93#include <tpl_graph.H>
94#include <tpl_hRbTree.H>
95#include <tpl_hRbTreeRk.H>
96#include <tpl_hash.H>
97#include <tpl_memArray.H>
99#include <tpl_odhash.H>
100#include <tpl_olhash.H>
101#include <tpl_rand_tree.H>
102#include <tpl_random_queue.H>
103#include <tpl_rb_tree.H>
104#include <tpl_rbRk.H>
105#include <tpl_small_vector.H>
106#include <tpl_splay_tree.H>
107#include <tpl_splay_treeRk.H>
108#include <tpl_tdRbTree.H>
109#include <tpl_tdRbTreeRk.H>
110#include <tpl_treap.H>
111#include <tpl_treapRk.H>
112
113#include <array>
114#include <cstddef>
115#include <cstdlib>
116#include <functional>
117#include <memory>
118#include <optional>
119#include <string>
120#include <type_traits>
121#include <utility>
122
123// The heap of malloc() is looked at where glibc reports it and no
124// sanitizer replaces malloc()
125#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__)
126# define TEST_UNDER_A_SANITIZER 1
127#elif defined(__has_feature)
128# if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) || \
129 __has_feature(memory_sanitizer)
130# define TEST_UNDER_A_SANITIZER 1
131# endif
132#endif
133#ifndef TEST_UNDER_A_SANITIZER
134# define TEST_UNDER_A_SANITIZER 0
135#endif
136
137#define TEST_SEES_THE_HEAP 0
138#if defined(__GLIBC__) && !TEST_UNDER_A_SANITIZER
139# if __GLIBC_PREREQ(2, 33)
140# include <malloc.h>
141# undef TEST_SEES_THE_HEAP
142# define TEST_SEES_THE_HEAP 1
143# endif
144#endif
145
146using namespace Aleph;
147
148namespace
149{
150 // An item whose default construction allocates, as that of an Array
151 // does: it keeps its number in the heap. Its move takes the number, so
152 // it does not allocate, and leaves the other item without one
153 struct Allocating
154 {
155 std::unique_ptr<int> number;
156
157 Allocating() : number(new int(-1)) {}
158
159 Allocating(const int i) : number(new int(i)) {}
160
161 Allocating(const Allocating & o) : number(new int(o.value())) {}
162
163 Allocating(Allocating &&) noexcept = default;
164
165 Allocating & operator = (const Allocating & o)
166 {
167 number.reset(new int(o.value()));
168 return *this;
169 }
170
171 Allocating & operator = (Allocating &&) noexcept = default;
172
173 int value() const noexcept { return number == nullptr ? -2 : *number; }
174
175 bool operator < (const Allocating & o) const noexcept { return value() < o.value(); }
176
177 bool operator == (const Allocating & o) const noexcept { return value() == o.value(); }
178 };
179
180 // An item as Allocating, of a class of before C++11: with a copy written
181 // by hand and no move, so that moving it copies it, which allocates.
182 // What moves or swaps such items allocates, and must not be noexcept;
183 // what moves a container of them must move none
184 struct Without_Move
185 {
186 std::unique_ptr<int> number;
187
188 Without_Move() : number(new int(-1)) {}
189
190 Without_Move(const int i) : number(new int(i)) {}
191
192 Without_Move(const Without_Move & o) : number(new int(o.value())) {}
193
194 Without_Move & operator = (const Without_Move & o)
195 {
196 number.reset(new int(o.value()));
197 return *this;
198 }
199
200 int value() const noexcept { return *number; }
201
202 bool operator < (const Without_Move & o) const noexcept { return value() < o.value(); }
203
204 bool operator == (const Without_Move & o) const noexcept { return value() == o.value(); }
205 };
206
207 // The hash of the tables of Aleph, which they find by the namespace
208 size_t aleph_hash_value(const Allocating & a) noexcept
209 {
210 return static_cast<size_t>(a.value()) * 40503u;
211 }
212
213 size_t aleph_hash_value(const Without_Move & a) noexcept
214 {
215 return static_cast<size_t>(a.value()) * 40503u;
216 }
217
218 // Another hash function of the keys of a map
219 size_t another_hash(const int & k) noexcept
220 {
221 return static_cast<size_t>(k) * 40503u + 7;
222 }
223
224 // What a check leaves out, where the code gives the reason
225 struct Leaving_Out
226 {
227 bool use_after_move = false; // a fixed capacity: no array after a move
228 };
229
230 constexpr Leaving_Out nothing{};
231 constexpr Leaving_Out its_use_after_a_move{true};
232
233 template <class C>
234 constexpr bool nothrow_swap =
235 requires (C & a, C & b) { { a.swap(b) } noexcept; };
236
237 // Builds, moves, move assigns and swaps containers of type C, which
238 // fill(c, from) fills with three items, from the number `from`; what is
239 // noexcept among them must not allocate. Then the container that the
240 // move left takes items again
241 template <class C, class Fill>
242 void expect_that_what_is_noexcept_does_not_allocate(const char * name, Fill fill,
243 const Leaving_Out out = nothing)
244 {
245 SCOPED_TRACE(name);
246
247 if (std::is_nothrow_default_constructible_v<C>)
248 {
249 std::optional<C> built;
250 const size_t before = allocations;
251 built.emplace();
252 EXPECT_EQ(allocations - before, 0u) << "its default construction";
253 }
254
255 C source;
256 fill(source, 0);
257 if (std::is_nothrow_move_constructible_v<C>)
258 {
259 std::optional<C> target;
260 const size_t before = allocations;
261 target.emplace(std::move(source));
262 EXPECT_EQ(allocations - before, 0u) << "its move construction";
263 if (not out.use_after_move)
264 {
265 fill(source, 10); // the moved-from one takes items
266 fill(*target, 20); // and so does the one that took them
267 }
268 }
269
270 if (std::is_nothrow_move_assignable_v<C>)
271 {
272 C from, to;
273 fill(from, 0);
274 fill(to, 30);
275 const size_t before = allocations;
276 to = std::move(from);
277 EXPECT_EQ(allocations - before, 0u) << "its move assignment";
278 if (not out.use_after_move)
279 {
280 fill(from, 40); // the one that was moved from takes items
281 fill(to, 50); // and so does the one that took them
282 }
283 }
284
285 if constexpr (nothrow_swap<C>)
286 {
287 C a, b;
288 fill(a, 0);
289 const size_t before = allocations;
290 a.swap(b);
291 EXPECT_EQ(allocations - before, 0u) << "its swap";
292 }
293 }
294
295 // The ways of filling a container with the items 0, 1 and 2 from `from`
296 template <class T>
297 struct With
298 {
299 static T item(const int i) { return T(i); }
300
301 static constexpr auto append = [] (auto & c, const int from)
302 {
303 for (int i = from; i < from + 3; ++i)
304 (void) c.append(item(i));
305 };
306
307 static constexpr auto insert = [] (auto & c, const int from)
308 {
309 for (int i = from; i < from + 3; ++i)
310 (void) c.insert(item(i));
311 };
312
313 static constexpr auto push = [] (auto & c, const int from)
314 {
315 for (int i = from; i < from + 3; ++i)
316 (void) c.push(item(i));
317 };
318
319 static constexpr auto put = [] (auto & c, const int from)
320 {
321 for (int i = from; i < from + 3; ++i)
322 (void) c.put(item(i));
323 };
324
325 static constexpr auto push_back = [] (auto & c, const int from)
326 {
327 for (int i = from; i < from + 3; ++i)
328 c.push_back(item(i));
329 };
330
331 // a map from int to T
332 static constexpr auto insert_value = [] (auto & c, const int from)
333 {
334 for (int i = from; i < from + 3; ++i)
335 (void) c.insert(i, item(i));
336 };
337
338 // a map from T to int
339 static constexpr auto insert_key = [] (auto & c, const int from)
340 {
341 for (int i = from; i < from + 3; ++i)
342 (void) c.insert(item(i), i);
343 };
344
345 static constexpr auto insert_node = [] (auto & g, const int from)
346 {
347 for (int i = from; i < from + 3; ++i)
348 (void) g.insert_node(item(i));
349 };
350
351 static constexpr auto write = [] (auto & m, const int from)
352 {
353 m.set_dimension(2, 2);
354 m.write(0, 1, item(from));
355 };
356 };
357
358 // The lists, the arrays, the stacks, the queues and the heaps of T
359 template <class T>
360 void check_the_sequences(const std::string & of)
361 {
362 auto name = [&of] (const char * container) { return container + ("<" + of + ">"); };
363 const auto w = With<T>();
364 // two macros, and not one with __VA_OPT__, which the preprocessor of
365 // MSVC does not take
366# define CHECK(Container, how) \
367 expect_that_what_is_noexcept_does_not_allocate<Container<T>> \
368 (name(#Container).c_str(), w.how)
369# define CHECK_FIXED(Container, how) \
370 expect_that_what_is_noexcept_does_not_allocate<Container<T>> \
371 (name(#Container).c_str(), w.how, its_use_after_a_move)
372
373 CHECK(DynList, append);
374 CHECK(DynDlist, append);
375 CHECK(DynListStack, push);
376 CHECK(DynListQueue, put);
377 CHECK(ArrayStack, push);
378 CHECK(ArrayQueue, put);
379 CHECK_FIXED(FixedStack, push);
381 CHECK(DynArray, append);
382 CHECK(Array, append);
383 CHECK(MemArray, append);
384 CHECK(DynArrayHeap, insert);
385 CHECK_FIXED(ArrayHeap, insert);
386 CHECK(DynBinHeap, insert);
387 CHECK(DynSkipList, insert);
388 CHECK(FlatSet, insert);
389 CHECK(Random_Set, put);
390 CHECK(DynMatrix, write);
391# undef CHECK
392# undef CHECK_FIXED
393 expect_that_what_is_noexcept_does_not_allocate<SmallVector<T, 4>>
394 (name("SmallVector").c_str(), w.push_back);
395 expect_that_what_is_noexcept_does_not_allocate<FlatMap<int, T>>
396 (name("FlatMap<int, ").c_str(), w.insert_value);
397 }
398
399 // The sets and the maps of T on each tree, and the mapping, which keeps
400 // a map. The move of a set moves its tree, whose header nodes take the
401 // keys of those of the other tree when building one by default may
402 // throw: with a key whose default construction allocates and whose move
403 // does not, it is noexcept and allocates nothing. With a key that has no
404 // move, the header nodes are built by default, which allocates, and the
405 // move is not noexcept, on every tree with such nodes
406 template <class T>
407 void check_the_trees(const std::string & of)
408 {
409 auto name = [&of] (const char * tree) { return "DynSetTree<" + of + ", " + tree + ">"; };
410 const auto w = With<T>();
411# define CHECK(Tree) \
412 expect_that_what_is_noexcept_does_not_allocate<DynSetTree<T, Tree>> \
413 (name(#Tree).c_str(), w.insert); \
414 expect_that_what_is_noexcept_does_not_allocate<DynMapTree<int, T, Tree>> \
415 (("DynMapTree<int, " + of + ", " #Tree ">").c_str(), w.insert_value)
416
417 CHECK(BinTree);
420 CHECK(Rb_Tree);
428 CHECK(Treap);
431# undef CHECK
432 expect_that_what_is_noexcept_does_not_allocate<DynMapTree<T, int>>
433 (("DynMapTree<" + of + ", int>").c_str(), w.insert_key);
434 expect_that_what_is_noexcept_does_not_allocate<AHMapping<int, T>>
435 (("AHMapping<int, " + of + ">").c_str(), w.insert_value);
436 }
437
438 // The sets and the maps of T on each hash table. The move of a linear
439 // one builds a table for the one that it moves from: its DynArray makes
440 // no directory until it writes, and the header of a list holds no key,
441 // so that it builds no item and allocates nothing, with every item
442 template <class T>
443 void check_the_hash_tables(const std::string & of)
444 {
445 const auto w = With<T>();
446 const Leaving_Out linear = nothing;
447# define CHECK_SET(Set, out) \
448 expect_that_what_is_noexcept_does_not_allocate<Set<T>> \
449 ((std::string(#Set "<") + of + ">").c_str(), w.insert, out)
450# define CHECK_MAP(Map, out) \
451 expect_that_what_is_noexcept_does_not_allocate<Map<int, T>> \
452 ((std::string(#Map "<int, ") + of + ">").c_str(), w.insert_value, out);\
453 expect_that_what_is_noexcept_does_not_allocate<Map<T, int>> \
454 ((std::string(#Map "<") + of + ", int>").c_str(), w.insert_key, out)
455
456 CHECK_SET(DynSetLhash, nothing);
457 CHECK_SET(DynSetHash, nothing);
458 CHECK_SET(DynSetLinHash, linear);
459 CHECK_SET(SetODhash, nothing);
460 CHECK_SET(SetOLhash, nothing);
461 CHECK_SET(HashSet, nothing);
462 CHECK_MAP(DynMapHash, nothing);
463 CHECK_MAP(DynMapLinHash, linear);
464 CHECK_MAP(MapODhash, nothing);
465 CHECK_MAP(MapOLhash, nothing);
466 CHECK_MAP(HashMap, nothing);
467 CHECK_MAP(DynLhashTable, nothing);
468# undef CHECK_SET
469# undef CHECK_MAP
470 }
471}
472
473// The tests need the operator new of allocation_failure.H
474struct NoexceptAllocation : public ::testing::Test
475{
476 void SetUp() override
477 {
479 GTEST_SKIP() << "ThreadSanitizer provides the allocation functions";
480 }
481};
482
483TEST_F(NoexceptAllocation, TheItemAllocatesWhenItIsBuiltByDefaultAndNotWhenItMoves)
484{
485 ASSERT_FALSE(std::is_nothrow_default_constructible_v<Allocating>);
486 ASSERT_TRUE(std::is_nothrow_move_constructible_v<Allocating>);
487
488 size_t before = allocations;
489 Allocating a;
490 EXPECT_EQ(allocations - before, 1u);
491
492 before = allocations;
493 const Allocating b(std::move(a));
494 EXPECT_EQ(allocations - before, 0u);
495 EXPECT_EQ(b.value(), -1);
496}
497
498// The third item is what it must be: built by default, copied and moved,
499// it allocates, and neither its move nor its swap is noexcept
500TEST_F(NoexceptAllocation, TheItemWithoutMoveAllocatesWhenItIsMoved)
501{
502 ASSERT_FALSE(std::is_nothrow_default_constructible_v<Without_Move>);
503 ASSERT_FALSE(std::is_nothrow_move_constructible_v<Without_Move>);
504 ASSERT_FALSE(std::is_nothrow_swappable_v<Without_Move>);
505
506 size_t before = allocations;
507 Without_Move a(7);
508 EXPECT_EQ(allocations - before, 1u);
509
510 before = allocations;
511 const Without_Move b(std::move(a));
512 EXPECT_EQ(allocations - before, 1u);
513 EXPECT_EQ(b.value(), 7);
514 EXPECT_EQ(a.value(), 7);
515}
516
518{
519 check_the_sequences<int>("int");
520 check_the_sequences<Allocating>("Allocating");
521 check_the_sequences<Without_Move>("Without_Move");
522 expect_that_what_is_noexcept_does_not_allocate<BitArray>
523 ("BitArray", [] (BitArray & b, const int) { b.push(1); b.push(0); });
524}
525
526TEST_F(NoexceptAllocation, SetsAndMapsOnTrees)
527{
528 check_the_trees<int>("int");
529 check_the_trees<Allocating>("Allocating");
530 check_the_trees<Without_Move>("Without_Move");
531
532 // the keys of the map of a polynomial of several variables are arrays,
533 // whose default construction allocates
534 expect_that_what_is_noexcept_does_not_allocate<MultiPolynomial>
535 ("MultiPolynomial", [] (MultiPolynomial & p, const int from)
536 {
537 p = MultiPolynomial(2, 1.0 + from);
538 });
539}
540
541// The keys and the values that the checks above take are what they must
542// be: the move of a set of int is noexcept, and so it is checked; so is
543// the one of a set of the item that allocates when it is built by default
544// and not when it moves, which said that it may throw until 7.9.0; and
545// the one of a set of the item without a move is not, on a tree with
546// header nodes, and it is noexcept on the one without them
547TEST_F(NoexceptAllocation, TheMovesOfTheSetsOnTreesThatAreChecked)
548{
549 EXPECT_TRUE(std::is_nothrow_move_constructible_v<DynSetTree<int>>);
550 EXPECT_TRUE((std::is_nothrow_move_constructible_v<DynMapTree<int, int>>));
551 EXPECT_TRUE((std::is_nothrow_move_constructible_v<AHMapping<int, int>>));
552 EXPECT_TRUE(std::is_nothrow_move_constructible_v<DynSetTree<Allocating>>);
553 EXPECT_TRUE((std::is_nothrow_move_constructible_v<DynMapTree<int, Allocating>>));
554 EXPECT_TRUE((std::is_nothrow_move_constructible_v<DynMapTree<Allocating, int>>));
555 EXPECT_TRUE((std::is_nothrow_move_constructible_v<AHMapping<int, Allocating>>));
556 EXPECT_TRUE(std::is_nothrow_move_constructible_v<MultiPolynomial>);
557 EXPECT_FALSE(std::is_nothrow_move_constructible_v<DynSetTree<Without_Move>>);
558 EXPECT_FALSE((std::is_nothrow_move_constructible_v<DynMapTree<int, Without_Move>>));
559 EXPECT_FALSE((std::is_nothrow_move_constructible_v<DynMapTree<Without_Move, int>>));
560 EXPECT_FALSE((std::is_nothrow_move_constructible_v<AHMapping<int, Without_Move>>));
561 EXPECT_TRUE((std::is_nothrow_move_constructible_v<DynSetTree<Without_Move, Splay_Tree_Rk>>));
562 EXPECT_TRUE((std::is_nothrow_move_constructible_v<DynSetTree<Without_Move, Rand_Tree>>));
563}
564
565TEST_F(NoexceptAllocation, SetsAndMapsOnHashTables)
566{
567 check_the_hash_tables<int>("int");
568 check_the_hash_tables<Allocating>("Allocating");
569 check_the_hash_tables<Without_Move>("Without_Move");
570}
571
572// The moves of the linear tables are noexcept with every item, and are
573// checked above: they allocated, and with the item without a move their
574// move assignment did too, for the swap of the default values of the two
575// arrays. The set of random draws keeps its items in a DynArray: its move
576// follows that of the array, and its move assignment, which swaps the
577// default values of two arrays, says that it may throw with an item whose
578// swap may; it was noexcept without a condition, and allocated
579TEST_F(NoexceptAllocation, TheMovesOfTheLinearTablesAndOfTheRandomSetThatAreChecked)
580{
581 EXPECT_TRUE(std::is_nothrow_move_constructible_v<DynSetLinHash<int>>);
582 EXPECT_TRUE(std::is_nothrow_move_constructible_v<DynSetLinHash<Allocating>>);
583 EXPECT_TRUE(std::is_nothrow_move_constructible_v<DynSetLinHash<Without_Move>>);
584 EXPECT_TRUE(std::is_nothrow_move_assignable_v<DynSetLinHash<Without_Move>>);
585 EXPECT_TRUE((std::is_nothrow_move_constructible_v<DynMapLinHash<int, Without_Move>>));
586 EXPECT_TRUE((std::is_nothrow_move_assignable_v<DynMapLinHash<Without_Move, int>>));
587
588 EXPECT_TRUE(std::is_nothrow_move_constructible_v<Random_Set<int>>);
589 EXPECT_TRUE(std::is_nothrow_move_assignable_v<Random_Set<int>>);
590 EXPECT_FALSE(std::is_nothrow_move_constructible_v<Random_Set<Allocating>>);
591 EXPECT_TRUE(std::is_nothrow_move_assignable_v<Random_Set<Allocating>>);
592 EXPECT_FALSE(std::is_nothrow_move_constructible_v<Random_Set<Without_Move>>);
593 EXPECT_FALSE(std::is_nothrow_move_assignable_v<Random_Set<Without_Move>>);
594}
595
596// A map that took another hash function of the keys keeps it as the one
597// that it was built with: in the buffer of the std::function of its table
598TEST_F(NoexceptAllocation, AMapThatTookAnotherHashFunctionMovesWithoutAllocating)
599{
600 const auto fill = [] (auto & m, const int from)
601 {
602 m.set_hash_fct(another_hash);
603 for (int i = from; i < from + 3; ++i)
604 (void) m.insert(i, i);
605 };
606 expect_that_what_is_noexcept_does_not_allocate<DynMapHash<int, int>>
607 ("DynMapHash<int, int> after set_hash_fct()", fill);
608}
609
610namespace
611{
612 // A hash function with 128 bytes of state: it does not fit in the buffer
613 // of a std::function, which keeps it in the heap and allocates to copy it
614 struct Large_Hash
615 {
616 std::array<size_t, 16> salt{};
617
618 size_t operator () (const int & k) const noexcept
619 {
620 return static_cast<size_t>(k) * 40503u + salt[0];
621 }
622 };
623}
624
625// The move assignment of a table of chained lists copies no hash function:
626// the two tables swap them. So it allocates nothing even with a hash
627// function whose copy allocates. The move constructor copies it, so that
628// the table that it moves from keeps it: with such a function it
629// allocates, in a constructor that is noexcept
630TEST_F(NoexceptAllocation, AMoveAssignmentOfATableOfChainedListsCopiesNoHashFunction)
631{
632 using Fct = std::function<size_t(const int &)>;
633 {
634 const Fct large{Large_Hash()};
635 const size_t before = allocations;
636 const Fct copy(large);
637 ASSERT_GT(allocations - before, 0u) << "the hash function of this test must not fit";
638 }
639
640 LhashTable<int> from(101), to(101);
641 from.set_hash_fct(Fct(Large_Hash()));
642 to.set_hash_fct(Fct(Large_Hash()));
643 for (int i = 0; i < 3; ++i)
644 ASSERT_NE(from.insert(new LhashBucket<int>(i)), nullptr);
645 size_t before = allocations;
646 to = std::move(from);
647 EXPECT_EQ(allocations - before, 0u) << "the move assignment of LhashTable";
648 EXPECT_NE(to.search(1), nullptr);
649 ASSERT_NE(from.insert(new LhashBucket<int>(9)), nullptr); // it goes on
650 EXPECT_NE(from.search(9), nullptr);
651
652 DynSetLhash<int> set_from, set_to;
653 set_from.set_hash_fct(Fct(Large_Hash()));
654 set_to.set_hash_fct(Fct(Large_Hash()));
655 for (int i = 0; i < 3; ++i)
656 ASSERT_NE(set_from.insert(i), nullptr);
657 before = allocations;
658 set_to = std::move(set_from);
659 EXPECT_EQ(allocations - before, 0u) << "the move assignment of DynSetLhash";
660 EXPECT_TRUE(set_to.contains(1));
661 ASSERT_NE(set_from.insert(9), nullptr);
662 EXPECT_TRUE(set_from.contains(9));
663}
664
666{
668 using Arc = Graph_Arc<int>;
669 const auto w = With<Allocating>();
670 expect_that_what_is_noexcept_does_not_allocate<List_Graph<Node, Arc>>("List_Graph", w.insert_node);
671 expect_that_what_is_noexcept_does_not_allocate<List_Digraph<Node, Arc>>("List_Digraph", w.insert_node);
672}
673
674#if TEST_SEES_THE_HEAP
675namespace
676{
677 // The bytes of malloc() in use, those of operator new included
678 size_t heap_in_use()
679 {
680 const struct mallinfo2 m = mallinfo2();
681 return m.uordblks + m.hblkhd;
682 }
683
684 // malloc() keeps the small blocks that a thread frees in a cache of the
685 // thread, of some seven blocks of each size up to about a kilobyte, and
686 // counts them as in use: a block that is taken from that cache does not
687 // change the bytes in use, so that the heap would not show the directory
688 // of a DynArray, of 512 bytes, once another one was freed. While one of
689 // these lives, it holds eight blocks of each of those sizes, taken from
690 // the cache first: the cache is empty, and a block that is allocated
691 // shows. Its pointers are volatile: an optimizer drops a malloc() whose
692 // block is only freed
693 class Empty_Thread_Cache
694 {
695 static constexpr size_t Largest = 1040, Step = 16, Of_Each = 8;
696
697 void * volatile held[(Largest / Step) * Of_Each];
698
699 public:
700 Empty_Thread_Cache() noexcept
701 {
702 size_t i = 0;
703 for (size_t size = Step; size <= Largest; size += Step)
704 for (size_t k = 0; k < Of_Each; ++k)
705 held[i++] = std::malloc(size - 8);
706 }
707
708 ~Empty_Thread_Cache()
709 {
710 for (void * block : held)
711 std::free(block);
712 }
713
714 Empty_Thread_Cache(const Empty_Thread_Cache &) = delete;
715 Empty_Thread_Cache & operator = (const Empty_Thread_Cache &) = delete;
716 };
717
718 // What building a container by default, and then moving it twice, take
719 // of the heap of malloc(), in bytes: {built, after the two moves}
720 template <class C>
721 std::pair<long, long> heap_taken_by()
722 {
723 const Empty_Thread_Cache no_cache;
724 const size_t before = heap_in_use();
725 const auto since = [before]
726 {
727 return static_cast<long>(heap_in_use()) - static_cast<long>(before);
728 };
729 std::optional<C> a, b, c;
730 a.emplace();
731 const long built = since();
732 if constexpr (std::is_move_constructible_v<C>)
733 {
734 b.emplace(std::move(*a));
735 c.emplace(std::move(*b));
736 }
737 return {built, since()};
738 }
739
740 template <class C>
741 void expect_no_memory_of_malloc(const char * name)
742 {
743 const auto [built, moved] = heap_taken_by<C>();
744 EXPECT_EQ(built, 0) << name << ", built by default";
745 EXPECT_EQ(moved, 0) << name << ", moved twice";
746 }
747}
748#endif
749
750// A DynArray makes its directory, a block of malloc(), when it first
751// writes: building one, and what keeps one, takes no memory, and neither
752// does moving it. A linear hash table keeps its lists in a DynArray, and
753// the move of a DynSetLinHash builds a table: it took a directory, inside
754// a move that is noexcept, which the counts of operator new did not see
755TEST_F(NoexceptAllocation, WhatKeepsADynArrayTakesNoMemoryUntilItWrites)
756{
757#if TEST_SEES_THE_HEAP
758 // The heap must show a block of the size of a directory once the cache
759 // of the thread is empty: else the checks below would see nothing. A
760 // cache that holds more blocks than Empty_Thread_Cache takes, as with
761 // GLIBC_TUNABLES=glibc.malloc.tcache_count=16, may hide it: the test is
762 // then skipped. The pointer to the block is volatile, as those of
763 // Empty_Thread_Cache: with optimizations, a malloc() whose block is only
764 // freed was dropped, and the heap showed nothing
765 {
766 const Empty_Thread_Cache no_cache;
767 const size_t before = heap_in_use();
768 void * volatile block = std::malloc(512);
769 const bool shows = heap_in_use() > before;
770 std::free(block);
771 if (not shows)
772 GTEST_SKIP() << "the heap does not show a block of 512 bytes";
773 }
774
775 expect_no_memory_of_malloc<DynArray<int>>("DynArray<int>");
776 expect_no_memory_of_malloc<DynArrayHeap<int>>("DynArrayHeap<int>");
777 expect_no_memory_of_malloc<Random_Set<int>>("Random_Set<int>");
778 expect_no_memory_of_malloc<BitArray>("BitArray");
779 expect_no_memory_of_malloc<LinearHashTable<int>>("LinearHashTable<int>");
780 expect_no_memory_of_malloc<DynSetLinHash<int>>("DynSetLinHash<int>");
781 expect_no_memory_of_malloc<DynSetLinHash<std::string>>("DynSetLinHash<std::string>");
782 expect_no_memory_of_malloc<DynMapLinHash<int, int>>("DynMapLinHash<int, int>");
783
784 // and the heap shows the directory that the first write of an array
785 // takes
786 {
787 DynArray<int> array;
788 const Empty_Thread_Cache no_cache;
789 const size_t before = heap_in_use();
790 (void) array.exist(0); // a reader makes no directory
791 EXPECT_EQ(heap_in_use(), before);
792 {
793 const DynArray<int> copy(array); // nor the copy of one that has none
794 EXPECT_EQ(heap_in_use(), before);
795 }
796 array.touch(0) = 1;
797 EXPECT_GT(heap_in_use(), before);
798 }
799#else
800 GTEST_SKIP() << "the heap of malloc() cannot be looked at here";
801#endif
802}
Bidirectional mapping between two types.
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
A global operator new that a test can make fail.
#define ALEPH_ALLOCATION_FAILURE_UNDER_TSAN
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
Space-efficient bit array implementation.
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
A generic key-value mapping container with inverse operation support.
Definition ah-mapping.H:70
Fixed-capacity binary heap backed by a raw array.
Queue implemented with a single dynamic array.
Stack implemented with simple dynamic array and with bounds verification.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
Contiguous array of bits.
Definition bitArray.H:201
void push(const unsigned int value)
Inserts the value at the end of the array.
Definition bitArray.H:506
Dynamic heap (priority queue) backed by DynArray.
T & touch(const size_t i)
Touch the entry i.
bool exist(const size_t i) const
Return true if the i-th entry is accessible.
Dynamic heap of elements of type T ordered by a comparison functor.
Dynamic doubly linked list with O(1) size and bidirectional access.
Self-adjusting dynamic hash table.
bool contains(const Key &key) const noexcept
Return true if the key exists in the table.
Key * insert(const Key &key)
Inserts key into the hash set.
Dynamic hash table mapping keys to records with separate chaining.
Dynamic queue of elements of generic type T based on single linked list.
Dynamic stack of elements of generic type T based on a singly linked list.
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 matrix with sparse storage.
Definition tpl_dynMat.H:122
Dynamic set backed by balanced binary search trees with automatic memory management.
Dynamic ordered set implemented with a Skip List.
Very simple queue implemented with a contiguous array.
Fixed length stack.
Ordered set stored as a sorted contiguous array.
Bucket * search(const Key &key) const noexcept
Search in the table for a bucket with key.
Definition tpl_lhash.H:555
void set_hash_fct(Hash_Fct fct)
Sets the hash function.
Definition tpl_lhash.H:454
Sparse multivariate polynomial.
Hybrid top-down/bottom-up red-black tree with rank support.
Hybrid top-down/bottom-up red-black tree.
Definition tpl_hRbTree.H:86
Simple, scalable and fast dynamic array.
Open addressing hash table with double hashing collision resolution.
Definition tpl_odhash.H:193
void set_hash_fct(Hash_Fct fct)
Definition tpl_odhash.H:653
Open addressing hash table with linear probing collision resolution.
Definition tpl_olhash.H:175
Top-down red-black tree with rank (no virtual destructor).
Top-down red-black tree without virtual destructor.
Key * insert(const Key &key)
Inserts a key into the hash table (copy version).
Definition hashDry.H:507
Singly linked list implementations with head-tail access.
Compiler_SSA_Block & block(Compiler_SSA_Function &function, const Compiler_SSA_Block_Id id)
Definition SSA.H:636
Main namespace for Aleph-w library functions.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
Gen_MultiPolynomial< double, Grevlex_Order > MultiPolynomial
Multivariate polynomial with double coefficients, grevlex.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
void fill(Itor beg, const Itor &end, const T &value)
Fill a range with a value.
Definition ahAlgo.H:707
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
size_t aleph_hash_value(const AdversarialTranspositionKey< StateKey > &key) noexcept
Definition Negamax.H:134
STL namespace.
#define CHECK_FIXED(Container, how)
#define CHECK_SET(Set, out)
#define CHECK_MAP(Map, out)
TEST_F(NoexceptAllocation, TheItemAllocatesWhenItIsBuiltByDefaultAndNotWhenItMoves)
#define CHECK(Container, how)
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
Binary search tree with nodes without virtual destructors,.
Hash-based dynamic set (defined in tpl_dynSetHash.H).
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Node belonging to a graph implemented with a double linked adjacency list.
Definition tpl_graph.H:126
Generic hash table with collision resolution by separate chaining and buckets without virtual destruc...
Definition tpl_lhash.H:1008
Open addressing hash map using double hashing.
Open addressing hash map using linear probing.
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.
Extended treap (a special type of randomized binary search tree) which manages selection and splittin...
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)
static int * k
Fixed-capacity binary heap and heapsort algorithms.
Circular queue implementations backed by arrays.
Stack implementations backed by dynamic or fixed arrays.
Dynamic array container with automatic resizing.
AVL tree with rank (order statistics).
AVL tree implementation (height-balanced BST).
Generic unbalanced binary search tree.
Array-based dynamic binary heap.
Lazy and scalable dynamic array implementation.
Dynamic binary heap with node-based storage.
Dynamic doubly linked list implementation.
Dynamic hash table mapping keys to records with separate chaining.
Dynamic queue implementation based on linked lists.
Dynamic stack implementation based on linked lists.
Dynamic map with open hashing.
Dynamic key-value map based on balanced binary search trees.
Dynamic matrix with lazy allocation.
Dynamic set implementations based on hash tables.
Dynamic set implementations based on balanced binary search trees.
Dynamic ordered set implemented with a Skip List.
Sorted-array map (Aleph::FlatMap), a cache-friendly ordered map.
Sorted-array set (Aleph::FlatSet), a cache-friendly ordered set.
Generic graph and digraph implementations.
Hybrid top-down/bottom-up red-black tree with rank support.
Hybrid top-down/bottom-up red-black tree implementation.
Unified hash table interface.
Simple, scalable, contiguous dynamic array.
Sparse multivariate polynomial over an arbitrary coefficient ring.
Open addressing hash table with double hashing.
Open addressing hash table with linear probing.
Randomized binary search tree.
Random access queue (bag) with O(1) random pop.
Red-Black tree with rank (order statistics).
Red-Black tree implementation (bottom-up balancing).
Dynamic array with inline storage (Aleph::SmallVector).
Top-down splay tree with rank support.
Top-down splay tree implementation (without rank support).
Top-down Red-Black tree with rank support.
Top-down Red-Black tree implementation.
Treap with rank (order statistics).
Treap: randomized BST combining tree and heap properties.