Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
interval_tree_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
37# include <gtest/gtest.h>
38# include <tpl_interval_tree.H>
39# include <random>
40# include <algorithm>
41# include <memory>
42# include <string>
43# include <vector>
44# include <type_traits>
45
46using namespace Aleph;
47using namespace testing;
48
49static_assert(not std::is_copy_constructible_v<Interval_Tree<int>>);
50static_assert(not std::is_copy_assignable_v<Interval_Tree<int>>);
51static_assert(not std::is_move_constructible_v<Interval_Tree<int>>);
52static_assert(not std::is_move_assignable_v<Interval_Tree<int>>);
53
55{
56 int *counter;
57
58 explicit CountingLess(int *c = nullptr) noexcept : counter(c) {}
59
60 bool operator ()(const int &a, const int &b) const noexcept
61 {
62 if (counter != nullptr)
63 ++*counter;
64 return a < b;
65 }
66};
67
68// ─────────────────────────────────────────────────────────────────
69// Interval<T> value type tests
70// ─────────────────────────────────────────────────────────────────
71
72class IntervalTypeTest : public Test {};
73
75{
76 Interval<int> a(1, 5);
77 EXPECT_EQ(a.low, 1);
78 EXPECT_EQ(a.high, 5);
79
80 auto pt = Interval<int>::point(3);
81 EXPECT_EQ(pt.low, 3);
82 EXPECT_EQ(pt.high, 3);
83}
84
86{
87 Interval<int> valid(1, 5);
88 EXPECT_TRUE(valid.is_valid());
89
90 Interval<int> point(3, 3);
91 EXPECT_TRUE(point.is_valid());
92
93 Interval<int> invalid(5, 1);
94 EXPECT_FALSE(invalid.is_valid());
95}
96
97TEST_F(IntervalTypeTest, OverlapDetection)
98{
99 Interval<int> a(1, 5);
100 Interval<int> b(3, 7);
101 Interval<int> c(6, 10);
102 Interval<int> d(1, 5);
103 Interval<int> e(10, 15);
104
105 EXPECT_TRUE(a.overlaps(b)); // partial overlap
106 EXPECT_FALSE(a.overlaps(c)); // a.high=5 < c.low=6
107 EXPECT_TRUE(a.overlaps(d)); // identical
108 EXPECT_FALSE(a.overlaps(e)); // disjoint
109
110 // touching endpoints count as overlap for closed intervals
111 Interval<int> f(5, 10);
112 EXPECT_TRUE(a.overlaps(f));
113}
114
116{
117 Interval<int> a(1, 5);
118 EXPECT_TRUE(a.contains(1));
119 EXPECT_TRUE(a.contains(3));
120 EXPECT_TRUE(a.contains(5));
121 EXPECT_FALSE(a.contains(0));
122 EXPECT_FALSE(a.contains(6));
123}
124
125TEST_F(IntervalTypeTest, PointIntervals)
126{
127 auto pt = Interval<int>::point(5);
128 EXPECT_TRUE(pt.is_valid());
129 EXPECT_TRUE(pt.contains(5));
130 EXPECT_FALSE(pt.contains(4));
131 EXPECT_FALSE(pt.contains(6));
132
133 Interval<int> a(3, 7);
134 EXPECT_TRUE(pt.overlaps(a));
135
136 Interval<int> b(6, 10);
137 EXPECT_FALSE(pt.overlaps(b));
138}
139
141{
143 Interval<int> a(1, 5);
144 Interval<int> b(2, 3);
145 Interval<int> c(1, 7);
146
147 EXPECT_TRUE(cmp(a, b)); // 1 < 2
148 EXPECT_FALSE(cmp(b, a));
149 EXPECT_TRUE(cmp(a, c)); // same low, 5 < 7
150 EXPECT_FALSE(cmp(c, a));
151 EXPECT_FALSE(cmp(a, a)); // irreflexive
152}
153
154// ─────────────────────────────────────────────────────────────────
155// Low-level Interval_Tree tests
156// ─────────────────────────────────────────────────────────────────
157
159{
160protected:
164
166
167 void SetUp() override { tree.set_seed(42); }
168
169 void TearDown() override
170 {
172 }
173
174 Node * make_node(int lo, int hi)
175 {
176 return new Node(Key(lo, hi));
177 }
178};
179
181{
182 EXPECT_TRUE(tree.is_empty());
183 EXPECT_EQ(tree.size(), 0u);
184 EXPECT_TRUE(tree.verify());
185 EXPECT_EQ(tree.search(Key(0, 0)), nullptr);
186 EXPECT_EQ(tree.overlap_search(Key(0, 10)), nullptr);
187}
188
190{
191 auto * p = make_node(1, 5);
192 EXPECT_NE(tree.insert(p), nullptr);
193 EXPECT_EQ(tree.size(), 1u);
194 EXPECT_TRUE(tree.verify());
195 EXPECT_NE(tree.search(Key(1, 5)), nullptr);
196}
197
199{
200 tree.insert(make_node(15, 20));
201 tree.insert(make_node(10, 30));
202 tree.insert(make_node(17, 19));
203 tree.insert(make_node(5, 20));
204 tree.insert(make_node(12, 15));
205 tree.insert(make_node(30, 40));
206
207 EXPECT_EQ(tree.size(), 6u);
208 EXPECT_TRUE(tree.verify());
209}
210
212{
213 auto * p1 = make_node(1, 5);
214 auto * p2 = make_node(1, 5);
215 EXPECT_NE(tree.insert(p1), nullptr);
216 EXPECT_EQ(tree.insert(p2), nullptr);
217 EXPECT_EQ(tree.size(), 1u);
218 EXPECT_TRUE(tree.verify());
219 delete p2;
220}
221
223{
224 auto * p1 = make_node(1, 5);
225 auto * p2 = make_node(1, 5);
226 tree.insert_dup(p1);
227 tree.insert_dup(p2);
228 EXPECT_EQ(tree.size(), 2u);
229 EXPECT_TRUE(tree.verify());
230}
231
233{
234 tree.insert(make_node(1, 5));
235 tree.insert(make_node(10, 20));
236 tree.insert(make_node(3, 7));
237
238 EXPECT_EQ(tree.size(), 3u);
239 EXPECT_TRUE(tree.verify());
240
241 auto * removed = tree.remove(Key(10, 20));
242 EXPECT_NE(removed, nullptr);
243 EXPECT_EQ(tree.size(), 2u);
244 EXPECT_TRUE(tree.verify());
245 delete removed;
246}
247
248TEST_F(IntervalTreeRawTest, RemoveNonexistent)
249{
250 tree.insert(make_node(1, 5));
251 auto * removed = tree.remove(Key(99, 100));
252 EXPECT_EQ(removed, nullptr);
253 EXPECT_EQ(tree.size(), 1u);
254 EXPECT_TRUE(tree.verify());
255}
256
257TEST_F(IntervalTreeRawTest, OverlapSearchFound)
258{
259 tree.insert(make_node(15, 20));
260 tree.insert(make_node(10, 30));
261 tree.insert(make_node(17, 19));
262 tree.insert(make_node(5, 20));
263 tree.insert(make_node(12, 15));
264 tree.insert(make_node(30, 40));
265
266 auto * result = tree.overlap_search(Key(14, 16));
267 ASSERT_NE(result, nullptr);
268 EXPECT_TRUE(KEY(result).overlaps(Key(14, 16)));
269}
270
271TEST_F(IntervalTreeRawTest, OverlapSearchNotFound)
272{
273 tree.insert(make_node(1, 5));
274 tree.insert(make_node(10, 15));
275 tree.insert(make_node(20, 25));
276
277 auto * result = tree.overlap_search(Key(6, 9));
278 EXPECT_EQ(result, nullptr);
279}
280
282{
283 tree.insert(make_node(1, 5));
284 tree.insert(make_node(3, 8));
285 tree.insert(make_node(7, 10));
286 tree.insert(make_node(15, 20));
287
288 DynList<Key> results;
289 tree.all_overlaps(Key(4, 7), [&results](const Key & iv) {
290 results.append(iv);
291 });
292
293 // [1,5] overlaps [4,7]: yes (5>=4 and 1<=7)
294 // [3,8] overlaps [4,7]: yes
295 // [7,10] overlaps [4,7]: yes (7<=7)
296 // [15,20] overlaps [4,7]: no
297 EXPECT_EQ(results.size(), 3u);
298}
299
301{
302 tree.insert(make_node(1, 5));
303 tree.insert(make_node(3, 8));
304 tree.insert(make_node(7, 10));
305 tree.insert(make_node(15, 20));
306
307 auto results = tree.find_stab(4);
308 // [1,5] contains 4: yes
309 // [3,8] contains 4: yes
310 // [7,10] contains 4: no
311 // [15,20] contains 4: no
312 EXPECT_EQ(results.size(), 2u);
313}
314
315TEST_F(IntervalTreeRawTest, PointIntervalQueries)
316{
317 tree.insert(make_node(5, 5));
318 tree.insert(make_node(3, 7));
319
320 auto * result = tree.overlap_search(Key(5, 5));
321 ASSERT_NE(result, nullptr);
322 EXPECT_TRUE(KEY(result).overlaps(Key(5, 5)));
323}
324
325TEST_F(IntervalTreeRawTest, MaxEndpointInvariant)
326{
327 tree.insert(make_node(1, 10));
328 EXPECT_TRUE(tree.verify());
329
330 tree.insert(make_node(5, 20));
331 EXPECT_TRUE(tree.verify());
332
333 tree.insert(make_node(15, 25));
334 EXPECT_TRUE(tree.verify());
335
336 auto * r1 = tree.remove(Key(5, 20));
337 EXPECT_TRUE(tree.verify());
338 delete r1;
339
340 auto * r2 = tree.remove(Key(1, 10));
341 EXPECT_TRUE(tree.verify());
342 delete r2;
343}
344
345TEST_F(IntervalTreeRawTest, IteratorOrdering)
346{
347 tree.insert(make_node(10, 20));
348 tree.insert(make_node(5, 15));
349 tree.insert(make_node(1, 3));
350 tree.insert(make_node(20, 30));
351
353 Key prev_key;
354 bool first = true;
355 for (IvTree::Iterator it(tree); it.has_curr(); it.next())
356 {
357 Key k = KEY(it.get_curr());
358 if (not first)
359 EXPECT_TRUE(cmp(prev_key, k) or (not cmp(k, prev_key) and not cmp(prev_key, k)));
360 prev_key = k;
361 first = false;
362 }
363}
364
365TEST_F(IntervalTreeRawTest, CLRSTextbookExample)
366{
367 // CLRS 3rd ed, Figure 14.4 intervals
368 tree.insert(make_node(0, 3));
369 tree.insert(make_node(5, 8));
370 tree.insert(make_node(6, 10));
371 tree.insert(make_node(8, 9));
372 tree.insert(make_node(15, 23));
373 tree.insert(make_node(16, 21));
374 tree.insert(make_node(17, 19));
375 tree.insert(make_node(19, 20));
376 tree.insert(make_node(25, 30));
377 tree.insert(make_node(26, 26));
378
379 EXPECT_EQ(tree.size(), 10u);
380 EXPECT_TRUE(tree.verify());
381
382 // Query [22, 25]: should overlap [15,23] and [25,30]
383 auto overlaps = tree.find_all_overlaps(Key(22, 25));
384 EXPECT_GE(overlaps.size(), 2u);
385 overlaps.for_each([](const Key & iv) {
386 EXPECT_TRUE(iv.overlaps(Key(22, 25)));
387 });
388
389 // Query [11, 14]: should not overlap anything
390 auto * result = tree.overlap_search(Key(11, 14));
391 EXPECT_EQ(result, nullptr);
392}
393
394TEST_F(IntervalTreeRawTest, LargeRandomizedVerification)
395{
396 std::mt19937 gen(12345);
397 std::uniform_int_distribution<int> dist(0, 10000);
398
399 const size_t N = 5000;
400 std::vector<Key> intervals;
401 intervals.reserve(N);
402
403 for (size_t i = 0; i < N; ++i)
404 {
405 int a = dist(gen), b = dist(gen);
406 if (a > b) std::swap(a, b);
407 tree.insert_dup(make_node(a, b));
408 intervals.push_back(Key(a, b));
409 }
410
411 EXPECT_EQ(tree.size(), N);
412 EXPECT_TRUE(tree.verify());
413
414 // Verify overlap_search against brute force for a sample of queries
415 for (int q = 0; q < 100; ++q)
416 {
417 int a = dist(gen), b = dist(gen);
418 if (a > b) std::swap(a, b);
419 Key query(a, b);
420
421 auto * found = tree.overlap_search(query);
422 bool brute_force_found = false;
423 for (const auto & iv : intervals)
424 if (iv.overlaps(query))
425 {
426 brute_force_found = true;
427 break;
428 }
429
430 if (brute_force_found)
431 EXPECT_NE(found, nullptr) << "BF found overlap for ["
432 << a << "," << b << "] but tree didn't";
433 else
434 EXPECT_EQ(found, nullptr) << "BF found no overlap for ["
435 << a << "," << b << "] but tree did";
436 }
437}
438
439// ─────────────────────────────────────────────────────────────────
440// DynIntervalTree tests
441// ─────────────────────────────────────────────────────────────────
442
444{
445protected:
448};
449
451{
452 EXPECT_TRUE(tree.is_empty());
453 EXPECT_EQ(tree.size(), 0u);
454 EXPECT_TRUE(tree.empty());
455 EXPECT_TRUE(tree.verify());
456}
457
459{
460 tree.insert(Key(1, 5));
461 tree.insert(Key(10, 20));
462 EXPECT_EQ(tree.size(), 2u);
463 EXPECT_TRUE(tree.verify());
464
465 auto * found = tree.search(Key(1, 5));
466 ASSERT_NE(found, nullptr);
467 EXPECT_EQ(found->low, 1);
468 EXPECT_EQ(found->high, 5);
469
470 EXPECT_EQ(tree.search(Key(2, 3)), nullptr);
471}
472
473TEST_F(DynIntervalTreeTest, InsertByEndpoints)
474{
475 tree.insert(1, 5);
476 tree.insert(10, 20);
477 EXPECT_EQ(tree.size(), 2u);
478 EXPECT_TRUE(tree.verify());
479}
480
482{
483 tree.insert(Key(1, 5));
484 tree.insert(Key(10, 20));
485 tree.insert(Key(3, 7));
486
487 EXPECT_TRUE(tree.remove(Key(10, 20)));
488 EXPECT_EQ(tree.size(), 2u);
489 EXPECT_TRUE(tree.verify());
490 EXPECT_EQ(tree.search(Key(10, 20)), nullptr);
491}
492
493TEST_F(DynIntervalTreeTest, RemoveByEndpoints)
494{
495 tree.insert(1, 5);
496 EXPECT_TRUE(tree.remove(1, 5));
497 EXPECT_TRUE(tree.is_empty());
498}
499
500TEST_F(DynIntervalTreeTest, RemoveNonexistent)
501{
502 tree.insert(Key(1, 5));
503 EXPECT_FALSE(tree.remove(Key(99, 100)));
504 EXPECT_EQ(tree.size(), 1u);
505}
506
507TEST_F(DynIntervalTreeTest, InvalidIntervalThrows)
508{
509 EXPECT_THROW(tree.insert(Key(5, 1)), std::domain_error);
510 EXPECT_TRUE(tree.is_empty());
511}
512
514{
515 tree.insert(Key(1, 5));
516 tree.insert(Key(10, 15));
517 tree.insert(Key(20, 25));
518
519 auto * result = tree.overlap_search(Key(4, 11));
520 ASSERT_NE(result, nullptr);
521 EXPECT_TRUE(result->overlaps(Key(4, 11)));
522
523 EXPECT_EQ(tree.overlap_search(Key(6, 9)), nullptr);
524}
525
526TEST_F(DynIntervalTreeTest, OverlapSearchByEndpoints)
527{
528 tree.insert(Key(1, 5));
529 auto * result = tree.overlap_search(3, 4);
530 ASSERT_NE(result, nullptr);
531}
532
534{
535 tree.insert(Key(1, 5));
536 tree.insert(Key(3, 8));
537 tree.insert(Key(7, 10));
538 tree.insert(Key(15, 20));
539
540 auto results = tree.find_all_overlaps(Key(4, 7));
541 EXPECT_EQ(results.size(), 3u);
542
543 results.for_each([](const Key & iv) {
544 EXPECT_TRUE(iv.overlaps(Key(4, 7)));
545 });
546}
547
548TEST_F(DynIntervalTreeTest, FindAllOverlapsByEndpoints)
549{
550 tree.insert(Key(1, 5));
551 tree.insert(Key(3, 8));
552 auto results = tree.find_all_overlaps(2, 4);
553 EXPECT_EQ(results.size(), 2u);
554}
555
557{
558 tree.insert(Key(1, 5));
559 tree.insert(Key(3, 8));
560 tree.insert(Key(7, 10));
561
562 size_t count = 0;
563 tree.stab(4, [&count](const Key &) { ++count; });
564 EXPECT_EQ(count, 2u);
565}
566
568{
569 tree.insert(Key(1, 10));
570 tree.insert(Key(5, 15));
571 tree.insert(Key(20, 25));
572
573 auto results = tree.find_stab(7);
574 EXPECT_EQ(results.size(), 2u);
575
576 results = tree.find_stab(20);
577 EXPECT_EQ(results.size(), 1u);
578
579 results = tree.find_stab(16);
580 EXPECT_EQ(results.size(), 0u);
581}
582
583TEST_F(DynIntervalTreeTest, CopyConstruction)
584{
585 tree.insert(Key(1, 5));
586 tree.insert(Key(10, 20));
587 tree.insert(Key(3, 7));
588
590 EXPECT_EQ(copy.size(), 3u);
591 EXPECT_TRUE(copy.verify());
592 EXPECT_NE(copy.search(Key(1, 5)), nullptr);
593 EXPECT_NE(copy.search(Key(10, 20)), nullptr);
594 EXPECT_NE(copy.search(Key(3, 7)), nullptr);
595}
596
597TEST_F(DynIntervalTreeTest, MoveConstruction)
598{
599 tree.insert(Key(1, 5));
600 tree.insert(Key(10, 20));
601
602 DynIntervalTree<int> moved(std::move(tree));
603 EXPECT_EQ(moved.size(), 2u);
604 EXPECT_TRUE(moved.verify());
605 EXPECT_TRUE(tree.is_empty());
606}
607
609{
610 tree.insert(Key(1, 5));
611 tree.insert(Key(10, 20));
612
614 other.insert(Key(100, 200));
615
616 other = tree;
617 EXPECT_EQ(other.size(), 2u);
618 EXPECT_TRUE(other.verify());
619}
620
622{
623 tree.insert(Key(1, 5));
624 tree.insert(Key(10, 20));
625
627 other = std::move(tree);
628 EXPECT_EQ(other.size(), 2u);
629 EXPECT_TRUE(other.verify());
630 EXPECT_TRUE(tree.is_empty());
631}
632
633TEST(IntervalTreeComparatorStateTest, CopyAssignmentPropagatesComparatorState)
634{
635 int left_counter = 0;
636 int right_counter = 0;
637
640
641 left.insert(Interval<int>(1, 3));
642 right.insert(Interval<int>(10, 20));
643
644 left = right;
645
646 left_counter = 0;
647 right_counter = 0;
648
649 const auto *found = left.search(Interval<int>(10, 20));
650 ASSERT_NE(found, nullptr);
651 EXPECT_EQ(left_counter, 0);
652 EXPECT_GT(right_counter, 0);
653}
654
655TEST_F(DynIntervalTreeTest, FunctionalForEach)
656{
657 tree.insert(Key(1, 5));
658 tree.insert(Key(10, 20));
659 tree.insert(Key(3, 7));
660
661 size_t count = 0;
662 tree.for_each([&count](const Key &) { ++count; });
663 EXPECT_EQ(count, 3u);
664}
665
666TEST_F(DynIntervalTreeTest, FunctionalExists)
667{
668 tree.insert(Key(1, 5));
669 tree.insert(Key(10, 20));
670
671 EXPECT_TRUE(tree.exists([](const Key & iv) { return iv.low == 10; }));
672 EXPECT_FALSE(tree.exists([](const Key & iv) { return iv.low == 99; }));
673}
674
675TEST_F(DynIntervalTreeTest, FunctionalFilter)
676{
677 tree.insert(Key(1, 5));
678 tree.insert(Key(10, 20));
679 tree.insert(Key(3, 7));
680
681 auto wide = tree.filter([](const Key & iv) {
682 return (iv.high - iv.low) >= 5;
683 });
684 EXPECT_EQ(wide.size(), 1u); // [1,5] has width 4, [10,20] has 10, [3,7] has 4
685}
686
688{
689 DynIntervalTree<int> t = {Key(1, 5), Key(10, 20), Key(3, 7)};
690 EXPECT_EQ(t.size(), 3u);
691 EXPECT_TRUE(t.verify());
692}
693
695{
696 tree.insert(Key(1, 5));
697 tree.insert(Key(10, 20));
698 tree.insert(Key(3, 7));
699 tree.insert(Key(25, 30));
700 tree.insert(Key(0, 2));
701
702 EXPECT_TRUE(tree.verify());
703}
704
706{
707 tree.insert(Key(1, 5));
708 tree.insert(Key(10, 20));
709 tree.insert(Key(3, 7));
710
711 size_t count = 0;
712 for (const auto & iv : tree)
713 {
714 EXPECT_TRUE(iv.is_valid());
715 ++count;
716 }
717 EXPECT_EQ(count, 3u);
718}
719
720// ─────────────────────────────────────────────────────────────────
721// Type tests
722// ─────────────────────────────────────────────────────────────────
723
724TEST(IntervalTreeTypeTest, IntIntervals)
725{
727 tree.insert(Interval<int>(1, 5));
728 tree.insert(Interval<int>(3, 8));
729
730 auto * result = tree.overlap_search(Interval<int>(4, 6));
731 ASSERT_NE(result, nullptr);
732 EXPECT_TRUE(tree.verify());
733}
734
735TEST(IntervalTreeTypeTest, DoubleIntervals)
736{
738 tree.insert(Interval<double>(1.0, 5.5));
739 tree.insert(Interval<double>(3.2, 8.1));
740 tree.insert(Interval<double>(10.0, 20.0));
741
742 EXPECT_EQ(tree.size(), 3u);
743 EXPECT_TRUE(tree.verify());
744
745 auto * result = tree.overlap_search(Interval<double>(4.0, 6.0));
746 ASSERT_NE(result, nullptr);
747 EXPECT_TRUE(result->overlaps(Interval<double>(4.0, 6.0)));
748
749 EXPECT_EQ(tree.overlap_search(Interval<double>(8.2, 9.9)), nullptr);
750}
751
752TEST(IntervalTreeTypeTest, StringIntervals)
753{
755 tree.insert(Interval<std::string>("apple", "cherry"));
756 tree.insert(Interval<std::string>("banana", "grape"));
757 tree.insert(Interval<std::string>("mango", "peach"));
758
759 EXPECT_EQ(tree.size(), 3u);
760 EXPECT_TRUE(tree.verify());
761
762 auto * result = tree.overlap_search(
763 Interval<std::string>("blueberry", "cantaloupe"));
764 ASSERT_NE(result, nullptr);
765}
766
767// ─────────────────────────────────────────────────────────────────
768// Stress test: insertions + removals + queries stay consistent
769// ─────────────────────────────────────────────────────────────────
770
771TEST(IntervalTreeStressTest, InsertRemoveVerify)
772{
774 std::mt19937 gen(54321);
775 std::uniform_int_distribution<int> dist(0, 1000);
776
777 DynList<Interval<int>> inserted;
778
779 // Insert 1000 intervals
780 for (int i = 0; i < 1000; ++i)
781 {
782 int a = dist(gen), b = dist(gen);
783 if (a > b) std::swap(a, b);
784 Interval<int> iv(a, b);
785 tree.insert_dup(iv);
786 inserted.append(iv);
787 }
788
789 EXPECT_EQ(tree.size(), 1000u);
790 EXPECT_TRUE(tree.verify());
791
792 // Remove half
793 size_t removed = 0;
794 DynList<Interval<int>> remaining;
795 inserted.for_each([&](const Interval<int> & iv) {
796 if (removed < 500)
797 {
798 tree.remove(iv);
799 ++removed;
800 }
801 else
802 remaining.append(iv);
803 });
804
805 EXPECT_TRUE(tree.verify());
806
807 // Verify remaining intervals are still findable
808 remaining.for_each([&](const Interval<int> & iv) {
809 auto * found = tree.search(iv);
810 EXPECT_NE(found, nullptr)
811 << "Lost interval [" << iv.low << "," << iv.high << "]";
812 });
813}
814
815TEST(IntervalTreeStressTest, AllOverlapsBruteForce)
816{
817 std::mt19937 gen(99999);
818 std::uniform_int_distribution<int> dist(0, 100);
819
821 std::vector<Interval<int>> intervals;
822
823 for (int i = 0; i < 200; ++i)
824 {
825 int a = dist(gen), b = dist(gen);
826 if (a > b) std::swap(a, b);
827 Interval<int> iv(a, b);
828 tree.insert_dup(iv);
829 intervals.push_back(iv);
830 }
831
832 EXPECT_TRUE(tree.verify());
833
834 // Compare all_overlaps against brute force
835 for (int q = 0; q < 50; ++q)
836 {
837 int a = dist(gen), b = dist(gen);
838 if (a > b) std::swap(a, b);
839 Interval<int> query(a, b);
840
841 auto tree_results = tree.find_all_overlaps(query);
842
843 size_t bf_count = 0;
844 for (const auto & iv : intervals)
845 if (iv.overlaps(query))
846 ++bf_count;
847
848 EXPECT_EQ(tree_results.size(), bf_count)
849 << "Mismatch for query [" << a << "," << b << "]";
850 }
851}
852
853// ─────────────────────────────────────────────────────────────────
854// key_comp() with a comparator whose copy may throw
855// ─────────────────────────────────────────────────────────────────
856
857namespace
858{
859 struct Copy_Error {};
860
861 // Compares as less<int> does; its copy throws when it is told to fail.
862 struct LessWithFallibleCopy
863 {
864 static inline bool copy_fails = false;
865
866 LessWithFallibleCopy() = default;
867
868 LessWithFallibleCopy(const LessWithFallibleCopy &)
869 {
870 if (copy_fails)
871 throw Copy_Error();
872 }
873
874 LessWithFallibleCopy & operator = (const LessWithFallibleCopy &) = default;
875
876 bool operator ()(const int a, const int b) const noexcept { return a < b; }
877 };
878
879 // While one lives, copying a LessWithFallibleCopy throws.
880 struct Failing_Copies
881 {
882 Failing_Copies() noexcept { LessWithFallibleCopy::copy_fails = true; }
883 ~Failing_Copies() { LessWithFallibleCopy::copy_fails = false; }
884 };
885}
886
887// The comparator of intervals that key_comp() returns holds a copy of the
888// comparator of endpoints. What that copy throws has to reach the caller: a
889// noexcept key_comp() would end the program instead.
890TEST(IntervalTreeComparator, KeyCompThrowsWhatCopyingTheComparatorThrows)
891{
892 static_assert(noexcept(std::declval<const Interval_Tree<int> &>().key_comp()));
893 static_assert(noexcept(std::declval<const DynIntervalTree<int> &>().key_comp()));
894
897 static_assert(not noexcept(std::declval<const Raw_Tree &>().key_comp()));
898 static_assert(not noexcept(std::declval<const Tree &>().key_comp()));
899
900 Tree tree;
901 tree.insert(1, 5);
902 tree.insert(3, 8);
903
904 const auto less = tree.key_comp();
905 EXPECT_TRUE(less(Interval<int>(1, 5), Interval<int>(3, 8)));
906 EXPECT_FALSE(less(Interval<int>(3, 8), Interval<int>(1, 5)));
907
908 {
909 const Failing_Copies failing;
910 EXPECT_THROW((void) tree.key_comp(), Copy_Error);
911 }
912
913 EXPECT_TRUE(tree.verify());
914 EXPECT_EQ(tree.size(), 2u);
915}
916
917// ─────────────────────────────────────────────────────────────────
918// A comparison, or a copy of an endpoint, that throws
919// ─────────────────────────────────────────────────────────────────
920
921namespace
922{
923 struct Call_Error : std::runtime_error
924 {
925 Call_Error() : std::runtime_error("the call that throws") {}
926 };
927
928 long calls_left = -1; // the calls until the one that throws; -1 for none
929 long calls_made = 0;
930
931 // A call of the comparison of Throwing_Less, or a copy of a Fragile
932 void a_call()
933 {
934 ++calls_made;
935 if (calls_left == 0)
936 {
937 calls_left = -1;
938 throw Call_Error();
939 }
940 if (calls_left > 0)
941 --calls_left;
942 }
943
944 struct Throwing_Less
945 {
946 bool operator ()(const int & a, const int & b) const
947 {
948 a_call();
949 return a < b;
950 }
951 };
952
953 // An endpoint whose copies may throw, and whose moves do not
954 struct Fragile
955 {
956 int value = 0;
957
958 Fragile() noexcept = default;
959
960 explicit Fragile(const int v) noexcept : value(v) {}
961
962 Fragile(const Fragile & f) : value(f.value) { a_call(); }
963
964 Fragile(Fragile && f) noexcept : value(f.value) {}
965
966 Fragile & operator =(const Fragile & f)
967 {
968 a_call();
969 value = f.value;
970 return *this;
971 }
972
973 Fragile & operator =(Fragile && f) noexcept
974 {
975 value = f.value;
976 return *this;
977 }
978 };
979
980 static_assert(not std::is_nothrow_copy_assignable_v<Fragile>);
981 static_assert(std::is_nothrow_move_assignable_v<Fragile>);
982 static_assert(std::is_nothrow_copy_assignable_v<int>);
983
984 struct Fragile_Less
985 {
986 bool operator ()(const Fragile & a, const Fragile & b) const noexcept
987 {
988 return a.value < b.value;
989 }
990 };
991
992 // An endpoint whose copies may throw, and whose move assignment too
993 struct Brittle
994 {
995 int value = 0;
996
997 Brittle() noexcept = default;
998
999 explicit Brittle(const int v) noexcept : value(v) {}
1000
1001 Brittle(const Brittle & b) : value(b.value) { a_call(); }
1002
1003 Brittle(Brittle && b) noexcept : value(b.value) {}
1004
1005 Brittle & operator =(const Brittle & b)
1006 {
1007 a_call();
1008 value = b.value;
1009 return *this;
1010 }
1011
1012 Brittle & operator =(Brittle && b)
1013 {
1014 a_call();
1015 value = b.value;
1016 return *this;
1017 }
1018 };
1019
1020 static_assert(not std::is_nothrow_copy_assignable_v<Brittle>);
1021 static_assert(not std::is_nothrow_move_assignable_v<Brittle>);
1022
1023 struct Brittle_Less
1024 {
1025 bool operator ()(const Brittle & a, const Brittle & b) const noexcept
1026 {
1027 return a.value < b.value;
1028 }
1029 };
1030
1031 // An endpoint with its copy assignment alone, which may throw: an rvalue
1032 // of it is assigned by a copy
1033 struct Copy_Only
1034 {
1035 int value = 0;
1036
1037 Copy_Only() noexcept = default;
1038
1039 explicit Copy_Only(const int v) noexcept : value(v) {}
1040
1041 Copy_Only(const Copy_Only & c) : value(c.value) { a_call(); }
1042
1043 Copy_Only & operator =(const Copy_Only & c)
1044 {
1045 a_call();
1046 value = c.value;
1047 return *this;
1048 }
1049 };
1050
1051 static_assert(std::is_move_assignable_v<Copy_Only>);
1052 static_assert(not std::is_nothrow_move_assignable_v<Copy_Only>);
1053
1054 // An endpoint whose move assignment is deleted: only an lvalue of it can
1055 // be assigned
1056 struct No_Move
1057 {
1058 int value = 0;
1059
1060 No_Move() noexcept = default;
1061
1062 explicit No_Move(const int v) noexcept : value(v) {}
1063
1064 No_Move(const No_Move & n) : value(n.value) { a_call(); }
1065
1066 No_Move & operator =(const No_Move & n)
1067 {
1068 a_call();
1069 value = n.value;
1070 return *this;
1071 }
1072
1073 No_Move & operator =(No_Move &&) = delete;
1074 };
1075
1076 static_assert(std::is_copy_assignable_v<No_Move>);
1077 static_assert(not std::is_move_assignable_v<No_Move>);
1078
1079 int value_of(const int v) noexcept { return v; }
1080
1081 int value_of(const Fragile & f) noexcept { return f.value; }
1082
1083 int value_of(const Brittle & b) noexcept { return b.value; }
1084
1085 int value_of(const Copy_Only & c) noexcept { return c.value; }
1086
1087 int value_of(const No_Move & n) noexcept { return n.value; }
1088
1089 // A comparison of any of those endpoints, which does not throw
1090 struct Value_Less
1091 {
1092 template <class Endpoint>
1093 bool operator ()(const Endpoint & a, const Endpoint & b) const noexcept
1094 {
1095 return value_of(a) < value_of(b);
1096 }
1097 };
1098
1099 // The result of a comparison that does not throw, whose conversion to
1100 // bool is a call, and so may throw
1101 struct Touchy_Bool
1102 {
1103 bool value;
1104
1105 operator bool() const
1106 {
1107 a_call();
1108 return value;
1109 }
1110 };
1111
1112 struct Touchy_Less
1113 {
1114 Touchy_Bool operator ()(const int & a, const int & b) const noexcept { return {a < b}; }
1115 };
1116
1117 static_assert(StrictWeakOrder<Touchy_Less, int>);
1118
1119 // A node as it is and where it hangs, to tell a tree that is as it was
1120 template <class Node>
1121 struct Seen
1122 {
1123 const Node *node;
1124 const Node *left;
1125 const Node *right;
1126 int low;
1127 int high;
1128 int max;
1129 unsigned long priority;
1130
1131 bool operator ==(const Seen &) const = default;
1132 };
1133
1134 template <class Node>
1135 void see(Node *p, std::vector<Seen<Node>> & nodes)
1136 {
1137 if (p == Node::NullPtr)
1138 return;
1139 nodes.push_back({p, LLINK(p), RLINK(p), value_of(KEY(p).low), value_of(KEY(p).high),
1140 value_of(MAX_EP(p)), PRIO(p)});
1141 see(LLINK(p), nodes);
1142 see(RLINK(p), nodes);
1143 }
1144
1145 template <class Node>
1146 std::vector<Seen<Node>> seen(Node *root)
1147 {
1148 std::vector<Seen<Node>> nodes;
1149 see(root, nodes);
1150 return nodes;
1151 }
1152
1153 // The nodes of a tree and where they hang, whatever their maxima are
1154 template <class Node>
1155 std::vector<Seen<Node>> links(Node *root)
1156 {
1157 std::vector<Seen<Node>> nodes = seen(root);
1158 for (auto & node : nodes)
1159 node.max = 0;
1160 return nodes;
1161 }
1162
1163 // The intervals, the maxima, the priorities and the form of a tree,
1164 // whatever its nodes are
1165 template <class Node>
1166 std::string shape(Node *p)
1167 {
1168 if (p == Node::NullPtr)
1169 return ".";
1170 return "(" + std::to_string(value_of(KEY(p).low)) + "," + std::to_string(value_of(KEY(p).high)) +
1171 " max " + std::to_string(value_of(MAX_EP(p))) + " prio " + std::to_string(PRIO(p)) + " " +
1172 shape(LLINK(p)) + " " + shape(RLINK(p)) + ")";
1173 }
1174
1175 // True if two trees have the same intervals, maxima and priorities at the
1176 // same places
1177 template <class Node>
1178 bool same(Node *a, Node *b)
1179 {
1180 if (a == Node::NullPtr or b == Node::NullPtr)
1181 return a == b;
1182 return value_of(KEY(a).low) == value_of(KEY(b).low) and
1183 value_of(KEY(a).high) == value_of(KEY(b).high) and
1184 value_of(MAX_EP(a)) == value_of(MAX_EP(b)) and PRIO(a) == PRIO(b) and
1185 same(LLINK(a), LLINK(b)) and same(RLINK(a), RLINK(b));
1186 }
1187
1188 // The intervals of a tree, in order
1189 template <class Node>
1190 std::string intervals(Node *p)
1191 {
1192 if (p == Node::NullPtr)
1193 return "";
1194 return intervals(LLINK(p)) + "[" + std::to_string(value_of(KEY(p).low)) + "," +
1195 std::to_string(value_of(KEY(p).high)) + "]" + intervals(RLINK(p));
1196 }
1197
1198 // The insertions and the removal of the tree through 7.7.5: rotations, and
1199 // the maximum of each node computed again from its children on the way
1200 // back, after the links
1201 template <class Node, class Compare>
1202 struct Old_Tree
1203 {
1204 using Key = typename Node::key_type;
1206
1207 Node *root = Node::NullPtr;
1208 Compare cmp;
1209
1210 ~Old_Tree() { destroyRec(root); }
1211
1212 static void update_max(Node *p, const Compare & cmp)
1213 {
1214 auto & mx = MAX_EP(p);
1215 mx = KEY(p).high;
1216 if (LLINK(p) != Node::NullPtr)
1217 if (cmp(mx, MAX_EP(LLINK(p))))
1218 mx = MAX_EP(LLINK(p));
1219 if (RLINK(p) != Node::NullPtr)
1220 if (cmp(mx, MAX_EP(RLINK(p))))
1221 mx = MAX_EP(RLINK(p));
1222 }
1223
1224 static Node * rotate_to_right(Node *p, const Compare & cmp)
1225 {
1226 Node *q = LLINK(p);
1227 LLINK(p) = RLINK(q);
1228 RLINK(q) = p;
1229 update_max(p, cmp);
1230 update_max(q, cmp);
1231 return q;
1232 }
1233
1234 static Node * rotate_to_left(Node *p, const Compare & cmp)
1235 {
1236 Node *q = RLINK(p);
1237 RLINK(p) = LLINK(q);
1238 LLINK(q) = p;
1239 update_max(p, cmp);
1240 update_max(q, cmp);
1241 return q;
1242 }
1243
1244 Node * insert(Node *root, Node *p)
1245 {
1246 if (root == Node::NullPtr)
1247 return p;
1248
1249 const Key & pk = KEY(p);
1250 const Key & rk = KEY(root);
1251 const Interval_Cmp interval_cmp(cmp);
1252 Node *result = nullptr;
1253 if (interval_cmp(pk, rk))
1254 {
1255 result = insert(LLINK(root), p);
1256 if (result == Node::NullPtr)
1257 return Node::NullPtr;
1258 LLINK(root) = result;
1259 update_max(root, cmp);
1260 if (PRIO(LLINK(root)) < PRIO(root))
1261 return rotate_to_right(root, cmp);
1262 return root;
1263 }
1264 if (interval_cmp(rk, pk))
1265 {
1266 result = insert(RLINK(root), p);
1267 if (result == Node::NullPtr)
1268 return Node::NullPtr;
1269 RLINK(root) = result;
1270 update_max(root, cmp);
1271 if (PRIO(RLINK(root)) < PRIO(root))
1272 return rotate_to_left(root, cmp);
1273 return root;
1274 }
1275
1276 return Node::NullPtr; // duplicate
1277 }
1278
1279 Node * insert_dup(Node *root, Node *p)
1280 {
1281 if (root == Node::NullPtr)
1282 return p;
1283
1284 const Key & pk = KEY(p);
1285 const Key & rk = KEY(root);
1286 const Interval_Cmp interval_cmp(cmp);
1287 if (interval_cmp(pk, rk))
1288 {
1289 LLINK(root) = insert_dup(LLINK(root), p);
1290 update_max(root, cmp);
1291 if (PRIO(LLINK(root)) < PRIO(root))
1292 return rotate_to_right(root, cmp);
1293 return root;
1294 }
1295 RLINK(root) = insert_dup(RLINK(root), p);
1296 update_max(root, cmp);
1297 if (PRIO(RLINK(root)) < PRIO(root))
1298 return rotate_to_left(root, cmp);
1299 return root;
1300 }
1301
1302 static Node * join_exclusive(Node *t1, Node *t2, const Compare & cmp)
1303 {
1304 if (t1 == Node::NullPtr)
1305 return t2;
1306 if (t2 == Node::NullPtr)
1307 return t1;
1308
1309 if (PRIO(t1) < PRIO(t2))
1310 {
1311 RLINK(t1) = join_exclusive(RLINK(t1), t2, cmp);
1312 update_max(t1, cmp);
1313 return t1;
1314 }
1315 LLINK(t2) = join_exclusive(t1, LLINK(t2), cmp);
1316 update_max(t2, cmp);
1317 return t2;
1318 }
1319
1320 Node * remove(Node *& root, const Key & key)
1321 {
1322 if (root == Node::NullPtr)
1323 return Node::NullPtr;
1324
1325 const Key & rk = KEY(root);
1326 const Interval_Cmp interval_cmp(cmp);
1327 Node *ret_val;
1328 if (interval_cmp(key, rk))
1329 ret_val = remove(LLINK(root), key);
1330 else if (interval_cmp(rk, key))
1331 ret_val = remove(RLINK(root), key);
1332 else
1333 {
1334 ret_val = root;
1335 root = join_exclusive(LLINK(root), RLINK(root), cmp);
1336 return ret_val;
1337 }
1338
1339 if (ret_val == Node::NullPtr)
1340 return Node::NullPtr;
1341
1342 update_max(root, cmp);
1343 return ret_val;
1344 }
1345 };
1346
1347 // The same operations, at random and with many intervals the same, on a
1348 // tree and on an old one whose nodes take the same priorities. With
1349 // `priorities` other than zero, the nodes take one of that many
1350 // priorities, so that most of them are equal.
1351 template <class E, class Less>
1352 void same_trees_as_the_old_ones(const unsigned seed, const int operations, const unsigned priorities)
1353 {
1355 using Node = typename Tree::Node;
1356
1357 // The tree does not free its nodes: this does, also when an assertion
1358 // ends the function
1359 struct Owner
1360 {
1361 Tree tree;
1362
1363 explicit Owner(const unsigned seed) : tree(seed) {}
1364
1365 ~Owner()
1366 {
1367 destroyRec(tree.getRoot());
1368 tree.reset_num_nodes();
1369 }
1370 } owner(seed);
1371 Tree & tree = owner.tree;
1372 Old_Tree<Node, Less> old;
1373 std::mt19937 gen(seed);
1374 for (int i = 0; i < operations; ++i)
1375 {
1376 const int lo = static_cast<int>(gen() % 40);
1377 const int hi = lo + static_cast<int>(gen() % 12);
1378 const Interval<E> key{E(lo), E(hi)};
1379 if (priorities != 0)
1380 tree.set_seed(gen() % priorities);
1381 switch (gen() % 4)
1382 {
1383 case 0:
1384 {
1385 std::unique_ptr<Node> p(new Node(key));
1386 std::unique_ptr<Node> q(new Node(key));
1387 if (tree.insert(p.get()) == nullptr)
1388 {
1389 ASSERT_EQ(old.insert(old.root, q.get()), Node::NullPtr);
1390 break; // the two that did not enter are freed
1391 }
1392 PRIO(q.get()) = PRIO(p.release()); // the tree has p
1393 Node *root = old.insert(old.root, q.get());
1394 ASSERT_NE(root, Node::NullPtr);
1395 old.root = root;
1396 q.release(); // the old tree has q
1397 break;
1398 }
1399 case 1:
1400 {
1401 std::unique_ptr<Node> p(new Node(key));
1402 std::unique_ptr<Node> q(new Node(key));
1403 tree.insert_dup(p.get());
1404 PRIO(q.get()) = PRIO(p.release());
1405 old.root = old.insert_dup(old.root, q.release());
1406 break;
1407 }
1408 default:
1409 {
1410 const std::unique_ptr<Node> p(tree.remove(key));
1411 Node *taken = old.remove(old.root, key);
1412 const std::unique_ptr<Node> q(taken == Node::NullPtr ? nullptr : taken);
1413 ASSERT_EQ(p == nullptr, q == nullptr);
1414 if (p != nullptr) // it goes out as its reset() leaves it
1415 {
1416 EXPECT_EQ(LLINK(p.get()), Node::NullPtr);
1417 EXPECT_EQ(RLINK(p.get()), Node::NullPtr);
1418 EXPECT_EQ(value_of(MAX_EP(p.get())), value_of(KEY(p.get()).high));
1419 }
1420 }
1421 }
1422 ASSERT_TRUE(same(tree.getRoot(), old.root))
1423 << "after the operation " << i << ": " << shape(tree.getRoot()) << " and " << shape(old.root);
1424 }
1425 EXPECT_TRUE(tree.verify());
1426 EXPECT_GT(tree.size(), 0u);
1427 }
1428
1429 // A tree of n intervals with even endpoints, some of them the same and
1430 // some that reach far, which frees its nodes
1431 template <class E, class Less>
1432 struct Grove
1433 {
1435 using Node = typename Tree::Node;
1436
1437 Tree tree;
1438
1439 static Interval<E> interval(const int i)
1440 {
1441 const int lo = 2 * ((i * 7) % 23);
1442 return {E(lo), E(lo + 2 * ((i * 5) % 11) + (i % 4 == 0 ? 80 : 0))};
1443 }
1444
1445 Grove(const unsigned long seed, const int n) : tree(seed)
1446 {
1447 for (int i = 0; i < n; ++i)
1448 tree.insert_dup(new Node(interval(i)));
1449 }
1450
1451 ~Grove()
1452 {
1453 destroyRec(tree.getRoot());
1454 tree.reset_num_nodes();
1455 }
1456 };
1457
1458 enum class Kind { Insert, Insert_Dup, Remove };
1459
1460 // One operation on a tree, whose call number `arm` throws: none if it is
1461 // -1. It gives the calls that the operation made
1462 template <class E, class Less>
1463 long apply(Interval_Tree<E, Less> & tree, const Kind kind, const int lo, const int hi, const long arm)
1464 {
1465 using Node = typename Interval_Tree<E, Less>::Node;
1466
1467 const Interval<E> key{E(lo), E(hi)};
1468 Node *p = kind == Kind::Remove ? nullptr : new Node(key);
1469 calls_made = 0;
1470 calls_left = arm;
1471 try
1472 {
1473 switch (kind)
1474 {
1475 case Kind::Insert:
1476 if (tree.insert(p) != nullptr)
1477 p = nullptr;
1478 break;
1479 case Kind::Insert_Dup:
1480 tree.insert_dup(p);
1481 p = nullptr;
1482 break;
1483 case Kind::Remove:
1484 p = tree.remove(key);
1485 break;
1486 }
1487 }
1488 catch (...)
1489 {
1490 calls_left = -1;
1491 delete p; // the node that did not enter
1492 throw;
1493 }
1494 calls_left = -1;
1495 const long made = calls_made;
1496 delete p; // the duplicate that did not enter, or the node taken out
1497 return made;
1498 }
1499
1500 // An operation on a tree of n intervals, with each of its calls throwing
1501 // in turn: the tree must stay as it was, to the pointer, and then take
1502 // the operation. If not `whole`, only its nodes must stay where they
1503 // were: their maxima may change
1504 template <class E, class Less>
1505 void every_failed_call(const unsigned long seed, const int n, const Kind kind, const int lo, const int hi,
1506 const bool whole)
1507 {
1508 SCOPED_TRACE("seed " + std::to_string(seed) + ", " + std::to_string(n) + " intervals, operation " +
1509 std::to_string(static_cast<int>(kind)) + " of [" + std::to_string(lo) + "," +
1510 std::to_string(hi) + "]");
1511 long total = 0;
1512 std::string expected_shape;
1513 std::string expected_intervals;
1514 {
1515 Grove<E, Less> grove(seed, n);
1516 total = apply(grove.tree, kind, lo, hi, -1);
1517 ASSERT_TRUE(grove.tree.verify());
1518 expected_shape = shape(grove.tree.getRoot());
1519 expected_intervals = intervals(grove.tree.getRoot());
1520 }
1521 for (long k = 0; k < total; ++k)
1522 {
1523 SCOPED_TRACE("call " + std::to_string(k) + " of " + std::to_string(total));
1524 Grove<E, Less> grove(seed, n);
1525 const auto before = whole ? seen(grove.tree.getRoot()) : links(grove.tree.getRoot());
1526 const size_t size = grove.tree.size();
1527 EXPECT_THROW(apply(grove.tree, kind, lo, hi, k), Call_Error);
1528 EXPECT_TRUE((whole ? seen(grove.tree.getRoot()) : links(grove.tree.getRoot())) == before);
1529 EXPECT_EQ(grove.tree.size(), size);
1530 if (not whole)
1531 continue;
1532 EXPECT_TRUE(grove.tree.verify());
1533
1534 apply(grove.tree, kind, lo, hi, -1);
1535 EXPECT_TRUE(grove.tree.verify());
1536 EXPECT_EQ(intervals(grove.tree.getRoot()), expected_intervals);
1537 if (kind == Kind::Remove) // an insertion takes another priority
1538 EXPECT_EQ(shape(grove.tree.getRoot()), expected_shape);
1539 }
1540 }
1541
1542 // Every removal, and insertions before, among and after the intervals of
1543 // trees of up to `sizes` of them, with a high endpoint below the maxima
1544 // and with one above them all
1545 template <class E, class Less>
1546 long every_failed_call_of_every_operation(const int sizes, const bool whole = true)
1547 {
1548 long operations = 0;
1549 for (unsigned long seed = 1; seed <= 3; ++seed)
1550 for (int n = 0; n <= sizes; ++n)
1551 {
1552 for (int i = 0; i < n; ++i, ++operations)
1553 {
1554 const auto iv = Grove<E, Less>::interval(i);
1555 every_failed_call<E, Less>(seed, n, Kind::Remove, value_of(iv.low), value_of(iv.high), whole);
1556 }
1557 every_failed_call<E, Less>(seed, n, Kind::Remove, 15, 17, whole); // not in the tree
1558 ++operations;
1559 for (const Kind kind : {Kind::Insert, Kind::Insert_Dup})
1560 {
1561 for (const int lo : {-1, 15, 47})
1562 for (const int hi : {lo, lo + 9, 999}) // odd: not in the tree
1563 {
1564 every_failed_call<E, Less>(seed, n, kind, lo, hi, whole);
1565 ++operations;
1566 }
1567 if (n == 0)
1568 continue;
1569 for (const int i : {0, n / 2}) // in the tree
1570 {
1571 const auto iv = Grove<E, Less>::interval(i);
1572 every_failed_call<E, Less>(seed, n, kind, value_of(iv.low), value_of(iv.high), whole);
1573 ++operations;
1574 }
1575 }
1576 }
1577 return operations;
1578 }
1579}
1580
1581// The tree that an insertion or a removal leaves is the one that the
1582// rotations of 7.7.5 left: the same nodes at the same places, with the same
1583// maxima. Also with priorities that are equal, where a rotation is not made.
1584TEST(IntervalTreeInsertionAndRemoval, SameTreesAsTheRotations)
1585{
1586 for (const unsigned seed : {1u, 2u, 3u})
1587 {
1588 same_trees_as_the_old_ones<int, Aleph::less<int>>(seed, 5000, 0);
1589 same_trees_as_the_old_ones<int, Aleph::less<int>>(seed, 1500, 1);
1590 same_trees_as_the_old_ones<int, Aleph::less<int>>(seed, 1500, 3);
1591 same_trees_as_the_old_ones<Fragile, Fragile_Less>(seed, 2000, 0);
1592 same_trees_as_the_old_ones<Fragile, Fragile_Less>(seed, 1000, 3);
1593 }
1594}
1595
1596// Through 7.7.5 the maxima were computed with the comparison after the
1597// links, in the rotations and in the join of a removal: when it threw, an
1598// insertion left the node in the tree, which DynIntervalTree then freed, and
1599// a removal left nodes that hung twice, or took the node out without giving
1600// it back.
1601TEST(IntervalTreeThrowingCompare, EveryFailedCallLeavesTheTreeAsItWas)
1602{
1603 const long operations = every_failed_call_of_every_operation<int, Throwing_Less>(12);
1604 EXPECT_GT(operations, 900);
1605}
1606
1607// The copies of the endpoints are made before the tree changes too: the
1608// maxima that change are copied first, and then moved to their nodes.
1609TEST(IntervalTreeThrowingCopy, EveryFailedCopyLeavesTheTreeAsItWas)
1610{
1611 const long operations = every_failed_call_of_every_operation<Fragile, Fragile_Less>(12);
1612 EXPECT_GT(operations, 900);
1613}
1614
1615// The limit that the documentation states. A move assignment of an endpoint
1616// that throws, when its copy assignment may throw too, may leave the maxima
1617// of some nodes changed; but every node stays where it was, the node of an
1618// insertion out of the tree and that of a removal in it: the maxima are
1619// given before any link changes.
1620TEST(IntervalTreeThrowingMove, AFailedMoveLeavesEveryNodeWhereItWas)
1621{
1622 const long operations = every_failed_call_of_every_operation<Brittle, Brittle_Less>(12, false);
1623 EXPECT_GT(operations, 900);
1624}
1625
1626// The same limit, for an endpoint that has its copy assignment alone, which
1627// assigns an rvalue too and may throw; and for one whose move assignment is
1628// deleted, which did not compile: the maximum was always given by a move.
1629TEST(IntervalTreeThrowingMove, AFailedCopyOfAnEndpointWithoutAMoveLeavesEveryNodeWhereItWas)
1630{
1631 const long copied = every_failed_call_of_every_operation<Copy_Only, Value_Less>(8, false);
1632 EXPECT_GT(copied, 400);
1633 const long not_moved = every_failed_call_of_every_operation<No_Move, Value_Less>(8, false);
1634 EXPECT_GT(not_moved, 400);
1635}
1636
1637// A comparison may give something that is not a bool, whose conversion to
1638// bool may throw: it is a part of the comparison for the tree, which stays
1639// as it was, and for what search() and Interval_Less say that they throw.
1640TEST(IntervalTreeThrowingCompare, AConversionToBoolThatThrowsIsAComparisonThatThrows)
1641{
1642 static_assert(not noexcept(std::declval<const Interval_Tree<int, Touchy_Less> &>()
1643 .search(Interval<int>())));
1644 static_assert(not noexcept(std::declval<const DynIntervalTree<int, Touchy_Less> &>()
1645 .search(Interval<int>())));
1646 static_assert(not noexcept(std::declval<const Interval_Less<int, Touchy_Less> &>()(Interval<int>(),
1647 Interval<int>())));
1648 static_assert(noexcept(std::declval<const Interval_Less<int> &>()(Interval<int>(), Interval<int>())));
1649 static_assert(not noexcept(Interval<int>().overlaps(Interval<int>(), Touchy_Less())));
1650 static_assert(not noexcept(Interval<int>().contains(0, Touchy_Less())));
1651 static_assert(not noexcept(Interval<int>().is_valid(Touchy_Less())));
1652
1653 const long operations = every_failed_call_of_every_operation<int, Touchy_Less>(8);
1654 EXPECT_GT(operations, 400);
1655
1657 tree.insert(1, 5);
1658 ASSERT_NE(tree.search(Interval<int>(1, 5)), nullptr);
1659 for (long k = 0; k < 3; ++k) // [1,6] goes through the three comparisons of [1,5]
1660 {
1661 calls_left = k;
1662 EXPECT_THROW((void) tree.search(Interval<int>(1, 6)), Call_Error) << "conversion " << k;
1663 calls_left = -1;
1664 }
1665 EXPECT_EQ(tree.search(Interval<int>(1, 6)), nullptr);
1666}
1667
1668// The constructor of a node from an rvalue, and reset(), copy the high
1669// endpoint to the maximum of the node. They were noexcept whatever that copy
1670// did: an insertion by move of DynIntervalTree ended the program there.
1671TEST(IntervalTreeThrowingCopy, ANodeThatCannotCopyItsEndpointSaysSo)
1672{
1675 static_assert(std::is_nothrow_constructible_v<Interval_Tree<int>::Node, Interval<int> &&>);
1676 static_assert(std::is_nothrow_constructible_v<Interval_Tree_Vtl<int>::Node, Interval<int> &&>);
1677 static_assert(not std::is_nothrow_constructible_v<Node, Interval<Fragile> &&>);
1678 static_assert(not std::is_nothrow_constructible_v<Node_Vtl, Interval<Fragile> &&>);
1679 static_assert(noexcept(std::declval<Interval_Tree<int>::Node &>().reset()));
1680 static_assert(noexcept(std::declval<Interval_Tree_Vtl<int>::Node &>().reset()));
1681 static_assert(not noexcept(std::declval<Node &>().reset()));
1682 static_assert(not noexcept(std::declval<Node_Vtl &>().reset()));
1683
1684 calls_left = 0;
1685 EXPECT_THROW(Node(Interval<Fragile>(Fragile(1), Fragile(5))), Call_Error);
1686 calls_left = 0;
1687 EXPECT_THROW(Node_Vtl(Interval<Fragile>(Fragile(1), Fragile(5))), Call_Error);
1688 calls_left = -1;
1689
1690 // reset() keeps the links of a node whose endpoint it could not copy
1691 Node a(Interval<Fragile>(Fragile(1), Fragile(5)));
1692 Node b(Interval<Fragile>(Fragile(2), Fragile(9)));
1693 LLINK(&a) = &b;
1694 MAX_EP(&a) = Fragile(9);
1695 calls_left = 0;
1696 EXPECT_THROW(a.reset(), Call_Error);
1697 calls_left = -1;
1698 EXPECT_EQ(LLINK(&a), &b);
1699 EXPECT_EQ(MAX_EP(&a).value, 9);
1700 a.reset();
1701 EXPECT_EQ(LLINK(&a), Node::NullPtr);
1702 EXPECT_EQ(MAX_EP(&a).value, 5);
1703
1704 // The insertion by move of DynIntervalTree, with each copy failing in
1705 // turn: that of the node, and those of the maxima that change
1707 const auto listed = [](const Tree & tree)
1708 {
1709 std::string s;
1710 tree.for_each([&s](const Interval<Fragile> & iv)
1711 {
1712 s += "[" + std::to_string(iv.low.value) + "," + std::to_string(iv.high.value) + "]";
1713 });
1714 return s;
1715 };
1716 long failed = 0;
1717 for (long k = 0; ; ++k)
1718 {
1719 Tree tree(7);
1720 for (int i = 0; i < 9; ++i)
1721 tree.insert_dup(Grove<Fragile, Fragile_Less>::interval(i));
1722 const std::string before = listed(tree);
1723 bool thrown = false;
1724 calls_left = k;
1725 try
1726 {
1727 tree.insert(Interval<Fragile>(Fragile(15), Fragile(999)));
1728 }
1729 catch (const Call_Error &)
1730 {
1731 thrown = true;
1732 }
1733 calls_left = -1;
1734 EXPECT_TRUE(tree.verify());
1735 if (not thrown)
1736 {
1737 EXPECT_EQ(tree.size(), 10u);
1738 break;
1739 }
1740 ++failed;
1741 EXPECT_EQ(listed(tree), before) << "copy " << k;
1742 EXPECT_EQ(tree.size(), 9u);
1743 }
1744 EXPECT_GT(failed, 2);
1745}
1746
1747// DynIntervalTree frees the node of an insertion that throws: the tree must
1748// not have it. And its removal must not lose the node that it does not free.
1749TEST(IntervalTreeThrowingCompare, DynIntervalTreeKeepsItsIntervals)
1750{
1752 const auto fill = [](Tree & tree, const int n)
1753 {
1754 for (int i = 0; i < n; ++i)
1755 tree.insert_dup(Grove<int, Throwing_Less>::interval(i));
1756 };
1757 const auto listed = [](const Tree & tree)
1758 {
1759 std::string s;
1760 tree.for_each([&s](const Interval<int> & iv)
1761 {
1762 s += "[" + std::to_string(iv.low) + "," + std::to_string(iv.high) + "]";
1763 });
1764 return s;
1765 };
1766 const auto every = [&](const int n, const auto & operation)
1767 {
1768 long total = 0;
1769 {
1770 Tree tree(7);
1771 fill(tree, n);
1772 calls_made = 0;
1773 operation(tree);
1774 total = calls_made;
1775 }
1776 for (long k = 0; k < total; ++k)
1777 {
1778 Tree tree(7);
1779 fill(tree, n);
1780 const std::string before = listed(tree);
1781 calls_left = k;
1782 EXPECT_THROW(operation(tree), Call_Error) << "call " << k << " of " << total;
1783 calls_left = -1;
1784 EXPECT_EQ(listed(tree), before);
1785 EXPECT_EQ(tree.size(), static_cast<size_t>(n));
1786 EXPECT_TRUE(tree.verify());
1787 operation(tree);
1788 EXPECT_TRUE(tree.verify());
1789 }
1790 return total;
1791 };
1792
1793 long calls = 0;
1794 for (int n = 0; n <= 14; ++n)
1795 {
1796 calls += every(n, [](Tree & tree) { tree.insert(15, 999); });
1797 calls += every(n, [](Tree & tree) { tree.insert(Interval<int>(-1, 3)); });
1798 calls += every(n, [](Tree & tree) { tree.insert_dup(Interval<int>(15, 21)); });
1799 calls += every(n, [](Tree & tree) { tree.append(Interval<int>(0, 80)); });
1800 if (n > 0)
1801 {
1802 calls += every(n, [](Tree & tree) { EXPECT_TRUE(tree.remove(0, 80)); });
1803 calls += every(n, [n](Tree & tree)
1804 {
1805 EXPECT_TRUE(tree.remove(Grove<int, Throwing_Less>::interval(n / 2)));
1806 });
1807 }
1808 }
1809 EXPECT_GT(calls, 500);
1810}
1811
1812// search() runs the comparison and copies it: it is noexcept only when
1813// neither throws. It was noexcept without a condition in DynIntervalTree.
1814TEST(IntervalTreeThrowingCompare, SearchThrowsWhatTheComparisonThrows)
1815{
1816 static_assert(noexcept(std::declval<const Interval_Tree<int> &>().search(Interval<int>())));
1817 static_assert(noexcept(std::declval<const DynIntervalTree<int> &>().search(Interval<int>())));
1818 static_assert(not noexcept(std::declval<const Interval_Tree<int, Throwing_Less> &>()
1819 .search(Interval<int>())));
1820 static_assert(not noexcept(std::declval<const DynIntervalTree<int, Throwing_Less> &>()
1821 .search(Interval<int>())));
1822 static_assert(not noexcept(std::declval<const DynIntervalTree<int, LessWithFallibleCopy> &>()
1823 .search(Interval<int>())));
1824
1826 tree.insert(1, 5);
1827 tree.insert(3, 8);
1828 ASSERT_NE(tree.search(Interval<int>(3, 8)), nullptr);
1829 calls_left = 0;
1830 EXPECT_THROW((void) tree.search(Interval<int>(3, 8)), Call_Error);
1831 calls_left = -1;
1832 EXPECT_EQ(tree.search(Interval<int>(4, 8)), nullptr);
1833 EXPECT_TRUE(tree.verify());
1834}
1835
1836// Every member of DynIntervalTree and of its iterator compiles. The
1837// iterator had a prev() that called one that the iterator of the tree does
1838// not have: it compiled only because nothing called it.
1839template class Aleph::DynIntervalTree<int>;
WeightedDigraph::Node Node
@ KEY
Definition btreepic.C:169
size_t size_t int32_t value
Definition ca-c-api.h:116
High-level interval tree with automatic memory management.
DynList< Key > find_all_overlaps(const Key &query) const
Find all overlapping intervals.
const Key * search(const Key &iv) const noexcept(noexcept(std::declval< const Tree & >().search(iv)))
Search for an exact interval.
Key & insert_dup(const Key &iv)
Insert interval, allowing duplicates.
Key & insert(const Key &iv)
Insert an interval (unique).
const Key * overlap_search(const Key &query) const
Find any interval overlapping query.
bool verify() const
Verify all tree invariants (BST, Treap, MaxEndpoint).
size_t size() const noexcept
Return the number of intervals in the tree.
bool remove(const Key &iv)
Remove an interval from the tree.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
void insert_dup(Node *root, Node *p, Step *up)
Go down to the place of p and put it there, after the intervals that are the same as its own.
Node * insert(Node *root, Node *p, Step *up)
Go down to the place of p and put it there, unless its interval is in the tree, which then gives Node...
Node *& getRoot() noexcept
Return the tree's root.
void set_seed(const unsigned long seed)
Seeds the Mersenne Twister of the tree, as gsl_rng_set() did: the priorities are from then on those o...
Node * remove(Node *root, const Key &key, Step *up)
Go down to the node of the interval key and take it out of the tree.
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
DynIntervalTree< int > tree
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
Node * make_node(int lo, int hi)
QuadTree - Hierarchical spatial index for 2D points.
Definition quadtree.H:126
void for_each(Op &op)
Apply an operation to each node in the tree.
Definition quadtree.H:612
void remove(const Point &p)
Remove a point from the tree.
Definition quadtree.H:565
QuadNode Node
Definition quadtree.H:128
Point * insert(Node *&r, const Point &p)
Recursive insert helper.
Definition quadtree.H:281
#define TEST(name)
#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_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
__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
Node * rotate_to_left(Node *p) noexcept
Rotate to the left the tree with root p
Node * rotate_to_right(Node *p) noexcept
Rotate to the right the tree with root p
Node * join_exclusive(Node *&ts, Node *&tg) noexcept
Exclusive join of two binary trees.
void destroyRec(Node *&root) noexcept
Free all the memory occupied by the tree root
unsigned long & PRIO(Node *p) noexcept
Access the priority of a treap node.
Definition treapNode.H:120
TEST_F(IntervalTypeTest, Construction)
Main namespace for Aleph-w library functions.
auto & MAX_EP(Node *p) noexcept
Access max_endpoint of an interval tree node.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
static long & low(typename GT::Node *p)
Internal helper: low-link value stored directly in NODE_COOKIE(p).
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
void fill(Itor beg, const Itor &end, const T &value)
Fill a range with a value.
Definition ahAlgo.H:707
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
Itor1 search(Itor1 beg, const Itor1 &end, Itor2 searchBeg, const Itor2 &searchEnd, BinaryPredicate op=BinaryPredicate())
Search for a subrange within a range.
Definition ahAlgo.H:309
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.
BST comparator for intervals: order by (low, then high).
Interval tree using nodes with virtual destructor.
Closed interval [low, high].
bool contains(const T &p, const Compare &cmp=Compare()) const noexcept(NothrowPredicateWith< const Compare &, const T &, const T & >)
Return true if this interval contains the point p.
static Interval point(const T &p) noexcept(std::is_nothrow_copy_constructible_v< T >)
Construct a point interval [p, p].
bool is_valid(const Compare &cmp=Compare()) const noexcept(NothrowPredicateWith< const Compare &, const T &, const T & >)
Return true if low <= high.
bool overlaps(const Interval &other, const Compare &cmp=Compare()) const noexcept(NothrowPredicateWith< const Compare &, const T &, const T & >)
Return true if this interval overlaps with other.
T low
Lower endpoint.
T high
Upper endpoint.
CountingLess(int *c=nullptr) noexcept
bool operator()(const int &a, const int &b) const noexcept
#define RLINK(i, n)
#define LLINK(i, n)
Dnode< int > Test
Definition testDnode.C:42
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Interval tree: augmented BST for overlap/stabbing queries.