Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
dynarrayheap.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
38#include <gtest/gtest.h>
39
40#include <tpl_dynArrayHeap.H>
41
42#include <algorithm>
43#include <cstdint>
44#include <ostream>
45#include <queue>
46#include <random>
47#include <stdexcept>
48#include <type_traits>
49#include <utility>
50#include <vector>
51
52using namespace Aleph;
53using namespace testing;
54
55namespace
56{
57 template <typename Heap>
58 std::vector<typename Heap::Item_Type> drain(Heap & h)
59 {
60 std::vector<typename Heap::Item_Type> out;
61 while (!h.is_empty())
62 out.push_back(h.getMin());
63 return out;
64 }
65
66 struct Greater
67 {
68 bool operator()(int a, int b) const noexcept { return a > b; }
69 };
70
71} // namespace
72
73TEST(DynArrayHeapBasics, EmptyAndSize)
74{
76 EXPECT_TRUE(heap.is_empty());
77 EXPECT_EQ(heap.size(), 0U);
78}
79
80TEST(DynArrayHeapBasics, TopAndGetMinThrowOnEmpty)
81{
83 EXPECT_THROW((void)heap.top(), std::underflow_error);
84 EXPECT_THROW((void)static_cast<const DynArrayHeap<int> &>(heap).top(), std::underflow_error);
85 EXPECT_THROW((void)heap.getMin(), std::underflow_error);
86}
87
88TEST(DynArrayHeapBasics, InsertAndExtractInOrder)
89{
91 heap.insert(5);
92 heap.insert(2);
93 heap.insert(4);
94 heap.insert(1);
95
96 EXPECT_EQ(heap.size(), 4U);
97 EXPECT_EQ(heap.top(), 1);
98
99 EXPECT_EQ(heap.getMin(), 1);
100 EXPECT_EQ(heap.get(), 2);
101 EXPECT_EQ(heap.getMax(), 4);
102 EXPECT_EQ(heap.getMin(), 5);
103 EXPECT_TRUE(heap.is_empty());
104}
105
106TEST(DynArrayHeapBasics, ReserveRejectsShrinkingBelowSize)
107{
109 heap.insert(3);
110 heap.insert(1);
111 EXPECT_THROW(heap.reserve(1), std::out_of_range);
112}
113
114TEST(DynArrayHeapBasics, InsertDirectBehavesLikeInsert)
115{
117 heap.reserve(16);
118 heap.insert(10);
119 heap.insert_direct(1);
120 heap.insert_direct(5);
121 EXPECT_EQ(heap.top(), 1);
122
123 auto drained = drain(heap);
124 EXPECT_TRUE(std::is_sorted(drained.begin(), drained.end()));
125}
126
127TEST(DynArrayHeapBasics, PutAndAppendAliasesWork)
128{
130 heap.put(3);
131 heap.append(2);
132 heap.put(1);
133 EXPECT_EQ(heap.top(), 1);
134}
135
136TEST(DynArrayHeapCompare, GreaterMakesMaxHeap)
137{
139 heap.insert(1);
140 heap.insert(10);
141 heap.insert(3);
142 EXPECT_EQ(heap.top(), 10);
143 EXPECT_EQ(heap.getMin(), 10);
144 EXPECT_EQ(heap.getMin(), 3);
145 EXPECT_EQ(heap.getMin(), 1);
146}
147
148TEST(DynArrayHeapIterator, TraverseVisitsAllElements)
149{
151 for (int i = 1; i <= 10; ++i)
152 heap.insert(i);
153
154 std::vector<int> visited;
155 struct Op
156 {
157 std::vector<int> *v;
158 bool operator()(int x)
159 {
160 v->push_back(x);
161 return true;
162 }
163 };
164
165 Op op{&visited};
166 EXPECT_TRUE(heap.traverse(op));
167 EXPECT_EQ(visited.size(), 10U);
168}
169
170TEST(DynArrayHeapIterator, TraverseStopsEarly)
171{
173 for (int i = 1; i <= 10; ++i)
174 heap.insert(i);
175
176 int count = 0;
177 struct Op
178 {
179 int *c;
180 bool operator()(int)
181 {
182 ++(*c);
183 return *c < 3;
184 }
185 };
186
187 Op op{&count};
188 EXPECT_FALSE(heap.traverse(op));
189 EXPECT_EQ(count, 3);
190}
191
192TEST(DynArrayHeapRandomized, MatchesStdPriorityQueueMinHeap)
193{
194 std::mt19937_64 rng(0xD15EA5EULL);
195 std::uniform_int_distribution<int> op_dist(0, 99);
196 std::uniform_int_distribution<int> val_dist(-10000, 10000);
197
199 std::priority_queue<int, std::vector<int>, std::greater<int>> ref;
200
201 constexpr int ops = 30000;
202 for (int i = 0; i < ops; ++i)
203 {
204 const int op = op_dist(rng);
205 if (op < 60)
206 {
207 const int v = val_dist(rng);
208 heap.insert(v);
209 ref.push(v);
210 }
211 else
212 {
213 if (ref.empty())
214 {
215 EXPECT_TRUE(heap.is_empty());
216 EXPECT_THROW((void)heap.getMin(), std::underflow_error);
217 }
218 else
219 {
220 ASSERT_FALSE(heap.is_empty());
221 EXPECT_EQ(heap.top(), ref.top());
222 EXPECT_EQ(heap.getMin(), ref.top());
223 ref.pop();
224 }
225 }
226
227 EXPECT_EQ(heap.size(), ref.size());
228 EXPECT_EQ(heap.is_empty(), ref.empty());
229 if (!ref.empty())
230 EXPECT_EQ(heap.top(), ref.top());
231 }
232
233 while (!ref.empty())
234 {
235 ASSERT_FALSE(heap.is_empty());
236 EXPECT_EQ(heap.top(), ref.top());
237 EXPECT_EQ(heap.getMin(), ref.top());
238 ref.pop();
239 }
240 EXPECT_TRUE(heap.is_empty());
241}
242
243namespace
244{
245 // A comparison with an overload for items that are not constant, which
246 // is noexcept, and another one for constant items, which is not
247 struct Two_Overloads
248 {
249 size_t *plain_calls;
250 size_t *const_calls;
251
252 bool operator()(int & a, int & b) noexcept
253 {
254 ++*plain_calls;
255 return a < b;
256 }
257
258 bool operator()(const int & a, const int & b) const
259 {
260 ++*const_calls;
261 return a < b;
262 }
263 };
264
265 // An item whose operator & does not give its address
266 struct No_Address
267 {
268 int v = 0;
269
270 No_Address() = default;
271 No_Address(const int x) noexcept : v(x) {}
272 No_Address *operator&() noexcept { return nullptr; }
273 const No_Address *operator&() const noexcept { return nullptr; }
274 bool operator<(const No_Address & o) const noexcept { return v < o.v; }
275 };
276
277 // An item whose move construction from a 9 throws while armed. Its move
278 // assignment does not throw
279 struct Hard_To_Build
280 {
281 static inline bool armed = false;
282
283 int v = 0;
284
285 Hard_To_Build() = default;
286 Hard_To_Build(const int x) noexcept : v(x) {}
287 Hard_To_Build(const Hard_To_Build &) = default;
288 Hard_To_Build & operator=(const Hard_To_Build &) = default;
289 Hard_To_Build(Hard_To_Build && o) : v(o.v)
290 {
291 if (armed and v == 9)
292 throw std::runtime_error("move construction");
293 }
294 Hard_To_Build & operator=(Hard_To_Build && o) noexcept
295 {
296 v = o.v;
297 return *this;
298 }
299 bool operator<(const Hard_To_Build & o) const noexcept { return v < o.v; }
300 };
301
302 // Compares the first of a pair, its priority, and not the second, its
303 // identity
304 struct First_Less
305 {
306 bool operator()(const std::pair<int, int> & a, const std::pair<int, int> & b) const noexcept
307 {
308 return a.first < b.first;
309 }
310 };
311
312 // The array of the heap, in its order, as traverse() and the iterator
313 // see it
314 template <class Heap>
315 std::vector<typename Heap::Item_Type> layout(const Heap & h)
316 {
317 using T = typename Heap::Item_Type;
318 std::vector<T> by_traverse;
319 h.traverse([&by_traverse](const T & x) { by_traverse.push_back(x); return true; });
320 std::vector<T> by_iterator;
321 for (typename Heap::Iterator it(h); it.has_curr(); it.next_ne())
322 by_iterator.push_back(it.get_curr());
323 EXPECT_EQ(by_traverse, by_iterator);
324 return by_traverse;
325 }
326}
327
328namespace
329{
330 // Every way of going through a heap gives its items, in the order of
331 // traverse(), and no more; and each member of the iterator takes the
332 // number of items as the end
333 template <class Heap>
334 void expect_iterated(Heap & h)
335 {
336 using T = typename Heap::Item_Type;
337 std::vector<T> items;
338 h.traverse([&items](const T & x) { items.push_back(x); return true; });
339 ASSERT_EQ(items.size(), h.size());
340 const long n = static_cast<long>(items.size());
341
342 typename Heap::Iterator it(h);
343 for (long k = 0; k < n; ++k, it.next())
344 {
345 ASSERT_TRUE(it.has_curr());
346 EXPECT_EQ(it.get_pos(), k);
347 EXPECT_EQ(it.get_curr(), items[k]);
348 EXPECT_EQ(it.get_curr_ne(), items[k]);
349 EXPECT_EQ(it.is_last(), k == n - 1);
350 }
351 EXPECT_FALSE(it.has_curr()); // at the end
352 EXPECT_FALSE(it.is_last());
353 EXPECT_EQ(it.get_pos(), n);
354 EXPECT_THROW((void) it.get_curr(), std::overflow_error);
355 EXPECT_THROW(it.next(), std::overflow_error);
356
357 for (long k = n - 1; k >= 0; --k)
358 {
359 it.prev();
360 ASSERT_TRUE(it.has_curr());
361 EXPECT_EQ(it.get_curr(), items[k]);
362 }
363 it.prev(); // before the first item
364 EXPECT_FALSE(it.has_curr());
365 EXPECT_THROW((void) it.get_curr(), std::underflow_error);
366 EXPECT_THROW(it.prev(), std::underflow_error);
367
368 it.reset_last();
369 EXPECT_EQ(it.has_curr(), n > 0);
370 EXPECT_EQ(it.is_last(), n > 0);
371 EXPECT_EQ(it.get_pos(), n - 1);
372 it.reset_first();
373 EXPECT_EQ(it.has_curr(), n > 0);
374 EXPECT_EQ(it.get_pos(), 0);
375 it.end();
376 EXPECT_FALSE(it.has_curr());
377 EXPECT_EQ(it.get_pos(), n);
378 for (long k = 0; k < n; ++k)
379 {
380 it.set_pos(k);
381 EXPECT_EQ(it.get_curr(), items[k]);
382 }
383
384 std::vector<T> seen;
385 for (const T & x : h)
386 seen.push_back(x);
387 EXPECT_EQ(seen, items);
388 seen.clear();
389 for (const T & x : std::as_const(h))
390 seen.push_back(x);
391 EXPECT_EQ(seen, items);
392 seen.clear();
393 for (auto i = h.get_it(); i.has_curr(); i.next_ne())
394 seen.push_back(i.get_curr());
395 EXPECT_EQ(seen, items);
396 seen.clear();
397 for (auto i = std::as_const(h).get_it(); i.has_curr(); i.next())
398 seen.push_back(i.get_curr());
399 EXPECT_EQ(seen, items);
400 }
401}
402
403// The iterator goes through the items of the heap, the entries 1 to size()
404// of its array, whatever the array has beyond them. It went to the end of
405// the array: after reserve(10) and three insert_direct() it visited 9
406// entries, and reset_first() left it on the entry 0, which holds no item
407TEST(DynArrayHeapIterator, GoesThroughTheItemsWhateverTheArrayHas)
408{
410 expect_iterated(heap); // never used
411
412 heap.reserve(10);
413 expect_iterated(heap); // entries and no item
414 for (const int x : {5, 1, 3})
415 heap.insert_direct(x);
416 EXPECT_EQ(layout(heap), (std::vector<int>{1, 5, 3}));
417 expect_iterated(heap); // more entries than items
418
419 for (int x = 20; x > 0; --x)
420 heap.insert(x); // beyond the reserved entries
421 expect_iterated(heap);
422
423 while (heap.size() > 4)
424 (void) heap.getMin();
425 expect_iterated(heap);
426
427 while (not heap.is_empty())
428 (void) heap.getMin();
429 expect_iterated(heap); // emptied: the array keeps its entry 0
430}
431
432// An iterator built without a heap has no item
433TEST(DynArrayHeapIterator, WithoutAHeapItHasNoItem)
434{
436 EXPECT_FALSE(it.has_curr());
437 EXPECT_FALSE(it.is_last());
438 EXPECT_THROW((void) it.get_curr(), std::overflow_error);
439 EXPECT_THROW(it.next(), std::overflow_error);
440 it.reset_last();
441 EXPECT_FALSE(it.has_curr());
442 it.end();
443 EXPECT_FALSE(it.has_curr());
444}
445
446// An insertion by move makes the place of the key before it moves it. If
447// that move throws, the heap is as it was for the iterator too, which saw
448// the new entry of the array as one item more
449TEST(DynArrayHeapIterator, DoesNotSeeThePlaceOfAKeyThatWasNotMoved)
450{
452 for (const int x : {1, 5, 3})
453 heap.insert(Hard_To_Build(x));
454
455 Hard_To_Build key(9);
456 Hard_To_Build::armed = true;
457 EXPECT_THROW(heap.insert(std::move(key)), std::runtime_error);
458 Hard_To_Build::armed = false;
459 EXPECT_EQ(key.v, 9);
460 EXPECT_EQ(heap.size(), 3U);
461 std::vector<int> seen;
462 for (DynArrayHeap<Hard_To_Build>::Iterator it(heap); it.has_curr(); it.next_ne())
463 seen.push_back(it.get_curr().v);
464 EXPECT_EQ(seen, (std::vector<int>{1, 5, 3}));
465}
466
467// The noexcept specification of the sifts looks at the comparison of two
468// items that are not constant. The heap must call that overload alone, as
469// 7.7.4 did: another one that threw would end the program
470TEST(DynArrayHeapCompare, ComparesItemsThatAreNotConstant)
471{
472 static_assert(not NothrowPredicateWith<Two_Overloads &, int &, const int &>);
473 static_assert(noexcept(sift_up(std::declval<DynArray<int> &>(), size_t(), size_t(),
474 std::declval<Two_Overloads &>())));
475 static_assert(noexcept(sift_down(std::declval<DynArray<int> &>(), size_t(), size_t(),
476 std::declval<Two_Overloads &>())));
477
478 size_t plain_calls = 0, const_calls = 0;
479 DynArrayHeap<int, Two_Overloads> heap(Two_Overloads{&plain_calls, &const_calls});
480 heap.reserve(64);
481 std::vector<int> expected;
482 for (int k = 0; k < 40; ++k)
483 {
484 const int key = (k * 7) % 11;
485 switch (k % 4)
486 {
487 case 0: heap.insert(key); break;
488 case 1: heap.insert(int(key)); break;
489 case 2: heap.insert_direct(key); break;
490 default: heap.insert_direct(int(key));
491 }
492 expected.push_back(key);
493 }
494 std::sort(expected.begin(), expected.end());
495 EXPECT_EQ(drain(heap), expected);
496 EXPECT_GT(plain_calls, 0U);
497 EXPECT_EQ(const_calls, 0U);
498}
499
500// The sifts keep the addresses of the items that they pass: the real ones,
501// whatever the operator & of the items gives
502TEST(DynArrayHeapBasics, ItemsWithTheirOwnOperatorAmpersand)
503{
505 for (int k = 0; k < 50; ++k)
506 if (const No_Address key((k * 37) % 50); k % 2 == 0) // each of 0 to 49, once
507 heap.insert(key);
508 else
509 heap.insert(No_Address(key));
510 for (int k = 0; k < 50; ++k)
511 ASSERT_EQ(heap.getMin().v, k);
512 EXPECT_TRUE(heap.is_empty());
513}
514
515// getMin() takes the last item to its place with assignments alone, as
516// 7.7.4 did. A temporary built from it could throw with the minimum
517// already out of the heap, which lost it
518TEST(DynArrayHeapBasics, GetMinBuildsNoTemporaryOfTheLastItem)
519{
521 for (const int x : {1, 5, 3, 9}) // the array is 1, 5, 3, 9
522 heap.insert(Hard_To_Build(x));
523
524 int min = 0;
525 Hard_To_Build::armed = true;
526 EXPECT_NO_THROW(min = heap.getMin().v);
527 Hard_To_Build::armed = false;
528 EXPECT_EQ(min, 1);
529 EXPECT_EQ(heap.size(), 3U);
530 for (const int x : {3, 5, 9})
531 EXPECT_EQ(heap.getMin().v, x);
532}
533
534// The key may be an item of the heap itself when it is copied, or when a
535// move leaves it as it was, even on the way of the new item, among others
536// of its priority: the heap must end as with a key that is not in it
537TEST(DynArrayHeapBasics, AKeyThatIsAnItemOfTheHeap)
538{
539 using Pair = std::pair<int, int>; // a priority and an identity
541 for (int op = 0; op < 4; ++op) // insert and insert_direct, of a copy and of a move
542 for (int n = 1; n <= 12; ++n)
543 for (int place = 1; place <= n; ++place) // that of the key in the array
544 {
545 SCOPED_TRACE(testing::Message() << "op " << op << ", n " << n << ", place " << place);
546 Heap heap, other;
547 heap.reserve(n + 2);
548 other.reserve(n + 2);
549 for (int k = 1; k <= n; ++k)
550 {
551 heap.insert(Pair(k % 3, k));
552 other.insert(Pair(k % 3, k));
553 }
554 Pair *key = nullptr;
555 int at = 0;
556 heap.traverse([&key, &at, place](Pair & x)
557 {
558 if (++at == place)
559 key = &x;
560 return true;
561 });
562 ASSERT_NE(key, nullptr);
563 const Pair copy = *key;
564 switch (op)
565 {
566 case 0: heap.insert(*key); other.insert(copy); break;
567 case 1: heap.insert(std::move(*key)); other.insert(Pair(copy)); break;
568 case 2: heap.insert_direct(*key); other.insert_direct(copy); break;
569 default: heap.insert_direct(std::move(*key)); other.insert_direct(Pair(copy));
570 }
571 EXPECT_EQ(layout(heap), layout(other));
572 }
573}
574
575namespace
576{
577 // An item with a priority, which the comparisons look at, and an
578 // identity, which they do not: it tells apart the items of a priority.
579 // A move takes the identity of its source away
580 struct Item
581 {
582 static constexpr int gone = -1;
583
584 int pri = 0;
585 int id = 0;
586
587 Item() = default;
588 Item(const int p, const int i) noexcept : pri(p), id(i) {}
589 Item(const Item &) = default;
590 Item & operator=(const Item &) = default;
591 Item(Item && o) noexcept : pri(o.pri), id(std::exchange(o.id, gone)) {}
592 Item & operator=(Item && o) noexcept
593 {
594 pri = o.pri;
595 id = std::exchange(o.id, gone);
596 return *this;
597 }
598 bool operator==(const Item &) const = default;
599 };
600
601 void PrintTo(const Item & x, std::ostream *os) { *os << x.pri << '#' << x.id; }
602
603 // The calls of a Counted_Less: how many, the one that throws (0: none),
604 // and the identities of the two items of each one, in order
605 struct Calls
606 {
607 size_t count = 0;
608 size_t throw_at = 0;
609 std::vector<std::pair<int, int>> items;
610 };
611
612 template <class X>
613 struct Counted_Less_Of
614 {
615 Calls *calls;
616
617 bool operator()(const X & a, const X & b) const
618 {
619 if (++calls->count == calls->throw_at)
620 throw std::runtime_error("comparison");
621 calls->items.emplace_back(a.id, b.id);
622 return a.pri < b.pri;
623 }
624 };
625
626 using Counted_Less = Counted_Less_Of<Item>;
627 using Counted_Heap = DynArrayHeap<Item, Counted_Less>;
628
629 // An item whose move leaves in its source the priority `left`, which
630 // each test chooses, and no identity
631 struct Husk
632 {
633 static inline int left = 0;
634
635 int pri = 0;
636 int id = 0;
637
638 Husk() = default;
639 Husk(const int p, const int i) noexcept : pri(p), id(i) {}
640 Husk(const Husk &) = default;
641 Husk & operator=(const Husk &) = default;
642 Husk(Husk && o) noexcept : pri(std::exchange(o.pri, left)), id(std::exchange(o.id, 0)) {}
643 Husk & operator=(Husk && o) noexcept
644 {
645 pri = std::exchange(o.pri, left);
646 id = std::exchange(o.id, 0);
647 return *this;
648 }
649 bool operator==(const Husk &) const = default;
650 };
651
652 // The key of an insertion by move takes its item back by a move
653 // assignment when the comparison throws: the heap promises to be as it
654 // was only if that assignment does not throw, as with these items
655 static_assert(std::is_nothrow_move_assignable_v<Item>);
656 static_assert(std::is_nothrow_move_assignable_v<Husk>);
657
658 void PrintTo(const Husk & x, std::ostream *os) { *os << x.pri << "#" << x.id; }
659
660 // The sifts of 7.7.4, which exchanged an item with its parent or child
661 // at each level, as a reference for the order of the new ones
662 template <class X>
663 size_t old_sift_up(DynArray<X> & a, size_t l, size_t r, Counted_Less_Of<X> & cmp)
664 {
665 for (size_t p, i = r; i > l; i = p)
666 {
667 p = i / 2;
668 if (cmp(a.access(p), a.access(i)))
669 return i;
670 std::swap(a.access(p), a.access(i));
671 }
672 return l;
673 }
674
675 template <class X>
676 void old_sift_down(DynArray<X> & a, size_t l, size_t r, Counted_Less_Of<X> & cmp)
677 {
678 for (size_t i = l; ;)
679 {
680 size_t c = 2 * i;
681 if (c > r)
682 return;
683 if (c + 1 <= r and cmp(a.access(c + 1), a.access(c)))
684 ++c;
685 if (cmp(a.access(i), a.access(c)))
686 return;
687 std::swap(a.access(c), a.access(i));
688 i = c;
689 }
690 }
691}
692
693// Each failed comparison of an insertion or an extraction leaves the heap
694// as it was: its items in the same places, none moved from, and its size,
695// with the key of an insertion by move untouched. 7.7.4 left the item
696// counted, or the minimum lost, and the heap out of order
697TEST(DynArrayHeapThrowingCompare, EveryFailedCallLeavesTheHeapAsItWas)
698{
699 std::mt19937 rng(20261120);
700 std::uniform_int_distribution<int> values(0, 30);
701 for (size_t n = 0; n <= 40; ++n)
702 for (int op = 0; op < 5; ++op) // insert and insert_direct, of a copy and of a move; getMin
703 {
704 if (op == 4 and n == 0)
705 continue;
706 std::vector<Item> items;
707 for (size_t k = 0; k < n; ++k)
708 items.emplace_back(values(rng), static_cast<int>(k + 1));
709 const Item key(values(rng), static_cast<int>(n + 1));
710 for (size_t at = 1; ; ++at)
711 {
712 SCOPED_TRACE(testing::Message() << "n " << n << ", op " << op << ", call " << at);
713 Calls calls;
714 Counted_Heap heap(Counted_Less{&calls});
715 const bool reserved = op == 2 or op == 3; // insert_direct() writes in reserved entries
716 if (reserved)
717 heap.reserve(n + 2);
718 for (const Item & x : items)
719 heap.insert(x);
720 const std::vector<Item> before = layout(heap);
721 calls.throw_at = calls.count + at;
722 bool thrown = false;
723 Item moved = key;
724 try
725 {
726 switch (op)
727 {
728 case 0: heap.insert(key); break;
729 case 1: heap.insert(std::move(moved)); break;
730 case 2: heap.insert_direct(key); break;
731 case 3: heap.insert_direct(std::move(moved)); break;
732 default: (void) heap.getMin();
733 }
734 }
735 catch (const std::runtime_error &)
736 {
737 thrown = true;
738 }
739 calls.throw_at = 0;
740 if (not thrown)
741 break;
742 EXPECT_EQ(heap.size(), n);
743 EXPECT_EQ(layout(heap), before);
744 EXPECT_EQ(moved, key);
745 }
746 }
747}
748
749// The new sifts compare the same items in the same order as the old ones,
750// and leave every item in the same place, those of a same priority too
751TEST(DynArrayHeapThrowingCompare, SameComparisonsAndPlacesAsTheOldSifts)
752{
753 std::mt19937 rng(77);
754 std::uniform_int_distribution<int> values(0, 50); // many items of a same priority
755 Calls calls, old_calls;
756 Counted_Heap heap(Counted_Less{&calls});
757 Counted_Less old_cmp{&old_calls};
758 DynArray<Item> old;
759 size_t old_n = 0;
760 for (int k = 0; k < 5000; ++k)
761 {
762 if (old_n == 0 or rng() % 3 != 0)
763 {
764 const Item x(values(rng), k + 1);
765 if (k % 2 == 0)
766 heap.insert(x);
767 else
768 heap.insert(Item(x));
769 old.touch(++old_n) = x;
770 old_sift_up(old, 1, old_n, old_cmp);
771 }
772 else
773 {
774 const Item min = heap.getMin();
775 ASSERT_EQ(min, old.access(1));
776 old.access(1) = old.access(old_n);
777 --old_n;
778 old_sift_down(old, 1, old_n, old_cmp);
779 }
780 ASSERT_EQ(calls.items, old_calls.items) << "operation " << k;
781 calls.items.clear();
782 old_calls.items.clear();
783 std::vector<Item> old_layout;
784 for (size_t i = 1; i <= old_n; ++i)
785 old_layout.push_back(old.access(i));
786 ASSERT_EQ(layout(heap), old_layout) << "operation " << k;
787 }
788}
789
790namespace
791{
792 using Husk_Less = Counted_Less_Of<Husk>;
793 using Husk_Heap = DynArrayHeap<Husk, Husk_Less>;
794
795 // The item at a place of the array of a heap, from 1
796 Husk & item_at(Husk_Heap & heap, const int place)
797 {
798 Husk *found = nullptr;
799 int at = 0;
800 heap.traverse([&found, &at, place](Husk & x)
801 {
802 if (++at == place)
803 found = &x;
804 return true;
805 });
806 return *found;
807 }
808}
809
810// The key of an insertion by move may be an item of the heap itself, which
811// the move changes where it is. The key is moved before the comparisons, as
812// in 7.7.4, so that they see that item as it is left: the same comparisons
813// and the same places as then, whatever the place of the item, on the way
814// of the new one or not, and whatever the move leaves in it, before the
815// other items, among them or after them
816TEST(DynArrayHeapBasics, AKeyThatItsMoveChangesInTheHeap)
817{
818 for (const int left : {-1, 1, 99}) // the priorities are 0, 1 and 2
819 for (const bool direct : {false, true})
820 for (int n = 1; n <= 12; ++n)
821 for (int place = 1; place <= n; ++place)
822 {
823 SCOPED_TRACE(testing::Message() << "left " << left << ", direct " << direct
824 << ", n " << n << ", place " << place);
825 Husk::left = left;
826 Calls calls, old_calls;
827 Husk_Heap heap(Husk_Less{&calls});
828 heap.reserve(n + 2);
829 Husk_Less old_cmp{&old_calls};
830 DynArray<Husk> old;
831 std::vector<Husk> old_layout;
832 for (int k = 1; k <= n; ++k)
833 {
834 const Husk x(k % 3, k);
835 heap.insert(x);
836 old.touch(k) = x;
837 old_sift_up(old, 1, k, old_cmp);
838 }
839 for (int i = 1; i <= n; ++i)
840 old_layout.push_back(old.access(i));
841 ASSERT_EQ(layout(heap), old_layout);
842
843 Husk & key = item_at(heap, place);
844 if (direct)
845 heap.insert_direct(std::move(key));
846 else
847 heap.insert(std::move(key));
848 old.touch(n + 1) = std::move(old.access(place));
849 old_sift_up(old, 1, n + 1, old_cmp);
850
851 EXPECT_EQ(calls.items, old_calls.items);
852 old_layout.clear();
853 for (int i = 1; i <= n + 1; ++i)
854 old_layout.push_back(old.access(i));
855 EXPECT_EQ(layout(heap), old_layout);
856 }
857}
858
859// If the comparison throws in that insertion, the key, one of the items of
860// the heap, takes back what was moved from it, and the heap is as it was
861TEST(DynArrayHeapThrowingCompare, AKeyThatItsMoveChangesStaysInTheHeap)
862{
863 for (const int left : {-1, 99})
864 for (const bool direct : {false, true})
865 for (int n = 1; n <= 9; ++n)
866 for (int place = 1; place <= n; ++place)
867 for (size_t at = 1; ; ++at)
868 {
869 SCOPED_TRACE(testing::Message() << "left " << left << ", direct " << direct << ", n " << n
870 << ", place " << place << ", call " << at);
871 Husk::left = left;
872 Calls calls;
873 Husk_Heap heap(Husk_Less{&calls});
874 heap.reserve(n + 2);
875 for (int k = 1; k <= n; ++k)
876 heap.insert(Husk(k % 3, k));
877 const std::vector<Husk> before = layout(heap);
878 Husk & key = item_at(heap, place);
879 calls.throw_at = calls.count + at;
880 bool thrown = false;
881 try
882 {
883 if (direct)
884 heap.insert_direct(std::move(key));
885 else
886 heap.insert(std::move(key));
887 }
888 catch (const std::runtime_error &)
889 {
890 thrown = true;
891 }
892 calls.throw_at = 0;
893 if (not thrown)
894 break;
895 EXPECT_EQ(heap.size(), static_cast<size_t>(n));
896 EXPECT_EQ(layout(heap), before);
897 }
898}
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
void PrintTo(const mpq_class &q, std::ostream *os)
#define X(p)
Definition btreepic.C:374
long double h
Definition btreepic.C:154
size_t size_t int32_t * out
Definition ca-c-api.h:120
Iterator on the items of the heap, in the order of its array, which is not the sorted one.
const T & get_curr() const
The current item, read-only: the heap order must not be broken.
bool is_last() const noexcept
Return true if the iterator is on the last item.
bool has_curr() const noexcept
Return true if the iterator is on an item.
void reset_last() noexcept
Put the iterator on the last item.
void next()
Move one position forward, from the last item to the end too.
void end() noexcept
Put the iterator at the end, after the last item.
Dynamic heap (priority queue) backed by DynArray.
void reserve(size_t n)
Ensure the underlying array has capacity for at least n elements.
constexpr bool is_empty() const noexcept
Return true if the heap is empty.
T getMin()
Remove and return the top element.
T & put(const T &key)
Alias for insert().
T get()
See getMin().
T & append(const T &key)
Alias for insert().
T & insert(const T &key)
Insert a copy of key into the heap.
T getMax()
See getMin(); useful if priority order is inverted.
T & top()
Return the element with highest priority (the heap top).
T & insert_direct(const T &key)
Insert by directly indexing into the backing array.
bool traverse(Operation &operation) noexcept(Aleph::NothrowPredicateWith< Operation &, T & >)
Traverse all elements in the heap.
constexpr size_t size() const noexcept
Return the number of elements.
T & touch(const size_t i)
Touch the entry i.
T & access(const size_t i) noexcept
Fast access without checking allocation and bound_min_clock checking.
Minimal std::expected-style result type for C++20.
#define TEST(name)
static mt19937 rng
__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< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_binary_and > > operator&(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4112
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
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.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
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
STL namespace.
static int * k
Gsl_Compatible_Rng r
Array-based dynamic binary heap.
DynList< int > l