Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
throwing_copy_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
50# include <stdexcept>
51# include <string>
52# include <tuple>
53# include <type_traits>
54# include <utility>
55
56# include <gtest/gtest.h>
57# include <gtest/gtest-spi.h>
58
59# include <ah-zip.H>
60# include <htlist.H>
61# include <tpl_array.H>
62# include <tpl_dnode.H>
63# include <tpl_dynArray.H>
64# include <tpl_dynMapTree.H>
65# include <tpl_dynMapOhash.H>
66# include <tpl_dynSetHash.H>
67# include <tpl_odhash.H>
68# include <tpl_olhash.H>
69# include <tpl_binHeap.H>
70
71using namespace Aleph;
72
73namespace
74{
75 // What an item throws when the test asks one of its operations to fail
76 struct Injected_Failure : public std::runtime_error
77 {
78 using std::runtime_error::runtime_error;
79 };
80
81 // The operations of the items that may fail. While a Failing_From
82 // lives, they fail from the k-th on.
83 struct Failures
84 {
85 static inline long countdown = -1; // that still succeed; negative: none fails
86 static inline long fired = 0; // that failed
87 static inline long done = 0; // that were tried
88 static inline long defaults = 0; // of them, default constructions
89 static inline long alive = 0; // items alive
90
91 static void hit(const char * operation)
92 {
93 ++done;
94 if (countdown == 0)
95 {
96 ++fired;
97 throw Injected_Failure(operation);
98 }
99 if (countdown > 0)
100 --countdown;
101 }
102 };
103
104 class Failing_From
105 {
106 public:
107 explicit Failing_From(const long k) noexcept
108 {
109 Failures::countdown = k;
110 Failures::fired = 0;
111 Failures::done = 0;
112 }
113
114 ~Failing_From() { Failures::countdown = -1; }
115
116 Failing_From(const Failing_From &) = delete;
117 Failing_From & operator = (const Failing_From &) = delete;
118 };
119
120 // An item whose copy fails when asked to. It has no move constructor,
121 // so building one from an rvalue copies it too.
122 struct Copy_Fails
123 {
124 long value = 0;
125
126 Copy_Fails() noexcept { ++Failures::alive; }
127
128 Copy_Fails(const long v) noexcept : value(v) { ++Failures::alive; }
129
130 Copy_Fails(const Copy_Fails & item) : value(item.value)
131 {
132 Failures::hit("copy");
133 ++Failures::alive;
134 }
135
136 Copy_Fails & operator = (const Copy_Fails & item)
137 {
138 Failures::hit("copy assignment");
139 value = item.value;
140 return *this;
141 }
142
143 ~Copy_Fails() { --Failures::alive; }
144
145 bool operator < (const Copy_Fails & item) const noexcept { return value < item.value; }
146
147 bool operator == (const Copy_Fails & item) const noexcept { return value == item.value; }
148 };
149
150 // An item whose move fails when asked to; its copy does not fail
151 struct Move_Fails
152 {
153 long value = 0;
154
155 Move_Fails() noexcept { ++Failures::alive; }
156
157 Move_Fails(const long v) noexcept : value(v) { ++Failures::alive; }
158
159 Move_Fails(const Move_Fails & item) noexcept : value(item.value) { ++Failures::alive; }
160
161 Move_Fails(Move_Fails && item) : value(item.value)
162 {
163 Failures::hit("move");
164 ++Failures::alive;
165 }
166
167 Move_Fails & operator = (const Move_Fails & item) noexcept
168 {
169 value = item.value;
170 return *this;
171 }
172
173 Move_Fails & operator = (Move_Fails && item)
174 {
175 Failures::hit("move assignment");
176 value = item.value;
177 return *this;
178 }
179
180 ~Move_Fails() { --Failures::alive; }
181
182 bool operator < (const Move_Fails & item) const noexcept { return value < item.value; }
183
184 bool operator == (const Move_Fails & item) const noexcept { return value == item.value; }
185 };
186
187 // An item whose default construction fails when asked to
188 struct Default_Fails
189 {
190 long value = 0;
191
192 Default_Fails()
193 {
194 ++Failures::defaults;
195 Failures::hit("default construction");
196 ++Failures::alive;
197 }
198
199 Default_Fails(const long v) noexcept : value(v) { ++Failures::alive; }
200
201 Default_Fails(const Default_Fails & item) noexcept : value(item.value) { ++Failures::alive; }
202
203 Default_Fails & operator = (const Default_Fails & item) noexcept = default;
204
205 ~Default_Fails() { --Failures::alive; }
206
207 bool operator < (const Default_Fails & item) const noexcept { return value < item.value; }
208
209 bool operator == (const Default_Fails & item) const noexcept { return value == item.value; }
210 };
211
212 long value_of(const long v) noexcept { return v; }
213
214 long value_of(const Copy_Fails & item) noexcept { return item.value; }
215
216 size_t hash_of(const Copy_Fails & item) noexcept
217 {
218 return static_cast<size_t>(item.value) * 2654435761u;
219 }
220
221 // More operations than any call here makes
222 constexpr long Max_Failure_Point = 100000;
223
224 // Calls op(fixture) on a new Fixture for each k = 0, 1, ..., with the
225 // operations of the items failing from the k-th on, until op completes
226 // before the k-th. A failure must reach the caller if lets_through, and
227 // must not otherwise. Then valid(fixture, threw) checks the fixture, and
228 // destroying it must leave as many items alive as before building it.
229 // An op that makes no operation that can fail tests nothing: it fails
230 // the test.
231 template <class Fixture, class Op, class Valid>
232 void try_every_failure(const std::string & what, const bool lets_through,
233 Op op, Valid valid)
234 {
235 for (long k = 0; k < Max_Failure_Point; ++k)
236 {
237 SCOPED_TRACE(what + ", failing from the operation " + std::to_string(k));
238 const long alive = Failures::alive;
239 long fired = 0;
240 {
241 Fixture fixture;
242 bool threw = false;
243 {
244 Failing_From failing(k);
245 try
246 {
247 op(fixture);
248 }
249 catch (const Injected_Failure &)
250 {
251 threw = true;
252 }
253 fired = Failures::fired;
254 }
255
256 if (lets_through)
257 EXPECT_EQ(threw, fired > 0) << "a failure did not reach the caller";
258 else
259 EXPECT_FALSE(threw) << "a failure reached the caller";
260 valid(fixture, threw);
261 }
262 EXPECT_EQ(Failures::alive, alive) << "items leaked or destroyed twice";
263 if (fired == 0)
264 {
265 if (k == 0)
266 ADD_FAILURE() << what << " made no operation that can fail: nothing was tested";
267 return;
268 }
269 }
270 ADD_FAILURE() << what << " made more than " << Max_Failure_Point << " operations";
271 }
272
273 // The harness: an operation that makes no operation that can fail, as a
274 // set_hash_fct() that would not change the function, completes at the
275 // first try with the fixture as it was; it must fail the test instead of
276 // passing it
277 TEST(Failure_Harness, AnOperationThatCannotFailFailsTheTest)
278 {
279 struct Nothing {};
280 EXPECT_NONFATAL_FAILURE(try_every_failure<Nothing>("doing nothing", true,
281 [] (Nothing &) {},
282 [] (Nothing &, bool) {}),
283 "nothing was tested");
284 }
285
286 // =========================================================================
287 // The nodes of the binary trees (DECLARE_BINNODE in tpl_binNode.H)
288 // =========================================================================
289
290 // A node template and the control data of its nodes
291 template <template <class> class N, class C>
292 struct Node_Kind
293 {
294 template <class Key>
295 using Node = N<Key>;
296
297 using Control_Data = C;
298 };
299
300 // A node, once built, and a key to build it from
301 template <class Node, class Key>
302 struct Node_Fixture
303 {
304 Key key = Key(7);
305 Node * node = nullptr;
306
307 Node_Fixture() = default;
308 Node_Fixture(const Node_Fixture &) = delete;
309 Node_Fixture & operator = (const Node_Fixture &) = delete;
310 ~Node_Fixture() { delete node; }
311 };
312
313 template <class Kind>
314 struct Node_Construction : public ::testing::Test
315 {
316 // Node(Key &&) moves the key into the node; a key without a move
317 // constructor is copied
318 template <class Key>
319 static void check_from_rvalue(const std::string & what)
320 {
321 using Node = typename Kind::template Node<Key>;
322 using Fixture = Node_Fixture<Node, Key>;
323 if constexpr (std::is_nothrow_constructible_v<Node, Key &&>)
324 ADD_FAILURE() << what << " is noexcept, but the key may throw";
325 else
326 try_every_failure<Fixture>(what, true,
327 [] (Fixture & f) { f.node = new Node(std::move(f.key)); },
328 [] (Fixture & f, const bool threw)
329 {
330 EXPECT_EQ(f.key.value, 7);
331 EXPECT_EQ(f.node == nullptr, threw);
332 if (f.node != nullptr)
333 {
334 EXPECT_EQ(KEY(f.node).value, 7);
335 }
336 });
337 }
338 };
339
340 using Node_Kinds = ::testing::Types<Node_Kind<BinNode, Empty_Node>,
341 Node_Kind<BinNodeVtl, Empty_Node>,
342 Node_Kind<AvlNode, AvlNode_Data>,
343 Node_Kind<AvlNodeVtl, AvlNode_Data>,
344 Node_Kind<AvlNodeRk, AvlNodeRk_Data>,
345 Node_Kind<RbNode, RbNode_Data>,
346 Node_Kind<RbNodeVtl, RbNode_Data>,
347 Node_Kind<RbNodeRk, RbNodeRk_Data>,
348 Node_Kind<TreapNode, TreapNode_Data>,
349 Node_Kind<Treap_Rk_Node, TreapRkNode_Data>,
350 Node_Kind<BinNodeXt, BinNodeXt_Data>,
351 Node_Kind<RandNode, BinNodeXt_Data>,
352 Node_Kind<BinHeapNode, BinHeapNode_Data>>;
353 TYPED_TEST_SUITE(Node_Construction, Node_Kinds);
354
355 TYPED_TEST(Node_Construction, FromAnRvalueLetsTheFailureThrough)
356 {
357 this->template check_from_rvalue<Copy_Fails>("Node(Key &&) with a key that is copied");
358 this->template check_from_rvalue<Move_Fails>("Node(Key &&) with a key that is moved");
359 }
360
361 // Node(const Control_Data &) builds the key by default
362 TYPED_TEST(Node_Construction, FromControlDataLetsTheFailureThrough)
363 {
364 using Node = typename TypeParam::template Node<Default_Fails>;
365 using Control_Data = typename TypeParam::Control_Data;
366 using Fixture = Node_Fixture<Node, long>;
367 if constexpr (std::is_nothrow_constructible_v<Node, const Control_Data &>)
368 ADD_FAILURE() << "Node(const Control_Data &) is noexcept, but the key may throw";
369 else
370 try_every_failure<Fixture>("Node(const Control_Data &)", true,
371 [] (Fixture & f) { f.node = new Node(Control_Data()); },
372 [] (Fixture & f, const bool threw)
373 {
374 EXPECT_EQ(f.node == nullptr, threw);
375 });
376 }
377
378 // The keys whose move and default construction do not throw keep the
379 // noexcept, and so the code that they had
380 static_assert(std::is_nothrow_constructible_v<AvlNode<int>, int &&>);
381 static_assert(std::is_nothrow_constructible_v<RbNode<std::string>, std::string &&>);
382 static_assert(std::is_nothrow_constructible_v<BinNode<std::string>, const Empty_Node &>);
383
384 // =========================================================================
385 // Dnode (tpl_dnode.H)
386 // =========================================================================
387
388 // A list with the nodes 1, 2 and 3, the second one to move
389 struct Dnode_List
390 {
392 Dnode<Move_Fails> * middle = nullptr;
393 Dnode<Move_Fails> * moved = nullptr; // built from middle, if it was
394
395 Dnode_List()
396 {
397 for (long v = 1; v <= 3; ++v)
398 {
399 auto * p = new Dnode<Move_Fails>(Move_Fails(v));
400 head.append(p);
401 if (v == 2)
402 middle = p;
403 }
404 }
405
406 Dnode_List(const Dnode_List &) = delete;
407 Dnode_List & operator = (const Dnode_List &) = delete;
408
409 ~Dnode_List()
410 {
411 while (not head.is_empty())
412 delete head.remove_first_ne();
413 if (moved != nullptr) // middle left the list
414 delete middle;
415 }
416
417 // The node in the second place and whether the values are 1, 2, 3
418 Dnode<Move_Fails> * second(bool & values_ok) const
419 {
420 Array<long> values;
421 for (auto * p = head.get_next(); p != &head; p = p->get_next())
422 values.append(p->get_data().value);
423 values_ok = values.size() == 3 and values(0) == 1 and values(1) == 2 and values(2) == 3;
424 return head.get_next()->get_next();
425 }
426 };
427
428 TEST(Dnode_Construction, ByDefaultLetsTheFailureThrough)
429 {
431 using Fixture = Node_Fixture<Node, long>;
432 if constexpr (std::is_nothrow_default_constructible_v<Node>)
433 ADD_FAILURE() << "Dnode() is noexcept, but the item may throw";
434 else
435 try_every_failure<Fixture>("Dnode()", true,
436 [] (Fixture & f) { f.node = new Node; },
437 [] (Fixture & f, const bool threw)
438 {
439 EXPECT_EQ(f.node == nullptr, threw);
440 });
441 }
442
443 // The moved node takes the place of the other one in its list; a move
444 // that fails must leave the list as it was
445 TEST(Dnode_Construction, ByMoveLetsTheFailureThroughAndKeepsTheList)
446 {
447 if constexpr (std::is_nothrow_move_constructible_v<Dnode<Move_Fails>>)
448 ADD_FAILURE() << "Dnode(Dnode &&) is noexcept, but the item may throw";
449 else
450 try_every_failure<Dnode_List>("Dnode(Dnode &&)", true,
451 [] (Dnode_List & l)
452 {
453 l.moved = new Dnode<Move_Fails>(std::move(*l.middle));
454 },
455 [] (Dnode_List & l, const bool threw)
456 {
457 bool values_ok = false;
458 Dnode<Move_Fails> * second = l.second(values_ok);
459 EXPECT_TRUE(values_ok);
460 EXPECT_EQ(l.moved == nullptr, threw);
461 EXPECT_EQ(second, threw ? l.middle : l.moved);
462 if (not threw)
463 {
464 EXPECT_TRUE(l.middle->is_empty());
465 }
466 });
467 }
468
469 static_assert(std::is_nothrow_default_constructible_v<Dnode<std::string>>);
470 static_assert(std::is_nothrow_move_constructible_v<Dnode<std::string>>);
471 static_assert(std::is_nothrow_move_constructible_v<Dnode<int>>);
472
473 // =========================================================================
474 // The zip iterators (ah-zip.H): get_curr_ne() copies the items into a
475 // tuple
476 // =========================================================================
477
478 // The items 1, 2 and 3 in a container of type C
479 template <class C>
480 C one_two_three()
481 {
482 C c;
483 for (long v = 1; v <= 3; ++v)
484 c.append(typename C::Item_Type(v));
485 return c;
486 }
487
488 template <class Tuple, size_t... I>
489 bool items_are(const Tuple & t, const long v, std::index_sequence<I...>)
490 {
491 return (... and (value_of(std::get<I>(t)) == v));
492 }
493
494 // The containers to zip, and whether the iterator enumerates them
495 template <bool Enumerated, class... Cs>
496 struct Zip_Of
497 {
498 using Iterator = std::conditional_t<Enumerated, EnumZipIterator<Cs...>, ZipIterator<Cs...>>;
499
500 // The containers and an iterator on their second items
501 struct Fixture
502 {
503 std::tuple<Cs...> containers{one_two_three<Cs>()...};
504 Iterator it = std::apply([] (const Cs & ... c) { return Iterator(c...); }, containers);
505
506 Fixture() { it.next_ne(); }
507 };
508
509 // Whether the iterator is on the second items
510 static void on_the_second_items(const Iterator & it)
511 {
512 ASSERT_TRUE(it.has_curr());
513 const auto t = it.get_curr_ne();
514 EXPECT_TRUE(items_are(t, 2, std::make_index_sequence<sizeof...(Cs)>()));
515 if constexpr (Enumerated)
516 {
517 EXPECT_EQ(std::get<sizeof...(Cs)>(t), 1u);
518 }
519 }
520 };
521
522 template <class Zip>
523 struct Zip_Current : public ::testing::Test {};
524
525 using Zips = ::testing::Types<Zip_Of<false, DynList<Copy_Fails>>,
526 Zip_Of<false, DynList<Copy_Fails>, DynList<long>>,
527 Zip_Of<false, DynList<long>, DynArray<Copy_Fails>>,
528 Zip_Of<false, DynArray<Copy_Fails>, DynList<Copy_Fails>,
530 Zip_Of<true, DynList<Copy_Fails>>,
531 Zip_Of<true, DynList<Copy_Fails>, DynList<long>>,
532 Zip_Of<true, DynList<long>, DynArray<Copy_Fails>>,
533 Zip_Of<true, DynArray<Copy_Fails>, DynList<Copy_Fails>,
535 TYPED_TEST_SUITE(Zip_Current, Zips);
536
537 TYPED_TEST(Zip_Current, LetsTheFailureThroughAndKeepsThePosition)
538 {
539 using Iterator = typename TypeParam::Iterator;
540 using Fixture = typename TypeParam::Fixture;
541 if constexpr (noexcept(std::declval<const Iterator &>().get_curr_ne()))
542 ADD_FAILURE() << "get_curr_ne() is noexcept, but copying an item may throw";
543 else
544 try_every_failure<Fixture>("get_curr_ne()", true,
545 [] (Fixture & f) { (void) f.it.get_curr_ne(); },
546 [] (Fixture & f, bool)
547 {
548 TypeParam::on_the_second_items(f.it);
549 });
550 }
551
552 static_assert(noexcept(std::declval<const ZipIterator<DynList<int>, DynList<long>> &>()
553 .get_curr_ne()));
554 static_assert(noexcept(std::declval<const ZipIterator<DynList<int>> &>().get_curr_ne()));
555 static_assert(noexcept(std::declval<const EnumZipIterator<DynList<int>, DynList<double>> &>()
556 .get_curr_ne()));
557
558 // The reading of a DynArray may allocate, on a modifiable array, so its
559 // iterator is not noexcept: neither is the zip that reads one
560 static_assert(not noexcept(std::declval<const ZipIterator<DynList<int>, DynArray<long>> &>()
561 .get_curr_ne()));
562 static_assert(not noexcept(std::declval<const EnumZipIterator<DynArray<int>> &>()
563 .get_curr_ne()));
564
565 // =========================================================================
566 // The linear hash table (tpl_linHash.H): its lists are headed by a
567 // Dlink, which holds no key. They were Dnode<Key> headers, and cutting
568 // the array reset those that left it, which copied a Key, inside
569 // empty() and remove(), which are noexcept: the table had to absorb
570 // what that copy threw. Now those operations copy no key at all
571 // =========================================================================
572
573 constexpr long Keys = 300; // enough to make a table of 101 lists grow
574
575 struct Grown_Table
576 {
577 DynSetLinHash<Copy_Fails> * table = new DynSetLinHash<Copy_Fails>(101, hash_of);
578
579 Grown_Table()
580 {
581 for (long k = 0; k < Keys; ++k)
582 table->insert(Copy_Fails(k));
583 }
584
585 Grown_Table(const Grown_Table &) = delete;
586 Grown_Table & operator = (const Grown_Table &) = delete;
587
588 ~Grown_Table() { delete table; }
589
590 // Whether the table is empty and still works
591 void empty_and_usable()
592 {
593 ASSERT_NE(table, nullptr);
594 EXPECT_TRUE(table->is_empty());
595 EXPECT_EQ(table->size(), 0u);
596 for (long k = 0; k < Keys; ++k)
597 EXPECT_FALSE(table->contains(Copy_Fails(k))) << "key " << k;
598 for (long k = 0; k < Keys; ++k)
599 EXPECT_NE(table->insert(Copy_Fails(k)), nullptr) << "key " << k;
600 EXPECT_EQ(table->size(), static_cast<size_t>(Keys));
601 for (long k = 0; k < Keys; ++k)
602 EXPECT_TRUE(table->contains(Copy_Fails(k))) << "key " << k;
603 }
604 };
605
606 TEST(Linear_Hash_Table, GrowsInTheseTests)
607 {
608 Grown_Table t;
609 EXPECT_GT(t.table->capacity(), 101u);
610 }
611
612 // Runs op on a table that grew, with every operation of a key failing:
613 // op must make none. Then valid(table) checks the table, and destroying
614 // it must leave as many keys alive as before building it
615 template <class Op, class Valid>
616 void expect_no_operation_of_a_key(const char * what, Op op, Valid valid)
617 {
618 SCOPED_TRACE(what);
619 const long alive = Failures::alive;
620 {
621 Grown_Table t;
622 long done = -1;
623 bool threw = false;
624 {
625 Failing_From failing(0);
626 try
627 {
628 op(t);
629 }
630 catch (const Injected_Failure &)
631 {
632 threw = true;
633 }
634 done = Failures::done;
635 }
636 EXPECT_FALSE(threw) << "a failure reached the caller";
637 EXPECT_EQ(done, 0) << "it copied a key";
638 valid(t);
639 }
640 EXPECT_EQ(Failures::alive, alive) << "keys leaked or destroyed twice";
641 }
642
643 // The table of the tests above builds a key only for each bucket: the
644 // headers of its lists hold none. With headers that held one, a table
645 // of 101 lists built hundreds of keys before the first insertion
646 TEST(Linear_Hash_Table, ItBuildsNoKeyForItsLists)
647 {
648 const long alive = Failures::alive;
649 {
650 DynSetLinHash<Copy_Fails> table(101, hash_of);
651 EXPECT_EQ(Failures::alive, alive) << "an empty table holds keys";
652 for (long k = 0; k < Keys; ++k)
653 table.insert(Copy_Fails(k));
654 EXPECT_GT(table.capacity(), 101u);
655 EXPECT_EQ(Failures::alive, alive + Keys) << "the lists hold keys of their own";
656 table.empty();
657 EXPECT_EQ(Failures::alive, alive);
658 }
659 EXPECT_EQ(Failures::alive, alive);
660 }
661
662 TEST(Linear_Hash_Table, EmptyCopiesNoKey)
663 {
664 expect_no_operation_of_a_key("empty()",
665 [] (Grown_Table & t) { t.table->empty(); },
666 [] (Grown_Table & t) { t.empty_and_usable(); });
667 }
668
669 TEST(Linear_Hash_Table, TheDestructorCopiesNoKey)
670 {
671 expect_no_operation_of_a_key("~DynSetLinHash()",
672 [] (Grown_Table & t)
673 {
674 delete t.table;
675 t.table = nullptr;
676 },
677 [] (Grown_Table & t) { EXPECT_EQ(t.table, nullptr); });
678 }
679
680 // Each remove may contract the table, down to its first capacity
681 TEST(Linear_Hash_Table, RemoveCopiesNoKey)
682 {
683 expect_no_operation_of_a_key("remove()",
684 [] (Grown_Table & t)
685 {
686 for (long k = Keys - 1; k >= 0; --k)
687 t.table->remove(t.table->search(Copy_Fails(k)));
688 },
689 [] (Grown_Table & t)
690 {
691 EXPECT_EQ(t.table->capacity(), 101u);
692 t.empty_and_usable();
693 });
694 }
695
696 // Neither do the moves of the table, which build an empty one and swap
697 // them: the array of the empty one builds no default value with a key,
698 // and the swap of the two arrays swaps no key. They are noexcept
699 TEST(Linear_Hash_Table, ItsMovesCopyNoKey)
700 {
701 static_assert(std::is_nothrow_move_constructible_v<DynSetLinHash<Copy_Fails>>);
702 static_assert(std::is_nothrow_move_assignable_v<DynSetLinHash<Copy_Fails>>);
703 expect_no_operation_of_a_key("the move constructor",
704 [] (Grown_Table & t)
705 {
706 DynSetLinHash<Copy_Fails> taken(std::move(*t.table));
707 EXPECT_EQ(taken.size(), static_cast<size_t>(Keys));
708 EXPECT_TRUE(t.table->is_empty());
709 // the keys are freed with every operation failing
710 },
711 [] (Grown_Table & t) { t.empty_and_usable(); });
712 expect_no_operation_of_a_key("the move assignment",
713 [] (Grown_Table & t)
714 {
715 DynSetLinHash<Copy_Fails> taken(101, hash_of);
716 taken = std::move(*t.table);
717 EXPECT_EQ(taken.size(), static_cast<size_t>(Keys));
718 EXPECT_TRUE(t.table->is_empty());
719 },
720 [] (Grown_Table & t) { t.empty_and_usable(); });
721 }
722
723 // DynMapLinHash searches by the key alone: it copies no key and builds no
724 // Data
725 TEST(Linear_Hash_Map, SearchCopiesNothing)
726 {
728 for (long k = 0; k < Keys; k += 2)
729 (void) map.insert(Copy_Fails(k), Default_Fails(k));
730 const auto & const_map = map;
731
732 for (long k = -1; k <= Keys; ++k)
733 {
734 const Copy_Fails key(k);
735 const bool in = k >= 0 and k < Keys and k % 2 == 0;
736 Failures::done = 0;
737 auto * p = map.search(key);
738 const auto * q = const_map.search(key);
739 const bool has = map.has(key);
740 const bool contains = map.contains(key);
741 EXPECT_EQ(Failures::done, 0) << "searching for " << k << " copied a key or built a Data";
742 EXPECT_EQ(p != nullptr, in) << "key " << k;
743 EXPECT_EQ(q, p) << "key " << k;
744 EXPECT_EQ(has, in) << "key " << k;
745 EXPECT_EQ(contains, in) << "key " << k;
746 if (p != nullptr)
747 {
748 EXPECT_EQ(p->second.value, k);
749 }
750 }
751 }
752
753
754 // =========================================================================
755 // set_hash_fct() and the copies of the keys. A map of tpl_dynSetHash.H
756 // given a function of pairs, which gives no hash of a key alone, searches
757 // for a pair built from the key, a copy of it and a Data built by
758 // default: their failure reaches the caller and the map keeps its pairs.
759 // A function of the keys brings back the search that copies nothing. An
760 // open table with keys places them again with a new function, as
761 // rehash() does, which copies them: if a copy fails, the table keeps its
762 // function and its keys.
763 // =========================================================================
764
765 size_t other_hash_of(const Copy_Fails & item) noexcept
766 {
767 return static_cast<size_t>(item.value) * 40503u + 17;
768 }
769
770 // Another function than hash_of(), which the maps are built with: a
771 // search by the hash of the keys that the map was built with misses
772 size_t pair_hash_of(const std::pair<Copy_Fails, Default_Fails> & p) noexcept
773 {
774 return other_hash_of(p.first);
775 }
776
777 size_t second_hash_of(const Copy_Fails & item) noexcept
778 {
779 return static_cast<size_t>(item.value) * 3 + 11;
780 }
781
782 // A map that searches by pairs, with the pairs (k, k) of the even k
783 template <class Map>
784 struct Map_By_Pairs
785 {
786 Map map{101, hash_of};
787
788 Map_By_Pairs()
789 {
790 map.set_hash_fct(pair_hash_of);
791 for (long k = 0; k < Keys; k += 2)
792 (void) map.insert(Copy_Fails(k), Default_Fails(k));
793 }
794
795 void holds_its_pairs()
796 {
797 for (long k = -1; k <= Keys; ++k)
798 {
799 const Copy_Fails key(k);
800 const auto * p = map.search(key);
801 EXPECT_EQ(p != nullptr, k >= 0 and k < Keys and k % 2 == 0) << "key " << k;
802 if (p != nullptr)
803 EXPECT_EQ(p->second.value, k);
804 }
805 }
806 };
807
808 template <class Map>
809 void search_by_pairs_lets_the_failure_through(const std::string & name)
810 {
811 static_assert(not noexcept(std::declval<Map &>().search(std::declval<const Copy_Fails &>())));
812 for (const long key : {4L, 5L}) // a key of the map and one that is not
813 try_every_failure<Map_By_Pairs<Map>>(name + "::search() by pairs", true,
814 [key] (Map_By_Pairs<Map> & t)
815 {
816 const Copy_Fails k(key);
817 (void) t.map.search(k);
818 },
819 [] (Map_By_Pairs<Map> & t, bool) { t.holds_its_pairs(); });
820 }
821
822 TEST(Hash_Map_By_Pairs, SearchLetsTheFailureThrough)
823 {
824 search_by_pairs_lets_the_failure_through<DynMapLinHash<Copy_Fails, Default_Fails>>("DynMapLinHash");
825 search_by_pairs_lets_the_failure_through<DynMapHash<Copy_Fails, Default_Fails>>("DynMapHash");
826 }
827
828 template <class Map>
829 void search_by_keys_copies_nothing()
830 {
831 Map map(101, hash_of);
832 map.set_hash_fct(pair_hash_of);
833 map.set_hash_fct(other_hash_of);
834 for (long k = 0; k < Keys; k += 2)
835 (void) map.insert(Copy_Fails(k), Default_Fails(k));
836
837 for (long k = -1; k <= Keys; ++k)
838 {
839 const Copy_Fails key(k);
840 Failures::done = 0;
841 const auto * p = map.search(key);
842 const bool has = map.has(key);
843 EXPECT_EQ(Failures::done, 0) << "searching for " << k << " copied a key or built a Data";
844 EXPECT_EQ(p != nullptr, k >= 0 and k < Keys and k % 2 == 0) << "key " << k;
845 EXPECT_EQ(has, p != nullptr) << "key " << k;
846 }
847 }
848
849 TEST(Hash_Map_By_Keys, SearchCopiesNothingAfterAFunctionOfPairs)
850 {
851 search_by_keys_copies_nothing<DynMapLinHash<Copy_Fails, Default_Fails>>();
852 search_by_keys_copies_nothing<DynMapHash<Copy_Fails, Default_Fails>>();
853 }
854
855 // An open table with the keys [0, Keys)
856 template <class Table>
857 struct Open_Table
858 {
859 Table table = make();
860
861 static Table make()
862 {
863 if constexpr (std::is_same_v<Table, ODhashTable<Copy_Fails>>)
864 return Table(101, hash_of, second_hash_of);
865 else
866 return Table(101, hash_of);
867 }
868
869 Open_Table()
870 {
871 for (long k = 0; k < Keys; ++k)
872 (void) table.insert(Copy_Fails(k));
873 }
874
875 void holds_its_keys()
876 {
877 EXPECT_EQ(table.size(), static_cast<size_t>(Keys));
878 for (long k = -1; k <= Keys; ++k)
879 EXPECT_EQ(table.search(Copy_Fails(k)) != nullptr, k >= 0 and k < Keys) << "key " << k;
880 }
881 };
882
883 // Whether the hash function fct of a table is the function fct_ptr
884 template <class Hash_Fct>
885 bool is_the_function(const Hash_Fct & fct, size_t (*fct_ptr)(const Copy_Fails &))
886 {
887 // std-interop: the open tables keep their functions in a std::function
888 const auto * target = fct.template target<size_t (*)(const Copy_Fails &)>();
889 return target != nullptr and *target == fct_ptr;
890 }
891
892 // After each try, the table has the function that it had if a copy
893 // failed, and the new one otherwise
894 TEST(Open_Hash_Table, SetHashFctKeepsItsFunctionWhenACopyFails)
895 {
896 using OL = Open_Table<OLhashTable<Copy_Fails>>;
897 using OD = Open_Table<ODhashTable<Copy_Fails>>;
898 try_every_failure<OL>("OLhashTable::set_hash_fct()", true,
899 [] (OL & t) { t.table.set_hash_fct(other_hash_of); },
900 [] (OL & t, const bool threw)
901 {
902 t.holds_its_keys();
903 EXPECT_TRUE(is_the_function(t.table.get_hash_fct(),
904 threw ? hash_of : other_hash_of));
905 });
906 try_every_failure<OD>("ODhashTable::set_hash_fct()", true,
907 [] (OD & t) { t.table.set_hash_fct(other_hash_of); },
908 [] (OD & t, const bool threw)
909 {
910 t.holds_its_keys();
911 EXPECT_TRUE(is_the_function(t.table.get_hash_fct(),
912 threw ? hash_of : other_hash_of));
913 EXPECT_TRUE(is_the_function(t.table.get_second_hash_fct(),
914 second_hash_of));
915 });
916 try_every_failure<OD>("ODhashTable::set_second_hash_fct()", true,
917 [] (OD & t) { t.table.set_second_hash_fct(other_hash_of); },
918 [] (OD & t, const bool threw)
919 {
920 t.holds_its_keys();
921 EXPECT_TRUE(is_the_function(t.table.get_hash_fct(), hash_of));
922 EXPECT_TRUE(is_the_function(t.table.get_second_hash_fct(),
923 threw ? second_hash_of : other_hash_of));
924 });
925 }
926
927
928 // =========================================================================
929 // The maps of tpl_dynMapOhash.H search for a pair built from the key, a
930 // copy of it and a Data built by default, as their table searches for
931 // pairs: their failure reaches the caller, and the map keeps its pairs.
932 // =========================================================================
933
934 template <class Map>
935 struct Open_Map_With_Pairs
936 {
937 Map map{101, hash_of, second_hash_of};
938
939 Open_Map_With_Pairs()
940 {
941 for (long k = 0; k < Keys; k += 2)
942 (void) map.insert(Copy_Fails(k), Default_Fails(k));
943 }
944
945 void holds_its_pairs()
946 {
947 for (long k = -1; k <= Keys; ++k)
948 {
949 const Copy_Fails key(k);
950 const auto * p = map.search(key);
951 EXPECT_EQ(p != nullptr, k >= 0 and k < Keys and k % 2 == 0) << "key " << k;
952 if (p != nullptr)
953 EXPECT_EQ(p->second.value, k);
954 }
955 }
956 };
957
958 template <class Map>
959 void open_map_search_lets_the_failure_through(const std::string & name)
960 {
961 using Fixture = Open_Map_With_Pairs<Map>;
962 static_assert(not noexcept(std::declval<Map &>().search(std::declval<const Copy_Fails &>())));
963 static_assert(not noexcept(std::declval<const Map &>().has(std::declval<const Copy_Fails &>())));
964 static_assert(not noexcept(std::declval<const Map &>().contains(std::declval<Copy_Fails>())));
965 for (const long key : {4L, 5L}) // a key of the map and one that is not
966 {
967 try_every_failure<Fixture>(name + "::search()", true,
968 [key] (Fixture & t)
969 {
970 const Copy_Fails k(key);
971 (void) t.map.search(k);
972 },
973 [] (Fixture & t, bool) { t.holds_its_pairs(); });
974 try_every_failure<Fixture>(name + "::has()", true,
975 [key] (Fixture & t)
976 {
977 const Copy_Fails k(key);
978 (void) t.map.has(k);
979 },
980 [] (Fixture & t, bool) { t.holds_its_pairs(); });
981 }
982 }
983
984 TEST(Open_Hash_Map, SearchLetsTheFailureThrough)
985 {
986 open_map_search_lets_the_failure_through<MapOLhash<Copy_Fails, Default_Fails>>("MapOLhash");
987 open_map_search_lets_the_failure_through<MapODhash<Copy_Fails, Default_Fails>>("MapODhash");
988 static_assert(noexcept(std::declval<MapOLhash<int, int> &>().search(1)));
989 static_assert(noexcept(std::declval<const MapODhash<int, int> &>().has(1)));
990 }
991
992 // =========================================================================
993 // DynMapTree (tpl_dynMapTree.H): search(), has(), contains() and find()
994 // search by the key alone; they used to build a pair, with a copy of the
995 // key and a Data, inside noexcept. remove_key() still builds one, out of
996 // noexcept: what that throws must reach the caller.
997 // =========================================================================
998
999 // A tree type. The splay trees search for a pair built from the key, as
1000 // only their own search moves what it finds to the root; besides, they
1001 // build a whole node, with a key built by default, as the header of each
1002 // splay (splay_impl() of tpl_splay_tree.H and tpl_splay_treeRk.H).
1003 template <template <typename, class> class T, bool Splays = false>
1004 struct Tree_Kind
1005 {
1006 template <class Key, class Data>
1007 using Map = DynMapTree<Key, Data, T>;
1008
1009 static constexpr bool splays = Splays;
1010 };
1011
1012 constexpr long Pairs = 100; // the keys 0, 2, ..., 2 * (Pairs - 1)
1013
1014 bool in_the_map(const long k) noexcept
1015 {
1016 return k >= 0 and k < 2 * Pairs and k % 2 == 0;
1017 }
1018
1019 // A map with the keys of in_the_map(), inserted out of order, so that
1020 // the tree is of any shape
1021 template <class Map>
1022 struct Map_Fixture
1023 {
1024 Map map;
1025
1026 Map_Fixture()
1027 {
1028 for (long i = 0; i < Pairs; ++i)
1029 {
1030 const long k = 2 * ((i * 37) % Pairs);
1031 (void) map.insert(Copy_Fails(k), typename Map::Value_Type(k));
1032 }
1033 }
1034 };
1035
1036 template <class Kind>
1037 struct Map_Search : public ::testing::Test {};
1038
1039 using Tree_Kinds = ::testing::Types<Tree_Kind<BinTree>, Tree_Kind<Avl_Tree>,
1040 Tree_Kind<Avl_Tree_Rk>, Tree_Kind<Rb_Tree>,
1041 Tree_Kind<Rb_Tree_Rk>, Tree_Kind<TdRbTree>,
1042 Tree_Kind<TdRbTreeRk>, Tree_Kind<HtdRbTree>,
1043 Tree_Kind<HtdRbTreeRk>, Tree_Kind<Treap>,
1044 Tree_Kind<Treap_Rk>, Tree_Kind<Rand_Tree>,
1045 Tree_Kind<Splay_Tree, true>,
1046 Tree_Kind<Splay_Tree_Rk, true>>;
1047 TYPED_TEST_SUITE(Map_Search, Tree_Kinds);
1048
1049 // But in the splay trees, the searches copy no key and build no Data
1050 TYPED_TEST(Map_Search, SearchesCopyNothing)
1051 {
1052 using Map = typename TypeParam::template Map<Copy_Fails, Default_Fails>;
1053 Map_Fixture<Map> f;
1054 auto & map = f.map;
1055 const auto & const_map = f.map;
1056 for (long k = -1; k <= 2 * Pairs; ++k)
1057 {
1058 const Copy_Fails key(k);
1059 const bool in = in_the_map(k);
1060 Failures::done = 0;
1061 auto * p = map.search(key);
1062 const auto * q = const_map.search(key);
1063 auto * r = map.search(Copy_Fails(k));
1064 const auto * s = const_map.search(Copy_Fails(k));
1065 // each one apart: with and, a key that is not in the map would skip
1066 // the overload for an rvalue
1067 const bool has = const_map.has(key);
1068 const bool has_rvalue = const_map.has(Copy_Fails(k));
1069 const bool contains = const_map.contains(key);
1070 const bool contains_rvalue = const_map.contains(Copy_Fails(k));
1071 if (in)
1072 {
1073 EXPECT_EQ(map.find(key).value, k);
1074 EXPECT_EQ(const_map.find(key).value, k);
1075 }
1076 else
1077 {
1078 EXPECT_THROW((void) map.find(key), std::domain_error) << "key " << k;
1079 EXPECT_THROW((void) const_map.find(key), std::domain_error) << "key " << k;
1080 }
1081 if constexpr (not TypeParam::splays)
1082 {
1083 EXPECT_EQ(Failures::done, 0) << "searching for " << k << " copied a key or built a Data";
1084 }
1085 EXPECT_EQ(p != nullptr, in) << "key " << k;
1086 EXPECT_TRUE(q == p and r == p and s == p) << "key " << k;
1087 EXPECT_EQ(has, in) << "key " << k;
1088 EXPECT_EQ(has_rvalue, in) << "key " << k;
1089 EXPECT_EQ(contains, in) << "key " << k;
1090 EXPECT_EQ(contains_rvalue, in) << "key " << k;
1091 if (p != nullptr)
1092 {
1093 EXPECT_EQ(p->second.value, k);
1094 }
1095 }
1096 EXPECT_TRUE(map.verify());
1097 EXPECT_EQ(map.size(), static_cast<size_t>(Pairs));
1098 }
1099
1100 // What building the pair throws, in the searches of a splay tree and in
1101 // remove_key(), must reach the caller and leave the map as it was. The
1102 // data are long, so that the header of each splay, a node whose key is
1103 // built by default inside noexcept, never fails. The search of the other
1104 // trees builds nothing, so nothing of it can fail: SearchesCopyNothing
1105 // checks it.
1106 TYPED_TEST(Map_Search, SearchLetsTheFailureThrough)
1107 {
1108 using Map = typename TypeParam::template Map<Copy_Fails, long>;
1109 using Fixture = Map_Fixture<Map>;
1110 if constexpr (not TypeParam::splays)
1111 GTEST_SKIP() << "the search of this tree builds no pair";
1112 else if constexpr (noexcept(std::declval<Map &>().search(Copy_Fails(0))))
1113 ADD_FAILURE() << "search() is noexcept, but it copies a key that may throw";
1114 else
1115 for (const long k : {0L, 1L, 98L})
1116 try_every_failure<Fixture>("search(" + std::to_string(k) + ")", true,
1117 [k] (Fixture & f) { (void) f.map.search(Copy_Fails(k)); },
1118 [] (Fixture & f, bool)
1119 {
1120 EXPECT_TRUE(f.map.verify());
1121 EXPECT_EQ(f.map.size(), static_cast<size_t>(Pairs));
1122 });
1123 }
1124
1125 // A key that is not in the map, as 99, is refused with std::domain_error
1126 TYPED_TEST(Map_Search, RemoveKeyLetsTheFailureThrough)
1127 {
1128 using Map = typename TypeParam::template Map<Copy_Fails, long>;
1129 using Fixture = Map_Fixture<Map>;
1130 for (const long k : {0L, 98L, 99L})
1131 {
1132 bool refused = false; // remove_key() threw std::domain_error
1133 try_every_failure<Fixture>("remove_key(" + std::to_string(k) + ")", true,
1134 [k, &refused] (Fixture & f)
1135 {
1136 refused = false;
1137 try
1138 {
1139 f.map.remove_key(Copy_Fails(k));
1140 }
1141 catch (const std::domain_error &)
1142 {
1143 refused = true;
1144 }
1145 },
1146 [k, &refused] (Fixture & f, const bool threw)
1147 {
1148 if (not threw)
1149 EXPECT_EQ(refused, not in_the_map(k))
1150 << "std::domain_error, for a key not in the map alone";
1151 const bool removed = in_the_map(k) and not threw;
1152 EXPECT_EQ(f.map.has(Copy_Fails(k)),
1153 in_the_map(k) and not removed);
1154 EXPECT_EQ(f.map.size(),
1155 static_cast<size_t>(removed ? Pairs - 1 : Pairs));
1156 EXPECT_TRUE(f.map.verify());
1157 });
1158 }
1159 }
1160
1161 static_assert(noexcept(std::declval<const DynMapTree<int, int> &>().search(1)));
1162 static_assert(noexcept(std::declval<DynMapTree<long, Array<int>, Rb_Tree> &>().has(1L)));
1163 static_assert(noexcept(std::declval<DynMapTree<long, int, Splay_Tree> &>().has(1L)));
1164
1165 // =========================================================================
1166 // The removals of DynSetTree that give a copy of the key, del() and
1167 // remove_pos(): the node leaves the tree before that copy, which leaked
1168 // it and left it counted when it threw
1169 // =========================================================================
1170
1171 // A map and a ranked set with the keys 0 to 9
1172 struct Removal_Fixture
1173 {
1176
1177 Removal_Fixture()
1178 {
1179 for (long k = 0; k < 10; ++k)
1180 {
1181 (void) map.insert(k, Copy_Fails(k));
1182 (void) ranked.insert(Copy_Fails(k));
1183 }
1184 }
1185 };
1186
1187 // remove() of a map gives the data of the pair that del() copies
1188 TEST(Set_Removal, DelFreesTheNodeWhenItsCopyFails)
1189 {
1190 try_every_failure<Removal_Fixture>("remove(5)", true,
1191 [] (Removal_Fixture & f)
1192 {
1193 (void) f.map.remove(5);
1194 },
1195 [] (Removal_Fixture & f, bool)
1196 {
1197 const bool removed = not f.map.contains(5);
1198 EXPECT_EQ(f.map.size(), removed ? 9u : 10u);
1199 EXPECT_TRUE(f.map.verify());
1200 });
1201 }
1202
1203 TEST(Set_Removal, RemovePosFreesTheNodeWhenItsCopyFails)
1204 {
1205 try_every_failure<Removal_Fixture>("remove_pos(3)", true,
1206 [] (Removal_Fixture & f)
1207 {
1208 EXPECT_EQ(f.ranked.remove_pos(3).value, 3);
1209 },
1210 [] (Removal_Fixture & f, bool)
1211 {
1212 EXPECT_FALSE(f.ranked.contains(Copy_Fails(3)));
1213 EXPECT_EQ(f.ranked.size(), 9u);
1214 EXPECT_TRUE(f.ranked.verify());
1215 });
1216 }
1217
1218 // =========================================================================
1219 // The zip iterators: the reading of a container may throw too, and the
1220 // copies of the items come from constant items
1221 // =========================================================================
1222
1223 // A container of the user whose reading fails when asked to, of items
1224 // whose copy cannot throw
1225 struct Reading_Fails
1226 {
1227 using Item_Type = long;
1228
1229 long items[3] = {1, 2, 3};
1230
1231 struct Iterator
1232 {
1233 using Item_Type = long;
1234
1235 const Reading_Fails * container;
1236 size_t i = 0;
1237
1238 Iterator(const Reading_Fails & c) noexcept : container(&c) {}
1239
1240 bool has_curr() const noexcept { return i < 3; }
1241
1242 const long & get_curr_ne() const
1243 {
1244 Failures::hit("reading");
1245 return container->items[i];
1246 }
1247
1248 const long & get_curr() const { return get_curr_ne(); }
1249
1250 void next_ne() noexcept { ++i; }
1251
1252 void next() noexcept { next_ne(); }
1253 };
1254 };
1255
1256 // The zip iterators took the copy of a long as all that could throw, and
1257 // read the container inside noexcept
1258 TEST(Zip_Reading, LetsTheFailureOfTheReadingThrough)
1259 {
1262 EXPECT_FALSE(noexcept(std::declval<const Zip &>().get_curr_ne()));
1263 EXPECT_FALSE(noexcept(std::declval<const Enum_Zip &>().get_curr_ne()));
1264 EXPECT_FALSE(noexcept(std::declval<const ZipIterator<Reading_Fails> &>().get_curr_ne()));
1265
1266 const Reading_Fails container;
1267 const auto list = one_two_three<DynList<long>>();
1268 const Zip zip(container, list);
1269 const Enum_Zip enum_zip(container, list);
1270 {
1271 Failing_From failing(0);
1272 EXPECT_THROW((void) zip.get_curr_ne(), Injected_Failure);
1273 EXPECT_THROW((void) enum_zip.get_curr_ne(), Injected_Failure);
1274 }
1275 EXPECT_EQ(std::get<0>(zip.get_curr_ne()), 1);
1276 EXPECT_EQ(std::get<1>(enum_zip.get_curr_ne()), 1);
1277 }
1278
1279 // An item whose copy from a constant item cannot throw, and whose copy
1280 // from one that is not constant fails when asked to
1281 struct Copy_From_Mutable_Fails
1282 {
1283 long value = 0;
1284
1285 Copy_From_Mutable_Fails(const long v) noexcept : value(v) {}
1286
1287 Copy_From_Mutable_Fails(const Copy_From_Mutable_Fails & item) noexcept
1288 : value(item.value) {}
1289
1290 Copy_From_Mutable_Fails(Copy_From_Mutable_Fails & item) : value(item.value)
1291 {
1292 Failures::hit("copy from an item that is not constant");
1293 }
1294
1295 Copy_From_Mutable_Fails &
1296 operator = (const Copy_From_Mutable_Fails &) noexcept = default;
1297 };
1298
1299 // get_curr_ne() of the zip of several containers concatenates the copy
1300 // of the first item with the others: it copied it again from a tuple that
1301 // was not constant, with the copy that the noexcept did not check
1302 TEST(Zip_Current_Copies, CopiesFromConstantItems)
1303 {
1305 const C a = one_two_three<C>(), b = one_two_three<C>(), c = one_two_three<C>();
1306 const ZipIterator<C, C, C> zip(a, b, c);
1307 const EnumZipIterator<C, C, C> enum_zip(a, b, c);
1308 Failing_From failing(0);
1309 const auto t = zip.get_curr_ne();
1310 const auto u = enum_zip.get_curr_ne();
1311 EXPECT_EQ(Failures::fired, 0);
1312 EXPECT_EQ(std::get<0>(t).value + std::get<1>(t).value + std::get<2>(t).value, 3);
1313 EXPECT_EQ(std::get<2>(u).value, 1);
1314 }
1315
1316 // An item that can be copied only from one that is not constant, with a
1317 // copy that fails when asked to, and moved
1318 struct Mutable_Copy_Only
1319 {
1320 long value = 0;
1321
1322 Mutable_Copy_Only(const long v) noexcept : value(v) {}
1323
1324 Mutable_Copy_Only(Mutable_Copy_Only & item) : value(item.value)
1325 {
1326 Failures::hit("copy from an item that is not constant");
1327 }
1328
1329 Mutable_Copy_Only(const Mutable_Copy_Only &) = delete;
1330
1331 Mutable_Copy_Only(Mutable_Copy_Only && item) noexcept : value(item.value) {}
1332 };
1333
1334 // A container of the items 1, 2 and 3, which its iterator gives by value
1335 struct By_Value_Items
1336 {
1337 using Item_Type = Mutable_Copy_Only;
1338
1339 struct Iterator
1340 {
1341 using Item_Type = Mutable_Copy_Only;
1342
1343 long i = 0;
1344
1345 Iterator(const By_Value_Items &) noexcept {}
1346
1347 bool has_curr() const noexcept { return i < 3; }
1348
1349 Mutable_Copy_Only get_curr_ne() const noexcept { return Mutable_Copy_Only(i + 1); }
1350
1351 Mutable_Copy_Only get_curr() const noexcept { return get_curr_ne(); }
1352
1353 void next_ne() noexcept { ++i; }
1354
1355 void next() noexcept { next_ne(); }
1356 };
1357 };
1358
1359 // The zips of several containers took such an item from a tuple that was
1360 // not constant, with T(T &); copying it from a constant one, with the
1361 // copy that it does not have, did not compile
1362 TEST(Zip_Current_Copies, CopiesAnItemThatCopiesOnlyFromOneNotConstant)
1363 {
1364 using List = DynList<long>;
1367 EXPECT_FALSE(noexcept(std::declval<const Zip &>().get_curr_ne()));
1368 EXPECT_FALSE(noexcept(std::declval<const Enum_Zip &>().get_curr_ne()));
1369
1370 const By_Value_Items items;
1371 const auto list = one_two_three<List>();
1372 long sum = 0;
1373 for (Zip it(items, list); it.has_curr(); it.next_ne())
1374 sum += std::get<0>(it.get_curr_ne()).value * std::get<1>(it.get_curr_ne());
1375 for (Enum_Zip it(items, list); it.has_curr(); it.next_ne())
1376 sum += std::get<0>(it.get_curr_ne()).value + static_cast<long>(std::get<2>(it.get_curr_ne()));
1377 EXPECT_EQ(sum, (1 + 4 + 9) + (1 + 3 + 5));
1378
1379 const Zip zip(items, list);
1380 const Enum_Zip enum_zip(items, list);
1381 {
1382 Failing_From failing(0);
1383 EXPECT_THROW((void) zip.get_curr_ne(), Injected_Failure);
1384 EXPECT_THROW((void) enum_zip.get_curr_ne(), Injected_Failure);
1385 }
1386 EXPECT_EQ(std::get<0>(zip.get_curr_ne()).value, 1);
1387 }
1388
1389 // =========================================================================
1390 // A base of the nodes that throws, as a user may give to DECLARE_BINNODE
1391 // =========================================================================
1392
1393 // A base whose default construction and copy fail when asked to
1394 struct Failing_Base
1395 {
1396 Failing_Base() { Failures::hit("default construction of the base"); }
1397
1398 Failing_Base(const Failing_Base &) { Failures::hit("copy of the base"); }
1399
1400 Failing_Base & operator = (const Failing_Base &) noexcept = default;
1401
1402 void reset() noexcept {}
1403 };
1404
1405 DECLARE_BINNODE(Failing_Base_Node, 64, Failing_Base);
1406
1407 // Node(Key &&) builds the base by default and Node(const Control_Data &)
1408 // copies it: they were noexcept as the key, which does not throw, and
1409 // what the base threw ended the program
1410 TEST(Node_Construction_Base, LetsTheFailureOfTheBaseThrough)
1411 {
1412 using Node = Failing_Base_Node<long>;
1413 EXPECT_FALSE((std::is_nothrow_constructible_v<Node, long &&>));
1414 EXPECT_FALSE((std::is_nothrow_constructible_v<Node, const Failing_Base &>));
1415
1416 const Failing_Base base;
1417 {
1418 Failing_From failing(0);
1419 EXPECT_THROW((void) Node(7L), Injected_Failure);
1420 }
1421 {
1422 Failing_From failing(0);
1423 EXPECT_THROW((void) Node(base), Injected_Failure);
1424 }
1425
1426 // the bases of the library do not throw: their nodes keep the noexcept
1427 EXPECT_TRUE((std::is_nothrow_constructible_v<AvlNode<long>, long &&>));
1428 EXPECT_TRUE((std::is_nothrow_constructible_v<BinNode<long>, const Empty_Node &>));
1429 }
1430}
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
Zip iterators and functional operations for multiple containers.
TYPED_TEST_SUITE(ArcHeapLifecycle, ArcHeapKinds)
TYPED_TEST(ArcHeapLifecycle, ClearNullsTheHandles)
WeightedDigraph::Node Node
@ KEY
Definition btreepic.C:169
size_t size_t int32_t value
Definition ca-c-api.h:116
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
Node for binary search tree.
Node belonging to a double circular linked list with header node.
Definition tpl_dnode.H:106
Dnode< T > *& get_next() const noexcept
Return the next node to this
Definition tpl_dnode.H:114
Dnode< T > * remove_first_ne() noexcept
Remove the first node and return its address.
Definition tpl_dnode.H:152
bool contains(const Key &key) const noexcept
Return true if the key exists in the table.
Key * insert(const Key &key)
Inserts key into the hash set.
bool is_empty() const noexcept
Checks if the container is empty.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
Generic key-value map implemented on top of a binary search tree.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Dynamic set backed by balanced binary search trees with automatic memory management.
Key * insert(const Key &key)
Inserts a key into the dynamic set.
Generic linear hash table.
const size_t & size() const noexcept
Returns the number of elements in the table.
Bucket * insert(Bucket *bucket)
Insert bucket in the table.
Bucket * search(const Key &key) const noexcept
Search for key in the linear hash table.
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Declare AvlNode type with 40-byte pool allocation.
Definition avlNode.H:98
Iterator that traverses multiple containers with enumeration index.
Iterator that traverses multiple Aleph containers in lockstep.
#define TEST(name)
#define N
Definition fib.C:294
#define DECLARE_BINNODE(Name, height, Control_Data)
Specify tree node for a binary tree.
Singly linked list implementations with head-tail access.
LinearHashTable< int > Table
Definition lin-hash.cc:56
@ I
Infected (and infectious).
Main namespace for Aleph-w library functions.
T Item_Type
Type of elements from the first container.
Definition ah-zip.H:161
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
auto get_curr_ne() const noexcept(zip_detail::nothrow_curr_copy< Aleph::const_iterator_t< HeadC >, T > and zip_detail::nothrow_item_copy< T > and zip_detail::nothrow_tail_curr< ZipIterator< TailC... > >)
Return the current tuple (unchecked variant).
Definition ah-zip.H:216
DynList< std::pair< typename Container1::Item_Type, typename Container2::Item_Type > > zip(const Container1 &a, const Container2 &b)
Zip two containers into a list of pairs.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
bool contains(const std::string_view &str, const std::string_view &substr)
Check if substr appears inside str.
auto get_curr() const
Return the current tuple (bounds-checked).
Definition ah-zip.H:192
and
Check uniqueness with explicit hash + equality functors.
bool has_curr() const noexcept
Return true if all underlying iterators are positioned on a valid item.
Definition ah-zip.H:173
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
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
void next_ne() noexcept(noexcept(std::declval< Aleph::const_iterator_t< HeadC > & >().next_ne()) and noexcept(std::declval< ZipIterator< TailC... > & >().next_ne()))
Advance all underlying iterators (unchecked variant).
Definition ah-zip.H:252
@ Tuple
Tuple type such as (Int, Bool).
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Red-black tree with nodes without virtual destructor.
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Binary heap implementation using tree structure.
Doubly linked list node with typed data.
Lazy and scalable dynamic array implementation.
Dynamic map with open hashing.
Dynamic key-value map based on balanced binary search trees.
Dynamic set implementations based on hash tables.
Open addressing hash table with double hashing.
Open addressing hash table with linear probing.
DynList< int > l