Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
flat_map_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 <iterator>
41#include <limits>
42#include <map>
43#include <new>
44#include <random>
45#include <stdexcept>
46#include <string>
47#include <utility>
48#include <vector>
49
50#include <gtest/gtest.h>
51
52#include <tpl_flat_map.H>
53
54using Aleph::FlatMap;
55
56namespace
57{
58// A value whose move assignment throws once a budget of them is spent, to
59// interrupt a shift or a relocation half way. Nothing else throws.
60struct Throwing_Move
61{
62 static inline int moves_left = -1; // -1 means that it never throws
63
64 int value = 0;
65
66 Throwing_Move() = default;
67 Throwing_Move(const int v) : value(v) {}
68 Throwing_Move(const Throwing_Move &) = default;
69 Throwing_Move(Throwing_Move &&) = default;
70 Throwing_Move &operator = (const Throwing_Move &) = default;
71 Throwing_Move &operator = (Throwing_Move &&other)
72 {
73 if (moves_left == 0)
74 throw std::runtime_error("move assignment");
75 if (moves_left > 0)
76 --moves_left;
77 value = other.value;
78 return *this;
79 }
80};
81
82// A value that moves without throwing but whose copies throw on demand.
83struct Throwing_Copy
84{
85 static inline bool fail = false;
86
87 int value = 0;
88
89 Throwing_Copy() = default;
90 Throwing_Copy(const int v) : value(v) {}
91 Throwing_Copy(const Throwing_Copy &other) : value(other.value)
92 {
93 if (fail)
94 throw std::runtime_error("copy");
95 }
96 Throwing_Copy(Throwing_Copy &&) noexcept = default;
97 Throwing_Copy &operator = (const Throwing_Copy &other)
98 {
99 if (fail)
100 throw std::runtime_error("copy assignment");
101 value = other.value;
102 return *this;
103 }
104 Throwing_Copy &operator = (Throwing_Copy &&) noexcept = default;
105};
106
107// A value whose default construction fails on demand, as the allocation of
108// a buffer does: a new buffer is filled with default values before any
109// entry is moved to it. Its moves throw or not, by declaration only.
110template <bool Nothrow_Move>
111struct Failing_Default
112{
113 static inline bool fail = false;
114
115 int value = 0;
116
117 Failing_Default()
118 {
119 if (fail)
120 throw std::bad_alloc();
121 }
122 Failing_Default(const int v) : value(v) {}
123 Failing_Default(const Failing_Default &) = default;
124 Failing_Default(Failing_Default &&other) noexcept(Nothrow_Move) : value(other.value) {}
125 Failing_Default &operator = (const Failing_Default &) = default;
126 Failing_Default &operator = (Failing_Default &&other) noexcept(Nothrow_Move)
127 {
128 value = other.value;
129 return *this;
130 }
131};
132
133// The keys are strictly increasing and each one still has its own value,
134// which every test below sets to ten times the key.
135template <class Map>
136::testing::AssertionResult is_consistent(const Map &m)
137{
138 for (size_t i = 0; i < m.size(); ++i)
139 {
140 if (i > 0 and not (m.nth_key(i - 1) < m.nth_key(i)))
141 return ::testing::AssertionFailure()
142 << "keys " << m.nth_key(i - 1) << " and " << m.nth_key(i)
143 << " at " << i - 1 << " are not strictly increasing";
144 if (m.nth_value(i).value != 10 * m.nth_key(i))
145 return ::testing::AssertionFailure()
146 << "key " << m.nth_key(i) << " holds " << m.nth_value(i).value;
147 }
148 return ::testing::AssertionSuccess();
149}
150
151class Pair_Input_Iterator
152{
153 const std::vector<std::pair<int, std::string>> *items_ = nullptr;
154 size_t pos_ = 0;
155
156public:
157
158 using iterator_category = std::input_iterator_tag;
159 using value_type = std::pair<int, std::string>;
160 using difference_type = std::ptrdiff_t;
161 using pointer = void;
162 using reference = const value_type &;
163
164 Pair_Input_Iterator() = default;
165
166 Pair_Input_Iterator(const std::vector<std::pair<int, std::string>> &items,
167 size_t pos) noexcept
168 : items_(&items), pos_(pos) {}
169
170 reference operator*() const noexcept { return (*items_)[pos_]; }
171
172 Pair_Input_Iterator &operator++() noexcept
173 {
174 ++pos_;
175 return *this;
176 }
177
178 Pair_Input_Iterator operator++(int) noexcept
179 {
180 Pair_Input_Iterator ret = *this;
181 ++(*this);
182 return ret;
183 }
184
185 bool operator==(const Pair_Input_Iterator &it) const noexcept
186 {
187 return items_ == it.items_ and pos_ == it.pos_;
188 }
189
190 bool operator!=(const Pair_Input_Iterator &it) const noexcept
191 {
192 return not (*this == it);
193 }
194};
195} // namespace
196
197TEST(FlatMap, EmptyMapBasics)
198{
200 EXPECT_TRUE(m.is_empty());
201 EXPECT_EQ(m.size(), 0u);
202 EXPECT_FALSE(m.contains("x"));
203 EXPECT_EQ(m.find("x"), m.end());
204 EXPECT_EQ(m.begin(), m.end());
205}
206
207TEST(FlatMap, SubscriptInsertsAndUpdates)
208{
210 m["b"] = 2;
211 m["a"] = 1;
212 m["c"] = 3;
213 ASSERT_EQ(m.size(), 3u);
214
215 m["a"] += 10; // update through subscript
216 EXPECT_EQ(m.at("a"), 11);
217
218 // Absent key gets a default-constructed value.
219 EXPECT_EQ(m["zz"], 0);
220 EXPECT_EQ(m.size(), 4u);
221
222 // Keys must come out sorted.
223 EXPECT_EQ(m.nth_key(0), "a");
224 EXPECT_EQ(m.nth_key(1), "b");
225 EXPECT_EQ(m.nth_key(2), "c");
226 EXPECT_EQ(m.nth_key(3), "zz");
227}
228
229TEST(FlatMap, AtThrowsOnMissingKey)
230{
231 FlatMap<std::string, int> m = {{"a", 1}};
232 EXPECT_EQ(m.at("a"), 1);
233 EXPECT_THROW((void) m.at("nope"), std::out_of_range);
234
235 const FlatMap<std::string, int> &cm = m;
236 EXPECT_EQ(cm.at("a"), 1);
237 EXPECT_THROW((void) cm.at("nope"), std::out_of_range);
238}
239
240TEST(FlatMap, InitializerListDropsDuplicateKeysFirstWins)
241{
242 FlatMap<int, std::string> m = {{3, "three"}, {1, "one"},
243 {3, "THREE"}, {2, "two"}};
244 ASSERT_EQ(m.size(), 3u);
245 EXPECT_EQ(m.at(3), "three"); // first occurrence wins
246 EXPECT_EQ(m.nth_key(0), 1);
247 EXPECT_EQ(m.nth_key(2), 3);
248}
249
250TEST(FlatMap, RangeConstructorAcceptsIteratorsWithoutArrow)
251{
252 const std::vector<std::pair<int, std::string>> items =
253 {{3, "three"}, {1, "one"}, {2, "two"}};
254
255 FlatMap<int, std::string> m(Pair_Input_Iterator(items, 0),
256 Pair_Input_Iterator(items, items.size()));
257
258 ASSERT_EQ(m.size(), 3u);
259 EXPECT_EQ(m.at(1), "one");
260 EXPECT_EQ(m.at(2), "two");
261 EXPECT_EQ(m.at(3), "three");
262}
263
264// The map's own iterators yield a (key, value) proxy with no common
265// reference with std::pair, so they do not model std::input_iterator; the
266// range constructor must still accept them.
267TEST(FlatMap, RangeConstructorAcceptsOwnIteratorAndConstIterator)
268{
269 FlatMap<int, std::string> src = {{2, "two"}, {1, "one"}, {3, "three"}};
270 const FlatMap<int, std::string> &csrc = src;
271
272 FlatMap<int, std::string> from_it(src.begin(), src.end());
273 FlatMap<int, std::string> from_cit(csrc.begin(), csrc.end());
274 FlatMap<int, std::string> from_tail(src.begin() + 1, src.end());
275
276 EXPECT_EQ(from_it, src);
277 EXPECT_EQ(from_cit, src);
278 ASSERT_EQ(from_tail.size(), 2u);
279 EXPECT_FALSE(from_tail.contains(1));
280 EXPECT_EQ(from_tail.at(3), "three");
281}
282
283TEST(FlatMap, InsertRejectsDuplicateInsertOrAssignOverwrites)
284{
286 EXPECT_TRUE(m.insert(1, 100).second);
287 EXPECT_FALSE(m.insert(1, 999).second);
288 EXPECT_EQ(m.at(1), 100); // original value kept
289
290 EXPECT_FALSE(m.insert_or_assign(1, 999).second);
291 EXPECT_EQ(m.at(1), 999); // overwritten
292
293 EXPECT_TRUE(m.insert_or_assign(2, 200).second);
294 EXPECT_EQ(m.at(2), 200);
295
296 // Pair-based insert.
297 EXPECT_TRUE(m.insert(std::pair<int, int>(3, 300)).second);
298 EXPECT_EQ(m.at(3), 300);
299}
300
301TEST(FlatMap, EraseByKeyAndIterator)
302{
303 FlatMap<int, int> m = {{1, 10}, {2, 20}, {3, 30}, {4, 40}};
304
305 EXPECT_EQ(m.erase(2), 1u);
306 EXPECT_EQ(m.erase(2), 0u);
307 EXPECT_EQ(m.size(), 3u);
308
309 auto it = m.find(3);
310 ASSERT_NE(it, m.end());
311 it = m.erase(it);
312 EXPECT_EQ((*it).first, 4); // entry following the erased one
313 EXPECT_EQ(m.size(), 2u);
314
315 EXPECT_THROW((void) m.erase(m.end()), std::out_of_range);
316}
317
318TEST(FlatMap, ProxyIterationAndStructuredBindings)
319{
320 FlatMap<std::string, int> m = {{"b", 2}, {"a", 1}, {"c", 3}};
321
322 std::vector<std::string> ks;
323 int sum = 0;
324 for (auto [k, v] : m)
325 {
326 ks.push_back(k);
327 sum += v;
328 }
329 EXPECT_EQ(ks, (std::vector<std::string>{"a", "b", "c"}));
330 EXPECT_EQ(sum, 6);
331
332 // Mutation through the iterator proxy.
333 for (auto [k, v] : m)
334 v *= 10;
335 EXPECT_EQ(m.at("a"), 10);
336 EXPECT_EQ(m.at("b"), 20);
337 EXPECT_EQ(m.at("c"), 30);
338
339 // Arrow access.
340 auto it = m.find("b");
341 ASSERT_NE(it, m.end());
342 EXPECT_EQ(it->first, "b");
343 it->second = 7;
344 EXPECT_EQ(m.at("b"), 7);
345}
346
347TEST(FlatMap, IteratorRandomAccessOperations)
348{
349 FlatMap<int, int> m = {{1, 10}, {2, 20}, {3, 30}, {4, 40}};
350
351 auto it = m.begin();
352 EXPECT_EQ(m.end() - it, 4);
353 EXPECT_EQ((it + 2)->first, 3);
354 EXPECT_EQ(it[3].second, 40);
355 ++it;
356 --it;
357 EXPECT_EQ(it->first, 1);
358 EXPECT_TRUE(it < m.end());
359
360 // Mutable-to-const iterator conversion.
362 EXPECT_EQ(cit->second, 10);
363}
364
365TEST(FlatMap, BoundsAndEqualRange)
366{
367 const FlatMap<int, int> m = {{10, 1}, {20, 2}, {30, 3}};
368
369 EXPECT_EQ(m.lower_bound(20)->first, 20);
370 EXPECT_EQ(m.lower_bound(25)->first, 30);
371 EXPECT_EQ(m.upper_bound(20)->first, 30);
372 EXPECT_EQ(m.lower_bound(31), m.end());
373
374 auto [lo, hi] = m.equal_range(20);
375 EXPECT_EQ(hi - lo, 1);
376 auto [lo2, hi2] = m.equal_range(15);
377 EXPECT_EQ(lo2, hi2);
378}
379
380TEST(FlatMap, KeysAndValuesLists)
381{
382 FlatMap<std::string, int> m = {{"b", 2}, {"a", 1}, {"c", 3}};
383
384 auto ks = m.keys();
385 auto vs = m.values();
386 ASSERT_EQ(ks.size(), 3u);
387 ASSERT_EQ(vs.size(), 3u);
388 EXPECT_EQ(ks.get_first(), "a");
389 EXPECT_EQ(ks.get_last(), "c");
390 EXPECT_EQ(vs.get_first(), 1);
391 EXPECT_EQ(vs.get_last(), 3);
392}
393
394TEST(FlatMap, TraverseMutatingAndEarlyStop)
395{
396 FlatMap<int, int> m = {{1, 1}, {2, 2}, {3, 3}};
397
398 EXPECT_TRUE(m.traverse([] (const int &, int &v) { v += 100; return true; }));
399 EXPECT_EQ(m.at(1), 101);
400
401 int visited = 0;
402 const FlatMap<int, int> &cm = m;
403 EXPECT_FALSE(cm.traverse([&visited] (const int &k, const int &)
404 {
405 ++visited;
406 return k < 2;
407 }));
408 EXPECT_EQ(visited, 2);
409}
410
411TEST(FlatMap, CopyMoveEqualityAndSwap)
412{
413 FlatMap<std::string, int> m = {{"x", 1}, {"y", 2}};
415 EXPECT_EQ(copy, m);
416
417 FlatMap<std::string, int> moved = std::move(copy);
418 EXPECT_EQ(moved, m);
419
420 moved["z"] = 3;
421 EXPECT_NE(moved, m);
422
423 FlatMap<std::string, int> other = {{"q", 9}};
424 m.swap(other);
425 EXPECT_EQ(m.size(), 1u);
426 EXPECT_EQ(m.at("q"), 9);
427 EXPECT_EQ(other.size(), 2u);
428}
429
430TEST(FlatMap, CustomComparatorDescendingOrder)
431{
433 = {{1, "one"}, {5, "five"}, {3, "three"}};
434 EXPECT_EQ(m.nth_key(0), 5);
435 EXPECT_EQ(m.nth_key(1), 3);
436 EXPECT_EQ(m.nth_key(2), 1);
437 EXPECT_EQ(m.at(3), "three");
438}
439
440TEST(FlatMap, ParallelStorageAccessors)
441{
442 FlatMap<int, int> m = {{2, 20}, {1, 10}, {3, 30}};
443 const int *kp = m.keys_data();
444 const int *vp = m.values_data();
445 for (size_t i = 0; i < m.size(); ++i)
446 EXPECT_EQ(vp[i], kp[i] * 10);
447}
448
449// Randomized parity test: FlatMap must behave exactly like std::map under
450// an arbitrary interleaving of subscripts, inserts, erases and lookups.
451TEST(FlatMap, RandomizedParityWithStdMap)
452{
453 std::mt19937 rng(20260702);
454 std::uniform_int_distribution<int> key_dist(0, 150);
455 std::uniform_int_distribution<int> val_dist(0, 1000000);
456 std::uniform_int_distribution<int> op_dist(0, 3);
457
459 std::map<int, int> ref;
460
461 for (int step = 0; step < 4000; ++step)
462 {
463 const int k = key_dist(rng);
464 const int v = val_dist(rng);
465 switch (op_dist(rng))
466 {
467 case 0:
468 fm[k] = v;
469 ref[k] = v;
470 break;
471 case 1:
472 EXPECT_EQ(fm.insert(k, v).second, ref.insert({k, v}).second);
473 break;
474 case 2:
475 EXPECT_EQ(fm.erase(k), ref.erase(k));
476 break;
477 default:
478 {
479 const auto it = ref.find(k);
480 if (it == ref.end())
481 EXPECT_FALSE(fm.contains(k));
482 else
483 EXPECT_EQ(fm.at(k), it->second);
484 }
485 break;
486 }
487 }
488
489 ASSERT_EQ(fm.size(), ref.size());
490 size_t i = 0;
491 for (const auto &[k, v] : ref)
492 {
493 EXPECT_EQ(fm.nth_key(i), k);
494 EXPECT_EQ(fm.nth_value(i), v);
495 ++i;
496 }
497}
498
499TEST(FlatMap, InsertedValueMayBeAnEntryOfTheSameMap)
500{
502 const std::string thirty(40, 'c'); // longer than any small-string buffer
503 m.insert(1, std::string(40, 'a'));
504 m.insert(3, thirty);
505 m.insert(5, std::string(40, 'e'));
506
507 // without growth: the shift moves the value of 3 before it is read
508 ASSERT_LT(m.size(), m.capacity());
509 EXPECT_TRUE(m.insert(0, m.at(3)).second);
510 EXPECT_EQ(m.at(0), thirty);
511 EXPECT_EQ(m.at(3), thirty);
512
513 // with growth: the reallocation frees the buffer that holds the value
514 int next = 100;
515 while (m.size() < m.capacity())
516 m.insert(next++, std::string(40, 'x'));
517 EXPECT_TRUE(m.insert(next, m.at(3)).second);
518 EXPECT_EQ(m.at(next), thirty);
519
520 while (m.size() < m.capacity())
521 m.insert(++next, std::string(40, 'x'));
522 EXPECT_TRUE(m.insert_or_assign(-1, m.at(3)).second);
523 EXPECT_EQ(m.at(-1), thirty);
524
525 while (m.size() < m.capacity())
526 m.insert(++next, std::string(40, 'x'));
527 EXPECT_TRUE(m.insert(-2, std::move(m.at(0))).second);
528 EXPECT_EQ(m.at(-2), thirty);
529}
530
531TEST(FlatMap, InsertedKeyMayBeAValueOfTheSameMap)
532{
534 m.insert(1, 10);
535 m.insert(3, 30);
536 m.insert(5, 50);
537
538 ASSERT_LT(m.size(), m.capacity());
539 EXPECT_TRUE(m.insert(m.at(1), 7).second); // the key is the value 10
540 EXPECT_EQ(m.at(10), 7);
541
542 m[m.at(3)] = 8; // the key is the value 30
543 EXPECT_EQ(m.at(30), 8);
544
545 int next = 100;
546 while (m.size() < m.capacity())
547 m.insert(next++, 0);
548 m[m.at(5)] = 9; // the key is the value 50, and the arrays grow
549 EXPECT_EQ(m.at(50), 9);
550 EXPECT_EQ(m.at(5), 50);
551}
552
553TEST(FlatMap, CopyThatThrowsLeavesTheMapUntouched)
554{
556 for (const int k : {1, 3, 5, 7})
557 m.insert(k, Throwing_Copy(10 * k));
558 const Throwing_Copy value(0);
559
560 Throwing_Copy::fail = true;
561 EXPECT_THROW(m.insert(0, value), std::runtime_error);
562 EXPECT_THROW(m.insert(4, value), std::runtime_error);
563 EXPECT_THROW(m.insert_or_assign(9, value), std::runtime_error);
564 Throwing_Copy::fail = false;
565
566 ASSERT_EQ(m.size(), 4u);
567 EXPECT_TRUE(is_consistent(m));
568 EXPECT_FALSE(m.contains(0));
569 EXPECT_FALSE(m.contains(4));
570 EXPECT_FALSE(m.contains(9));
571}
572
573TEST(FlatMap, CopyAssignmentThatThrowsLeavesTheTargetUntouched)
574{
576 for (const int k : {2, 4, 6, 8, 10})
577 source.insert(k, Throwing_Copy(10 * k));
579 target.insert(1, Throwing_Copy(10));
580
581 Throwing_Copy::fail = true;
582 EXPECT_THROW(target = source, std::runtime_error);
583 Throwing_Copy::fail = false;
584
585 ASSERT_EQ(target.size(), 1u);
586 EXPECT_EQ(target.nth_key(0), 1);
587 EXPECT_EQ(target.nth_value(0).value, 10);
588
589 target = source;
590 ASSERT_EQ(target.size(), 5u);
591 EXPECT_TRUE(is_consistent(target));
592}
593
594// If moving a value can throw, an insertion, a removal or a reservation
595// interrupted at any of its moves must leave a valid map: either the
596// operation took effect or the map was emptied, never a duplicated key or a
597// key apart from its value.
598TEST(FlatMap, MoveThatThrowsAtAnyPointLeavesAValidMap)
599{
600 const auto build = []
601 {
603 for (const int k : {1, 3, 5, 7, 9})
604 m.insert(k, Throwing_Move(10 * k));
605 return m;
606 };
607
608 enum class Operation { insert_first, insert_middle, erase_first, reserve };
609 for (const auto operation : {Operation::insert_first, Operation::insert_middle,
610 Operation::erase_first, Operation::reserve})
611 for (int budget = 0; budget < 12; ++budget)
612 {
613 SCOPED_TRACE(testing::Message() << "operation " << static_cast<int>(operation)
614 << ", moves allowed " << budget);
615 auto m = build();
616 bool thrown = false;
617 Throwing_Move::moves_left = budget;
618 try
619 {
620 switch (operation)
621 {
622 case Operation::insert_first: m.insert(0, Throwing_Move(0)); break;
623 case Operation::insert_middle: m.insert(4, Throwing_Move(40)); break;
624 case Operation::erase_first: m.erase(1); break;
625 case Operation::reserve: m.reserve(4 * m.capacity()); break;
626 }
627 }
628 catch (const std::runtime_error &)
629 {
630 thrown = true;
631 }
632 Throwing_Move::moves_left = -1;
633
634 EXPECT_TRUE(is_consistent(m));
635 if (thrown)
636 EXPECT_TRUE(m.is_empty());
637 else if (operation == Operation::erase_first)
638 EXPECT_EQ(m.size(), 4u);
639 else if (operation == Operation::reserve)
640 EXPECT_EQ(m.size(), 5u);
641 else
642 EXPECT_EQ(m.size(), 6u);
643
644 // the map remains usable in both cases
645 m.insert(100, Throwing_Move(1000));
646 EXPECT_TRUE(m.contains(100));
647 EXPECT_TRUE(is_consistent(m));
648 }
649
650 // the sweep reached the point where nothing throws
651 auto m = build();
652 Throwing_Move::moves_left = 11;
653 EXPECT_NO_THROW(m.insert(0, Throwing_Move(0)));
654 Throwing_Move::moves_left = -1;
655}
656
657// The map is emptied only when a move may have left an entry half way. A
658// failure that comes before, while the new buffers are obtained, must not
659// cost the entries, whatever the moves of their types declare.
660TEST(FlatMap, FailureBeforeAnyEntryMovesKeepsTheMap)
661{
662 using Value = Failing_Default<false>;
663 ASSERT_FALSE(std::is_nothrow_move_assignable_v<Value>);
664
666 for (int k = 0; k < 4; ++k)
667 m.insert(k, Value(10 * k));
668 ASSERT_EQ(m.size(), m.capacity()); // the next insertion has to grow
669
670 // a capacity that cannot be rounded up
671 EXPECT_THROW(m.reserve(std::numeric_limits<size_t>::max()), std::overflow_error);
672 EXPECT_EQ(m.size(), 4u);
673 EXPECT_TRUE(is_consistent(m));
674
675 // the buffer of the values cannot be built, with that of the keys already in place
676 Value::fail = true;
677 EXPECT_THROW(m.reserve(64), std::bad_alloc);
678 EXPECT_THROW(m.insert(9, Value(90)), std::bad_alloc);
679 EXPECT_THROW(m.insert_or_assign(9, Value(90)), std::bad_alloc);
680 Value::fail = false;
681 EXPECT_EQ(m.size(), 4u);
682 EXPECT_TRUE(is_consistent(m));
683 EXPECT_FALSE(m.contains(9));
684
685 m.insert(9, Value(90));
686 m.reserve(64);
687 EXPECT_EQ(m.size(), 5u);
688 EXPECT_GE(m.capacity(), 64u);
689 EXPECT_TRUE(is_consistent(m));
690}
691
692// An insertion that grows relocates the entries before it shifts them. A
693// move that throws during that relocation empties the map, as one that
694// throws during the shift does.
695TEST(FlatMap, MoveThatThrowsWhileAnInsertionGrowsLeavesAValidMap)
696{
697 bool completed = false;
698 for (int budget = 0; not completed; ++budget)
699 {
700 ASSERT_LT(budget, 64);
701 SCOPED_TRACE(testing::Message() << "moves allowed " << budget);
703 for (int k = 1; k <= 4; ++k)
704 m.insert(k, Throwing_Move(10 * k));
705 ASSERT_EQ(m.size(), m.capacity());
706
707 Throwing_Move::moves_left = budget;
708 try
709 {
710 m.insert(0, Throwing_Move(0));
711 completed = true;
712 }
713 catch (const std::runtime_error &)
714 {
715 EXPECT_TRUE(m.is_empty());
716 }
717 Throwing_Move::moves_left = -1;
718
719 EXPECT_TRUE(is_consistent(m));
720 if (completed)
721 {
722 EXPECT_EQ(m.size(), 5u);
723 EXPECT_GT(budget, 4); // the four entries were relocated and then shifted
724 }
725 m.insert(100, Throwing_Move(1000));
726 EXPECT_TRUE(m.contains(100));
727 EXPECT_TRUE(is_consistent(m));
728 }
729}
730
731// A map emptied by a move has no storage. If only one of its two arrays
732// gets a buffer, the map must not be left with a key and no value.
733TEST(FlatMap, FailedGrowthOfAMapEmptiedByAMoveLeavesItEmpty)
734{
735 for (const bool nothrow_move : {true, false})
736 {
737 SCOPED_TRACE(testing::Message() << "nothrow move " << nothrow_move);
738 const auto check = [] <class Value> (Value)
739 {
740 FlatMap<int, Value> source;
741 source.insert(1, Value(10));
742 FlatMap<int, Value> taken(std::move(source));
743 ASSERT_EQ(source.capacity(), 0u);
744
745 Value::fail = true; // the keys get their buffer, the values do not
746 EXPECT_THROW(source.insert(2, Value(20)), std::bad_alloc);
747 Value::fail = false;
748 ASSERT_TRUE(source.is_empty());
749 EXPECT_TRUE(source.begin() == source.end());
750
751 source.insert(2, Value(20));
752 EXPECT_EQ(source.size(), 1u);
753 EXPECT_TRUE(is_consistent(source));
754 EXPECT_EQ(taken.size(), 1u);
755 EXPECT_TRUE(is_consistent(taken));
756 };
757 if (nothrow_move)
758 check(Failing_Default<true>(0));
759 else
760 check(Failing_Default<false>(0));
761 }
762}
bool operator==(const Time &l, const Time &r)
Definition ah-time.H:134
size_t size_t int32_t value
Definition ca-c-api.h:116
Random-access proxy iterator over (key, value) entries.
Ordered map stored as two parallel sorted contiguous arrays.
const Key & nth_key(size_t i) const
Key of the i-th entry in sorted order (checked).
std::pair< iterator, bool > insert(const Key &k, const T &v)
Insert (k, v) if k is not mapped.
T & nth_value(size_t i)
Value of the i-th entry in sorted order (checked).
bool contains(const Key &k) const
Test whether key k is mapped.
size_t erase(const Key &k)
Remove the entry with key k, if present.
T & at(const Key &k)
Checked access to the value mapped to k.
bool traverse(Operation operation)
Traverse entries in key order while operation returns true.
iterator begin() noexcept
Iterator to the entry with the smallest key. O(1).
size_t size() const noexcept
Return the number of stored entries. O(1).
iterator end() noexcept
Iterator past the entry with the greatest key. O(1).
void swap(ODhashTable &other) noexcept
Swaps this table with other in constant time.
Definition tpl_odhash.H:470
constexpr bool contains(const Key &key) const noexcept
Alias for has().
Definition hashDry.H:769
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
constexpr size_t capacity() const noexcept
Returns the current capacity of the table.
Definition hashDry.H:964
constexpr bool is_empty() const noexcept
Checks if the table is empty.
Definition hashDry.H:959
DynList< Key > keys() const
Returns a list containing all keys in the table.
Definition hashDry.H:1247
Key * insert(const Key &key)
Inserts a key into the hash table (copy version).
Definition hashDry.H:507
Key & find(const Key &key)
Finds a key and returns a reference to it.
Definition hashDry.H:782
iterator end() noexcept
Return an STL-compatible end iterator.
iterator begin() noexcept
Return an STL-compatible iterator to the first element.
#define TEST(name)
static mt19937 rng
bool operator!=(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4120
bool completed() const noexcept
Return true if all underlying iterators are finished.
Definition ah-zip.H:183
@ Value
Regular runtime payload stored as Interpreter_Value.
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.
Matrix< Trow, Tcol, NumType > operator*(const NumType &scalar, const Matrix< Trow, Tcol, NumType > &m)
Scalar-matrix multiplication (scalar * matrix).
Definition al-matrix.H:1228
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
bool traverse(Operation &operation) noexcept(traverse_is_noexcept< Operation, typename Aleph::concepts_detail::traverse_arg< Container, Operation >::type, Container & >())
Traverse the container via its iterator and performs a conditioned operation on each item.
Definition ah-dry.H:411
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
bool check(GT &g)
static int * k
Sorted-array map (Aleph::FlatMap), a cache-friendly ordered map.