Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
binheap.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
33
38#include <algorithm>
39#include <functional>
40#include <memory>
41#include <numeric>
42#include <ostream>
43#include <random>
44#include <sstream>
45#include <stdexcept>
46#include <string>
47#include <tuple>
48#include <type_traits>
49#include <utility>
50#include <vector>
51
52#include <gtest/gtest.h>
53
54#include <tpl_binHeap.H>
55#include <tpl_dynBinHeap.H>
56
57using namespace Aleph;
58
59TEST(DynBinHeapTest, InsertExtractInOrder)
60{
61 DynBinHeap<int> heap;
62 const std::vector<int> values = {7, 3, 11, 0, 5, 9, 1};
63
64 for (const int v : values)
65 heap.insert(v);
66
67 std::vector<int> expected = values;
68 std::sort(expected.begin(), expected.end());
69
70 for (const int v : expected)
71 {
72 ASSERT_EQ(heap.top(), v);
73 EXPECT_EQ(heap.getMin(), v);
74 }
75
76 EXPECT_TRUE(heap.is_empty());
77 EXPECT_EQ(heap.size(), 0u);
78}
79
80TEST(DynBinHeapTest, RemoveArbitraryNodes)
81{
82 DynBinHeap<int> heap;
83 const std::vector<int> values = {40, 10, 30, 20, 50, 60, 70, 15};
84 std::vector<std::reference_wrapper<int>> refs;
85 refs.reserve(values.size());
86
87 for (const int v : values)
88 refs.emplace_back(heap.insert(v));
89
90 ASSERT_EQ(heap.size(), values.size());
91
92 heap.remove(refs[3]); // remove an interior node
93 heap.remove(refs.back()); // remove what used to be the last inserted node
94
95 std::vector<int> remaining;
96 while (!heap.is_empty())
97 remaining.push_back(heap.getMin());
98
99 std::vector<int> expected = values;
100 const auto erase_value = [&expected](int needle) {
101 const auto it = std::find(expected.begin(), expected.end(), needle);
102 ASSERT_NE(it, expected.end());
103 expected.erase(it);
104 };
105 erase_value(20);
106 erase_value(15);
107 std::sort(expected.begin(), expected.end());
108
109 EXPECT_EQ(remaining, expected);
110}
111
112TEST(DynBinHeapTest, UpdateReordersAfterPriorityChange)
113{
114 DynBinHeap<int> heap;
115 auto &high = heap.insert(50);
116 auto &low = heap.insert(5);
117 heap.insert(20);
118
119 high = 1; // becomes the best priority
120 heap.update(high);
121 EXPECT_EQ(heap.top(), 1);
122
123 low = 60; // now should sink
124 heap.update(low);
125
126 std::vector<int> drained;
127 while (!heap.is_empty())
128 drained.push_back(heap.getMin());
129
130 EXPECT_EQ(drained, std::vector<int>({1, 20, 60}));
131}
132
133TEST(DynBinHeapTest, RandomizedInsertExtract)
134{
135 DynBinHeap<int> heap;
136 std::vector<int> values(200);
137 std::iota(values.begin(), values.end(), -100);
138 std::mt19937 rng(42);
139 std::shuffle(values.begin(), values.end(), rng);
140
141 for (int v : values)
142 heap.insert(v);
143
144 std::vector<int> extracted;
145 while (!heap.is_empty())
146 extracted.push_back(heap.getMin());
147
148 std::vector<int> expected = values;
149 std::sort(expected.begin(), expected.end());
150 EXPECT_EQ(extracted, expected);
151}
152
153TEST(DynBinHeapTest, IteratorTraversesAllElements)
154{
155 DynBinHeap<int> heap;
156 constexpr size_t N = 64;
157 for (size_t i = 0; i < N; ++i)
158 heap.insert(static_cast<int>(i));
159
160 size_t count = 0;
161 for (auto it = heap.get_it(); it.has_curr(); it.next())
162 ++count;
163
164 EXPECT_EQ(count, N);
165}
166
167TEST(DynBinHeapTest, EmptyRemovesAllNodes)
168{
169 DynBinHeap<int> heap;
170 for (int i = 0; i < 50; ++i)
171 heap.insert(i);
172
173 heap.empty();
174 EXPECT_TRUE(heap.is_empty());
175 EXPECT_EQ(heap.size(), 0u);
176
177 // Verify heap can be reused after empty
178 heap.insert(10);
179 EXPECT_EQ(heap.getMin(), 10);
180 EXPECT_TRUE(heap.is_empty());
181}
182
183TEST(DynBinHeapTest, UpdateWithDuplicatePriorities)
184{
185 DynBinHeap<int> heap;
186 std::vector<std::reference_wrapper<int>> refs;
187 for (int i = 0; i < 5; ++i)
188 refs.emplace_back(heap.insert(10)); // duplicates
189
190 // Make one element the new minimum
191 refs.front().get() = -1;
192 heap.update(refs.front());
193 EXPECT_EQ(heap.top(), -1);
194
195 // Make another element very large to ensure sift-down works
196 refs.back().get() = 100;
197 heap.update(refs.back());
198
199 std::vector<int> drained;
200 while (!heap.is_empty())
201 drained.push_back(heap.getMin());
202
203 EXPECT_TRUE(std::is_sorted(drained.begin(), drained.end()));
204 EXPECT_EQ(drained.front(), -1);
205 EXPECT_EQ(drained.back(), 100);
206}
207
208namespace
209{
210 // Less than; counts its calls, and the call number fail_at throws (0 for
211 // none).
212 struct Failing_Less
213 {
214 long * calls = nullptr;
215 long fail_at = 0;
216
217 bool operator()(const int & a, const int & b) const
218 {
219 if (calls != nullptr and ++*calls == fail_at)
220 throw std::runtime_error("comparison failed");
221 return a < b;
222 }
223 };
224
225 using Failing_Heap = BinHeap<int, Failing_Less>;
226
227 // Inserts and then extracts values with a comparison that fails at its
228 // call fail_at; returns the extracted values
229 std::vector<int> insert_and_extract(const std::vector<int> & values,
230 long & calls, long fail_at)
231 {
232 Failing_Heap heap(Failing_Less{&calls, fail_at});
233 std::vector<int> out;
234 try
235 {
236 for (const int v : values)
237 { // insert() throws with the node out of the heap
238 std::unique_ptr<Failing_Heap::Node> node(new Failing_Heap::Node(v));
239 heap.insert(node.get());
240 node.release();
241 }
242
243 heap.update(heap.getRoot()); // its key is unchanged
244
245 while (not heap.is_empty())
246 { // getMin() throws with the node still in the heap
247 std::unique_ptr<Failing_Heap::Node> min(heap.getMin());
248 out.push_back(min->get_key());
249 }
250 }
251 catch (...)
252 {
253 heap.remove_all_and_delete();
254 throw;
255 }
256 return out;
257 }
258} // namespace
259
260// insert(), update() and getMin() were noexcept, so a comparison that
261// threw ended the program.
262TEST(BinHeapComparison, WhatTheComparisonThrowsReachesTheCaller)
263{
264 const std::vector<int> values = {7, 3, 11, 0, 5, 9, 1, 8};
265 long calls = 0;
266 const auto out = insert_and_extract(values, calls, 0);
267 ASSERT_TRUE(std::is_sorted(out.begin(), out.end()));
268 ASSERT_EQ(out.size(), values.size());
269
270 for (long k = 1; k <= calls; ++k)
271 {
272 long count = 0;
273 EXPECT_THROW(insert_and_extract(values, count, k), std::runtime_error)
274 << "call " << k;
275 }
276}
277
278// Emptying a heap of up to 3 nodes extracted them one by one, comparing
279// the keys left, so in a destructor a comparison that throws ended the
280// program.
281TEST(BinHeapComparison, RemoveAllAndDeleteDoesNotCompare)
282{
283 for (int n = 1; n <= 6; ++n)
284 {
285 long calls = 0;
286 Failing_Heap heap(Failing_Less{&calls, 0});
287 for (int i = 0; i < n; ++i)
288 heap.insert(new Failing_Heap::Node(n - i));
289
290 const long before = calls;
291 heap.remove_all_and_delete();
292 EXPECT_EQ(calls, before) << n << " nodes";
293 EXPECT_TRUE(heap.is_empty());
294
295 heap.insert(new Failing_Heap::Node(4)); // the heap can be used again
296 EXPECT_EQ(heap.top()->get_key(), 4);
297 heap.remove_all_and_delete();
298 }
299}
300
301// A remove() that threw took the node out of the heap, which could be left
302// out of order. Now it puts the node back at its place, and the last node
303// at the end, so the node stays in the heap, which is as it was.
304TEST(BinHeapComparison, RemoveLeavesTheNodeInTheHeapIfTheComparisonThrows)
305{
306 const std::vector<int> values = {7, 3, 11, 0, 5, 9, 1, 8, 4, 6};
307 std::vector<int> sorted = values;
308 std::sort(sorted.begin(), sorted.end());
309
310 for (size_t i = 0; i < values.size(); ++i)
311 for (long k = 1; ; ++k)
312 {
313 long calls = 0;
314 Failing_Heap heap(Failing_Less{&calls, 0});
315 std::vector<Failing_Heap::Node *> nodes;
316 for (const int v : values)
317 nodes.push_back(heap.insert(new Failing_Heap::Node(v)));
318
319 heap.key_comp().fail_at = calls + k; // the call k of remove()
320 bool threw = false;
321 try
322 {
323 heap.remove(nodes[i]);
324 }
325 catch (const std::runtime_error &)
326 {
327 threw = true;
328 }
329
330 heap.key_comp().fail_at = 0;
331 EXPECT_EQ(heap.size(), threw ? values.size() : values.size() - 1);
332 if (not threw)
333 heap.insert(nodes[i]); // it is out of the heap only if remove() returned
334 EXPECT_TRUE(heap.verify_heap());
335 std::vector<int> out;
336 while (not heap.is_empty())
337 {
338 std::unique_ptr<Failing_Heap::Node> min(heap.getMin());
339 out.push_back(min->get_key());
340 }
341 EXPECT_EQ(out, sorted) << "node " << i << ", call " << k; // in order
342
343 if (not threw)
344 break;
345 }
346}
347
348namespace
349{
350 // An int that counts the objects alive
351 struct Counted
352 {
353 static inline long alive = 0;
354 int value;
355
356 Counted(int v = 0) noexcept : value(v) { ++alive; }
357 Counted(const Counted & c) noexcept : value(c.value) { ++alive; }
358 ~Counted() { --alive; }
359 };
360
361 // Less than of Counted, with the failures of Failing_Less
362 struct Failing_Counted_Less
363 {
364 Failing_Less less;
365
366 bool operator()(const Counted & a, const Counted & b) const
367 {
368 return less(a.value, b.value);
369 }
370 };
371
372 using Failing_Dyn_Heap = DynBinHeap<Counted, Failing_Counted_Less>;
373
374 // Inserts the values in heap, whose comparison fails at some call, copies
375 // the heap, updates, removes and erases elements, and extracts the rest.
376 // If the comparison throws, then after disarm() the heap must still hold
377 // as many elements as it says.
378 template <class Heap, class Disarm>
379 void use_dyn_heap(Heap & heap, const std::vector<int> & values,
380 Disarm disarm)
381 {
382 using Item = typename Heap::Item_Type;
383 try
384 {
385 std::vector<Item *> items;
386 for (const int v : values)
387 items.push_back(&heap.insert(Item(v)));
388
389 Heap copy(heap);
390 copy = heap;
391
392 heap.update(*items[2]); // its key is unchanged
393 heap.remove(*items[3]);
394 heap.erase(*items[5]);
395 while (not heap.is_empty())
396 (void) heap.getMin();
397 }
398 catch (...)
399 {
400 disarm();
401 const size_t size = heap.size();
402 size_t extracted = 0;
403 for (; not heap.is_empty(); ++extracted)
404 (void) heap.getMin();
405 EXPECT_EQ(extracted, size);
406 throw;
407 }
408 }
409
410 // With a comparison that fails at its call fail_at
411 void use_dyn_heap(const std::vector<int> & values, long & calls,
412 long fail_at)
413 {
414 Failing_Dyn_Heap heap(Failing_Counted_Less{{&calls, fail_at}});
415 use_dyn_heap(heap, values, [&heap] { heap.key_comp().less.fail_at = 0; });
416 }
417} // namespace
418
419// insert(), update(), remove() and erase() of DynBinHeap were noexcept, so
420// a comparison that threw ended the program. When it threw, getMin() and
421// remove() also lost the node that they had taken out of the heap, and the
422// copy constructor the nodes that it had copied.
423TEST(DynBinHeapComparison, WhatTheComparisonThrowsReachesTheCaller)
424{
425 const std::vector<int> values = {7, 3, 11, 0, 5, 9, 1, 8};
426 const long alive = Counted::alive;
427 long calls = 0;
428 use_dyn_heap(values, calls, 0);
429 ASSERT_EQ(Counted::alive, alive);
430
431 for (long k = 1; k <= calls; ++k)
432 {
433 long count = 0;
434 EXPECT_THROW(use_dyn_heap(values, count, k), std::runtime_error)
435 << "call " << k;
436 EXPECT_EQ(Counted::alive, alive) << "call " << k;
437 }
438}
439
440// They are noexcept when the comparison is
441static_assert(noexcept(std::declval<DynBinHeap<int> &>()
442 .update(std::declval<int &>())));
443static_assert(noexcept(std::declval<DynBinHeap<int> &>()
444 .remove(std::declval<int &>())));
445static_assert(noexcept(std::declval<DynBinHeap<int> &>()
446 .erase(std::declval<int &>())));
447static_assert(not noexcept(std::declval<Failing_Dyn_Heap &>()
448 .update(std::declval<Counted &>())));
449static_assert(not noexcept(std::declval<Failing_Dyn_Heap &>()
450 .remove(std::declval<Counted &>())));
451static_assert(not noexcept(std::declval<Failing_Dyn_Heap &>()
452 .erase(std::declval<Counted &>())));
453
454// The insertions allocate the node, so they never were noexcept
455static_assert(not noexcept(std::declval<DynBinHeap<int> &>()
456 .insert(std::declval<const int &>())));
457static_assert(not noexcept(std::declval<DynBinHeap<int> &>()
458 .put(std::declval<const int &>())));
459static_assert(not noexcept(std::declval<DynBinHeap<int> &>()
460 .append(std::declval<const int &>())));
461
462namespace
463{
464 // A Counted whose < fails as Failing_Less does, and does not say
465 // noexcept; a heap compares it with its default comparison, Aleph::less
466 struct Failing_Key : Counted
467 {
468 using Counted::Counted;
469
470 static inline Failing_Less less;
471
472 bool operator<(const Failing_Key & other) const
473 {
474 return less(value, other.value);
475 }
476 };
477
478 using Failing_Key_Heap = DynBinHeap<Failing_Key>;
479
480 // With keys whose < fails at its call fail_at
481 void use_key_heap(const std::vector<int> & values, long & calls,
482 long fail_at)
483 {
484 struct Reset
485 {
486 ~Reset() { Failing_Key::less = Failing_Less{}; }
487 } reset;
488 Failing_Key::less = Failing_Less{&calls, fail_at};
489 Failing_Key_Heap heap;
490 use_dyn_heap(heap, values, [] { Failing_Key::less.fail_at = 0; });
491 }
492} // namespace
493
494// Aleph::less is noexcept as the < of its type, and so are the operations
495// of a heap that compares with it. Counted has no <, and its heap, which
496// compares with another functor, can still be copied: overload resolution
497// names DynBinHeap<Counted>, whose Aleph::less must give no error then
498static_assert(std::is_copy_constructible_v<Failing_Dyn_Heap>);
499static_assert(noexcept(Aleph::less<int>()(0, 0)));
500static_assert(not noexcept(Aleph::less<Failing_Key>()(
501 std::declval<const Failing_Key &>(),
502 std::declval<const Failing_Key &>())));
503static_assert(not noexcept(std::declval<Failing_Key_Heap &>()
504 .update(std::declval<Failing_Key &>())));
505static_assert(not noexcept(std::declval<Failing_Key_Heap &>()
506 .remove(std::declval<Failing_Key &>())));
507static_assert(not noexcept(std::declval<Failing_Key_Heap &>()
508 .erase(std::declval<Failing_Key &>())));
509
510// Aleph::less was noexcept whatever the < of its type, so a heap that
511// compared with it ended the program when that < threw
512TEST(DynBinHeapComparison, WhatTheLessThanOfTheKeysThrowsReachesTheCaller)
513{
514 const std::vector<int> values = {7, 3, 11, 0, 5, 9, 1, 8};
515 const long alive = Counted::alive;
516 long calls = 0;
517 use_key_heap(values, calls, 0);
518 ASSERT_EQ(Counted::alive, alive);
519 ASSERT_GT(calls, 0);
520
521 for (long k = 1; k <= calls; ++k)
522 {
523 long count = 0;
524 EXPECT_THROW(use_key_heap(values, count, k), std::runtime_error)
525 << "call " << k;
526 EXPECT_EQ(Counted::alive, alive) << "call " << k;
527 }
528}
529
530namespace
531{
532 std::vector<int> drain(DynBinHeap<int> & heap)
533 {
534 std::vector<int> out;
535 while (not heap.is_empty())
536 out.push_back(heap.getMin());
537 return out;
538 }
539} // namespace
540
541// swap() exchanged the roots but left each root pointing up to the header
542// of the other heap, so the moves of DynBinHeap, which swap, broke the heap.
543TEST(DynBinHeapTest, MoveConstructionOutlivesTheSource)
544{
545 for (int n = 0; n <= 7; ++n)
546 {
547 std::unique_ptr<DynBinHeap<int>> moved;
548 {
549 DynBinHeap<int> source;
550 for (int i = n; i > 0; --i)
551 source.insert(i);
552 moved = std::make_unique<DynBinHeap<int>>(std::move(source));
553 EXPECT_TRUE(source.is_empty());
554 source.insert(10); // the source can be used again
555 EXPECT_EQ(source.getMin(), 10);
556 }
557
558 std::vector<int> expected(n);
559 std::iota(expected.begin(), expected.end(), 1);
560 EXPECT_EQ(drain(*moved), expected) << n << " values";
561 }
562}
563
564TEST(DynBinHeapTest, MoveAssignmentOutlivesTheSource)
565{
566 DynBinHeap<int> target;
567 for (int i : {20, 30})
568 target.insert(i);
569 {
570 DynBinHeap<int> source;
571 for (int i : {5, 3, 8, 1, 9, 2})
572 source.insert(i);
573 target = std::move(source);
574 }
575 EXPECT_EQ(drain(target), (std::vector<int>{1, 2, 3, 5, 8, 9}));
576}
577
578TEST(DynBinHeapTest, SwapExchangesTheContents)
579{
580 DynBinHeap<int> a, b, spare;
581 for (int i : {4, 2, 6, 1})
582 a.insert(i);
583 for (int i : {7, 3, 5})
584 b.insert(i);
585
586 a.swap(b);
587 a.insert(0); // both heaps keep working after the swap
588 b.insert(10);
589 EXPECT_EQ(drain(a), (std::vector<int>{0, 3, 5, 7}));
590 EXPECT_EQ(drain(b), (std::vector<int>{1, 2, 4, 6, 10}));
591
592 for (int i : {9, 8})
593 a.insert(i);
594 a.swap(spare); // with an empty heap
595 EXPECT_TRUE(a.is_empty());
596 a.insert(1);
597 EXPECT_EQ(drain(a), std::vector<int>{1});
598 EXPECT_EQ(drain(spare), (std::vector<int>{8, 9}));
599}
600
601// ─────────────────────────────────────────────────────────────────
602// The representation: a complete tree whose nodes that lack a child are in
603// a list
604// ─────────────────────────────────────────────────────────────────
605
606namespace
607{
608 // The parent of a node; that of the root is the header node of its heap
609 template <class Node>
610 Node * parent_of(Node *p)
611 {
612 return reinterpret_cast<Node *&>(p->getU());
613 }
614
615 // The nodes of a heap by their places, which are numbered by levels from
616 // 1 (the entry 0 has the header node), taken through the children of the
617 // nodes that have two, and what in the links of those nodes differs from
618 // the representation that tpl_binHeap.H describes: the node at the place
619 // i has its parent at i / 2 and, if it has them, its children at 2 i and
620 // 2 i + 1, and the nodes at the places (n + 1) / 2 to n are in a circular
621 // doubly linked list, in that order, with their right link as the next
622 // node and their left one as the previous one
623 template <class Heap>
624 std::string shape_errors(const Heap & heap, std::vector<typename Heap::Node *> & at)
625 {
626 using Node = typename Heap::Node;
627 std::ostringstream err;
628 const size_t n = heap.size();
629 Node *root = heap.getRoot();
630 at.assign(n + 1, nullptr);
631 if (n == 0)
632 {
633 if (root != nullptr)
634 err << "an empty heap has a root; ";
635 return err.str();
636 }
637 if (root == nullptr)
638 {
639 err << "a heap of " << n << " nodes has no root; ";
640 return err.str();
641 }
642 at[0] = parent_of(root);
643 at[1] = root;
644 for (size_t i = 1; i <= n; ++i)
645 {
646 if (at[i] == nullptr)
647 { // nothing below it can be looked at
648 err << "no node at the place " << i << "; ";
649 return err.str();
650 }
651 if (2*i <= n)
652 at[2*i] = at[i]->getL();
653 if (2*i + 1 <= n)
654 at[2*i + 1] = at[i]->getR();
655 }
656 if (at[0] == nullptr)
657 {
658 err << "the root has no header node; ";
659 return err.str();
660 }
661 std::vector<Node *> sorted(at.begin() + 1, at.end());
662 std::sort(sorted.begin(), sorted.end());
663 if (std::adjacent_find(sorted.begin(), sorted.end()) != sorted.end())
664 err << "two places have the same node; ";
665 if (at[0]->getR() != root)
666 err << "the root is not the right child of the header node; ";
667 for (size_t i = 1; i <= n; ++i)
668 {
669 Node *p = at[i];
670 if (parent_of(p) != at[i / 2])
671 err << "the parent of " << i << "; ";
672 if (static_cast<bool>(p->get_control_fields().is_left) != (i > 1 and i % 2 == 0))
673 err << "is_left of " << i << "; ";
674 if (static_cast<bool>(p->get_control_fields().is_leaf) != (2*i > n))
675 err << "is_leaf of " << i << "; ";
676 }
677 const size_t first = (n + 1) / 2;
678 for (size_t i = first; i <= n; ++i)
679 {
680 if (at[i]->getR() != at[i == n ? first : i + 1])
681 err << "the next node of " << i << "; ";
682 if (at[i]->getL() != at[i == first ? n : i - 1])
683 err << "the previous node of " << i << "; ";
684 }
685 return err.str();
686 }
687
688 // The nodes of a heap by their places, after checking its representation.
689 // A heap that does not have it ends the test, with an exception that no
690 // test expects: what follows would use places that are not what they say
691 template <class Heap>
692 std::vector<typename Heap::Node *> places(const Heap & heap)
693 {
694 std::vector<typename Heap::Node *> at;
695 const std::string err = shape_errors(heap, at);
696 if (not err.empty())
697 {
698 ADD_FAILURE() << heap.size() << " nodes: " << err;
699 throw std::logic_error("the heap does not have its shape");
700 }
701 return at;
702 }
703
704 // Frees the nodes that are in a heap when the test leaves it, by a fatal
705 // failure too. A heap that does not have its shape is not walked: its
706 // nodes are left, and the failure that ended the test says why
707 template <class Heap>
708 struct Freed_At_Exit
709 {
710 Heap & heap;
711
712 ~Freed_At_Exit()
713 {
714 std::vector<typename Heap::Node *> at;
715 if (shape_errors(heap, at).empty())
716 heap.remove_all_and_delete();
717 }
718 };
719}
720
721// After each insertion and each extraction, the links of all the nodes are
722// those of the representation
723TEST(BinHeapShape, InsertionsAndExtractionsKeepTheTreeAndItsList)
724{
725 std::mt19937 rng(20261121);
726 std::uniform_int_distribution<int> keys(0, 1000);
727 BinHeap<int> heap;
728 Freed_At_Exit<BinHeap<int>> nodes{heap};
729 places(heap);
730 for (int k = 0; k < 600; ++k)
731 {
732 heap.insert(new BinHeap<int>::Node(keys(rng)));
733 places(heap);
734 }
735 while (not heap.is_empty())
736 {
737 delete heap.getMin();
738 places(heap);
739 }
740}
741
742// So they are after the removal of the node at each place of a heap of each
743// size, and after the update of that node with a key that takes it to the
744// root, and with one that takes it down
745TEST(BinHeapShape, RemovalsAndUpdatesKeepTheTreeAndItsList)
746{
747 std::mt19937 rng(7);
748 std::uniform_int_distribution<int> keys(0, 1000);
749 for (size_t n = 1; n <= 40; ++n)
750 for (size_t i = 1; i <= n; ++i)
751 for (int op = 0; op < 3; ++op)
752 {
753 SCOPED_TRACE(testing::Message() << "n " << n << ", place " << i << ", op " << op);
754 BinHeap<int> heap;
755 Freed_At_Exit<BinHeap<int>> nodes{heap};
756 for (size_t k = 0; k < n; ++k)
757 heap.insert(new BinHeap<int>::Node(keys(rng)));
758 const auto at = places(heap);
759 if (op == 0)
760 delete heap.remove(at[i]);
761 else
762 {
763 at[i]->get_key() = op == 1 ? -1 : 2000;
764 heap.update(at[i]);
765 if (op == 1)
766 {
767 EXPECT_EQ(heap.top(), at[i]);
768 }
769 }
770 places(heap);
771 EXPECT_TRUE(heap.verify_heap());
772 }
773}
774
775// The last node of the heap is the one at the place n: its removal compares
776// nothing, and that of any other node does
777TEST(BinHeapShape, TheLastNodeIsTheOneAtThePlaceN)
778{
779 std::mt19937 rng(11);
780 std::uniform_int_distribution<int> keys(0, 1000);
781 for (size_t n = 2; n <= 40; ++n)
782 for (size_t i = 1; i <= n; ++i)
783 {
784 long calls = 0;
785 Failing_Heap heap(Failing_Less{&calls, 0});
786 Freed_At_Exit<Failing_Heap> nodes{heap};
787 for (size_t k = 0; k < n; ++k)
788 heap.insert(new Failing_Heap::Node(keys(rng)));
789 const auto at = places(heap);
790 const long before = calls;
791 delete heap.remove(at[i]);
792 // the root of a heap of 2 nodes leaves it with one: nothing to compare
793 EXPECT_EQ(calls == before, i == n or n == 2) << "n " << n << ", place " << i;
794 }
795}
796
797// What the description of tpl_binHeap.H says of a heap of 10 nodes
798TEST(BinHeapShape, TheHeapOfTenNodesOfTheDescription)
799{
800 BinHeap<int> heap;
801 Freed_At_Exit<BinHeap<int>> nodes{heap};
802 for (int k = 1; k <= 10; ++k)
803 heap.insert(new BinHeap<int>::Node(k)); // in order: the node of key k is at the place k
804 const auto at = places(heap);
805 for (int k = 1; k <= 10; ++k)
806 ASSERT_EQ(at[k]->get_key(), k);
807
808 // 1 to 4 have two children
809 for (int k = 1; k <= 4; ++k)
810 {
811 EXPECT_EQ(at[k]->getL(), at[2*k]);
812 EXPECT_EQ(at[k]->getR(), at[2*k + 1]);
813 }
814 // the list: 5, 6, 7, 8, 9, 10 and 5 again
815 for (int k = 5; k <= 10; ++k)
816 {
817 EXPECT_EQ(at[k]->getR(), at[k == 10 ? 5 : k + 1]);
818 EXPECT_EQ(at[k]->getL(), at[k == 5 ? 10 : k - 1]);
819 }
820 // 5 has a left child only, 10, which is its previous node of the list too
821 EXPECT_EQ(at[5]->getL(), at[10]);
822 EXPECT_EQ(parent_of(at[10]), at[5]);
823 EXPECT_FALSE(static_cast<bool>(at[5]->get_control_fields().is_leaf));
824 EXPECT_EQ(at[5]->getR(), at[6]);
825 EXPECT_NE(parent_of(at[6]), at[5]);
826
827 // the next node goes under the first one of the list, which follows the last
829 EXPECT_EQ(parent_of(p), at[5]);
830 EXPECT_EQ(at[5]->getR(), p);
831 EXPECT_EQ(p->getL(), at[10]); // after the last one in the list
832 EXPECT_EQ(p->getR(), at[6]); // 5 left the list: 6 is its first node now
833}
834
835// verify_heap() went down by the right child only where there were two, so
836// it did not see a node out of order in a left subtree
837TEST(BinHeapShape, VerifyHeapLooksAtEveryNode)
838{
839 for (int n = 1; n <= 40; ++n)
840 {
841 BinHeap<int> heap;
842 Freed_At_Exit<BinHeap<int>> nodes{heap};
843 for (int k = 1; k <= n; ++k)
844 heap.insert(new BinHeap<int>::Node(10*k)); // the node of key 10 k is at the place k
845 const auto at = places(heap);
846 EXPECT_TRUE(heap.verify_heap()) << n << " nodes";
847 for (int i = 2; i <= n; ++i)
848 {
849 at[i]->get_key() = 10*(i / 2) - 1; // less than the key of its parent only
850 EXPECT_FALSE(heap.verify_heap()) << n << " nodes, place " << i;
851 at[i]->get_key() = 10*i;
852 }
853 EXPECT_TRUE(heap.verify_heap()) << n << " nodes";
854 }
855}
856
857// ─────────────────────────────────────────────────────────────────
858// A comparison that throws leaves the heap as it was
859// ─────────────────────────────────────────────────────────────────
860
861namespace
862{
863 // A key with a priority, which the comparisons look at, and an identity,
864 // which they do not: it tells apart the keys of a priority
865 struct Pri
866 {
867 int pri = 0;
868 int id = 0;
869
870 bool operator==(const Pri &) const = default;
871 };
872
873 void PrintTo(const Pri & x, std::ostream *os) { *os << x.pri << '#' << x.id; }
874
875 // The calls of a Counted_Less: how many, the one that throws (0: none),
876 // and the identities of the two keys of each one, in order
877 struct Calls
878 {
879 size_t count = 0;
880 size_t throw_at = 0;
881 std::vector<std::pair<int, int>> keys;
882 };
883
884 struct Counted_Less
885 {
886 Calls *calls;
887
888 bool operator()(const Pri & a, const Pri & b) const
889 {
890 if (++calls->count == calls->throw_at)
891 throw std::runtime_error("comparison");
892 calls->keys.emplace_back(a.id, b.id);
893 return a.pri < b.pri;
894 }
895 };
896
897 using Counted_Heap = BinHeap<Pri, Counted_Less>;
898
899 // The keys of a heap by the places of their nodes
900 std::vector<Pri> layout(const Counted_Heap & heap)
901 {
902 std::vector<Pri> keys;
903 const auto at = places(heap);
904 for (size_t i = 1; i <= heap.size(); ++i)
905 keys.push_back(at[i]->get_key());
906 return keys;
907 }
908
909 // The heap of 7.7.5 on a vector indexed by the places, whose entry 0 is
910 // not used: its sifts compared a node with its parent or its children and
911 // exchanged them level by level, and its operations linked and unlinked
912 // the nodes before they compared
913 struct Old_Heap
914 {
915 std::vector<Pri> a = std::vector<Pri>(1);
916 size_t n = 0;
917 Counted_Less cmp;
918
919 size_t sift_up(size_t i)
920 {
921 for (; i > 1 and cmp(a[i], a[i / 2]); i /= 2)
922 std::swap(a[i], a[i / 2]);
923 return i;
924 }
925
926 size_t sift_down(size_t i)
927 {
928 while (2*i <= n)
929 {
930 size_t c = 2*i;
931 if (c + 1 <= n and cmp(a[c + 1], a[c]))
932 ++c;
933 if (cmp(a[i], a[c]))
934 break;
935 std::swap(a[i], a[c]);
936 i = c;
937 }
938 return i;
939 }
940
941 void insert(const Pri & x)
942 {
943 a.resize(std::max(a.size(), n + 2));
944 a[++n] = x;
945 sift_up(n);
946 }
947
948 Pri getMin()
949 {
950 const Pri ret = a[1];
951 a[1] = a[n];
952 if (--n > 0)
953 sift_down(1);
954 return ret;
955 }
956
957 void update(const size_t i) { sift_up(sift_down(i)); }
958
959 void remove(const size_t i)
960 {
961 if (i == 1)
962 {
963 getMin();
964 return;
965 }
966 const Pri moved = a[n];
967 if (i == n--)
968 return;
969 a[i] = moved; // the last node takes the place of the removed one
970 update(i);
971 }
972
973 std::vector<Pri> layout() const { return {a.begin() + 1, a.begin() + 1 + static_cast<long>(n)}; }
974 };
975
976 // The links and the flags of a node
977 template <class Node>
978 auto links_of(Node *p)
979 {
980 return std::make_tuple(p->getL(), p->getR(), parent_of(p),
981 static_cast<bool>(p->get_control_fields().is_leaf),
982 static_cast<bool>(p->get_control_fields().is_left));
983 }
984}
985
986// The operations compare the same keys in the same order as those of 7.7.5,
987// and leave every node at the same place, those of a same priority too
988TEST(BinHeapThrowingCompare, SameComparisonsAndPlacesAsBefore)
989{
990 std::mt19937 rng(77);
991 std::uniform_int_distribution<int> values(0, 50); // many keys of a same priority
992 Calls calls, old_calls;
993 Counted_Heap heap(Counted_Less{&calls});
994 Freed_At_Exit<Counted_Heap> nodes{heap};
995 Old_Heap old{.cmp = Counted_Less{&old_calls}};
996 size_t updates = 0, removals = 0, extractions = 0;
997 for (int k = 0; k < 6000; ++k)
998 {
999 const unsigned op = old.n == 0 ? 0 : rng() % 8;
1000 if (op < 4)
1001 {
1002 const Pri x{values(rng), k + 1};
1003 heap.insert(new Counted_Heap::Node(x));
1004 old.insert(x);
1005 }
1006 else if (op == 4)
1007 {
1008 std::unique_ptr<Counted_Heap::Node> min(heap.getMin());
1009 ASSERT_EQ(min->get_key(), old.getMin());
1010 ++extractions;
1011 }
1012 else
1013 {
1014 const auto at = places(heap);
1015 const size_t i = 1 + rng() % old.n;
1016 if (op == 5)
1017 {
1018 std::unique_ptr<Counted_Heap::Node> out(heap.remove(at[i]));
1019 ASSERT_EQ(out.get(), at[i]);
1020 old.remove(i);
1021 ++removals;
1022 }
1023 else
1024 {
1025 const int pri = values(rng);
1026 at[i]->get_key().pri = pri;
1027 old.a[i].pri = pri;
1028 heap.update(at[i]);
1029 old.update(i);
1030 ++updates;
1031 }
1032 }
1033 ASSERT_EQ(calls.keys, old_calls.keys) << "operation " << k;
1034 calls.keys.clear();
1035 old_calls.keys.clear();
1036 ASSERT_EQ(layout(heap), old.layout()) << "operation " << k;
1037 }
1038 EXPECT_GT(updates, 1000u);
1039 EXPECT_GT(removals, 500u);
1040 EXPECT_GT(extractions, 500u);
1041 EXPECT_GT(heap.size(), 100u);
1042}
1043
1044// Each failed comparison of an insertion, an extraction, a removal or an
1045// update leaves the heap as it was: every node at its place and with its
1046// links, and the node of a failed insertion out of the heap, ready to be
1047// inserted again.
1048// 7.7.5 left the node of an insertion in a heap out of order, and took out
1049// that of an extraction or of a removal
1050TEST(BinHeapThrowingCompare, EveryFailedCallLeavesTheHeapAsItWas)
1051{
1052 std::mt19937 rng(20261121);
1053 std::uniform_int_distribution<int> values(0, 30);
1054 size_t failed = 0;
1055 for (size_t n = 0; n <= 40; ++n)
1056 for (int op = 0; op < 4; ++op) // insert, getMin, remove, update
1057 for (int round = 0; round < (n < 2 ? 1 : 3); ++round)
1058 {
1059 if (op != 0 and n == 0)
1060 continue;
1061 std::vector<Pri> keys;
1062 for (size_t k = 0; k < n; ++k)
1063 keys.push_back(Pri{values(rng), static_cast<int>(k + 1)});
1064 const Pri key{values(rng), static_cast<int>(n + 1)};
1065 const size_t where = n == 0 ? 0 : 1 + rng() % n; // of the removal and of the update
1066 const int new_pri = values(rng);
1067 for (size_t at_call = 1; ; ++at_call)
1068 {
1069 SCOPED_TRACE(testing::Message() << "n " << n << ", op " << op << ", place "
1070 << where << ", call " << at_call);
1071 Calls calls;
1072 Counted_Heap heap(Counted_Less{&calls});
1073 Freed_At_Exit<Counted_Heap> nodes{heap};
1074 for (const Pri & x : keys)
1075 heap.insert(new Counted_Heap::Node(x));
1076 std::vector<Counted_Heap::Node *> at = places(heap);
1077 if (op == 3)
1078 at[where]->get_key().pri = new_pri; // the heap is as its user left it
1079 std::vector<decltype(links_of(at[0]))> links;
1080 for (size_t i = 1; i <= n; ++i)
1081 links.push_back(links_of(at[i]));
1082 std::unique_ptr<Counted_Heap::Node> node(new Counted_Heap::Node(key));
1083
1084 calls.throw_at = calls.count + at_call;
1085 bool thrown = false;
1086 Counted_Heap::Node *out = nullptr;
1087 try
1088 {
1089 switch (op)
1090 {
1091 case 0: heap.insert(node.get()); break;
1092 case 1: out = heap.getMin(); break;
1093 case 2: out = heap.remove(at[where]); break;
1094 default: heap.update(at[where]);
1095 }
1096 }
1097 catch (const std::runtime_error &)
1098 {
1099 thrown = true;
1100 }
1101 calls.throw_at = 0;
1102 if (thrown)
1103 {
1104 ++failed;
1105 EXPECT_EQ(out, nullptr);
1106 EXPECT_EQ(heap.size(), n);
1107 EXPECT_EQ(places(heap), at);
1108 for (size_t i = 1; i <= n; ++i)
1109 EXPECT_EQ(links_of(at[i]), links[i - 1]) << "place " << i;
1110 if (op == 0)
1111 { // the node is out, and can be inserted again
1112 heap.insert(node.release());
1113 EXPECT_EQ(heap.size(), n + 1);
1114 places(heap);
1115 EXPECT_TRUE(heap.verify_heap());
1116 }
1117 }
1118 else
1119 {
1120 places(heap);
1121 EXPECT_TRUE(heap.verify_heap());
1122 if (op == 0)
1123 node.release(); // it is in the heap
1124 delete out;
1125 }
1126 if (not thrown)
1127 break;
1128 }
1129 }
1130 EXPECT_GT(failed, 1000u);
1131}
1132
1133namespace
1134{
1135 // What a comparison returns, whose conversion to bool may throw
1136 struct Touchy_Bool
1137 {
1138 bool value;
1139
1140 operator bool() const { return value; }
1141 };
1142
1143 // A comparison that does not throw, but the conversion of its result may
1144 struct Touchy_Less
1145 {
1146 Touchy_Bool operator()(const int a, const int b) const noexcept { return {a < b}; }
1147 };
1148
1149 using Touchy_Heap = BinHeap<int, Touchy_Less>;
1150 using Touchy_Dyn_Heap = DynBinHeap<int, Touchy_Less>;
1151}
1152
1153// The operations of a heap are noexcept if its comparison is, with the
1154// conversion of its result to bool, which they also make
1155static_assert(noexcept(std::declval<BinHeap<int> &>().insert(nullptr)));
1156static_assert(noexcept(std::declval<BinHeap<int> &>().getMin_ne()));
1157static_assert(noexcept(std::declval<BinHeap<int> &>().update(nullptr)));
1158static_assert(not noexcept(std::declval<Touchy_Heap &>().insert(nullptr)));
1159static_assert(not noexcept(std::declval<Touchy_Heap &>().getMin_ne()));
1160static_assert(not noexcept(std::declval<Touchy_Heap &>().update(nullptr)));
1161static_assert(not noexcept(std::declval<Touchy_Dyn_Heap &>().update(std::declval<int &>())));
1162static_assert(not noexcept(std::declval<Touchy_Dyn_Heap &>().remove(std::declval<int &>())));
1163static_assert(not noexcept(std::declval<Failing_Heap &>().insert(nullptr)));
1164
1165namespace
1166{
1167 // What a comparison returns. Its implicit conversion to bool does not
1168 // throw; the explicit one, which a condition chooses for a result that
1169 // has no name, may
1170 struct Sly_Bool
1171 {
1172 bool value;
1173 long *conversions; // those of the conditions, so far
1174 long throw_at; // the one that throws (0: none)
1175
1176 operator bool() const & noexcept { return value; }
1177
1178 explicit operator bool() &&
1179 {
1180 if (++*conversions == throw_at)
1181 throw std::runtime_error("conversion");
1182 return value;
1183 }
1184 };
1185
1186 // A comparison that does not throw. For two keys that are not const, as
1187 // the heap compares those of its nodes, the conversion of its result in
1188 // a condition may
1189 struct Sly_Less
1190 {
1191 long *conversions;
1192 long *throw_at;
1193
1194 bool operator()(const int & a, const int & b) const noexcept { return a < b; }
1195
1196 Sly_Bool operator()(int & a, int & b) const noexcept { return {a < b, conversions, *throw_at}; }
1197 };
1198
1199 using Sly_Heap = BinHeap<int, Sly_Less>;
1200}
1201
1202// The conversion that counts is the one that the conditions of the sifts
1203// make, not the implicit one, which this comparison has without throwing
1204static_assert(std::is_nothrow_invocable_r_v<bool, Sly_Less &, int &, int &>);
1205static_assert(not noexcept(std::declval<Sly_Heap &>().insert(nullptr)));
1206static_assert(not noexcept(std::declval<Sly_Heap &>().getMin_ne()));
1207static_assert(not noexcept(std::declval<Sly_Heap &>().update(nullptr)));
1208
1209// With that comparison the operations said that they were noexcept, and
1210// the conversion that threw in a sift ended the program. Now what it
1211// throws reaches the caller, from a heap that is as it was
1212TEST(BinHeapThrowingCompare, AConversionInAConditionThatThrowsIsUndone)
1213{
1214 size_t failed = 0;
1215 for (int op = 0; op < 4; ++op) // insert, getMin, remove, update
1216 for (long at_conversion = 1; ; ++at_conversion)
1217 {
1218 SCOPED_TRACE(testing::Message() << "op " << op << ", conversion " << at_conversion);
1219 long conversions = 0, throw_at = 0;
1220 Sly_Heap heap(Sly_Less{&conversions, &throw_at});
1221 Freed_At_Exit<Sly_Heap> nodes{heap};
1222 for (const int key : {10, 20, 30, 40, 50, 60, 70})
1223 heap.insert(new Sly_Heap::Node(key));
1224 const auto at = places(heap);
1225 std::vector<decltype(links_of(at[0]))> links;
1226 for (size_t i = 1; i <= 7; ++i)
1227 links.push_back(links_of(at[i]));
1228 std::unique_ptr<Sly_Heap::Node> node(new Sly_Heap::Node(5)); // it goes up to the root
1229 if (op == 3)
1230 at[7]->get_key() = 1; // the last node goes up to the root too
1231
1232 conversions = 0;
1233 throw_at = at_conversion;
1234 bool thrown = false;
1235 Sly_Heap::Node *out = nullptr;
1236 try
1237 {
1238 switch (op)
1239 {
1240 case 0: heap.insert(node.get()); break;
1241 case 1: out = heap.getMin(); break;
1242 case 2: out = heap.remove(at[2]); break;
1243 default: heap.update(at[7]);
1244 }
1245 }
1246 catch (const std::runtime_error &)
1247 {
1248 thrown = true;
1249 }
1250 throw_at = 0;
1251 if (not thrown)
1252 {
1253 places(heap);
1254 if (op == 0)
1255 {
1256 EXPECT_EQ(heap.top(), node.release()); // it is in the heap, at the root
1257 }
1258 if (op == 3)
1259 {
1260 EXPECT_EQ(heap.top(), at[7]);
1261 }
1262 delete out;
1263 break;
1264 }
1265 ++failed;
1266 EXPECT_EQ(out, nullptr);
1267 EXPECT_EQ(places(heap), at);
1268 for (size_t i = 1; i <= 7; ++i)
1269 EXPECT_EQ(links_of(at[i]), links[i - 1]) << "place " << i;
1270 }
1271 EXPECT_GT(failed, 8u);
1272}
1273
1274// Each failed comparison of an insertion, an extraction, a removal or an
1275// update of a DynBinHeap leaves it as it was: the same nodes at the same
1276// places, and as many items alive as before the call. 7.7.5 left the new
1277// item in a heap out of order, and destroyed that of an extraction or of a
1278// removal
1279TEST(DynBinHeapComparison, EveryFailedCallLeavesTheHeapAsItWas)
1280{
1282 std::mt19937 rng(20261121);
1283 std::uniform_int_distribution<int> values(0, 30);
1284 const long alive_at_start = Counted::alive;
1285 size_t failed = 0;
1286 for (size_t n = 0; n <= 24; ++n)
1287 for (int op = 0; op < 5; ++op) // insert of a copy and of a move, getMin, remove, update
1288 {
1289 if (op >= 2 and n == 0)
1290 continue;
1291 std::vector<int> keys;
1292 for (size_t k = 0; k < n; ++k)
1293 keys.push_back(values(rng));
1294 const int key = values(rng);
1295 const size_t where = n == 0 ? 0 : 1 + rng() % n;
1296 const int new_key = values(rng);
1297 for (long at_call = 1; ; ++at_call)
1298 {
1299 SCOPED_TRACE(testing::Message() << "n " << n << ", op " << op << ", place "
1300 << where << ", call " << at_call);
1301 long calls = 0;
1302 bool thrown = false;
1303 {
1304 Failing_Dyn_Heap heap(Failing_Counted_Less{{&calls, 0}});
1305 for (const int k : keys)
1306 heap.insert(Counted(k));
1307 const auto at = places(static_cast<const Base &>(heap));
1308 if (op == 4)
1309 at[where]->get_key().value = new_key; // the heap is as its user left it
1310 const Counted item(key);
1311 const long alive = Counted::alive;
1312
1313 heap.key_comp().less.fail_at = calls + at_call;
1314 try
1315 {
1316 switch (op)
1317 {
1318 case 0: heap.insert(item); break;
1319 case 1: heap.insert(Counted(key)); break;
1320 case 2: (void) heap.getMin(); break;
1321 case 3: heap.remove(at[where]->get_key()); break;
1322 default: heap.update(at[where]->get_key());
1323 }
1324 }
1325 catch (const std::runtime_error &)
1326 {
1327 thrown = true;
1328 }
1329 heap.key_comp().less.fail_at = 0;
1330 if (thrown)
1331 {
1332 ++failed;
1333 EXPECT_EQ(heap.size(), n);
1334 EXPECT_EQ(places(static_cast<const Base &>(heap)), at);
1335 EXPECT_EQ(Counted::alive, alive);
1336 }
1337 else
1338 {
1339 places(static_cast<const Base &>(heap));
1340 EXPECT_TRUE(heap.verify_heap());
1341 }
1342 }
1343 EXPECT_EQ(Counted::alive, alive_at_start); // the heap freed every item
1344 if (not thrown)
1345 break;
1346 }
1347 }
1348 EXPECT_GT(failed, 200u);
1349}
1350
1351namespace
1352{
1353 // A comparison that contradicts itself: each call gives what a generator
1354 // of random bits says, whatever the keys
1355 struct Random_Less
1356 {
1357 std::mt19937 *rng;
1358
1359 bool operator()(const int, const int) const { return (*rng)() & 1; }
1360 };
1361}
1362
1363// With a comparison that contradicts itself the heap cannot be in order,
1364// but its tree and the list of its nodes that lack a child are well formed
1365// after each operation, and no node is lost: the ways that the operations
1366// find never leave the tree
1367TEST(BinHeapShape, AComparisonThatContradictsItselfKeepsTheTree)
1368{
1369 std::mt19937 bits(99), rng(3);
1370 using Heap = BinHeap<int, Random_Less>;
1371 Heap heap(Random_Less{&bits});
1372 Freed_At_Exit<Heap> nodes{heap};
1373 std::vector<std::unique_ptr<Heap::Node>> out; // those that left the heap
1374 size_t removals = 0, updates = 0;
1375 for (int k = 0; k < 20000; ++k)
1376 {
1377 unsigned op = heap.is_empty() ? 0 : rng() % 7;
1378 if (op < 3 and heap.size() >= 150)
1379 op = 3; // the heap stays small, so that looking at all of it is cheap
1380 const size_t size = heap.size();
1381 if (op < 3)
1382 heap.insert(new Heap::Node(k));
1383 else if (op == 3)
1384 out.emplace_back(heap.getMin());
1385 else
1386 {
1387 std::vector<Heap::Node *> at;
1388 ASSERT_EQ(shape_errors(heap, at), "");
1389 Heap::Node *p = at[1 + rng() % size];
1390 if (op == 4)
1391 {
1392 Heap::Node *removed = heap.remove(p);
1393 out.emplace_back(removed);
1394 ASSERT_EQ(removed, p);
1395 ++removals;
1396 }
1397 else
1398 {
1399 heap.update(p);
1400 ++updates;
1401 }
1402 }
1403 std::vector<Heap::Node *> at;
1404 ASSERT_EQ(shape_errors(heap, at), "") << "operation " << k;
1405 ASSERT_EQ(heap.size(), op < 3 ? size + 1 : op <= 4 ? size - 1 : size);
1406 out.clear();
1407 }
1408 EXPECT_GT(removals, 1000u);
1409 EXPECT_GT(updates, 1000u);
1410}
1411
1412namespace
1413{
1414 // Its default construction throws while fail is true
1415 struct Fragile_Default_Key
1416 {
1417 static inline bool fail = false;
1418 int value = 0;
1419
1420 Fragile_Default_Key()
1421 {
1422 if (fail)
1423 throw std::runtime_error("default construction failed");
1424 }
1425
1426 Fragile_Default_Key(int v) noexcept : value(v) {}
1427
1428 bool operator < (const Fragile_Default_Key & other) const noexcept
1429 {
1430 return value < other.value;
1431 }
1432 };
1433} // namespace
1434
1435// The constructors of the heaps were noexcept, but they build the header
1436// node, whose key is built by default: a key whose default construction
1437// throws, as one that allocates, ended the program
1438TEST(BinHeapConstruction, ItsNoexceptFollowsTheDefaultConstructionOfTheKey)
1439{
1440 static_assert(std::is_nothrow_default_constructible_v<BinHeap<int>>);
1441 static_assert(std::is_nothrow_default_constructible_v<BinHeapVtl<int>>);
1442 static_assert(std::is_nothrow_default_constructible_v<DynBinHeap<int>>);
1443 static_assert(std::is_nothrow_default_constructible_v<DynBinHeap<std::string>>);
1444 static_assert(not std::is_nothrow_default_constructible_v<BinHeap<Fragile_Default_Key>>);
1445 static_assert(not std::is_nothrow_default_constructible_v<BinHeapVtl<Fragile_Default_Key>>);
1446 static_assert(not std::is_nothrow_default_constructible_v<DynBinHeap<Fragile_Default_Key>>);
1447
1448 Fragile_Default_Key::fail = true;
1449 EXPECT_THROW({ BinHeap<Fragile_Default_Key> heap; }, std::runtime_error);
1450 EXPECT_THROW({ DynBinHeap<Fragile_Default_Key> heap; }, std::runtime_error);
1452 EXPECT_THROW({ DynBinHeap<Fragile_Default_Key> heap(cmp); }, std::runtime_error);
1453 Fragile_Default_Key::fail = false;
1454
1456 for (int i = 5; i > 0; --i)
1457 heap.insert(Fragile_Default_Key(i));
1458 ASSERT_EQ(heap.size(), 5u);
1459 EXPECT_EQ(heap.top().value, 1);
1460}
1461
1462namespace
1463{
1464 // A comparison with two copies: the one from a comparison that is not
1465 // const may throw, and the one from a const one cannot
1466 struct Mutable_Copy_Less
1467 {
1468 static inline bool fail = false;
1469
1470 Mutable_Copy_Less() noexcept = default;
1471 Mutable_Copy_Less(const Mutable_Copy_Less &) noexcept = default;
1472
1473 Mutable_Copy_Less(Mutable_Copy_Less &)
1474 {
1475 if (fail)
1476 throw std::runtime_error("the copy of the comparison");
1477 }
1478
1479 Mutable_Copy_Less(Mutable_Copy_Less &&) noexcept = default;
1480 Mutable_Copy_Less & operator = (const Mutable_Copy_Less &) noexcept = default;
1481 Mutable_Copy_Less & operator = (Mutable_Copy_Less &&) noexcept = default;
1482
1483 bool operator () (const int a, const int b) const noexcept { return a < b; }
1484 };
1485}
1486
1487// The heap takes its comparison by value and copies it, from a comparison
1488// that is not const: its noexcept follows that copy, and what it throws
1489// reaches the caller
1490TEST(BinHeapConstruction, ItsNoexceptFollowsTheCopyOfTheComparisonThatItTakes)
1491{
1492 using Less = Mutable_Copy_Less;
1493 using Heap = BinHeap<int, Less>;
1494 static_assert(std::is_nothrow_copy_constructible_v<Less>);
1495 static_assert(not std::is_nothrow_constructible_v<Less, Less &>);
1496 static_assert(not std::is_nothrow_constructible_v<Heap, Less>);
1497 static_assert(std::is_nothrow_constructible_v<BinHeap<int>, Aleph::less<int>>);
1498
1499 Less::fail = true;
1500 EXPECT_THROW({ Heap heap{Less()}; }, std::runtime_error);
1501 Less::fail = false;
1502
1503 Heap heap{Less()};
1504 EXPECT_TRUE(heap.is_empty());
1505}
1506
1507namespace
1508{
1509 // A comparison whose default construction may throw, when asked
1510 struct Default_Throws_Less
1511 {
1512 static inline bool fail = false;
1513
1514 Default_Throws_Less()
1515 {
1516 if (fail)
1517 throw std::runtime_error("the default construction of the comparison");
1518 }
1519
1520 bool operator () (const int a, const int b) const noexcept { return a < b; }
1521 };
1522}
1523
1524// BinHeap and BinHeapVtl inherit the constructors of GenBinHeap: had the
1525// comparison been a default argument of the one that takes it, their
1526// implicit default constructor would be noexcept without counting it, and
1527// what its construction throws would end the program
1528TEST(BinHeapConstruction, BuiltByDefaultItLetsTheFailureOfTheComparisonThrough)
1529{
1530 using Less = Default_Throws_Less;
1531 using Heap = BinHeap<int, Less>;
1532 using Heap_Vtl = BinHeapVtl<int, Less>;
1533 using Dyn_Heap = DynBinHeap<int, Less>;
1534 static_assert(not std::is_nothrow_default_constructible_v<Heap>);
1535 static_assert(not std::is_nothrow_default_constructible_v<Heap_Vtl>);
1536 // DynBinHeap takes its comparison as a default argument of a constructor
1537 // of its own, which the caller evaluates: it throws as the others do, but
1538 // MSVC answers is_nothrow_default_constructible without counting that
1539 // argument, and so its trait is not asserted here
1540
1541 Less::fail = true;
1542 EXPECT_THROW({ Heap heap; }, std::runtime_error);
1543 EXPECT_THROW({ Heap_Vtl heap; }, std::runtime_error);
1544 EXPECT_THROW({ Dyn_Heap heap; }, std::runtime_error);
1545 Less::fail = false;
1546
1547 Heap heap;
1548 EXPECT_TRUE(heap.is_empty());
1549}
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
void PrintTo(const mpq_class &q, std::ostream *os)
WeightedDigraph::Node Node
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
BinHeapNode *& getR() noexcept
BinHeapNode *& getL() noexcept
Dynamic heap of elements of type T ordered by a comparison functor.
T get()
Alias for getMin().
T getMin()
Remove the minimum element (according to Compare) and return it.
void empty() noexcept
Remove every element.
bool remove(T &data) noexcept(Base::nothrow_cmp)
Remove an arbitrary element belonging to the heap.
void update(T &data) noexcept(Base::nothrow_cmp)
Adjust the position of an element after mutating its priority.
T & insert(const T &item)
Insert a copy of item into the heap.
const T & top() const
Return a reference to the smallest element.
Node * insert(Node *p) noexcept(nothrow_cmp)
Inserts a node into a heap.
virtual bool verify_heap(Node *p) const
Whether no node of the tree of root p has a key less than that of its parent.
bool is_empty() const noexcept
void update(Node *p) noexcept(nothrow_cmp)
Updates the priority of a node contained in the heap.
Node * remove(Node *node)
Removes node from the heap.
void swap(GenBinHeap &h) noexcept
Node * top()
Returns the node with the lowest priority according to the comparison criterion specified in the decl...
Node * getMin()
Removes the node with the lowest priority from the heap.
const size_t & size() const noexcept
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Minimal std::expected-style result type for C++20.
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
#define TEST(name)
static mt19937 rng
#define N
Definition fib.C:294
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
__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
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
Main namespace for Aleph-w library functions.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
void sift_down(T *ptr, const size_t l, const size_t r, Compare &cmp)
Restore the heap property by moving the element at position l downwards.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
static long & low(typename GT::Node *p)
Internal helper: low-link value stored directly in NODE_COOKIE(p).
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
and
Check uniqueness with explicit hash + equality functors.
Fw_Itor remove(Fw_Itor __first, const Fw_Itor &__last, const T &__value)
Remove elements equal to a value.
Definition ahAlgo.H:962
static bool is_leaf(BinNode< std::string > *p) noexcept
Definition Huffman.H:109
T & sift_up(T *ptr, const size_t l, const size_t r, Compare &cmp)
Restore the heap property by moving the element at position r upwards.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
Heap of nodes with virtual destructor.
Node heap without virtual destructor.
Counted(int v=0)
int keys[]
static int * k
Binary heap implementation using tree structure.
Dynamic binary heap with node-based storage.