52#include <gtest/gtest.h>
59TEST(DynBinHeapTest, InsertExtractInOrder)
62 const std::vector<int> values = {7, 3, 11, 0, 5, 9, 1};
64 for (
const int v : values)
72 ASSERT_EQ(heap.
top(), v);
73 EXPECT_EQ(heap.
getMin(), v);
77 EXPECT_EQ(heap.
size(), 0u);
80TEST(DynBinHeapTest, RemoveArbitraryNodes)
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());
87 for (
const int v : values)
88 refs.emplace_back(heap.
insert(v));
90 ASSERT_EQ(heap.
size(), values.size());
95 std::vector<int> remaining;
97 remaining.push_back(heap.
getMin());
100 const auto erase_value = [&
expected](
int needle) {
112TEST(DynBinHeapTest, UpdateReordersAfterPriorityChange)
115 auto &high = heap.
insert(50);
121 EXPECT_EQ(heap.
top(), 1);
126 std::vector<int> drained;
128 drained.push_back(heap.
getMin());
130 EXPECT_EQ(drained, std::vector<int>({1, 20, 60}));
133TEST(DynBinHeapTest, RandomizedInsertExtract)
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);
144 std::vector<int> extracted;
146 extracted.push_back(heap.
getMin());
153TEST(DynBinHeapTest, IteratorTraversesAllElements)
156 constexpr size_t N = 64;
157 for (
size_t i = 0; i <
N; ++i)
158 heap.
insert(
static_cast<int>(i));
161 for (
auto it = heap.
get_it(); it.has_curr(); it.next())
167TEST(DynBinHeapTest, EmptyRemovesAllNodes)
170 for (
int i = 0; i < 50; ++i)
175 EXPECT_EQ(heap.
size(), 0u);
179 EXPECT_EQ(heap.
getMin(), 10);
183TEST(DynBinHeapTest, UpdateWithDuplicatePriorities)
186 std::vector<std::reference_wrapper<int>> refs;
187 for (
int i = 0; i < 5; ++i)
188 refs.emplace_back(heap.
insert(10));
191 refs.front().
get() = -1;
192 heap.
update(refs.front());
193 EXPECT_EQ(heap.
top(), -1);
196 refs.back().get() = 100;
199 std::vector<int> drained;
201 drained.push_back(heap.
getMin());
203 EXPECT_TRUE(std::is_sorted(drained.begin(), drained.end()));
204 EXPECT_EQ(drained.front(), -1);
205 EXPECT_EQ(drained.back(), 100);
214 long * calls =
nullptr;
217 bool operator()(
const int & a,
const int & b)
const
219 if (calls !=
nullptr and ++*calls == fail_at)
220 throw std::runtime_error(
"comparison failed");
229 std::vector<int> insert_and_extract(
const std::vector<int> & values,
230 long & calls,
long fail_at)
232 Failing_Heap heap(Failing_Less{&calls, fail_at});
233 std::vector<int>
out;
236 for (
const int v : values)
238 std::unique_ptr<Failing_Heap::Node> node(
new Failing_Heap::Node(v));
239 heap.insert(node.get());
243 heap.update(heap.getRoot());
245 while (not heap.is_empty())
247 std::unique_ptr<Failing_Heap::Node>
min(heap.getMin());
248 out.push_back(
min->get_key());
253 heap.remove_all_and_delete();
262TEST(BinHeapComparison, WhatTheComparisonThrowsReachesTheCaller)
264 const std::vector<int> values = {7, 3, 11, 0, 5, 9, 1, 8};
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());
270 for (
long k = 1;
k <= calls; ++
k)
273 EXPECT_THROW(insert_and_extract(values,
count,
k), std::runtime_error)
281TEST(BinHeapComparison, RemoveAllAndDeleteDoesNotCompare)
283 for (
int n = 1; n <= 6; ++n)
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));
290 const long before = calls;
291 heap.remove_all_and_delete();
292 EXPECT_EQ(calls, before) << n <<
" nodes";
293 EXPECT_TRUE(heap.is_empty());
295 heap.insert(
new Failing_Heap::Node(4));
296 EXPECT_EQ(heap.top()->get_key(), 4);
297 heap.remove_all_and_delete();
304TEST(BinHeapComparison, RemoveLeavesTheNodeInTheHeapIfTheComparisonThrows)
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());
310 for (
size_t i = 0; i < values.size(); ++i)
311 for (
long k = 1; ; ++
k)
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)));
319 heap.key_comp().fail_at = calls +
k;
323 heap.remove(
nodes[i]);
325 catch (
const std::runtime_error &)
330 heap.key_comp().fail_at = 0;
331 EXPECT_EQ(heap.size(), threw ? values.size() : values.size() - 1);
333 heap.insert(
nodes[i]);
334 EXPECT_TRUE(heap.verify_heap());
335 std::vector<int>
out;
336 while (not heap.is_empty())
338 std::unique_ptr<Failing_Heap::Node>
min(heap.getMin());
339 out.push_back(
min->get_key());
341 EXPECT_EQ(
out, sorted) <<
"node " << i <<
", call " <<
k;
353 static inline long alive = 0;
356 Counted(
int v = 0) noexcept : value(v) { ++alive; }
357 Counted(
const Counted & c) noexcept :
value(c.value) { ++alive; }
362 struct Failing_Counted_Less
366 bool operator()(
const Counted & a,
const Counted & b)
const
368 return less(a.value, b.value);
378 template <
class Heap,
class Disarm>
379 void use_dyn_heap(Heap & heap,
const std::vector<int> & values,
382 using Item =
typename Heap::Item_Type;
385 std::vector<Item *> items;
386 for (
const int v : values)
392 heap.update(*items[2]);
393 heap.remove(*items[3]);
394 heap.erase(*items[5]);
395 while (not heap.is_empty())
396 (void) heap.getMin();
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);
411 void use_dyn_heap(
const std::vector<int> & values,
long & calls,
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; });
423TEST(DynBinHeapComparison, WhatTheComparisonThrowsReachesTheCaller)
425 const std::vector<int> values = {7, 3, 11, 0, 5, 9, 1, 8};
426 const long alive = Counted::alive;
428 use_dyn_heap(values, calls, 0);
429 ASSERT_EQ(Counted::alive, alive);
431 for (
long k = 1;
k <= calls; ++
k)
434 EXPECT_THROW(use_dyn_heap(values,
count,
k), std::runtime_error)
436 EXPECT_EQ(Counted::alive, alive) <<
"call " <<
k;
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 &>())));
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 &>())));
466 struct Failing_Key : Counted
470 static inline Failing_Less
less;
472 bool operator<(
const Failing_Key & other)
const
481 void use_key_heap(
const std::vector<int> & values,
long & calls,
486 ~Reset() { Failing_Key::less = Failing_Less{}; }
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; });
498static_assert(std::is_copy_constructible_v<Failing_Dyn_Heap>);
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 &>())));
512TEST(DynBinHeapComparison, WhatTheLessThanOfTheKeysThrowsReachesTheCaller)
514 const std::vector<int> values = {7, 3, 11, 0, 5, 9, 1, 8};
515 const long alive = Counted::alive;
517 use_key_heap(values, calls, 0);
518 ASSERT_EQ(Counted::alive, alive);
521 for (
long k = 1;
k <= calls; ++
k)
524 EXPECT_THROW(use_key_heap(values,
count,
k), std::runtime_error)
526 EXPECT_EQ(Counted::alive, alive) <<
"call " <<
k;
534 std::vector<int>
out;
543TEST(DynBinHeapTest, MoveConstructionOutlivesTheSource)
545 for (
int n = 0; n <= 7; ++n)
547 std::unique_ptr<DynBinHeap<int>> moved;
550 for (
int i = n; i > 0; --i)
552 moved = std::make_unique<DynBinHeap<int>>(std::move(source));
553 EXPECT_TRUE(source.is_empty());
555 EXPECT_EQ(source.getMin(), 10);
560 EXPECT_EQ(drain(*moved),
expected) << n <<
" values";
564TEST(DynBinHeapTest, MoveAssignmentOutlivesTheSource)
567 for (
int i : {20, 30})
571 for (
int i : {5, 3, 8, 1, 9, 2})
573 target = std::move(source);
575 EXPECT_EQ(drain(target), (std::vector<int>{1, 2, 3, 5, 8, 9}));
578TEST(DynBinHeapTest, SwapExchangesTheContents)
581 for (
int i : {4, 2, 6, 1})
583 for (
int i : {7, 3, 5})
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}));
597 EXPECT_EQ(drain(a), std::vector<int>{1});
598 EXPECT_EQ(drain(spare), (std::vector<int>{8, 9}));
609 template <
class Node>
612 return reinterpret_cast<Node *&
>(p->getU());
623 template <
class Heap>
624 std::string shape_errors(
const Heap & heap, std::vector<typename Heap::Node *> & at)
626 using Node =
typename Heap::Node;
627 std::ostringstream err;
628 const size_t n = heap.size();
630 at.assign(n + 1,
nullptr);
634 err <<
"an empty heap has a root; ";
639 err <<
"a heap of " << n <<
" nodes has no root; ";
642 at[0] = parent_of(
root);
644 for (
size_t i = 1; i <= n; ++i)
646 if (at[i] ==
nullptr)
648 err <<
"no node at the place " << i <<
"; ";
652 at[2*i] = at[i]->getL();
654 at[2*i + 1] = at[i]->getR();
656 if (at[0] ==
nullptr)
658 err <<
"the root has no header node; ";
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)
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 <<
"; ";
677 const size_t first = (n + 1) / 2;
678 for (
size_t i = first; i <= n; ++i)
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 <<
"; ";
691 template <
class Heap>
692 std::vector<typename Heap::Node *> places(
const Heap & heap)
694 std::vector<typename Heap::Node *> at;
695 const std::string err = shape_errors(heap, at);
698 ADD_FAILURE() << heap.size() <<
" nodes: " << err;
699 throw std::logic_error(
"the heap does not have its shape");
707 template <
class Heap>
714 std::vector<typename Heap::Node *> at;
715 if (shape_errors(heap, at).empty())
716 heap.remove_all_and_delete();
723TEST(BinHeapShape, InsertionsAndExtractionsKeepTheTreeAndItsList)
725 std::mt19937
rng(20261121);
726 std::uniform_int_distribution<int>
keys(0, 1000);
728 Freed_At_Exit<BinHeap<int>>
nodes{heap};
730 for (
int k = 0;
k < 600; ++
k)
745TEST(BinHeapShape, RemovalsAndUpdatesKeepTheTreeAndItsList)
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)
753 SCOPED_TRACE(testing::Message() <<
"n " << n <<
", place " << i <<
", op " << op);
755 Freed_At_Exit<BinHeap<int>>
nodes{heap};
756 for (
size_t k = 0;
k < n; ++
k)
758 const auto at = places(heap);
760 delete heap.
remove(at[i]);
763 at[i]->get_key() = op == 1 ? -1 : 2000;
767 EXPECT_EQ(heap.
top(), at[i]);
777TEST(BinHeapShape, TheLastNodeIsTheOneAtThePlaceN)
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)
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]);
793 EXPECT_EQ(calls == before, i == n or n == 2) <<
"n " << n <<
", place " << i;
798TEST(BinHeapShape, TheHeapOfTenNodesOfTheDescription)
801 Freed_At_Exit<BinHeap<int>>
nodes{heap};
802 for (
int k = 1;
k <= 10; ++
k)
804 const auto at = places(heap);
805 for (
int k = 1;
k <= 10; ++
k)
806 ASSERT_EQ(at[
k]->get_key(),
k);
809 for (
int k = 1;
k <= 4; ++
k)
811 EXPECT_EQ(at[
k]->getL(), at[2*
k]);
812 EXPECT_EQ(at[
k]->getR(), at[2*
k + 1]);
815 for (
int k = 5;
k <= 10; ++
k)
817 EXPECT_EQ(at[
k]->getR(), at[
k == 10 ? 5 :
k + 1]);
818 EXPECT_EQ(at[
k]->getL(), at[
k == 5 ? 10 :
k - 1]);
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]);
829 EXPECT_EQ(parent_of(p), at[5]);
830 EXPECT_EQ(at[5]->getR(), p);
831 EXPECT_EQ(p->
getL(), at[10]);
832 EXPECT_EQ(p->
getR(), at[6]);
837TEST(BinHeapShape, VerifyHeapLooksAtEveryNode)
839 for (
int n = 1; n <= 40; ++n)
842 Freed_At_Exit<BinHeap<int>>
nodes{heap};
843 for (
int k = 1;
k <= n; ++
k)
845 const auto at = places(heap);
847 for (
int i = 2; i <= n; ++i)
849 at[i]->get_key() = 10*(i / 2) - 1;
850 EXPECT_FALSE(heap.
verify_heap()) << n <<
" nodes, place " << i;
851 at[i]->get_key() = 10*i;
873 void PrintTo(
const Pri & x, std::ostream *os) { *os << x.pri <<
'#' << x.id; }
881 std::vector<std::pair<int, int>>
keys;
888 bool operator()(
const Pri & a,
const Pri & b)
const
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;
900 std::vector<Pri> layout(
const Counted_Heap & heap)
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());
915 std::vector<Pri> a = std::vector<Pri>(1);
921 for (; i > 1
and cmp(a[i], a[i / 2]); i /= 2)
922 std::swap(a[i], a[i / 2]);
931 if (c + 1 <= n
and cmp(a[c + 1], a[c]))
935 std::swap(a[i], a[c]);
941 void insert(
const Pri & x)
943 a.resize(std::max(a.size(), n + 2));
950 const Pri ret = a[1];
959 void remove(
const size_t i)
966 const Pri moved = a[n];
973 std::vector<Pri> layout()
const {
return {a.begin() + 1, a.begin() + 1 +
static_cast<long>(n)}; }
977 template <
class Node>
978 auto links_of(
Node *p)
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));
988TEST(BinHeapThrowingCompare, SameComparisonsAndPlacesAsBefore)
990 std::mt19937
rng(77);
991 std::uniform_int_distribution<int> values(0, 50);
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)
999 const unsigned op = old.n == 0 ? 0 :
rng() % 8;
1002 const Pri x{values(
rng),
k + 1};
1003 heap.insert(
new Counted_Heap::Node(x));
1008 std::unique_ptr<Counted_Heap::Node>
min(heap.getMin());
1009 ASSERT_EQ(
min->get_key(), old.getMin());
1014 const auto at = places(heap);
1015 const size_t i = 1 +
rng() % old.n;
1018 std::unique_ptr<Counted_Heap::Node>
out(heap.remove(at[i]));
1019 ASSERT_EQ(
out.get(), at[i]);
1025 const int pri = values(
rng);
1026 at[i]->get_key().pri = pri;
1033 ASSERT_EQ(calls.keys, old_calls.keys) <<
"operation " <<
k;
1035 old_calls.keys.clear();
1036 ASSERT_EQ(layout(heap), old.layout()) <<
"operation " <<
k;
1038 EXPECT_GT(updates, 1000u);
1039 EXPECT_GT(removals, 500u);
1040 EXPECT_GT(extractions, 500u);
1041 EXPECT_GT(heap.size(), 100u);
1050TEST(BinHeapThrowingCompare, EveryFailedCallLeavesTheHeapAsItWas)
1052 std::mt19937
rng(20261121);
1053 std::uniform_int_distribution<int> values(0, 30);
1055 for (
size_t n = 0; n <= 40; ++n)
1056 for (
int op = 0; op < 4; ++op)
1057 for (
int round = 0; round < (n < 2 ? 1 : 3); ++round)
1059 if (op != 0
and n == 0)
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;
1066 const int new_pri = values(
rng);
1067 for (
size_t at_call = 1; ; ++at_call)
1069 SCOPED_TRACE(testing::Message() <<
"n " << n <<
", op " << op <<
", place "
1070 << where <<
", call " << at_call);
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);
1078 at[where]->get_key().pri = new_pri;
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));
1084 calls.throw_at = calls.count + at_call;
1085 bool thrown =
false;
1086 Counted_Heap::Node *
out =
nullptr;
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]);
1097 catch (
const std::runtime_error &)
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;
1112 heap.insert(node.release());
1113 EXPECT_EQ(heap.size(), n + 1);
1115 EXPECT_TRUE(heap.verify_heap());
1121 EXPECT_TRUE(heap.verify_heap());
1130 EXPECT_GT(failed, 1000u);
1140 operator bool()
const {
return value; }
1146 Touchy_Bool operator()(
const int a,
const int b)
const noexcept {
return {a < b}; }
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)));
1176 operator bool() const & noexcept {
return value; }
1178 explicit operator bool() &&
1180 if (++*conversions == throw_at)
1181 throw std::runtime_error(
"conversion");
1194 bool operator()(
const int & a,
const int & b)
const noexcept {
return a < b; }
1196 Sly_Bool operator()(
int & a,
int & b)
const noexcept {
return {a < b, conversions, *throw_at}; }
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)));
1212TEST(BinHeapThrowingCompare, AConversionInAConditionThatThrowsIsUndone)
1215 for (
int op = 0; op < 4; ++op)
1216 for (
long at_conversion = 1; ; ++at_conversion)
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));
1230 at[7]->get_key() = 1;
1233 throw_at = at_conversion;
1234 bool thrown =
false;
1235 Sly_Heap::Node *
out =
nullptr;
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]);
1246 catch (
const std::runtime_error &)
1256 EXPECT_EQ(heap.top(), node.release());
1260 EXPECT_EQ(heap.top(), at[7]);
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;
1271 EXPECT_GT(failed, 8u);
1279TEST(DynBinHeapComparison, EveryFailedCallLeavesTheHeapAsItWas)
1282 std::mt19937
rng(20261121);
1283 std::uniform_int_distribution<int> values(0, 30);
1284 const long alive_at_start = Counted::alive;
1286 for (
size_t n = 0; n <= 24; ++n)
1287 for (
int op = 0; op < 5; ++op)
1289 if (op >= 2
and n == 0)
1291 std::vector<int>
keys;
1292 for (
size_t k = 0;
k < n; ++
k)
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)
1299 SCOPED_TRACE(testing::Message() <<
"n " << n <<
", op " << op <<
", place "
1300 << where <<
", call " << at_call);
1302 bool thrown =
false;
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));
1309 at[where]->get_key().value = new_key;
1310 const Counted item(key);
1311 const long alive = Counted::alive;
1313 heap.key_comp().less.fail_at = calls + at_call;
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());
1325 catch (
const std::runtime_error &)
1329 heap.key_comp().less.fail_at = 0;
1333 EXPECT_EQ(heap.size(), n);
1334 EXPECT_EQ(places(
static_cast<const Base &
>(heap)), at);
1335 EXPECT_EQ(Counted::alive, alive);
1339 places(
static_cast<const Base &
>(heap));
1340 EXPECT_TRUE(heap.verify_heap());
1343 EXPECT_EQ(Counted::alive, alive_at_start);
1348 EXPECT_GT(failed, 200u);
1359 bool operator()(
const int,
const int)
const {
return (*rng)() & 1; }
1367TEST(BinHeapShape, AComparisonThatContradictsItselfKeepsTheTree)
1369 std::mt19937
bits(99),
rng(3);
1371 Heap heap(Random_Less{&
bits});
1372 Freed_At_Exit<Heap>
nodes{heap};
1373 std::vector<std::unique_ptr<Heap::Node>>
out;
1374 size_t removals = 0, updates = 0;
1375 for (
int k = 0;
k < 20000; ++
k)
1378 if (op < 3
and heap.size() >= 150)
1380 const size_t size = heap.size();
1382 heap.insert(
new Heap::Node(
k));
1384 out.emplace_back(heap.getMin());
1387 std::vector<Heap::Node *> at;
1388 ASSERT_EQ(shape_errors(heap, at),
"");
1389 Heap::Node *p = at[1 +
rng() %
size];
1392 Heap::Node *removed = heap.remove(p);
1393 out.emplace_back(removed);
1394 ASSERT_EQ(removed, p);
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);
1408 EXPECT_GT(removals, 1000u);
1409 EXPECT_GT(updates, 1000u);
1415 struct Fragile_Default_Key
1417 static inline bool fail =
false;
1420 Fragile_Default_Key()
1423 throw std::runtime_error(
"default construction failed");
1426 Fragile_Default_Key(
int v) noexcept :
value(v) {}
1428 bool operator < (
const Fragile_Default_Key & other)
const noexcept
1430 return value < other.value;
1438TEST(BinHeapConstruction, ItsNoexceptFollowsTheDefaultConstructionOfTheKey)
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>>);
1448 Fragile_Default_Key::fail =
true;
1453 Fragile_Default_Key::fail =
false;
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);
1466 struct Mutable_Copy_Less
1468 static inline bool fail =
false;
1470 Mutable_Copy_Less() noexcept = default;
1471 Mutable_Copy_Less(const Mutable_Copy_Less &) noexcept = default;
1473 Mutable_Copy_Less(Mutable_Copy_Less &)
1476 throw std::runtime_error(
"the copy of the comparison");
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;
1483 bool operator () (const
int a, const
int b) const noexcept {
return a < b; }
1490TEST(BinHeapConstruction, ItsNoexceptFollowsTheCopyOfTheComparisonThatItTakes)
1492 using Less = Mutable_Copy_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>>);
1500 EXPECT_THROW({ Heap heap{
Less()}; }, std::runtime_error);
1504 EXPECT_TRUE(heap.is_empty());
1510 struct Default_Throws_Less
1512 static inline bool fail =
false;
1514 Default_Throws_Less()
1517 throw std::runtime_error(
"the default construction of the comparison");
1520 bool operator () (
const int a,
const int b)
const noexcept {
return a < b; }
1528TEST(BinHeapConstruction, BuiltByDefaultItLetsTheFailureOfTheComparisonThrough)
1530 using Less = Default_Throws_Less;
1534 static_assert(not std::is_nothrow_default_constructible_v<Heap>);
1535 static_assert(not std::is_nothrow_default_constructible_v<Heap_Vtl>);
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);
1548 EXPECT_TRUE(heap.is_empty());
bool operator<(const Time &l, const Time &r)
void PrintTo(const mpq_class &q, std::ostream *os)
WeightedDigraph::Node Node
size_t size_t int32_t value
size_t size_t int32_t * out
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.
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.
__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)
__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)
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
DynArray< Graph::Node * > nodes
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.
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.
static bool is_leaf(BinNode< std::string > *p) noexcept
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.
Heap of nodes with virtual destructor.
Node heap without virtual destructor.
Binary heap implementation using tree structure.
Dynamic binary heap with node-based storage.