Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
flat_set_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 https://github.com/lrleon/Aleph-w
6
7 This file is part of Aleph-w library
8
9 Copyright (c) 2002-2026 Leandro Rabindranath Leon
10
11 Permission is hereby granted, free of charge, to any person obtaining a copy
12 of this software and associated documentation files (the "Software"), to deal
13 in the Software without restriction, including without limitation the rights
14 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 copies of the Software, and to permit persons to whom the Software is
16 furnished to do so, subject to the following conditions:
17
18 The above copyright notice and this permission notice shall be included in all
19 copies or substantial portions of the Software.
20
21 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27 SOFTWARE.
28*/
29
40#include <limits>
41#include <new>
42#include <random>
43#include <set>
44#include <stdexcept>
45#include <string>
46#include <vector>
47
48#include <gtest/gtest.h>
49
50#include <tpl_flat_set.H>
51
52using Aleph::FlatSet;
53
54namespace
55{
56// A key whose move assignment throws once a budget of them is spent, to
57// interrupt a shift or a relocation half way. Nothing else throws.
58struct Throwing_Move_Key
59{
60 static inline int moves_left = -1; // -1 means that it never throws
61
62 int value = 0;
63
64 Throwing_Move_Key() = default;
65 Throwing_Move_Key(const int v) : value(v) {}
66 Throwing_Move_Key(const Throwing_Move_Key &) = default;
67 Throwing_Move_Key(Throwing_Move_Key &&) = default;
68 Throwing_Move_Key &operator = (const Throwing_Move_Key &) = default;
69 Throwing_Move_Key &operator = (Throwing_Move_Key &&other)
70 {
71 if (moves_left == 0)
72 throw std::runtime_error("move assignment");
73 if (moves_left > 0)
74 --moves_left;
75 value = other.value;
76 return *this;
77 }
78
79 bool operator < (const Throwing_Move_Key &other) const noexcept
80 {
81 return value < other.value;
82 }
83};
84
85// A key that moves without throwing but whose copies throw on demand.
86struct Throwing_Copy_Key
87{
88 static inline bool fail = false;
89
90 int value = 0;
91
92 Throwing_Copy_Key() = default;
93 Throwing_Copy_Key(const int v) : value(v) {}
94 Throwing_Copy_Key(const Throwing_Copy_Key &other) : value(other.value)
95 {
96 if (fail)
97 throw std::runtime_error("copy");
98 }
99 Throwing_Copy_Key(Throwing_Copy_Key &&) noexcept = default;
100 Throwing_Copy_Key &operator = (const Throwing_Copy_Key &other)
101 {
102 if (fail)
103 throw std::runtime_error("copy assignment");
104 value = other.value;
105 return *this;
106 }
107 Throwing_Copy_Key &operator = (Throwing_Copy_Key &&) noexcept = default;
108
109 bool operator < (const Throwing_Copy_Key &other) const noexcept
110 {
111 return value < other.value;
112 }
113};
114
115// A key whose default construction fails on demand, as the allocation of a
116// buffer does: a new buffer is filled with default keys before any key is
117// moved to it. Its moves are not declared noexcept, and never throw.
118struct Failing_Default_Key
119{
120 static inline bool fail = false;
121
122 int value = 0;
123
124 Failing_Default_Key()
125 {
126 if (fail)
127 throw std::bad_alloc();
128 }
129 Failing_Default_Key(const int v) : value(v) {}
130 Failing_Default_Key(const Failing_Default_Key &) = default;
131 Failing_Default_Key(Failing_Default_Key &&other) : value(other.value) {}
132 Failing_Default_Key &operator = (const Failing_Default_Key &) = default;
133 Failing_Default_Key &operator = (Failing_Default_Key &&other)
134 {
135 value = other.value;
136 return *this;
137 }
138
139 bool operator < (const Failing_Default_Key &other) const noexcept
140 {
141 return value < other.value;
142 }
143};
144
145template <class Set>
146::testing::AssertionResult is_strictly_sorted(const Set &s)
147{
148 for (size_t i = 1; i < s.size(); ++i)
149 if (not (s.nth(i - 1) < s.nth(i)))
150 return ::testing::AssertionFailure()
151 << "keys " << s.nth(i - 1).value << " and " << s.nth(i).value
152 << " at " << i - 1 << " are not strictly increasing";
153 return ::testing::AssertionSuccess();
154}
155} // namespace
156
157TEST(FlatSet, EmptySetBasics)
158{
159 FlatSet<int> s;
160 EXPECT_TRUE(s.is_empty());
161 EXPECT_EQ(s.size(), 0u);
162 EXPECT_FALSE(s.contains(42));
163 EXPECT_EQ(s.find(42), s.end());
164 EXPECT_EQ(s.begin(), s.end());
165 EXPECT_EQ(s.count(42), 0u);
166}
167
168TEST(FlatSet, InsertKeepsSortedOrderAndRejectsDuplicates)
169{
170 FlatSet<int> s;
171 EXPECT_TRUE(s.insert(5).second);
172 EXPECT_TRUE(s.insert(1).second);
173 EXPECT_TRUE(s.insert(3).second);
174 EXPECT_FALSE(s.insert(3).second); // duplicate
175
176 ASSERT_EQ(s.size(), 3u);
177 EXPECT_EQ(s.nth(0), 1);
178 EXPECT_EQ(s.nth(1), 3);
179 EXPECT_EQ(s.nth(2), 5);
180
181 // The iterator returned on a duplicate points to the existing element.
182 auto [it, inserted] = s.insert(1);
183 EXPECT_FALSE(inserted);
184 EXPECT_EQ(*it, 1);
185 EXPECT_EQ(it, s.begin());
186}
187
188TEST(FlatSet, InitializerListDropsDuplicates)
189{
190 FlatSet<int> s = {5, 1, 3, 1, 5, 5};
191 ASSERT_EQ(s.size(), 3u);
192 EXPECT_EQ(s.nth(0), 1);
193 EXPECT_EQ(s.nth(1), 3);
194 EXPECT_EQ(s.nth(2), 5);
195}
196
197TEST(FlatSet, RangeConstructor)
198{
199 const std::vector<int> v = {9, 7, 7, 8, 1};
200 FlatSet<int> s(v.begin(), v.end());
201 ASSERT_EQ(s.size(), 4u);
202 EXPECT_TRUE(std::is_sorted(s.begin(), s.end()));
203 EXPECT_TRUE(s.contains(7));
204 EXPECT_TRUE(s.contains(9));
205 EXPECT_FALSE(s.contains(2));
206}
207
208TEST(FlatSet, LookupBoundsAndEqualRange)
209{
210 const FlatSet<int> s = {10, 20, 30, 40};
211
212 EXPECT_EQ(*s.lower_bound(20), 20);
213 EXPECT_EQ(*s.lower_bound(25), 30);
214 EXPECT_EQ(*s.upper_bound(20), 30);
215 EXPECT_EQ(s.lower_bound(50), s.end());
216 EXPECT_EQ(s.upper_bound(40), s.end());
217 EXPECT_EQ(*s.lower_bound(5), 10);
218
219 auto [lo, hi] = s.equal_range(30);
220 ASSERT_EQ(hi - lo, 1);
221 EXPECT_EQ(*lo, 30);
222
223 auto [lo2, hi2] = s.equal_range(35);
224 EXPECT_EQ(lo2, hi2);
225}
226
227TEST(FlatSet, EraseByKeyAndIterator)
228{
229 FlatSet<int> s = {1, 2, 3, 4, 5};
230
231 EXPECT_EQ(s.erase(3), 1u);
232 EXPECT_EQ(s.erase(3), 0u); // already gone
233 EXPECT_EQ(s.size(), 4u);
234 EXPECT_FALSE(s.contains(3));
235
236 auto it = s.find(2);
237 ASSERT_NE(it, s.end());
238 it = s.erase(it);
239 EXPECT_EQ(*it, 4); // element following the erased one
240 EXPECT_EQ(s.size(), 3u);
241
242 // Erasing an end iterator must throw out_of_range.
243 EXPECT_THROW((void) s.erase(s.end()), std::out_of_range);
244}
245
246TEST(FlatSet, MinMaxAndCheckedAccess)
247{
248 FlatSet<int> s = {7, 3, 9};
249 EXPECT_EQ(s.get_first(), 3);
250 EXPECT_EQ(s.get_last(), 9);
251 EXPECT_EQ(s.min(), 3);
252 EXPECT_EQ(s.max(), 9);
253 EXPECT_THROW((void) s.nth(3), std::out_of_range);
254
255 const FlatSet<int> e;
256 EXPECT_THROW((void) e.get_first(), std::underflow_error);
257 EXPECT_THROW((void) e.get_last(), std::underflow_error);
258}
259
260TEST(FlatSet, AlephConventionsEmptyClearTraverse)
261{
262 FlatSet<int> s = {1, 2, 3};
263
264 // Aleph convention: empty() clears, is_empty() tests.
265 s.empty();
266 EXPECT_TRUE(s.is_empty());
267
268 s = {4, 5, 6, 7};
269 s.clear();
270 EXPECT_TRUE(s.is_empty());
271
272 s = {1, 2, 3, 4};
273 int sum = 0;
274 EXPECT_TRUE(s.traverse([&sum] (const int &x) { sum += x; return true; }));
275 EXPECT_EQ(sum, 10);
276
277 // Early stop: visit only until (and including) the first even key.
278 int visited = 0;
279 EXPECT_FALSE(s.traverse([&visited] (const int &x)
280 {
281 ++visited;
282 return x % 2 != 0;
283 }));
284 EXPECT_EQ(visited, 2); // 1 (odd, continue), 2 (even, stop)
285}
286
287TEST(FlatSet, CopyMoveAndEquality)
288{
289 FlatSet<std::string> s = {"beta", "alpha", "gamma"};
291 EXPECT_EQ(copy, s);
292
293 FlatSet<std::string> moved = std::move(copy);
294 EXPECT_EQ(moved, s);
295
296 moved.insert("delta");
297 EXPECT_NE(moved, s);
298
299 FlatSet<std::string> assigned;
300 assigned = s;
301 EXPECT_EQ(assigned, s);
302
303 FlatSet<std::string> move_assigned;
304 move_assigned = std::move(assigned);
305 EXPECT_EQ(move_assigned, s);
306}
307
308TEST(FlatSet, CustomComparatorDescendingOrder)
309{
310 FlatSet<int, std::greater<int>> s = {1, 5, 3};
311 EXPECT_EQ(s.nth(0), 5);
312 EXPECT_EQ(s.nth(1), 3);
313 EXPECT_EQ(s.nth(2), 1);
314 EXPECT_TRUE(s.contains(3));
315 EXPECT_FALSE(s.insert(5).second);
316}
317
318TEST(FlatSet, ReserveAndCapacity)
319{
320 FlatSet<int> s;
321 s.reserve(1000);
322 const size_t cap = s.capacity();
323 EXPECT_GE(cap, 1000u);
324 for (int i = 0; i < 1000; ++i)
325 s.insert(i);
326 EXPECT_EQ(s.capacity(), cap); // no reallocation after reserve
327 EXPECT_EQ(s.size(), 1000u);
328}
329
330TEST(FlatSet, DataIsSortedContiguousStorage)
331{
332 FlatSet<int> s = {4, 2, 8, 6};
333 const int *p = s.data();
334 ASSERT_EQ(s.size(), 4u);
335 EXPECT_EQ(p[0], 2);
336 EXPECT_EQ(p[3], 8);
337 EXPECT_EQ(s.begin(), p);
338 EXPECT_EQ(s.end(), p + 4);
339}
340
341TEST(FlatSet, SwapExchangesContents)
342{
343 FlatSet<int> a = {1, 2};
344 FlatSet<int> b = {9};
345 a.swap(b);
346 EXPECT_EQ(a.size(), 1u);
347 EXPECT_TRUE(a.contains(9));
348 EXPECT_EQ(b.size(), 2u);
349 EXPECT_TRUE(b.contains(1) and b.contains(2));
350}
351
352// Randomized parity test: FlatSet must behave exactly like std::set under
353// an arbitrary interleaving of insertions, removals and lookups.
354TEST(FlatSet, RandomizedParityWithStdSet)
355{
356 std::mt19937 rng(20260702);
357 std::uniform_int_distribution<int> key_dist(0, 200);
358 std::uniform_int_distribution<int> op_dist(0, 2);
359
360 FlatSet<int> fs;
361 std::set<int> ref;
362
363 for (int step = 0; step < 4000; ++step)
364 {
365 const int k = key_dist(rng);
366 switch (op_dist(rng))
367 {
368 case 0:
369 EXPECT_EQ(fs.insert(k).second, ref.insert(k).second);
370 break;
371 case 1:
372 EXPECT_EQ(fs.erase(k), ref.erase(k));
373 break;
374 default:
375 EXPECT_EQ(fs.contains(k), ref.count(k) == 1);
376 break;
377 }
378 }
379
380 ASSERT_EQ(fs.size(), ref.size());
381 size_t i = 0;
382 for (const int k : ref)
383 EXPECT_EQ(fs.nth(i++), k);
384}
385
386TEST(FlatSet, CopyThatThrowsLeavesTheSetUntouched)
387{
389 for (const int k : {1, 3, 5, 7})
390 s.insert(Throwing_Copy_Key(k));
391 const Throwing_Copy_Key first(0), middle(4);
392
393 Throwing_Copy_Key::fail = true;
394 EXPECT_THROW(s.insert(first), std::runtime_error);
395 EXPECT_THROW(s.insert(middle), std::runtime_error);
396 Throwing_Copy_Key::fail = false;
397
398 ASSERT_EQ(s.size(), 4u);
399 EXPECT_TRUE(is_strictly_sorted(s));
400 EXPECT_FALSE(s.contains(first));
401 EXPECT_FALSE(s.contains(middle));
402 EXPECT_TRUE(s.contains(Throwing_Copy_Key(5)));
403}
404
405// If moving a key can throw, an insertion, a removal or a reservation
406// interrupted at any of its moves must leave a valid set: either the
407// operation took effect or the set was emptied, never a duplicated key.
408TEST(FlatSet, MoveThatThrowsAtAnyPointLeavesAValidSet)
409{
410 const auto build = []
411 {
413 for (const int k : {1, 3, 5, 7, 9})
414 s.insert(Throwing_Move_Key(k));
415 return s;
416 };
417
418 enum class Operation { insert_first, insert_middle, erase_first, reserve };
419 for (const auto operation : {Operation::insert_first, Operation::insert_middle,
420 Operation::erase_first, Operation::reserve})
421 for (int budget = 0; budget < 12; ++budget)
422 {
423 SCOPED_TRACE(testing::Message() << "operation " << static_cast<int>(operation)
424 << ", moves allowed " << budget);
425 auto s = build();
426 bool thrown = false;
427 Throwing_Move_Key::moves_left = budget;
428 try
429 {
430 switch (operation)
431 {
432 case Operation::insert_first: s.insert(Throwing_Move_Key(0)); break;
433 case Operation::insert_middle: s.insert(Throwing_Move_Key(4)); break;
434 case Operation::erase_first: s.erase(Throwing_Move_Key(1)); break;
435 case Operation::reserve: s.reserve(4 * s.capacity()); break;
436 }
437 }
438 catch (const std::runtime_error &)
439 {
440 thrown = true;
441 }
442 Throwing_Move_Key::moves_left = -1;
443
444 EXPECT_TRUE(is_strictly_sorted(s));
445 if (thrown)
446 EXPECT_TRUE(s.is_empty());
447 else if (operation == Operation::erase_first)
448 EXPECT_EQ(s.size(), 4u);
449 else if (operation == Operation::reserve)
450 EXPECT_EQ(s.size(), 5u);
451 else
452 EXPECT_EQ(s.size(), 6u);
453
454 // the set remains usable in both cases
455 s.insert(Throwing_Move_Key(100));
456 EXPECT_TRUE(s.contains(Throwing_Move_Key(100)));
457 EXPECT_TRUE(is_strictly_sorted(s));
458 }
459
460 // the sweep reached the point where nothing throws
461 auto s = build();
462 Throwing_Move_Key::moves_left = 11;
463 EXPECT_NO_THROW(s.insert(Throwing_Move_Key(0)));
464 Throwing_Move_Key::moves_left = -1;
465}
466
467// The set is emptied only when a move may have left a key half way. A
468// failure that comes before, while the new buffer is obtained, must not
469// cost the keys, whatever the moves of their type declare.
470TEST(FlatSet, FailureBeforeAnyKeyMovesKeepsTheSet)
471{
472 using Key = Failing_Default_Key;
473 ASSERT_FALSE(std::is_nothrow_move_assignable_v<Key>);
474
475 FlatSet<Key> s;
476 for (int k = 0; k < 4; ++k)
477 s.insert(Key(k));
478 ASSERT_EQ(s.size(), s.capacity()); // the next insertion has to grow
479
480 const auto holds_the_four_keys = [&s]
481 {
482 if (s.size() != 4)
483 return false;
484 for (int k = 0; k < 4; ++k)
485 if (s.nth(k).value != k)
486 return false;
487 return true;
488 };
489
490 // a capacity that cannot be rounded up
491 EXPECT_THROW(s.reserve(std::numeric_limits<size_t>::max()), std::overflow_error);
492 EXPECT_TRUE(holds_the_four_keys());
493
494 // the new buffer cannot be built
495 Key::fail = true;
496 EXPECT_THROW(s.reserve(64), std::bad_alloc);
497 EXPECT_THROW(s.insert(Key(9)), std::bad_alloc);
498 Key::fail = false;
499 EXPECT_TRUE(holds_the_four_keys());
500
501 s.insert(Key(9));
502 s.reserve(64);
503 EXPECT_EQ(s.size(), 5u);
504 EXPECT_GE(s.capacity(), 64u);
505 EXPECT_TRUE(s.contains(Key(9)));
506 EXPECT_TRUE(is_strictly_sorted(s));
507}
508
509// An insertion that grows relocates the keys before it shifts them. A move
510// that throws during that relocation empties the set, as one that throws
511// during the shift does.
512TEST(FlatSet, MoveThatThrowsWhileAnInsertionGrowsLeavesAValidSet)
513{
514 bool completed = false;
515 for (int budget = 0; not completed; ++budget)
516 {
517 ASSERT_LT(budget, 64);
518 SCOPED_TRACE(testing::Message() << "moves allowed " << budget);
520 for (int k = 1; k <= 4; ++k)
521 s.insert(Throwing_Move_Key(k));
522 ASSERT_EQ(s.size(), s.capacity());
523
524 Throwing_Move_Key::moves_left = budget;
525 try
526 {
527 s.insert(Throwing_Move_Key(0));
528 completed = true;
529 }
530 catch (const std::runtime_error &)
531 {
532 EXPECT_TRUE(s.is_empty());
533 }
534 Throwing_Move_Key::moves_left = -1;
535
536 EXPECT_TRUE(is_strictly_sorted(s));
537 if (completed)
538 {
539 EXPECT_EQ(s.size(), 5u);
540 EXPECT_GT(budget, 4); // the four keys were relocated and then shifted
541 }
542 s.insert(Throwing_Move_Key(100));
543 EXPECT_TRUE(s.contains(Throwing_Move_Key(100)));
544 EXPECT_TRUE(is_strictly_sorted(s));
545 }
546}
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
size_t size_t int32_t value
Definition ca-c-api.h:116
Ordered set stored as a sorted contiguous array.
size_t capacity() const noexcept
Return the capacity of the backing array. O(1).
const Key & min() const
Smallest key (checked). Alias of get_first().
const_iterator upper_bound(const Key &k) const
First element greater than k.
size_t erase(const Key &k)
Remove the key equivalent to k, if present.
const_iterator end() const noexcept
Iterator past the greatest key. O(1).
const_iterator find(const Key &k) const
Find a key.
void empty() noexcept
Remove all keys (Aleph convention).
size_t count(const Key &k) const
Count occurrences of a key (0 or 1).
std::pair< const_iterator, const_iterator > equal_range(const Key &k) const
Range of elements equivalent to k.
void clear() noexcept
Remove all keys. Alias of empty(). Capacity is kept.
const Key & max() const
Greatest key (checked). Alias of get_last().
bool traverse(Operation operation) const
Traverse keys in sorted order while operation returns true.
const Key * data() const noexcept
Pointer to the underlying sorted, contiguous storage. O(1).
void reserve(size_t cap)
Reserve capacity for at least cap keys.
const_iterator lower_bound(const Key &k) const
First element not less than k.
bool contains(const Key &k) const
Test membership.
size_t size() const noexcept
Return the number of stored keys. O(1).
bool is_empty() const noexcept
Return true if the set holds no keys. O(1).
const Key & get_first() const
Smallest key (checked).
const Key & nth(size_t i) const
Positional access to the i-th smallest key (checked).
std::pair< const_iterator, bool > insert(const Key &k)
Insert a copy of k if no equivalent key exists.
const Key & get_last() const
Greatest key (checked).
void swap(FlatSet &s) noexcept(std::is_nothrow_swappable_v< Compare >)
Swap contents with s in O(1).
const_iterator begin() const noexcept
Iterator to the smallest key. O(1).
#define TEST(name)
static mt19937 rng
bool completed() const noexcept
Return true if all underlying iterators are finished.
Definition ah-zip.H:183
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
and
Check uniqueness with explicit hash + equality functors.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
static int * k
Sorted-array set (Aleph::FlatSet), a cache-friendly ordered set.