Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
random_structures_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
53#include <gtest/gtest.h>
54#include <ah-random.H>
55#include <ah_init_guard.H>
56#include <tpl_dynSkipList.H>
57#include <tpl_interval_tree.H>
58#include <tpl_rand_tree.H>
59#include <tpl_random_queue.H>
60#include <tpl_treap.H>
61#include <tpl_treapRk.H>
62
63#if defined(_MSC_VER) && !defined(__clang__)
64# define TEST_SKIP_LIST 0
65#else
66# define TEST_SKIP_LIST 1
67# include <tpl_skipList.H>
68#endif
69
70#include <cstdint>
71#include <cstdio>
72#include <cstdlib>
73#include <limits>
74#include <optional>
75#include <string>
76#include <thread>
77#include <type_traits>
78#include <utility>
79#include <vector>
80
81// The heap of malloc() is looked at where glibc reports it and no
82// sanitizer replaces malloc(): there, a structure that makes a Mersenne
83// Twister is seen to take its bytes
84#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__)
85# define TEST_UNDER_A_SANITIZER 1
86#elif defined(__has_feature)
87# if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) || \
88 __has_feature(memory_sanitizer)
89# define TEST_UNDER_A_SANITIZER 1
90# endif
91#endif
92#ifndef TEST_UNDER_A_SANITIZER
93# define TEST_UNDER_A_SANITIZER 0
94#endif
95
96#define TEST_SEES_THE_HEAP 0
97#if defined(__GLIBC__) && !TEST_UNDER_A_SANITIZER
98# if __GLIBC_PREREQ(2, 33)
99# include <malloc.h>
100# undef TEST_SEES_THE_HEAP
101# define TEST_SEES_THE_HEAP 1
102# endif
103#endif
104
105// The tests call on purpose the deprecated accessors of the structures:
106// rng(), gsl_rng_object() and get_rng()
107#if defined(__GNUC__)
108# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
109#elif defined(_MSC_VER)
110# pragma warning(disable: 4996)
111#endif
112
113using namespace Aleph;
114
115#if TEST_SKIP_LIST
116// The sentinel key of a skip list of int, which its user gives
117template <>
119{
120 return std::numeric_limits<int>::max();
121}
122#endif
123
124namespace
125{
126 // a fixed scramble of 0 .. n - 1
127 std::vector<int> keys(const int n)
128 {
129 std::vector<int> k(n);
130 for (int i = 0; i < n; ++i)
131 k[i] = (i * 37 + 11) % n;
132 return k;
133 }
134
135 void add(std::string & out, const char * fmt, unsigned long a)
136 {
137 char buf[64];
138 std::snprintf(buf, sizeof buf, fmt, a);
139 out += buf;
140 }
141
142 template <bool Prio, class Node>
143 void pre(Node * p, std::string & out)
144 {
145 if (p == Node::NullPtr)
146 return;
147 add(out, " %lu", static_cast<unsigned long>(KEY(p)));
148 if constexpr (Prio)
149 add(out, "/%lu", static_cast<unsigned long>(PRIO(p)));
150 pre<Prio>(LLINK(p), out);
151 pre<Prio>(RLINK(p), out);
152 }
153
154 void interval_pre(Interval_Tree<int>::Node * p, std::string & out)
155 {
157 return;
158 char buf[64];
159 std::snprintf(buf, sizeof buf, " [%d,%d]/%lu", KEY(p).low, KEY(p).high,
160 static_cast<unsigned long>(PRIO(p)));
161 out += buf;
162 interval_pre(LLINK(p), out);
163 interval_pre(RLINK(p), out);
164 }
165
166 std::uint64_t fnv1a(const std::string & s)
167 {
168 std::uint64_t h = 0xcbf29ce484222325ULL;
169 for (const unsigned char c : s)
170 {
171 h ^= c;
172 h *= 0x100000001b3ULL;
173 }
174 return h;
175 }
176
177 // The lines of output for a seed: the seed, and then each structure
178 std::vector<std::string> lines_for(const unsigned long s)
179 {
180 std::vector<std::string> lines;
181 std::string out = "== seed ";
182 add(out, "%lu", s);
183 lines.push_back(out);
184
185 {
186 Treap<int> t(s);
187 for (int k : keys(40))
188 t.insert(new Treap<int>::Node(k));
189 out = "treap:";
190 pre<true>(t.getRoot(), out);
191 add(out, " next %lu", t.rng().get());
192 lines.push_back(out);
193 destroyRec(t.getRoot());
194 }
195 {
196 Treap_Rk<int> t(s);
197 for (int k : keys(40))
198 t.insert(new Treap_Rk<int>::Node(k));
199 out = "treap_rk:";
200 pre<true>(t.getRoot(), out);
201 lines.push_back(out);
202 destroyRec(t.getRoot());
203 }
204 {
205 Rand_Tree<int> t(static_cast<unsigned int>(s));
206 for (int k : keys(60))
207 t.insert(new Rand_Tree<int>::Node(k));
208 for (int k = 0; k < 60; k += 7)
209 delete t.remove(k);
210 out = "rand_tree:";
211 pre<false>(t.getRoot(), out);
212 add(out, " next %lu", t.rng().get());
213 lines.push_back(out);
214 destroyRec(t.getRoot());
215 }
216 {
217#if TEST_SKIP_LIST
219 out = "skiplist:";
220 for (int i = 0; i < 64; ++i)
221 add(out, " %lu", static_cast<unsigned long>(l.generateRandomLevel()));
222 l.set_seed(s + 777);
223 for (int i = 0; i < 64; ++i)
224 add(out, " %lu", static_cast<unsigned long>(l.generateRandomLevel()));
225#else
226 out.clear(); // no SkipList: an empty line, which is not compared
227#endif
228 lines.push_back(out);
229 }
230 {
232 for (int k : keys(200))
233 l.insert(k);
234 out = "dynskiplist: next ";
235 add(out, "%lu", l.rng().get());
236 l.set_seed(s + 5);
237 for (int k = 200; k < 260; ++k)
238 l.insert(k);
239 add(out, " next %lu", l.rng().get());
240 lines.push_back(out);
241 }
242 {
244 q.set_seed(s);
245 for (int k = 0; k < 50; ++k)
246 q.append(k);
247 out = "random_set:";
248 for (int k = 0; k < 20; ++k)
249 add(out, " %lu", static_cast<unsigned long>(q.get()));
250 for (int k = 50; k < 60; ++k)
251 q.put(k);
252 while (not q.is_empty())
253 add(out, " %lu", static_cast<unsigned long>(q.get()));
254 add(out, " next %lu", q.rng().get());
255 lines.push_back(out);
256 }
257 {
259 for (int k : keys(30))
260 t.insert(new Interval_Tree<int>::Node(Interval<int>(k, k + (k % 5))));
261 out = "interval_tree:";
262 interval_pre(t.getRoot(), out);
263 add(out, " next %lu", t.rng().get());
264 lines.push_back(out);
265 destroyRec(t.getRoot());
266 }
267 return lines;
268 }
269} // namespace
270
271TEST(RandomStructures, WhatTheyMadeWithGsl)
272{
273 // The hashes of the lines that the structures gave with GSL
274 static const std::uint64_t golden[] = {
275 // seed 0: the line of the seed, treap, treap_rk, rand_tree, skiplist,
276 // dynskiplist, random_set and interval_tree
277 0xbf6aeb12f149fed4ULL, 0xaf0b5ce48c61a393ULL, 0x1d6615e62a03143dULL,
278 0x6a2166086b45a98cULL, 0x6c63d3b271929409ULL, 0xd12483814d06e78eULL,
279 0xb24574a6225d43afULL, 0x7cf954f63b5b566cULL,
280 // seed 1: the line of the seed, treap, treap_rk, rand_tree, skiplist,
281 // dynskiplist, random_set and interval_tree
282 0xbf6aec12f14a0087ULL, 0x9278d4c463049723ULL, 0x4a4d7bcbd6401c76ULL,
283 0xc799efa20f1ddcc9ULL, 0x7d0232dce7b87affULL, 0xe9fc8e3d9141e44bULL,
284 0x348d2efb0da28b7dULL, 0xe155284b0cd406abULL,
285 // seed 12345: the line of the seed, treap, treap_rk, rand_tree, skiplist,
286 // dynskiplist, random_set and interval_tree
287 0x118e2e24d31a4c4fULL, 0x9371ee5b6011fe82ULL, 0x023bbd9db1128c32ULL,
288 0x73f6f6e38ba2c668ULL, 0x99c9ec1e34beceadULL, 0x9a7271d69b2bb3f2ULL,
289 0xc2282e94fa57e861ULL, 0x279881ccaeee8bb8ULL,
290 // seed 4294967294: the line of the seed, treap, treap_rk, rand_tree, skiplist,
291 // dynskiplist, random_set and interval_tree
292 0x0d24555385f3f048ULL, 0x4f9361527a9e7f0bULL, 0xd30abfc5d0c391a5ULL,
293 0xbd37d372779f3bccULL, 0x799d90ae07e107c6ULL, 0xc197f84291991cd4ULL,
294 0xb18163959293eb53ULL, 0x25c23e87534c6092ULL,
295 // seed 4294967295: the line of the seed, treap, treap_rk, rand_tree, skiplist,
296 // dynskiplist, random_set and interval_tree
297 0x0d24565385f3f1fbULL, 0xaf0b5ce48c61a393ULL, 0x1d6615e62a03143dULL,
298 0x6a2166086b45a98cULL, 0x653c1a017fdf92a8ULL, 0x098538cb93321526ULL,
299 0x57f5924f1a57c31bULL, 0x7cf954f63b5b566cULL,
300 // seed 4294967301: the line of the seed, treap, treap_rk, rand_tree, skiplist,
301 // dynskiplist, random_set and interval_tree
302 0x042cb55380c9916dULL, 0x521310421689f20dULL, 0x4f50ad59636c17e3ULL,
303 0xdcef84f3309fdf82ULL, 0xfe21fd5f50f37f28ULL, 0xbe5611ca7fbc90b9ULL,
304 0xf18df4da3be551c4ULL, 0x491cadffd8e29cefULL,
305 };
306
307 // The last seed, above 32 bits, exists only where unsigned long has 64:
308 // where it has 32, its lines are skipped
309 const unsigned long long seeds[] = {0, 1, 12345, 0xfffffffeULL, 0xffffffffULL,
310 0x100000005ULL};
311 const size_t lines_per_seed = 8;
312 size_t i = 0;
313 for (const unsigned long long s : seeds)
314 {
315 if (s > std::numeric_limits<unsigned long>::max())
316 {
317 i += lines_per_seed;
318 continue;
319 }
320
321 const std::vector<std::string> lines = lines_for(static_cast<unsigned long>(s));
322 ASSERT_EQ(lines.size(), lines_per_seed);
323 for (const std::string & line : lines)
324 {
325 ASSERT_LT(i, std::size(golden));
326 if (not line.empty()) // that of a structure that is not built
327 EXPECT_EQ(fnv1a(line), golden[i]) << line;
328 ++i;
329 }
330 }
331 EXPECT_EQ(i, std::size(golden));
332}
333
334#if ALEPH_WITH_GSL
335TEST(RandomStructures, TheTreapPrioritiesAreTheNumbersOfGsl)
336{
337 // A treap seeded with s took its priorities, one per insertion, from a
338 // gsl_rng_mt19937 seeded with s, through an unsigned int, modulo 2^32 - 1
339 for (const unsigned long s : {0UL, 7UL, 0xfffffffeUL, 0xffffffffUL})
340 {
341 gsl_rng * r = gsl_rng_alloc(gsl_rng_mt19937);
342 gsl_rng_set(r, static_cast<unsigned int>(s) % gsl_rng_max(r));
343 Treap<int> t(s);
344 std::vector<Treap<int>::Node *> nodes;
345 for (int k : keys(100))
346 {
347 nodes.push_back(new Treap<int>::Node(k));
348 t.insert(nodes.back());
349 }
350 for (auto * p : nodes)
351 EXPECT_EQ(PRIO(p), gsl_rng_get(r)) << "seed " << s << ", key " << KEY(p);
352 destroyRec(t.getRoot());
353 gsl_rng_free(r);
354 }
355}
356
357# if defined(__GNUC__)
358# pragma GCC diagnostic push
359# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
360# elif defined(_MSC_VER)
361# pragma warning(push)
362# pragma warning(disable: 4996)
363# endif
364
365namespace
366{
367 // The gsl_rng of a structure acts on its generator: a seed set through it
368 // reseeds the generator, and the draws through it are those of a twin
369 template <class S>
370 void check_adapter(S & s, gsl_rng * r)
371 {
372 ASSERT_NE(r, nullptr);
373 EXPECT_EQ(gsl_rng_min(r), 0UL);
374 EXPECT_EQ(gsl_rng_max(r), 0xffffffffUL);
375 gsl_rng_set(r, 99);
376 EXPECT_EQ(s.rng(), Gsl_Compatible_Rng(99));
377 Gsl_Compatible_Rng twin(99);
378 for (int i = 0; i < 100; ++i)
379 {
380 EXPECT_EQ(gsl_rng_uniform_int(r, 1000), twin.uniform_int(1000));
381 EXPECT_EQ(gsl_rng_get(r), twin.get());
382 EXPECT_EQ(gsl_rng_uniform(r), twin.uniform());
383 }
384 EXPECT_EQ(s.rng(), twin);
385 }
386}
387
388TEST(RandomStructures, TheDeprecatedGslRngActsOnTheGenerator)
389{
390 Treap<int> treap(1);
391 check_adapter(treap, treap.gsl_rng_object());
392 EXPECT_EQ(treap.gsl_rng_object(), treap.gsl_rng_object()); // made once
393
394 Rand_Tree<int> rand_tree(1);
395 check_adapter(rand_tree, rand_tree.gsl_rng_object());
396
397# if TEST_SKIP_LIST
398 SkipList<int, int> skip_list(1UL);
399 check_adapter(skip_list, skip_list.gsl_rng_object());
400# endif
401
402 DynSkipList<int> dyn_skip_list(1UL);
403 check_adapter(dyn_skip_list, dyn_skip_list.gsl_rng_object());
404
405 Random_Set<int> random_set;
406 check_adapter(random_set, random_set.get_rng());
407
408 Interval_Tree<int> interval_tree(1);
409 check_adapter(interval_tree, interval_tree.gsl_rng_object());
410}
411
412TEST(RandomStructures, TheDeprecatedGslRngFollowsItsGenerator)
413{
414 // after a swap, the gsl_rng of a treap reads from the generator that went
415 // to the other one, as the gsl_rng itself went before
416 Treap<int> a(1), b(2);
417 gsl_rng * ra = a.gsl_rng_object();
418 a.swap(b);
419 Gsl_Compatible_Rng twin = b.rng();
420 EXPECT_EQ(twin, Gsl_Compatible_Rng(1));
421 EXPECT_EQ(gsl_rng_get(ra), twin.get());
422 EXPECT_EQ(b.rng(), twin);
423}
424
425TEST(RandomStructures, TheDeprecatedGslRngCopiesSavesAndRestoresTheGenerator)
426{
427 // its state is the generator, which GSL copies, saves and restores by its
428 // bytes
429 Treap<int> t(7);
430 gsl_rng * r = t.gsl_rng_object();
431 EXPECT_EQ(gsl_rng_size(r), sizeof(Gsl_Compatible_Rng));
432 EXPECT_EQ(gsl_rng_state(r), static_cast<void *>(&t.rng()));
433
434 // a clone goes on with the same numbers, on its own
435 gsl_rng * c = gsl_rng_clone(r);
436 ASSERT_NE(c, nullptr);
437 for (int i = 0; i < 1000; ++i)
438 ASSERT_EQ(gsl_rng_get(c), gsl_rng_get(r)) << "at " << i;
439 (void) gsl_rng_get(c);
440 EXPECT_FALSE(*static_cast<const Gsl_Compatible_Rng *>(gsl_rng_state(c)) == t.rng());
441 gsl_rng_free(c);
442
443 // saved, advanced and restored, the generator of the treap gives the
444 // same numbers again. Not with MSVC or clang-cl: their FILE is one of
445 // the UCRT, which the GSL of MSYS2, of another C runtime, cannot write
446# if !defined(_MSC_VER)
447 std::FILE * f = std::tmpfile();
448 ASSERT_NE(f, nullptr);
449 ASSERT_EQ(gsl_rng_fwrite(f, r), 0);
450 const Gsl_Compatible_Rng saved = t.rng();
451 std::vector<unsigned long> next(100);
452 for (auto & x : next)
453 x = t.rng().get();
454 std::rewind(f);
455 ASSERT_EQ(gsl_rng_fread(f, r), 0);
456 std::fclose(f);
457 EXPECT_EQ(t.rng(), saved);
458 for (const auto x : next)
459 EXPECT_EQ(gsl_rng_get(r), x);
460# endif
461
462 // gsl_rng_memcpy() copies the generator of a treap into that of another
463 Treap<int> u(8);
464 ASSERT_EQ(gsl_rng_memcpy(u.gsl_rng_object(), r), 0);
465 EXPECT_EQ(u.rng(), t.rng());
466}
467
468TEST(RandomStructures, TheDeprecatedGslRngIsMadeOnceFromSeveralThreads)
469{
470 // the gsl_rng of a const structure, which gsl_rng_object() makes the
471 // first time, is one even if several threads ask for it at once
472 for (int round = 0; round < 50; ++round)
473 {
474 const Interval_Tree<int> t(9);
475 std::vector<gsl_rng *> got(4, nullptr);
476 std::vector<std::thread> threads;
477 for (size_t k = 0; k < got.size(); ++k)
478 threads.emplace_back([&t, &got, k] { got[k] = t.gsl_rng_object(); });
479 for (auto & th : threads)
480 th.join();
481 for (gsl_rng * p : got)
482 ASSERT_EQ(p, got[0]) << "round " << round;
483 EXPECT_EQ(gsl_rng_state(got[0]), static_cast<void *>(&t.rng()));
484 }
485}
486
487# if defined(__GNUC__)
488# pragma GCC diagnostic pop
489# elif defined(_MSC_VER)
490# pragma warning(pop)
491# endif
492#else
493// Without GSL (ALEPH_WITH_GSL is 0), the cases that compare with it
494// report SKIPPED instead of disappearing from the run, as
495// docs/ci_sanitizer_policy.md asks of a case that a configuration
496// cannot run; the hashes of the other cases stand for GSL
497TEST(RandomStructures, TheTreapPrioritiesAreTheNumbersOfGsl)
498{
499 GTEST_SKIP() << "without GSL (ALEPH_WITH_GSL is 0)";
500}
501
502TEST(RandomStructures, TheDeprecatedGslRngActsOnTheGenerator)
503{
504 GTEST_SKIP() << "without GSL (ALEPH_WITH_GSL is 0)";
505}
506
507TEST(RandomStructures, TheDeprecatedGslRngFollowsItsGenerator)
508{
509 GTEST_SKIP() << "without GSL (ALEPH_WITH_GSL is 0)";
510}
511
512TEST(RandomStructures, TheDeprecatedGslRngCopiesSavesAndRestoresTheGenerator)
513{
514 GTEST_SKIP() << "without GSL (ALEPH_WITH_GSL is 0)";
515}
516
517TEST(RandomStructures, TheDeprecatedGslRngIsMadeOnceFromSeveralThreads)
518{
519 GTEST_SKIP() << "without GSL (ALEPH_WITH_GSL is 0)";
520}
521#endif // ALEPH_WITH_GSL
522
523TEST(RandomStructures, MovesAndSwapsKeepTheGenerators)
524{
525 Rand_Tree<int> a(5);
526 const Gsl_Compatible_Rng twin = a.rng();
527 Rand_Tree<int> b(std::move(a));
528 EXPECT_EQ(b.rng(), twin);
529
530 Rand_Tree<int> c(6);
531 c = std::move(b);
532 EXPECT_EQ(c.rng(), twin);
533
534 DynSkipList<int> d(7UL), e(8UL);
535 d.swap(e);
536 EXPECT_EQ(d.rng(), Gsl_Compatible_Rng(8));
537 EXPECT_EQ(e.rng(), Gsl_Compatible_Rng(7));
538
539 // a copy of a DynSkipList makes its own generator; a copy assignment
540 // keeps the one of the target
541 DynSkipList<int> f(9UL);
542 f.insert(1);
543 const Gsl_Compatible_Rng before = f.rng();
544 DynSkipList<int> g(10UL);
545 f = g;
546 EXPECT_EQ(f.rng(), before);
547
549 q.set_seed(3);
550 r.set_seed(4);
551 q.swap(r);
552 EXPECT_EQ(q.rng(), Gsl_Compatible_Rng(4));
553 EXPECT_EQ(r.rng(), Gsl_Compatible_Rng(3));
554 Random_Set<int> moved(std::move(q));
555 EXPECT_EQ(moved.rng(), Gsl_Compatible_Rng(4));
556}
557
558namespace
559{
560 // One of two treaps, by value: the copy cannot be elided, so that the one
561 // returned is moved
562 template <class Tree>
563 Tree one_of_two(const bool first, typename Tree::Node * p, Gsl_Compatible_Rng & twin)
564 {
565 Tree a(12), b(13);
566 Tree & t = first ? a : b;
567 t.insert(p);
568 twin = t.rng();
569 if (first)
570 return a;
571 return b;
572 }
573
574 // Whether the root of a treap is in the treap, and not in the one that it
575 // was moved from
576 template <class Tree>
577 bool owns_its_root(Tree & t)
578 {
579 const auto self = reinterpret_cast<std::uintptr_t>(&t);
580 const auto root = reinterpret_cast<std::uintptr_t>(&t.getRoot());
581 return root >= self and root < self + sizeof(t);
582 }
583
584 template <class Tree>
585 void check_moves()
586 {
587 for (const bool first : {true, false})
588 {
589 typename Tree::Node n1(1), n2(2);
591 Tree t = one_of_two<Tree>(first, &n1, twin);
592 EXPECT_TRUE(owns_its_root(t));
593 EXPECT_EQ(t.rng(), twin);
594 EXPECT_EQ(t.search(1), &n1);
595 t.insert(&n2);
596 EXPECT_EQ(t.search(2), &n2);
597
598 Tree u(std::move(t));
599 EXPECT_TRUE(owns_its_root(u));
600 EXPECT_EQ(u.search(1), &n1);
601 EXPECT_EQ(u.search(2), &n2);
602 EXPECT_EQ(t.getRoot(), Tree::Node::NullPtr);
603
604 // the moved one takes nodes and a generator again by a swap
605 Tree v(14);
606 t.swap(v);
607 EXPECT_EQ(t.rng(), Gsl_Compatible_Rng(14));
608 EXPECT_EQ(v.getRoot(), Tree::Node::NullPtr);
609 }
610 }
611} // namespace
612
613TEST(RandomStructures, AMovedTreapTakesItsNodesAndItsGenerator)
614{
615 // before, a move was a copy: the treap kept the head of the one that it
616 // came from, and both freed the same gsl_rng
617 check_moves<Treap<int>>();
618 check_moves<Treap_Rk<int>>();
619}
620
621TEST(RandomStructures, TheSeedsAreTakenAsForGsl)
622{
623 // through an unsigned int, modulo 2^32 - 1, in the constructors of the
624 // treaps and of the interval tree; set_seed() takes the seed as is
625 Treap<int> t(0xffffffffUL);
626 EXPECT_EQ(t.rng(), Gsl_Compatible_Rng(0)); // 2^32 - 1 modulo itself
627 t.set_seed(0xffffffffUL);
628 EXPECT_EQ(t.rng(), Gsl_Compatible_Rng(0xffffffffUL));
629
630 Interval_Tree<int> it(0xffffffffUL);
631 EXPECT_EQ(it.rng(), Gsl_Compatible_Rng(0));
632
633 // the randomized tree and the skip lists, modulo 2^32 - 1 also in set_seed()
634 // of the randomized tree
635 Rand_Tree<int> rt(0xffffffffU);
636 EXPECT_EQ(rt.rng(), Gsl_Compatible_Rng(0));
637 rt.set_seed(0xffffffffUL);
638 EXPECT_EQ(rt.rng(), Gsl_Compatible_Rng(0));
639
640#if TEST_SKIP_LIST
641 SkipList<int, int> sl(0xffffffffUL);
642 EXPECT_EQ(sl.rng(), Gsl_Compatible_Rng(0));
643 sl.set_seed(0xffffffffUL);
644 EXPECT_EQ(sl.rng(), Gsl_Compatible_Rng(0xffffffffUL));
645#endif
646}
647
648// ---------------------------------------------------------------------------
649// The source of random numbers of each structure
650// ---------------------------------------------------------------------------
651
652namespace
653{
654 using Engine = Random_Source::Engine;
655
656 // The seed that the Mersenne Twister of a structure takes for the seed
657 // of its constructor or of its set_seed(), as each one took it for GSL
658 unsigned long through_an_unsigned_int(const unsigned long s)
659 {
660 return static_cast<unsigned int>(s) % 0xffffffffUL;
661 }
662
663 unsigned long modulo_the_greatest_number(const unsigned long s) { return s % 0xffffffffUL; }
664
665 unsigned long as_it_is(const unsigned long s) { return s; }
666
667 // What the tests need of each randomized structure: how it is built with
668 // a seed, in place, as some cannot be moved; the seeds that it takes;
669 // how it takes an item; whether it is right; a line with what it holds,
670 // if that depends on its numbers; and how the nodes that it does not
671 // own are freed
672 template <class S> struct Randomized;
673
674 // The trees that take and give nodes
675 template <class Tree, bool Priorities>
676 struct Of_A_Tree
677 {
678 static void build_with_seed(std::optional<Tree> & tree, const unsigned long s)
679 {
680 tree.emplace(s);
681 }
682 static unsigned long seed_of_the_constructor(const unsigned long s)
683 {
684 return through_an_unsigned_int(s);
685 }
686 static unsigned long seed_of_set_seed(const unsigned long s) { return as_it_is(s); }
687 static void put(Tree & tree, const int k) { (void) tree.insert(new typename Tree::Node(k)); }
688 static bool is_right(const Tree & tree) { return tree.verify(); }
689 static std::string shape(Tree & tree)
690 {
691 std::string out;
692 pre<Priorities>(tree.getRoot(), out);
693 return out;
694 }
695 static void empty(Tree & tree) { destroyRec(tree.getRoot()); }
696 static constexpr bool has_a_shape = true;
697 // read only where the heap of malloc() is seen
698 [[maybe_unused]] static constexpr bool allocates_when_built = false;
699 };
700
701 template <> struct Randomized<Treap<int>> : Of_A_Tree<Treap<int>, true> {};
702
703 template <> struct Randomized<Treap_Rk<int>> : Of_A_Tree<Treap_Rk<int>, true> {};
704
705 template <> struct Randomized<Rand_Tree<int>> : Of_A_Tree<Rand_Tree<int>, false>
706 {
707 static void build_with_seed(std::optional<Rand_Tree<int>> & tree, const unsigned long s)
708 {
709 tree.emplace(static_cast<unsigned int>(s));
710 }
711 static unsigned long seed_of_set_seed(const unsigned long s)
712 {
713 return modulo_the_greatest_number(s);
714 }
715 };
716
717#if TEST_SKIP_LIST
718 // Its user allocates the nodes, with the room for their pointers: the
719 // tests draw their levels
720 template <> struct Randomized<SkipList<int, int>>
721 {
722 using List = SkipList<int, int>;
723
724 static void build_with_seed(std::optional<List> & list, const unsigned long s)
725 {
726 list.emplace(s);
727 }
728 static unsigned long seed_of_the_constructor(const unsigned long s)
729 {
730 return modulo_the_greatest_number(s);
731 }
732 static unsigned long seed_of_set_seed(const unsigned long s) { return as_it_is(s); }
733 static void put(List & list, int) { (void) list.generateRandomLevel(); }
734 static bool is_right(const List & list) { return list.checkSkipList(); }
735 static std::string shape(List &) { return ""; }
736 static void empty(List &) {}
737 static constexpr bool has_a_shape = false;
738 // read only where the heap of malloc() is seen
739 [[maybe_unused]] static constexpr bool allocates_when_built = false;
740 };
741#endif
742
743 template <> struct Randomized<DynSkipList<int>>
744 {
745 using List = DynSkipList<int>;
746
747 static void build_with_seed(std::optional<List> & list, const unsigned long s)
748 {
749 list.emplace(s);
750 }
751 static unsigned long seed_of_the_constructor(const unsigned long s)
752 {
753 return modulo_the_greatest_number(s);
754 }
755 static unsigned long seed_of_set_seed(const unsigned long s) { return as_it_is(s); }
756 static void put(List & list, const int k) { (void) list.insert(k); }
757 static bool is_right(const List & list)
758 {
759 size_t count = 0;
760 long last = std::numeric_limits<long>::min();
761 for (auto it = list.begin(); it.has_curr(); it.next())
762 {
763 if (it.get_curr() <= last)
764 return false;
765 last = it.get_curr();
766 ++count;
767 }
768 return count == list.size();
769 }
770 static std::string shape(List &) { return ""; }
771 static void empty(List & list) { list.empty(); }
772 static constexpr bool has_a_shape = false;
773 // read only where the heap of malloc() is seen
774 [[maybe_unused]] static constexpr bool allocates_when_built = true; // its header
775 };
776
777 template <> struct Randomized<Random_Set<int>>
778 {
779 using Set = Random_Set<int>;
780
781 // it has no constructor with a seed
782 static void build_with_seed(std::optional<Set> & set, const unsigned long s)
783 {
784 set.emplace();
785 set->set_seed(s);
786 }
787 static unsigned long seed_of_the_constructor(const unsigned long s) { return as_it_is(s); }
788 static unsigned long seed_of_set_seed(const unsigned long s) { return as_it_is(s); }
789 static void put(Set & set, const int k) { (void) set.append(k); }
790 static bool is_right(const Set &) { return true; }
791 static std::string shape(Set & set)
792 {
793 std::string out;
794 set.for_each([&out] (const int k) { add(out, " %lu", static_cast<unsigned long>(k)); });
795 return out;
796 }
797 static void empty(Set &) {}
798 static constexpr bool has_a_shape = true;
799 // read only where the heap of malloc() is seen
800 [[maybe_unused]] static constexpr bool allocates_when_built = true; // its array
801 };
802
803 template <> struct Randomized<Interval_Tree<int>>
804 {
805 using Tree = Interval_Tree<int>;
806
807 static void build_with_seed(std::optional<Tree> & tree, const unsigned long s)
808 {
809 tree.emplace(s);
810 }
811 static unsigned long seed_of_the_constructor(const unsigned long s)
812 {
813 return through_an_unsigned_int(s);
814 }
815 static unsigned long seed_of_set_seed(const unsigned long s) { return as_it_is(s); }
816 static void put(Tree & tree, const int k)
817 {
818 (void) tree.insert(new Tree::Node(Interval<int>(k, k + (k % 5))));
819 }
820 static bool is_right(const Tree & tree) { return tree.verify(); }
821 static std::string shape(Tree & tree)
822 {
823 std::string out;
824 interval_pre(tree.getRoot(), out);
825 return out;
826 }
827 static void empty(Tree & tree) { destroyRec(tree.getRoot()); }
828 static constexpr bool has_a_shape = true;
829 // read only where the heap of malloc() is seen
830 [[maybe_unused]] static constexpr bool allocates_when_built = false;
831 };
832
833 template <class S> class Randomized_Structure : public ::testing::Test {};
834
835#if TEST_SKIP_LIST
836 using Randomized_Structures = ::testing::Types<Treap<int>, Treap_Rk<int>, Rand_Tree<int>,
839#else
840 using Randomized_Structures = ::testing::Types<Treap<int>, Treap_Rk<int>, Rand_Tree<int>,
843#endif
844 TYPED_TEST_SUITE(Randomized_Structure, Randomized_Structures);
845
846 // n keys from `first` on, in a fixed scramble
847 template <class S>
848 void fill(S & s, const int first, const int n)
849 {
850 for (int i = 0; i < n; ++i)
851 Randomized<S>::put(s, first + (i * 37 + 11) % n);
852 }
853
854 // What a structure built by default is given before it is used
855 enum class Given { nothing, a_seed_for_splitmix64, a_seed_for_the_mersenne_twister };
856
857 constexpr Given every_gift[] = {Given::nothing, Given::a_seed_for_splitmix64,
858 Given::a_seed_for_the_mersenne_twister};
859
860 template <class S>
861 void give(S & s, const Given what, const unsigned long seed)
862 {
863 if (what == Given::a_seed_for_splitmix64)
864 s.random_source().seed(seed);
865 else if (what == Given::a_seed_for_the_mersenne_twister)
866 s.set_seed(seed);
867 }
868
869 Engine engine_of(const Given what)
870 {
871 return what == Given::a_seed_for_the_mersenne_twister ? Engine::Mersenne_Twister
872 : Engine::SplitMix64;
873 }
874
875#if TEST_SEES_THE_HEAP
876 // The bytes of malloc() in use, those of operator new included
877 size_t heap_in_use()
878 {
879 const struct mallinfo2 m = mallinfo2();
880 return m.uordblks + m.hblkhd;
881 }
882#endif
883} // namespace
884
885TYPED_TEST(Randomized_Structure, BuiltWithoutASeedItDrawsFromASplitMix64OfItsOwn)
886{
887 using R = Randomized<TypeParam>;
888 TypeParam a, b;
889 EXPECT_EQ(a.random_source().engine(), Engine::SplitMix64);
890 EXPECT_EQ(b.random_source().engine(), Engine::SplitMix64);
891 EXPECT_FALSE(a.random_source() == b.random_source());
892
893 // drawing makes no Mersenne Twister, and each one draws its own numbers
894 fill(a, 0, 200);
895 fill(b, 0, 200);
896 EXPECT_EQ(a.random_source().engine(), Engine::SplitMix64);
897 EXPECT_EQ(b.random_source().engine(), Engine::SplitMix64);
898 EXPECT_FALSE(a.random_source() == b.random_source());
899 EXPECT_TRUE(R::is_right(a));
900 EXPECT_TRUE(R::is_right(b));
901 if (R::has_a_shape)
902 EXPECT_NE(R::shape(a), R::shape(b));
903 R::empty(a);
904 R::empty(b);
905
906 // a constant one gives its source to read
907 const TypeParam & c = a;
908 static_assert(std::is_same_v<decltype(c.random_source()), const Random_Source &>);
909 static_assert(std::is_same_v<decltype(a.random_source()), Random_Source &>);
910 EXPECT_EQ(c.random_source().engine(), Engine::SplitMix64);
911}
912
913TYPED_TEST(Randomized_Structure, WithASeedItDrawsFromTheMersenneTwisterOfThatSeed)
914{
915 using R = Randomized<TypeParam>;
916 // 0, which GSL takes as 4357; the ends of the 32 bits, where the seeds
917 // of the constructors wrap around; and one above them, where unsigned
918 // long has the bits
919 for (const unsigned long long seed : {0ULL, 1ULL, 12345ULL, 0xfffffffeULL, 0xffffffffULL,
920 0x100000005ULL})
921 {
922 if (seed > std::numeric_limits<unsigned long>::max())
923 continue;
924 const auto s = static_cast<unsigned long>(seed);
925
926 std::optional<TypeParam> built;
927 R::build_with_seed(built, s);
928 EXPECT_EQ(built->random_source().engine(), Engine::Mersenne_Twister) << "seed " << s;
929 EXPECT_EQ(built->random_source(),
930 Random_Source(Engine::Mersenne_Twister, R::seed_of_the_constructor(s)))
931 << "seed " << s;
932
933 // set_seed() makes the Mersenne Twister of one built without a seed
934 const Random_Source expected(Engine::Mersenne_Twister, R::seed_of_set_seed(s));
935 TypeParam seeded_later;
936 seeded_later.set_seed(s);
937 EXPECT_EQ(seeded_later.random_source(), expected) << "seed " << s;
938
939 // and seeds again, where it is, that of one that has it
940 const Gsl_Compatible_Rng * const mt = &built->random_source().mersenne_twister();
941 fill(*built, 0, 20);
942 built->set_seed(s);
943 EXPECT_EQ(built->random_source(), expected) << "seed " << s;
944 EXPECT_EQ(&built->random_source().mersenne_twister(), mt) << "seed " << s;
945 R::empty(*built);
946 }
947
948 // neither may be noexcept: they may make a Mersenne Twister
949 TypeParam s;
950 static_assert(not noexcept(s.set_seed(1UL)));
951 static_assert(not noexcept(s.rng()));
952 static_assert(noexcept(s.random_source()));
953}
954
955TYPED_TEST(Randomized_Structure, WithTheSameSeedTwoMakeTheSameWithEachEngine)
956{
957 using R = Randomized<TypeParam>;
958 for (const Engine engine : {Engine::SplitMix64, Engine::Mersenne_Twister})
959 {
960 TypeParam a, b, c;
961 a.random_source().seed(engine, 42);
962 b.random_source().seed(engine, 42);
963 c.random_source().seed(engine, 43);
964 fill(a, 0, 200);
965 fill(b, 0, 200);
966 fill(c, 0, 200);
967 EXPECT_EQ(a.random_source().engine(), engine);
968 EXPECT_EQ(a.random_source(), b.random_source());
969 EXPECT_FALSE(a.random_source() == c.random_source());
970 EXPECT_FALSE(a.random_source() == Random_Source(engine, 42)); // it drew
971 if (R::has_a_shape)
972 {
973 EXPECT_EQ(R::shape(a), R::shape(b));
974 EXPECT_NE(R::shape(a), R::shape(c));
975 }
976 EXPECT_TRUE(R::is_right(a));
977 EXPECT_TRUE(R::is_right(c));
978 R::empty(a);
979 R::empty(b);
980 R::empty(c);
981 }
982}
983
984TYPED_TEST(Randomized_Structure, TheDeprecatedRngMakesTheMersenneTwisterOfOneWithoutASeed)
985{
986 using R = Randomized<TypeParam>;
987 // a SplitMix64 with a seed, so that the Mersenne Twister that it makes
988 // is known: that of a source with the same seed
989 TypeParam a;
990 a.random_source().seed(7);
991 Random_Source twin(7);
992 Gsl_Compatible_Rng & mt = a.rng();
993 EXPECT_EQ(a.random_source().engine(), Engine::Mersenne_Twister);
994 EXPECT_EQ(mt, twin.mersenne_twister());
995 EXPECT_EQ(&mt, &a.random_source().mersenne_twister());
996 EXPECT_EQ(&a.rng(), &mt); // one alone
997
998 // it is the generator of the structure: seeded through it, the
999 // structure makes what one seeded with set_seed() makes
1000 mt.seed(99);
1001 TypeParam b;
1002 b.set_seed(99);
1003 fill(a, 0, 100);
1004 fill(b, 0, 100);
1005 EXPECT_EQ(a.random_source(), b.random_source());
1006 if (R::has_a_shape)
1007 EXPECT_EQ(R::shape(a), R::shape(b));
1008 R::empty(a);
1009 R::empty(b);
1010
1011 // and so on a constant one, where rng() is a member of constant ones
1012 if constexpr (requires (const TypeParam & c) { c.rng(); })
1013 {
1014 const TypeParam c;
1015 (void) c.rng();
1016 EXPECT_EQ(c.random_source().engine(), Engine::Mersenne_Twister);
1017 }
1018}
1019
1020TYPED_TEST(Randomized_Structure, TheDeprecatedGslRngMakesTheMersenneTwisterOfOneWithoutASeed)
1021{
1022#if ALEPH_WITH_GSL
1023 TypeParam a;
1024 gsl_rng * r = nullptr;
1025 if constexpr (requires { a.gsl_rng_object(); })
1026 r = a.gsl_rng_object();
1027 else if constexpr (requires { a.get_rng(); })
1028 r = a.get_rng();
1029 else
1030 {
1031 // the treap with ranks alone never gave a gsl_rng
1032 EXPECT_TRUE((std::is_same_v<TypeParam, Treap_Rk<int>>));
1033 return;
1034 }
1035
1036 ASSERT_NE(r, nullptr);
1037 EXPECT_EQ(a.random_source().engine(), Engine::Mersenne_Twister);
1038 EXPECT_EQ(gsl_rng_state(r), static_cast<void *>(&a.random_source().mersenne_twister()));
1039 gsl_rng_set(r, 99);
1040 EXPECT_EQ(a.random_source(), Random_Source(Engine::Mersenne_Twister, 99));
1041#else
1042 GTEST_SKIP() << "without GSL (ALEPH_WITH_GSL is 0)";
1043#endif
1044}
1045
1046TYPED_TEST(Randomized_Structure, ACopyDrawsFromASplitMix64OfItsOwn)
1047{
1048 using R = Randomized<TypeParam>;
1049 // the two that are copied, as before
1050 const bool copied = std::is_same_v<TypeParam, DynSkipList<int>>
1051 or std::is_same_v<TypeParam, Random_Set<int>>;
1052 EXPECT_EQ(std::is_copy_constructible_v<TypeParam>, copied);
1053 EXPECT_EQ(std::is_copy_assignable_v<TypeParam>, copied);
1054
1055 if constexpr (std::is_copy_constructible_v<TypeParam>)
1056 for (const Given what : every_gift)
1057 {
1058 TypeParam a, twin;
1059 give(a, what, 5);
1060 give(twin, what, 5);
1061 fill(a, 0, 50);
1062 fill(twin, 0, 50);
1063
1064 // the copy holds the items, and draws from a generator of its
1065 // own, whatever that of the one copied, which keeps its own
1066 TypeParam c(a);
1067 EXPECT_EQ(c.size(), a.size());
1068 EXPECT_EQ(c.random_source().engine(), Engine::SplitMix64);
1069 EXPECT_FALSE(c.random_source() == a.random_source());
1070 EXPECT_EQ(a.random_source().engine(), engine_of(what));
1071 if (what != Given::nothing)
1072 EXPECT_EQ(a.random_source(), twin.random_source());
1073 fill(c, 1000, 50);
1074 EXPECT_TRUE(R::is_right(c));
1075
1076 // a copy assignment keeps the engine of the target, whichever
1077 // the one of the source
1078 for (const Given target : every_gift)
1079 {
1080 TypeParam d;
1081 give(d, target, 6);
1082 d = a;
1083 EXPECT_EQ(d.size(), a.size());
1084 EXPECT_EQ(d.random_source().engine(), engine_of(target));
1085 EXPECT_FALSE(d.random_source() == a.random_source());
1086 if (what != Given::nothing)
1087 EXPECT_EQ(a.random_source(), twin.random_source());
1088 }
1089 }
1090}
1091
1092TYPED_TEST(Randomized_Structure, AMoveTakesTheGeneratorAndTheOneMovedFromDrawsFromAnother)
1093{
1094 using R = Randomized<TypeParam>;
1095 // all but the interval tree, as before
1096 const bool moved = not std::is_same_v<TypeParam, Interval_Tree<int>>;
1097 EXPECT_EQ(std::is_move_constructible_v<TypeParam>, moved);
1098
1099 if constexpr (std::is_move_constructible_v<TypeParam>)
1100 for (const Given what : every_gift)
1101 {
1102 TypeParam a, twin;
1103 give(a, what, 5);
1104 give(twin, what, 5);
1105 fill(a, 0, 50);
1106 fill(twin, 0, 50);
1107
1108 TypeParam b(std::move(a));
1109 EXPECT_EQ(b.random_source().engine(), engine_of(what));
1110 if (what != Given::nothing)
1111 EXPECT_EQ(b.random_source(), twin.random_source());
1112
1113 // the one moved from draws from a SplitMix64 of its own
1114 EXPECT_EQ(a.random_source().engine(), Engine::SplitMix64);
1115 EXPECT_FALSE(a.random_source() == b.random_source());
1116 if (what == Given::a_seed_for_splitmix64)
1117 EXPECT_FALSE(a.random_source() == Random_Source(5));
1118
1119 // both take items again: the target goes on as its twin
1120 fill(a, 1000, 50);
1121 fill(b, 2000, 50);
1122 fill(twin, 2000, 50);
1123 EXPECT_TRUE(R::is_right(a));
1124 EXPECT_TRUE(R::is_right(b));
1125 EXPECT_EQ(a.random_source().engine(), Engine::SplitMix64);
1126 if (what != Given::nothing)
1127 {
1128 EXPECT_EQ(b.random_source(), twin.random_source());
1129 if (R::has_a_shape)
1130 EXPECT_EQ(R::shape(b), R::shape(twin));
1131 }
1132
1133 // a move assignment, where there is one, gives the generator too,
1134 // and leaves the source with one of SplitMix64
1135 if constexpr (std::is_move_assignable_v<TypeParam>)
1136 {
1137 TypeParam c;
1138 c = std::move(b);
1139 EXPECT_EQ(c.random_source().engine(), engine_of(what));
1140 if (what != Given::nothing)
1141 EXPECT_EQ(c.random_source(), twin.random_source());
1142 EXPECT_EQ(b.random_source().engine(), Engine::SplitMix64);
1143 EXPECT_FALSE(b.random_source() == c.random_source());
1144 fill(b, 3000, 20);
1145 EXPECT_TRUE(R::is_right(b));
1146 EXPECT_TRUE(R::is_right(c));
1147 R::empty(c);
1148 }
1149 R::empty(a);
1150 R::empty(b);
1151 R::empty(twin);
1152 }
1153}
1154
1155TYPED_TEST(Randomized_Structure, ASwapExchangesTheGenerators)
1156{
1157 using R = Randomized<TypeParam>;
1158 TypeParam a, b, twin;
1159 a.set_seed(5);
1160 twin.set_seed(5);
1161 b.random_source().seed(6);
1162 fill(a, 0, 30);
1163 fill(twin, 0, 30);
1164
1165 a.swap(b);
1166 EXPECT_EQ(b.random_source().engine(), Engine::Mersenne_Twister);
1167 EXPECT_EQ(b.random_source(), twin.random_source());
1168 EXPECT_EQ(a.random_source(), Random_Source(6));
1169 EXPECT_TRUE(R::is_right(a));
1170 EXPECT_TRUE(R::is_right(b));
1171 R::empty(a);
1172 R::empty(b);
1173 R::empty(twin);
1174}
1175
1176#if TEST_SEES_THE_HEAP
1177namespace
1178{
1179 // What a structure built by default holds in the heap of malloc() at
1180 // each step, counted from before it is built, and what a move takes
1181 struct Heap_Seen
1182 {
1183 long built = 0; // once it is built
1184 long after_drawing = 0; // once it has drawn numbers
1185 long with_a_generator = 0; // once it is asked for the Mersenne Twister
1186 long back = 0; // once its source goes back to SplitMix64
1187 long with_a_seeded_one = 0; // with another one, built with a seed
1188 long at_the_end = 0; // once both are destroyed
1189 long of_a_move = 0; // what the move of another one takes
1190 long after_the_move = 0; // once the two of the move are destroyed
1191 };
1192
1193 template <class S>
1194 Heap_Seen look_at_the_heap()
1195 {
1196 Heap_Seen seen;
1197 const auto since = [before = heap_in_use()]
1198 {
1199 return static_cast<long>(heap_in_use()) - static_cast<long>(before);
1200 };
1201 {
1202 std::optional<S> s;
1203 s.emplace();
1204 seen.built = since();
1205 for (int i = 0; i < 100; ++i)
1206 (void) s->random_source().uniform_int(1000);
1207 seen.after_drawing = since();
1208 s->set_seed(1);
1209 seen.with_a_generator = since();
1210 s->random_source().seed(1);
1211 seen.back = since();
1212 std::optional<S> seeded;
1213 Randomized<S>::build_with_seed(seeded, 1);
1214 seen.with_a_seeded_one = since();
1215 }
1216 seen.at_the_end = since();
1217
1218 if constexpr (std::is_move_constructible_v<S>)
1219 {
1220 std::optional<S> a, b;
1221 a.emplace();
1222 const long with_one = since();
1223 b.emplace(std::move(*a));
1224 seen.of_a_move = since() - with_one;
1225 }
1226 seen.after_the_move = since();
1227 return seen;
1228 }
1229} // namespace
1230#endif
1231
1232TYPED_TEST(Randomized_Structure, ItHoldsNoMersenneTwisterUntilItIsAskedForOne)
1233{
1234#if TEST_SEES_THE_HEAP
1235 using R = Randomized<TypeParam>;
1236 constexpr long generator = sizeof(Gsl_Compatible_Rng);
1237
1238 // glibc keeps the small blocks that a thread frees in a cache of the
1239 // thread, and reports them as in use. A first round leaves there those
1240 // that a structure takes for itself, as its header; the second one,
1241 // which is the one looked at, takes them from the cache and gives them
1242 // back to it, so that the heap moves only with what the cache does not
1243 // keep: a Mersenne Twister, of 2500 bytes. That holds with the cache as
1244 // glibc sizes it by default: its tunables may make it keep larger blocks
1245 if (std::getenv("GLIBC_TUNABLES") != nullptr)
1246 GTEST_SKIP() << "GLIBC_TUNABLES is set: the cache of malloc() may keep a Mersenne Twister";
1247 (void) look_at_the_heap<TypeParam>();
1248 const Heap_Seen seen = look_at_the_heap<TypeParam>();
1249
1250 // built, it holds no generator, and its numbers take nothing
1251 if (not R::allocates_when_built)
1252 EXPECT_EQ(seen.built, 0);
1253 EXPECT_LT(seen.built, generator);
1254 EXPECT_EQ(seen.after_drawing, seen.built);
1255
1256 // asked for the Mersenne Twister, it takes its bytes, which it gives
1257 // back when its source goes back to SplitMix64
1258 EXPECT_GE(seen.with_a_generator, seen.built + generator);
1259 EXPECT_EQ(seen.back, seen.built);
1260
1261 // one built with a seed holds it from the start
1262 EXPECT_GE(seen.with_a_seeded_one, 2 * seen.built + generator);
1263 EXPECT_LT(seen.with_a_seeded_one, 2 * seen.built + 2 * generator);
1264 EXPECT_EQ(seen.at_the_end, 0);
1265
1266 // a move builds what one built by default holds, for the one that it
1267 // moves from, and no generator
1268 if constexpr (std::is_move_constructible_v<TypeParam>)
1269 EXPECT_EQ(seen.of_a_move, seen.built);
1270 EXPECT_EQ(seen.after_the_move, 0);
1271#else
1272 GTEST_SKIP() << "the heap of malloc() is not seen: not glibc, or under a sanitizer";
1273#endif
1274}
1275
1276TEST(RandomStructures, ThePrioritiesAreTheNumbersOfTheSource)
1277{
1278 // a treap takes a number of its source for each node that it is given,
1279 // with each engine: the priorities are those of a twin source
1280 for (const Engine engine : {Engine::SplitMix64, Engine::Mersenne_Twister})
1281 {
1282 Treap<int> treap;
1283 Treap_Rk<int> treap_rk;
1284 Interval_Tree<int> interval_tree;
1285 treap.random_source().seed(engine, 2026);
1286 treap_rk.random_source().seed(engine, 2026);
1287 interval_tree.random_source().seed(engine, 2026);
1288 Random_Source twin(engine, 2026);
1289 // the trees, which do not own their nodes, free them also when an
1290 // assertion ends the test; a node that its tree does not take is
1291 // freed at once
1292 Init_Guard free_the_nodes([&]
1293 {
1294 destroyRec(treap.getRoot());
1295 destroyRec(treap_rk.getRoot());
1296 destroyRec(interval_tree.getRoot());
1297 });
1298 const auto put = [] (auto & tree, auto * node)
1299 {
1300 const bool taken = tree.insert(node) == node;
1301 if (not taken)
1302 delete node;
1303 return taken;
1304 };
1305 for (const int k : keys(100))
1306 {
1307 auto * p = new Treap<int>::Node(k);
1308 ASSERT_TRUE(put(treap, p)) << "key " << k;
1309 auto * q = new Treap_Rk<int>::Node(k);
1310 ASSERT_TRUE(put(treap_rk, q)) << "key " << k;
1311 auto * i = new Interval_Tree<int>::Node(Interval<int>(k, k + 1));
1312 ASSERT_TRUE(put(interval_tree, i)) << "key " << k;
1313 const unsigned long priority = twin.get();
1314 ASSERT_EQ(PRIO(p), priority) << "key " << k;
1315 ASSERT_EQ(PRIO(q), priority) << "key " << k;
1316 ASSERT_EQ(PRIO(i), priority) << "key " << k;
1317 }
1318 EXPECT_TRUE(treap.verify());
1319 EXPECT_TRUE(treap_rk.verify());
1320 EXPECT_TRUE(interval_tree.verify());
1321 }
1322}
1323
1324TEST(RandomStructures, TheTreesWithoutASeedAreBalanced)
1325{
1326 // 4096 keys in order, the worst case of a tree that is not balanced:
1327 // with the numbers of SplitMix64, a treap and a randomized tree are as
1328 // shallow as with those of the Mersenne Twister, well under the 60
1329 // levels that a tree of that size reaches once in 10^9 times. Without a
1330 // seed they draw from SplitMix64, which is seeded here, so that a
1331 // failure can be reproduced
1332 const int n = 4096;
1333 for (const bool mersenne : {false, true})
1334 {
1335 Treap<int> treap;
1336 Treap_Rk<int> treap_rk;
1337 Rand_Tree<int> rand_tree;
1338 EXPECT_EQ(treap.random_source().engine(), Engine::SplitMix64);
1339 EXPECT_EQ(treap_rk.random_source().engine(), Engine::SplitMix64);
1340 EXPECT_EQ(rand_tree.random_source().engine(), Engine::SplitMix64);
1341 if (mersenne)
1342 {
1343 treap.set_seed(1);
1344 treap_rk.set_seed(1);
1345 rand_tree.set_seed(1);
1346 }
1347 else
1348 {
1349 treap.random_source().seed(2026);
1350 treap_rk.random_source().seed(2026);
1351 rand_tree.random_source().seed(2026);
1352 }
1353 for (int k = 0; k < n; ++k)
1354 {
1355 (void) treap.insert(new Treap<int>::Node(k));
1356 (void) treap_rk.insert(new Treap_Rk<int>::Node(k));
1357 (void) rand_tree.insert(new Rand_Tree<int>::Node(k));
1358 }
1359 const char * const engine = mersenne ? "Mersenne Twister" : "SplitMix64";
1360 EXPECT_LT(computeHeightRec(treap.getRoot()), 60u) << engine;
1361 EXPECT_LT(computeHeightRec(treap_rk.getRoot()), 60u) << engine;
1362 EXPECT_LT(computeHeightRec(rand_tree.getRoot()), 60u) << engine;
1363 EXPECT_EQ(treap.random_source().engine(),
1364 mersenne ? Engine::Mersenne_Twister : Engine::SplitMix64);
1365 destroyRec(treap.getRoot());
1366 destroyRec(treap_rk.getRoot());
1367 destroyRec(rand_tree.getRoot());
1368 }
1369}
1370
1371TEST(RandomStructures, TheTreesAreBuiltAndMovedWithoutThrowing)
1372{
1373 // a tree that is given no seed allocates nothing: with a key and a
1374 // comparison that do not throw, it is built and moved without throwing,
1375 // and so are a set and a map on it
1376 static_assert(std::is_nothrow_default_constructible_v<Treap<int>>);
1377 static_assert(std::is_nothrow_default_constructible_v<Treap_Vtl<int>>);
1378 static_assert(std::is_nothrow_default_constructible_v<Treap_Rk<int>>);
1379 static_assert(std::is_nothrow_default_constructible_v<Treap_Rk_Vtl<int>>);
1380 static_assert(std::is_nothrow_default_constructible_v<Rand_Tree<int>>);
1381 static_assert(std::is_nothrow_default_constructible_v<Rand_Tree_Vtl<int>>);
1382 static_assert((std::is_nothrow_constructible_v<Treap<int>, const Aleph::less<int> &>));
1383 static_assert((std::is_nothrow_constructible_v<Treap_Rk<int>, Aleph::less<int>>));
1384 static_assert((std::is_nothrow_constructible_v<Rand_Tree<int>, const Aleph::less<int> &>));
1385 static_assert(std::is_nothrow_move_constructible_v<Treap<int>>);
1386 static_assert(std::is_nothrow_move_constructible_v<Treap_Rk<int>>);
1387 static_assert(std::is_nothrow_move_constructible_v<Rand_Tree<int>>);
1388 // one built with a seed makes its Mersenne Twister, and may throw
1389 static_assert(not std::is_nothrow_constructible_v<Treap<int>, unsigned long>);
1390 static_assert(not std::is_nothrow_constructible_v<Treap_Rk<int>, unsigned long>);
1391 static_assert(not std::is_nothrow_constructible_v<Rand_Tree<int>, unsigned int>);
1392 SUCCEED();
1393}
The random number generators of Aleph: the one that gives the numbers of the gsl_rng_mt19937 of GSL,...
RAII guard for exception-safe resource cleanup.
TYPED_TEST_SUITE(ArcHeapLifecycle, ArcHeapKinds)
TYPED_TEST(ArcHeapLifecycle, ClearNullsTheHandles)
WeightedDigraph::Node Node
@ KEY
Definition btreepic.C:169
long double h
Definition btreepic.C:154
size_t size_t int32_t * out
Definition ca-c-api.h:120
Node belonging to a double circular linked list with header node.
Definition tpl_dnode.H:106
T & insert(const T &item)
Definition htlist.H:1308
T get()
See remove().
Definition htlist.H:1485
Dynamic ordered set implemented with a Skip List.
Key * insert(const Key &key)
Insert an element into the set.
Gsl_Compatible_Rng & rng()
The Mersenne Twister of the list, which a list that was given no seed makes here, and draws from it f...
bool verify() const
Verify BST, heap, and max_endpoint invariants.
Gsl_Compatible_Rng & rng() const
The Mersenne Twister of the tree, which a tree that was given no seed makes here, and draws from it f...
Node *& getRoot() noexcept
Return the tree's root.
Random_Source & random_source() noexcept
The source of random numbers, which gives the priorities.
Gsl_Compatible_Rng & rng()
The Mersenne Twister of the tree, which a tree that was given no seed makes here, and draws from it f...
Random_Source & random_source() noexcept
The source of random numbers, which draws the positions of the nodes.
Node *& getRoot() noexcept
Return the tree's root.
void set_seed(const unsigned long seed)
Seeds the Mersenne Twister of the tree, modulo 2^32 - 1: the positions are from then on those of GSL ...
Node * insert(Node *p) noexcept(nothrow_compare_copy_v< Compare, Key >)
Insert a node in the tree.
Node *& getRoot() noexcept
Return the tree's root.
bool verify() const
Return true if the treap is consistent.
NodeType< Key > Node
bool insert(Node *&root, Node *p) noexcept(nothrow_compare_v< Compare, Key >)
Random_Source & random_source() noexcept
The source of random numbers, which gives the priorities.
void set_seed(const unsigned long seed)
Seeds the Mersenne Twister of the treap, as gsl_rng_set() did: the priorities are from then on those ...
NodeType< Key > Node
Definition tpl_treap.H:159
Random_Source & random_source() noexcept
The source of random numbers, which gives the priorities.
Definition tpl_treap.H:305
Node *& getRoot() noexcept
Return the tree's root.
Definition tpl_treap.H:338
bool verify() const
Return true if this is a consistent treap.
Definition tpl_treap.H:524
void set_seed(const unsigned long seed)
Seeds the Mersenne Twister of the treap, as gsl_rng_set() did: the priorities are from then on those ...
Definition tpl_treap.H:186
Node * insert(Node *root, Node *p) noexcept(nothrow_compare_v< Compare, Key >)
Definition tpl_treap.H:360
Gsl_Compatible_Rng & rng()
The Mersenne Twister of the treap, which a treap that was given no seed makes here,...
Definition tpl_treap.H:322
A random number generator with the sequences of GSL's gsl_rng_mt19937.
Definition ah-random.H:147
void seed(const unsigned long s) noexcept
Seeds again, as gsl_rng_set(r, s).
Definition ah-random.H:277
unsigned long get() noexcept
The next number, as operator()().
Definition ah-random.H:289
RAII guard for graph algorithm initialization.
void put(const T &item)
Insert an item by copy.
void set_seed(unsigned long seed) const
Seeds the Mersenne Twister of the set, as gsl_rng_set() did: the positions are from then on those of ...
Gsl_Compatible_Rng & rng() const
The Mersenne Twister of the set, which a set that was given no seed makes here, and draws from it fro...
bool is_empty() const
Return true if the queue is empty.
T get()
Extract randomly an item.
T & append(const T &item)
Insert randomly an item by copy.
void swap(Random_Set &s) noexcept(noexcept(array.swap(s.array)))
Swap in constant time this with s: their items and their generators.
The source of random numbers of a randomized structure, which draws from one of two generators.
Definition ah-random.H:883
Engine
The generators that a source draws from.
Definition ah-random.H:938
unsigned long get() noexcept
The next number, as operator()().
Definition ah-random.H:1128
Gsl_Compatible_Rng & mersenne_twister()
The Mersenne Twister of the source, which is its engine from now on.
Definition ah-random.H:1087
Engine engine() const noexcept
The generator that the source draws from.
Definition ah-random.H:1028
void seed(const std::uint64_t s) noexcept
Draws from now on from the SplitMix64 of a seed.
Definition ah-random.H:1040
Skip List - a probabilistic ordered data structure.
Random_Source r
Gsl_Compatible_Rng & rng()
The Mersenne Twister of the list, which a list that was given no seed makes here, and draws from it f...
void set_seed(unsigned long seed)
Seeds the Mersenne Twister of the list, as gsl_rng_set() did: the levels are from then on those of GS...
Node * insert(Node *p) noexcept
Insert a node into the skip list.
Minimal std::expected-style result type for C++20.
void emplace(Args &&... args)
Appends a new element into the container by constructing it from the given args.
Definition ah-dry.H:1292
Node for QuadTree spatial data structure.
Definition quadnode.H:95
QuadTree - Hierarchical spatial index for 2D points.
Definition quadtree.H:126
Point * search(const Point &p) noexcept
Search for a point in the tree.
Definition quadtree.H:524
Point * insert(Node *&r, const Point &p)
Recursive insert helper.
Definition quadtree.H:281
#define TEST(name)
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
void destroyRec(Node *&root) noexcept
Free all the memory occupied by the tree root
unsigned long & PRIO(Node *p) noexcept
Access the priority of a treap node.
Definition treapNode.H:120
size_t computeHeightRec(Node *root) noexcept
Compute the height of root
Main namespace for Aleph-w library functions.
static long & low(typename GT::Node *p)
Internal helper: low-link value stored directly in NODE_COOKIE(p).
void fill(Itor beg, const Itor &end, const T &value)
Fill a range with a value.
Definition ahAlgo.H:707
and
Check uniqueness with explicit hash + equality functors.
std::ostream & join(const C &c, const std::string &sep, std::ostream &out)
Join elements of an Aleph-style container into a stream.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
double add(double a, double b)
Interval tree using nodes without virtual destructor.
Closed interval [low, high].
Randomized binary search tree.
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)
#define RLINK(i, n)
int keys[]
#define LLINK(i, n)
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
static mt19937 engine
Dynamic ordered set implemented with a Skip List.
Interval tree: augmented BST for overlap/stabbing queries.
Randomized binary search tree.
Random access queue (bag) with O(1) random pop.
Skip list: probabilistic sorted linked structure.
Treap with rank (order statistics).
Treap: randomized BST combining tree and heap properties.
DynList< int > l