Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ah-dry.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
33
38# include <gtest/gtest.h>
39
40# include <limits>
41# include <numeric>
42# include <algorithm>
43# include <map>
44# include <stdexcept>
45# include <string>
46# include <utility>
47# include <vector>
48# include <ah-zip.H>
49# include <ahFunctional.H>
50# include <ah-string-utils.H>
51# include <ahSort.H>
52# include <htlist.H>
53# include <tpl_arrayHeap.H>
54# include <tpl_dynArrayHeap.H>
55# include <tpl_dynBinHeap.H>
56# include <tpl_dynDlist.H>
57# include <tpl_dynSetTree.H>
58# include <tpl_hash.H>
59# include <tpl_dynSetHash.H>
60# include <tpl_dynArray.H>
61# include <tpl_arrayQueue.H>
62# include <tpl_dynListStack.H>
63# include <tpl_dynarray_set.H>
64# include <tpl_random_queue.H>
65# include <tpl_dynListQueue.H>
66# include <tpl_arrayStack.H>
67# include <tpl_interval_tree.H>
68# include <tpl_dynMat.H>
69# include <tpl_dynSkipList.H>
70
71using namespace std;
72using namespace testing;
73using namespace Aleph;
74
75template <class Ctype>
76struct Container : public testing::Test
77{
78 static constexpr size_t N = 1000;
79 Ctype c;
82 {
83 for (size_t i = 0; i < N; ++i)
84 {
85 c.append(i);
87 }
89 }
90};
91
93
95{
96 auto N = this->N;
97 TypeParam c = this->c;
98 EXPECT_EQ(c.size(), N);
100 EXPECT_TRUE(c.traverse([&l] (auto & k) { l.append(k); return true; }));
101 EXPECT_TRUE(zip_all([] (auto t) { return get<0>(t) == get<1>(t); },
102 this->item_list, sort(l)));
103}
104
106{
107 auto N = this->N;
108 TypeParam c = this->c;
109 EXPECT_EQ(c.size(), N);
111 c.for_each([&l] (auto & k) { l.append(k); });
112 EXPECT_TRUE(zip_all([] (auto t) { return get<0>(t) == get<1>(t); },
113 this->item_list, sort(l)));
114}
115
117{
118 auto N = this->N;
119 TypeParam c = this->c;
120 EXPECT_EQ(c.size(), N);
121 auto ptr = c.find_ptr([N] (auto & k) { return k == int(N); });
122 EXPECT_EQ(ptr, nullptr);
123 this->item_list.for_each([&c] (auto & k)
124 {
125 auto ptr = c.find_ptr([k] (auto i) { return k == i; });
126 ASSERT_NE(ptr, nullptr);
127 ASSERT_EQ(*ptr, k);
128 });
129}
130
131TYPED_TEST_P(Container, find_index_nth)
132{
133 auto N = this->N;
134 TypeParam c = this->c;
135 EXPECT_EQ(c.size(), N);
136
137 auto idx = c.find_index([N] (auto & k) { return k == int(N); });
138 ASSERT_EQ(idx, N);
139
140 this->item_list.for_each([&c] (auto & k)
141 {
142 auto idx = c.find_index([k] (auto i) { return k == i; });
143 ASSERT_EQ(c.nth(idx), k);
144 });
145}
146
148{
149 auto N = this->N;
150 TypeParam c = this->c;
151 EXPECT_EQ(c.size(), N);
152
153 auto t = c.find_item([N] (auto & k) { return k == int(N); });
154 ASSERT_FALSE(get<0>(t));
155
156 this->item_list.for_each([&c] (auto & k)
157 {
158 auto t = c.find_item([k] (auto i) { return k == i; });
159 EXPECT_TRUE(get<0>(t));
160 ASSERT_EQ(get<1>(t), k);
161 });
162}
163
164TYPED_TEST_P(Container, iterator_operations)
165{
166 //auto N = this->N;
167 auto c = this->c;
168 const DynList<int> l = to_dynlist(c); // in the same order than iterator
169 const std::vector<int> v = c.to_vector(); // test to_vector method
170 const DynList<int> l2 = c.to_dynlist(); // test to_dynlist method
171
172 ASSERT_EQ(l.size(), c.size());
173 ASSERT_EQ(v.size(), c.size());
174 ASSERT_EQ(l2.size(), c.size());
175
176 // Verify to_vector and to_dynlist produce same content
177 size_t idx = 0;
178 l2.for_each([&v, &idx](int x) {
179 EXPECT_EQ(x, v[idx++]);
180 });
181
182 auto itl = l.get_it();
183 for (auto & item : c)
184 {
185 ASSERT_EQ(item, itl.get_curr_ne());
186 itl.next_ne();
187 }
188 auto it = c.get_it();
189 EXPECT_EQ(it.get_curr_ne(), l.get_first());
190 it.reset_last();
191 EXPECT_EQ(it.get_curr_ne(), l.get_last());
192 it.reset_first();
193 EXPECT_EQ(it.get_curr_ne(), l.get_first());
194 it.reset_last();
195 EXPECT_EQ(it.get_curr_ne(), l.get_last());
196}
197
199{
200 int N = this->N;
201 auto c = this->c;
202
203 c.nappend(N);
204 auto ptr = c.find_ptr([N] (auto i) { return i == N; });
205 EXPECT_EQ(c.size(), N + 1);
206 ASSERT_NE(ptr, nullptr);
207 EXPECT_EQ(*ptr, N);
208
209 c.nappend(N + 1, N + 2, N + 3);
210 EXPECT_EQ(c.size(), N + 4);
211
212 ptr = c.find_ptr([N] (auto i) { return i == N + 1; });
213 ASSERT_NE(ptr, nullptr);
214 EXPECT_EQ(*ptr, N + 1);
215
216 ptr = c.find_ptr([N] (auto i) { return i == N + 2; });
217 ASSERT_NE(ptr, nullptr);
218 EXPECT_EQ(*ptr, N + 2);
219
220 ptr = c.find_ptr([N] (auto i) { return i == N + 3; });
221 ASSERT_NE(ptr, nullptr);
222 EXPECT_EQ(*ptr, N + 3);
223}
224
225TYPED_TEST_P(Container, nappend_and_ninsert_count_the_items_added)
226{
227 int N = this->N;
228 auto c = this->c; // holds 0 ... N - 1
229
230 // N and N + 1 are new; the second N and 0 are repeated. A sequence adds
231 // the four items; a set leaves out the keys it already holds.
232 size_t before = c.size();
233 size_t added = c.nappend(N, N, N + 1, 0);
234 EXPECT_EQ(added, c.size() - before);
235 EXPECT_GE(added, 2u);
236 EXPECT_LE(added, 4u);
237
238 before = c.size();
239 added = c.ninsert(N + 2, N + 2, N + 3, 1);
240 EXPECT_EQ(added, c.size() - before);
241 EXPECT_GE(added, 2u);
242 EXPECT_LE(added, 4u);
243
244 before = c.size();
245 EXPECT_EQ(c.nappend(), 0u);
246 EXPECT_EQ(c.ninsert(), 0u);
247 EXPECT_EQ(c.size(), before);
248}
249
251{
252 int N = this->N;
253 auto c = this->c;
254
255 c.ninsert(N);
256 auto ptr = c.find_ptr([N] (auto i) { return i == N; });
257 EXPECT_EQ(c.size(), N + 1);
258 ASSERT_NE(ptr, nullptr);
259 EXPECT_EQ(*ptr, N);
260
261 c.ninsert(N + 1, N + 2, N + 3);
262 EXPECT_EQ(c.size(), N + 4);
263
264 ptr = c.find_ptr([N] (auto i) { return i == N + 1; });
265 ASSERT_NE(ptr, nullptr);
266 EXPECT_EQ(*ptr, N + 1);
267
268 ptr = c.find_ptr([N] (auto i) { return i == N + 2; });
269 ASSERT_NE(ptr, nullptr);
270 EXPECT_EQ(*ptr, N + 2);
271
272 ptr = c.find_ptr([N] (auto i) { return i == N + 3; });
273 ASSERT_NE(ptr, nullptr);
274 EXPECT_EQ(*ptr, N + 3);
275}
276
278{
279 int N = this->N;
280 auto c = this->c;
282 ASSERT_TRUE(c.all([&tbl] (auto i)
283 {
284 const bool ret = tbl.contains(i);
285 tbl.insert(i);
286 return not ret;
287 }));
288 EXPECT_EQ(tbl.size(), N);
289 EXPECT_EQ(sort(to_dynlist(c)), tbl.keys());
290}
291
293{
294 int N = this->N;
295 auto c = this->c;
296 auto & l = this->item_list;
297 EXPECT_TRUE(l.all([&c] (auto & i)
298 { return c.exists([i] (auto k) { return i == k; }); }));
299 EXPECT_FALSE(c.exists([N] (auto i) { return i == N; }));
300}
301
303{
304 auto c = this->c;
305 auto & l = this->item_list;
306 auto fct = [] (int i) { return i + 1; };
307 EXPECT_TRUE(zip(sort(to_dynlist(c.maps(fct))), sort(l.maps(fct))).
308 all([] (auto & p) { return p.first == p.second; }));
309 EXPECT_TRUE(zip(sort(to_dynlist(c.maps_if([] (auto i)
310 { return i < 7; }, fct))),
311 sort(l.maps_if([] (auto i)
312 { return i < 7; }, fct))).
313 all([] (auto & p) { return p.first == p.second; }));
314}
315
317{
318 auto c = this->c;
319 auto & l = this->item_list;
320 auto fct = [] (int i) { return i + 1; };
321 EXPECT_TRUE(zip(sort(to_dynlist(c.map(fct))), sort(l.map(fct))).
322 all([] (auto & p) { return p.first == p.second; }));
323 EXPECT_TRUE(zip(sort(to_dynlist(c.map_if([] (auto i)
324 { return i < 7; }, fct))),
325 sort(l.map_if([] (auto i)
326 { return i < 7; }, fct))).
327 all([] (auto & p) { return p.first == p.second; }));
328}
329
331{
332 int N = this->N;
333 auto c = this->c;
334 auto sum = c.foldl(0, [] (auto & a, auto & i) { return a + i; });
335 EXPECT_EQ(sum, N*(N-1)/2);
336}
337
339{
340 auto fct = [] (int a, int i) { return a + i; };
341 auto c = this->c;
342 auto sum = c.filter([] (auto i) { return i < 8; }).foldl(0, fct);
343 EXPECT_EQ(sum, 28);
344
345 auto l = c.ptr_filter([] (auto & i) { return i < 8; });
346 sum = l.foldl(0, [] (auto a, auto ptr) { return a + *ptr; });
347 EXPECT_EQ(sum, 28);
348
349 int N = this->N;
350 auto total = N*(N-1)/2;
351 auto p = c.partition([] (auto & i) { return i < 8; });
352 auto S = p.first.foldl(0, fct) + p.second.foldl(0, fct);
353 EXPECT_EQ(S, total);
354
355 auto t = c.tpartition([] (auto & i) { return i < 8; });
356 S = get<0>(t).foldl(0, fct) + get<1>(t).foldl(0, fct);
357 EXPECT_EQ(S, total);
358
359 auto l1 = c.take(8);
360 auto l2 = c.drop(8);
361 S = l1.foldl(0, fct) + l2.foldl(0, fct);
362 EXPECT_EQ(S, total);
363
364 EXPECT_EQ(sort(c.to_dynlist()).take(8, 12),
365 build_dynlist<int>(8, 9, 10, 11, 12));
366}
367
370{
371 int key;
372 bool operator()(const int & i) const noexcept { return i == key; }
373};
374
375TYPED_TEST_P(Container, nth_out_of_range)
376{
377 constexpr size_t largest = numeric_limits<size_t>::max();
378 const TypeParam & c = this->c;
379 EXPECT_THROW((void) c.nth(this->N), out_of_range);
380 EXPECT_THROW((void) c.nth(largest), out_of_range);
381
382 // nth(SIZE_MAX) on an empty container used to return a null reference:
383 // its check compared the count with n + 1, which overflows to zero.
384 TypeParam empty;
385 EXPECT_THROW((void) empty.nth(0), out_of_range);
386 EXPECT_THROW((void) empty.nth(largest), out_of_range);
387 EXPECT_THROW((void) as_const(empty).nth(largest), out_of_range);
388}
389
390TYPED_TEST_P(Container, take_with_step)
391{
392 const TypeParam & c = this->c;
393 vector<int> order; // positions refer to the traversal order
394 c.for_each([&order] (int i) { order.push_back(i); });
395 ASSERT_EQ(order.size(), this->N);
396
397 constexpr size_t largest = numeric_limits<size_t>::max();
398 const size_t cases[][3] = { {0, 999, 1}, {0, 999, 2}, {1, 998, 3}, {5, 5, 7},
399 {0, 10, 4}, {990, largest, 3}, {0, 999, 1000},
400 {3, 900, largest}, {999, 999, 1}, {10, 5, 2},
401 {0, 4, 0}, {1000, 1005, 1}, {5000, 6000, 3},
402 {largest, largest, 1} };
403 for (const auto & [i, j, step] : cases)
404 {
405 vector<int> expected;
406 if (step != 0)
407 for (size_t p = i; p <= j and p < order.size(); )
408 {
409 expected.push_back(order[p]);
410 if (j - p < step)
411 break;
412 p += step;
413 }
414 vector<int> taken;
415 c.take(i, j, step).for_each([&taken] (int x) { taken.push_back(x); });
416 EXPECT_EQ(taken, expected) << "take(" << i << ", " << j << ", " << step << ")";
417 }
418}
419
420TYPED_TEST_P(Container, mutable_drop_needs_remove)
421{
422 // mutable_drop() calls remove(); it used to be visible on containers
423 // without remove(), where using it failed to compile.
424 constexpr bool has_remove = requires (TypeParam & c) { c.remove(); };
425 static_assert((requires (TypeParam & c) { c.mutable_drop(size_t{}); }) == has_remove);
426 if constexpr (has_remove)
427 {
428 TypeParam c = this->c;
429 const int eleventh = c.nth(10);
430 c.mutable_drop(10);
431 EXPECT_EQ(c.size(), this->N - 10);
432 EXPECT_EQ(c.nth(0), eleventh);
433 }
434}
435
436// Traversals that are plain loops over lists, arrays or hash tables cannot
437// throw by themselves: the queries built on them inherit their noexcept.
438static_assert(Aleph::dry_detail::const_traversal_is_noexcept<DynList<int>, int>);
439static_assert(Aleph::dry_detail::const_traversal_is_noexcept<DynDlist<int>, int>);
440static_assert(Aleph::dry_detail::const_traversal_is_noexcept<DynArray<int>, int>);
441static_assert(Aleph::dry_detail::const_traversal_is_noexcept<ArrayQueue<int>, int>);
442static_assert(Aleph::dry_detail::const_traversal_is_noexcept<ArrayStack<int>, int>);
443static_assert(Aleph::dry_detail::const_traversal_is_noexcept<FixedStack<int>, int>);
444static_assert(Aleph::dry_detail::const_traversal_is_noexcept<FixedQueue<int>, int>);
445static_assert(Aleph::dry_detail::const_traversal_is_noexcept<DynListQueue<int>, int>);
446static_assert(Aleph::dry_detail::const_traversal_is_noexcept<DynListStack<int>, int>);
447static_assert(Aleph::dry_detail::const_traversal_is_noexcept<DynArrayHeap<int>, int>);
448static_assert(noexcept(declval<const DynList<int> &>().find_item(Nothrow_Match{0})));
449static_assert(noexcept(declval<const DynArray<int> &>().length()));
450
451TYPED_TEST_P(Container, find_item_noexcept_for_nothrow_items)
452{
453 // Copying or default-constructing an int cannot throw, so with a
454 // noexcept criterion find_item() is noexcept exactly when the traversal
455 // of the container cannot throw by itself (F2).
456 constexpr bool nothrow_traversal =
457 Aleph::dry_detail::const_traversal_is_noexcept<TypeParam, int>;
458 static_assert(noexcept(declval<TypeParam &>().find_item(Nothrow_Match{0})) == nothrow_traversal);
459 static_assert(noexcept(declval<const TypeParam &>().find_item(Nothrow_Match{0})) == nothrow_traversal);
460 const TypeParam & c = this->c;
461 const auto [found, item] = c.find_item(Nothrow_Match{7});
462 EXPECT_TRUE(found);
463 EXPECT_EQ(item, 7);
464}
465
466
469{
470 bool operator()(int & x) const { x = -x; return true; }
471};
472
474{
475 void operator()(int & x) const { x = -x; }
476};
477
478TYPED_TEST_P(Container, queries_reject_modifying_operations)
479{
480 // A constant container hands out its items as constant references: an
481 // operation that needs `int &` does not compile with any query (G4).
482 using C = TypeParam;
483 static_assert(not requires (const C & c, Modifying_Pred & op) { c.traverse(op); });
484 static_assert(not requires (const C & c, Modifying_Pred & op) { traverse(c, op); });
485 static_assert(not requires (const C & c, Modifying_Pred & op) { c.all(op); });
486 static_assert(not requires (const C & c, Modifying_Pred & op) { c.exists(op); });
487 static_assert(not requires (const C & c, Modifying_Pred & op) { c.none(op); });
488 static_assert(not requires (const C & c, Modifying_Pred & op) { c.count_if(op); });
489 static_assert(not requires (const C & c, Modifying_Pred & op) { c.find_ptr(op); });
490 static_assert(not requires (const C & c, Modifying_Pred & op) { c.find_index(op); });
491 static_assert(not requires (const C & c, Modifying_Pred & op) { c.find_item(op); });
492 static_assert(not requires (const C & c, Modifying_Pred & op) { c.find_opt(op); });
493 static_assert(not requires (const C & c, Modifying_Pred & op) { c.contains_if(op); });
494 static_assert(not requires (const C & c, Modifying_Pred & op) { c.filter(op); });
495 static_assert(not requires (const C & c, Modifying_Act & op) { c.for_each(op); });
496 static_assert(not requires (const C & c, Modifying_Act & op) { c.each(op); });
497 static_assert(not requires (const C & c, Modifying_Act & op) { c.each(0, 1, op); });
498
499 // The same operations are accepted when they only read.
500 auto reads = [] (const int & x) { return x >= 0; };
501 static_assert(requires (const C & c) { c.traverse(reads); c.all(reads); c.find_ptr(reads); });
502}
503
504TYPED_TEST_P(Container, each_with_position_and_slice)
505{
506 const TypeParam & c = this->c;
507 vector<int> order;
508 c.for_each([&order] (int i) { order.push_back(i); });
509
510 constexpr size_t largest = numeric_limits<size_t>::max();
511 const size_t cases[][2] = { {0, 1}, {3, 7}, {999, 1}, {1000, 1}, {5000, 2},
512 {0, largest}, {10, 0} };
513 for (const auto & [pos, slice] : cases)
514 {
515 vector<int> expected;
516 if (slice != 0)
517 for (size_t p = pos; p < order.size(); )
518 {
519 expected.push_back(order[p]);
520 if (order.size() - p <= slice)
521 break;
522 p += slice;
523 }
524 vector<int> visited;
525 EXPECT_NO_THROW(c.each(pos, slice, [&visited] (int x) { visited.push_back(x); }));
526 EXPECT_EQ(visited, expected) << "each(" << pos << ", " << slice << ")";
527 }
528
529 // An empty container visits nothing and does not throw (G10)
530 const TypeParam empty;
531 size_t calls = 0;
532 EXPECT_NO_THROW(empty.each(0, 1, [&calls] (int) { ++calls; }));
533 EXPECT_EQ(calls, 0u);
534}
535
536TYPED_TEST_P(Container, functional_operations)
537{
538 const TypeParam & c = this->c;
539 vector<int> order;
540 c.for_each([&order] (int i) { order.push_back(i); });
541 const auto pred = [] (int x) { return x % 3 == 0; };
542
543 EXPECT_EQ(c.count_if(pred), size_t(count_if(order.begin(), order.end(), pred)));
544 EXPECT_TRUE(c.none([] (int x) { return x < 0; }));
545 EXPECT_FALSE(c.none(pred));
546
547 const auto found = c.find_opt([&order] (int x) { return x == order[17]; });
548 ASSERT_TRUE(found.has_value());
549 EXPECT_EQ(*found, order[17]);
550 EXPECT_FALSE(c.find_opt([] (int x) { return x < 0; }).has_value());
551
552 // take_while() and drop_while() split at the first item that fails
553 const auto small = [&order] (int x) { return x != order[400]; };
554 vector<int> prefix, suffix;
555 c.take_while(small).for_each([&prefix] (int x) { prefix.push_back(x); });
556 c.drop_while(small).for_each([&suffix] (int x) { suffix.push_back(x); });
557 EXPECT_EQ(prefix, vector<int>(order.begin(), order.begin() + 400));
558 EXPECT_EQ(suffix, vector<int>(order.begin() + 400, order.end()));
559
560 // flat_map() concatenates in traversal order
561 vector<int> doubled;
562 c.flat_map([] (int x) { return DynList<int>({x, -x}); })
563 .for_each([&doubled] (int x) { doubled.push_back(x); });
564 ASSERT_EQ(doubled.size(), 2 * order.size());
565 EXPECT_EQ(doubled[2 * 5], order[5]);
566 EXPECT_EQ(doubled[2 * 5 + 1], -order[5]);
567
568 // foldr() folds from the last item: building a list rebuilds the order
569 const auto rebuilt = c.foldr(DynList<int>(), [] (int x, DynList<int> acc)
570 {
571 acc.insert(x);
572 return acc;
573 });
574 vector<int> again;
575 rebuilt.for_each([&again] (int x) { again.push_back(x); });
576 EXPECT_EQ(again, order);
577
578 // reduce() needs no initial value; an empty container gives nullopt
579 const auto total = c.reduce([] (int a, int x) { return a + x; });
580 ASSERT_TRUE(total.has_value());
581 EXPECT_EQ(*total, accumulate(order.begin(), order.end(), 0));
582 EXPECT_FALSE(TypeParam().reduce([] (int a, int x) { return a + x; }).has_value());
583}
584
585TYPED_TEST_P(Container, unchecked_iteration_matches_the_checked_one)
586{
587 // The _ne methods are the checked ones without the checks: in the
588 // pattern `for (...; it.has_curr(); it.next_ne())` they give the same
589 // sequence (G21).
590 const TypeParam & c = this->c;
591 vector<int> checked, unchecked;
592 for (auto it = c.get_it(); it.has_curr(); it.next())
593 checked.push_back(it.get_curr());
594 for (auto it = c.get_it(); it.has_curr(); it.next_ne())
595 unchecked.push_back(it.get_curr_ne());
596 EXPECT_EQ(checked, unchecked);
597 EXPECT_EQ(checked.size(), this->N);
598}
599
601 find_index_nth, find_item, iterator_operations,
602 nappend, ninsert,
603 nappend_and_ninsert_count_the_items_added,
604 all, exists, maps, map_synonyms,
605 foldl, filter_ops, nth_out_of_range, take_with_step,
606 mutable_drop_needs_remove,
607 find_item_noexcept_for_nothrow_items,
608 queries_reject_modifying_operations,
609 each_with_position_and_slice,
610 functional_operations,
611 unchecked_iteration_matches_the_checked_one);
612
613typedef
614Types< DynList<int>, DynDlist<int>, DynArray<int>,
624 >
626
628
629template <class C>
630struct CtorContainer : public ::testing::Test
631{
632 static constexpr size_t N = 10;
633 C * ptr_1 = nullptr;
634 C * ptr_2 = nullptr;
635 C * ptr_3 = nullptr;
637 {
638 ptr_1 = new C(range<int>(N));
639 ptr_2 = new C({ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 });
640 ptr_3 = new C(ptr_1->begin(), ptr_1->end()); // Use same container for begin/end
641 }
643 {
644 delete ptr_1;
645 delete ptr_2;
646 delete ptr_3;
647 }
648};
649
651
653{
654 auto N = this->N;
655 auto ptr_1 = this->ptr_1;
656 auto ptr_2 = this->ptr_2;
657 auto ptr_3 = this->ptr_3;
658 EXPECT_EQ(ptr_1->size(), N);
659 EXPECT_EQ(ptr_2->size(), 10);
660 EXPECT_EQ(ptr_3->size(), 10);
661
662 auto l1 = to_dynlist(*ptr_1);
663 auto l2 = to_dynlist(*ptr_2);
664 auto l3 = to_dynlist(*ptr_3);
665
666 const auto r1 = range<int>(N);
667 const auto r2 = build_dynlist<int>(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
668 const auto & r3 = r1;
669
670 ASSERT_EQ(sort(l1), r1);
671 ASSERT_EQ(sort(l2), r2);
672 ASSERT_EQ(sort(l3), r3);
673}
674
676
678
680{
681 Array<int> a1 = {1, 2, 3, 4, 5};
682 Array<int> a2 = {1, 2, 3, 4, 5};
683 Array<int> a3 = {1, 2, 3, 4};
684 Array<int> a4 = {5, 4, 3, 2, 1};
685 Array<int> a5 = {1, 2, 2, 3, 4, 5};
686
687 // 1. Size mismatch
688 EXPECT_FALSE(a1.equal_to(a3));
689 EXPECT_FALSE(a1 == a3);
690 EXPECT_TRUE(a1 != a3);
691
692 // 2. Self-comparison
693 EXPECT_TRUE(a1.equal_to(a1));
694 EXPECT_TRUE(a1 == a1);
695 EXPECT_FALSE(a1 != a1);
696
697 // 3. Same elements, same order
698 EXPECT_TRUE(a1.equal_to(a2));
699 EXPECT_TRUE(a1 == a2);
700 EXPECT_FALSE(a1 != a2);
701
702 // 4. Same elements, different order
703 EXPECT_FALSE(a1.equal_to(a4));
704 EXPECT_FALSE(a1 == a4);
705 EXPECT_TRUE(a1 != a4);
706
707 // 5. Multiplicity differences
708 EXPECT_FALSE(a1.equal_to(a5));
709 EXPECT_FALSE(a1 == a5);
710
711 // DynArray
712 DynArray<int> d1 = {1, 2, 3};
713 DynArray<int> d2 = {1, 2, 3};
714 DynArray<int> d3 = {3, 2, 1};
715
716 EXPECT_TRUE(d1 == d2);
717 EXPECT_FALSE(d1 == d3);
718}
719
720TEST(StdMapCoexistence, map_method_with_std_map)
721{
722 std::map<int, std::string> std_map;
723 std_map[1] = "one";
724 std_map[2] = "two";
725 std_map[3] = "three";
726
727 DynList<int> aleph_list = {1, 2, 3, 4, 5};
728
729 auto mapped = aleph_list.map([] (int x) { return x * 2; });
730 EXPECT_EQ(mapped.size(), 5);
731
732 EXPECT_EQ(std_map.size(), 3);
733 EXPECT_EQ(std_map[1], "one");
734
735 auto filtered_mapped = aleph_list.map_if(
736 [] (int x) { return x > 2; },
737 [] (int x) { return x * 3; }
738 );
739 EXPECT_EQ(filtered_mapped.size(), 3);
740
741 std::map<std::string, int> another_map;
742 another_map["a"] = 10;
743 another_map["b"] = 20;
744
745 EXPECT_EQ(another_map.size(), 2);
746 EXPECT_EQ(another_map["a"], 10);
747
748 auto result = mapped.foldl(0, [] (int acc, int val) { return acc + val; });
749 EXPECT_EQ(result, 30);
750}
751
752namespace
753{
755 struct Copy_Throws
756 {
757 static inline bool armed = false;
758 int value = 0;
759
760 Copy_Throws() noexcept = default;
761 explicit Copy_Throws(int v) noexcept : value(v) {}
762 Copy_Throws(const Copy_Throws & other) : value(other.value)
763 {
764 if (armed)
765 throw runtime_error("copy failed");
766 }
767 Copy_Throws & operator = (const Copy_Throws &) noexcept = default;
768 };
769
771 struct Default_Throws
772 {
773 static inline bool armed = false;
774 int value = 0;
775
776 Default_Throws()
777 {
778 if (armed)
779 throw runtime_error("default construction failed");
780 }
781 explicit Default_Throws(int v) noexcept : value(v) {}
782 };
783
787 template <class C>
788 void check_find_item_propagates()
789 {
790 using T = typename C::Item_Type;
791 auto match = [] (const T & x) noexcept { return x.value == 2; };
792 auto never = [] (const T &) noexcept { return false; };
793 static_assert(not noexcept(declval<C &>().find_item(match)));
794 static_assert(not noexcept(declval<const C &>().find_item(match)));
795
796 C c;
797 for (int i = 0; i < 4; ++i)
798 c.append(T(i));
799 const C & cc = c;
800
801 T::armed = true;
802 if constexpr (is_same_v<T, Copy_Throws>)
803 {
804 EXPECT_THROW((void) c.find_item(match), runtime_error);
805 EXPECT_THROW((void) cc.find_item(match), runtime_error);
806 }
807 else
808 {
809 EXPECT_THROW((void) c.find_item(never), runtime_error);
810 EXPECT_THROW((void) cc.find_item(never), runtime_error);
811 }
812 T::armed = false;
813
814 const auto [found, item] = c.find_item(match);
815 EXPECT_TRUE(found);
816 EXPECT_EQ(item.value, 2);
817 }
818}
819
820TEST(LocateFunctions, find_item_propagates_copy_exceptions)
821{
822 check_find_item_propagates<Array<Copy_Throws>>();
823 check_find_item_propagates<DynList<Copy_Throws>>();
824 check_find_item_propagates<DynArray<Copy_Throws>>();
825}
826
827TEST(LocateFunctions, find_item_propagates_default_construction_exceptions)
828{
829 check_find_item_propagates<Array<Default_Throws>>();
830 check_find_item_propagates<DynList<Default_Throws>>();
831 check_find_item_propagates<DynArray<Default_Throws>>();
832}
833
834namespace
835{
837 struct Copy_Counted
838 {
839 static inline size_t copies = 0;
840 vector<int> items;
841
842 Copy_Counted() = default;
843 Copy_Counted(const Copy_Counted & o) : items(o.items) { ++copies; }
844 Copy_Counted(Copy_Counted && o) noexcept : items(std::move(o.items)) {}
845 Copy_Counted & operator = (const Copy_Counted & o)
846 {
847 items = o.items;
848 ++copies;
849 return *this;
850 }
851 Copy_Counted & operator = (Copy_Counted && o) noexcept
852 {
853 items = std::move(o.items);
854 return *this;
855 }
856 bool operator == (const Copy_Counted & o) const { return items == o.items; }
857 };
858
859 template <class C>
860 constexpr bool foldl_without_operation = requires (const C & c) { c.foldl(0); };
861
862 template <class C, class Arg>
863 constexpr bool can_emplace = requires (C & c, Arg a) { c.emplace(a); };
864
865 template <class C, class Op>
866 constexpr bool can_find_item = requires (const C & c, Op & op) { c.find_item(op); };
867
868 template <class C>
869 constexpr bool has_equality = requires (const C & a, const C & b) { a == b; };
870
871 template <class C>
872 constexpr bool can_modify_each = requires (C & c, Modifying_Act & op) { c.mutable_for_each(op); };
873
874 struct No_Default
875 {
876 int value;
877 explicit No_Default(int v) : value(v) {}
878 bool operator == (const No_Default & o) const { return value == o.value; }
879 };
880
881 struct Item
882 {
883 int key;
884 bool valid;
885 [[nodiscard]] bool is_valid() const noexcept { return valid; }
886 };
887}
888
889TEST(FunctionalMethods, maps_deduces_the_item_type)
890{
891 // The item type of the result is that of the operation (G5): x / 2.0
892 // used to be truncated into a DynList<int>.
893 DynList<int> l = {1, 2, 3};
894 auto halves = l.maps([] (int x) { return x / 2.0; });
895 static_assert(is_same_v<decltype(halves), DynList<double>>);
896 EXPECT_DOUBLE_EQ(halves.get_first(), 0.5);
897 EXPECT_DOUBLE_EQ(halves.get_last(), 1.5);
898
899 auto names = l.maps([] (int x) { return to_string(x); });
900 static_assert(is_same_v<decltype(names), DynList<string>>);
901 EXPECT_EQ(names.get_last(), "3");
902
903 // A reference result is decayed; an explicit type is still honoured
904 auto same = l.maps([] (const int & x) -> const int & { return x; });
905 static_assert(is_same_v<decltype(same), DynList<int>>);
906 auto longs = l.template maps<long>([] (int x) { return x; });
907 static_assert(is_same_v<decltype(longs), DynList<long>>);
908 auto odd_halves = l.maps_if([] (int x) { return x % 2; }, [] (int x) { return x / 2.0; });
909 static_assert(is_same_v<decltype(odd_halves), DynList<double>>);
910 EXPECT_EQ(odd_halves.size(), 2u);
911 static_assert(is_same_v<decltype(l.map([] (int x) { return x * 1.0f; })), DynList<float>>);
912 static_assert(is_same_v<decltype(l.map_if([] (int) { return true; }, [] (int x) { return x * 1.0f; })),
914}
915
916TEST(FunctionalMethods, foldl_moves_the_accumulator)
917{
918 // Folding into a container took a copy of the accumulator per item: O(n^2).
920 for (int i = 0; i < 1000; ++i)
921 l.append(i);
922
923 Copy_Counted::copies = 0;
924 const auto by_value = l.foldl(Copy_Counted(), [] (Copy_Counted acc, int x)
925 {
926 acc.items.push_back(x);
927 return acc;
928 });
929 EXPECT_EQ(by_value.items.size(), 1000u);
930 EXPECT_EQ(Copy_Counted::copies, 1u); // only the copy of init
931
932 // An operation that returns a reference to its parameter, which is the
933 // accumulator itself, must not leave it self-move-assigned
934 Copy_Counted::copies = 0;
935 const auto by_rvalue = l.foldl(Copy_Counted(), [] (Copy_Counted && acc, int x) -> Copy_Counted &&
936 {
937 acc.items.push_back(x);
938 return std::move(acc);
939 });
940 EXPECT_EQ(by_rvalue.items.size(), 1000u);
941 EXPECT_EQ(Copy_Counted::copies, 1u);
942
943 // An operation that takes the accumulator by modifiable reference still works
944 const auto by_lvalue = l.foldl(Copy_Counted(), [] (Copy_Counted & acc, int x) -> Copy_Counted &
945 {
946 acc.items.push_back(x);
947 return acc;
948 });
949 EXPECT_EQ(by_lvalue.items.size(), 1000u);
950
951 EXPECT_EQ(l.fold(0, [] (int a, int x) { return a + x; }), 499500);
952 EXPECT_EQ(l.fold_left(0L, [] (long a, int x) { return a + x; }), 499500L);
953}
954
955TEST(FunctionalMethods, foldl_needs_an_operation)
956{
957 // foldl(init) used a default operation that returned T(), discarding
958 // init and every item (G7).
959 static_assert(not foldl_without_operation<DynList<int>>);
960 static_assert(not foldl_without_operation<DynArray<int>>);
961}
962
963TEST(FunctionalMethods, tpartition_moves_the_lists)
964{
966 for (int i = 0; i < 100; ++i)
967 {
968 Copy_Counted c;
969 c.items.push_back(i);
970 l.append(std::move(c));
971 }
972 const auto even = [] (const Copy_Counted & c) { return c.items[0] % 2 == 0; };
973
974 Copy_Counted::copies = 0;
975 const auto p = l.partition(even);
976 const size_t pair_copies = Copy_Counted::copies;
977 Copy_Counted::copies = 0;
978 const auto t = l.tpartition(even);
979 EXPECT_EQ(pair_copies, 100u);
980 EXPECT_EQ(Copy_Counted::copies, pair_copies); // it used to copy both lists again
981 EXPECT_EQ(get<0>(t).size(), p.first.size());
982}
983
984TEST(FunctionalMethods, projections_with_member_pointers)
985{
986 const DynList<Item> l = {Item{1, true}, Item{2, false}, Item{3, true}};
987 EXPECT_EQ(l.filter(&Item::is_valid).size(), 2u);
988 EXPECT_EQ(l.maps(&Item::key).get_last(), 3);
989 static_assert(is_same_v<decltype(l.maps(&Item::key)), DynList<int>>);
990 EXPECT_FALSE(l.all(&Item::valid));
991 EXPECT_TRUE(l.exists(&Item::valid));
992 EXPECT_EQ(l.count_if(&Item::is_valid), 2u);
993 EXPECT_EQ(l.find_ptr(&Item::is_valid)->key, 1);
994 EXPECT_EQ(l.find_index(&Item::valid), 0u);
995 EXPECT_EQ(l.partition(&Item::valid).second.size(), 1u);
996}
997
998TEST(FunctionalMethods, emplace_does_not_cast)
999{
1000 // emplace(arg) built T(arg), a C-style cast for one argument: it dropped
1001 // const and turned pointers into integers (G13).
1002 static_assert(not can_emplace<DynList<int *>, const int *>);
1003 static_assert(not can_emplace<DynList<long>, int *>);
1004 static_assert(can_emplace<DynList<int *>, int *>);
1005 static_assert(can_emplace<DynList<string>, const char *>);
1006
1008 l.emplace(3, 'x');
1009 l.emplace_ins("first");
1010 EXPECT_EQ(l.get_first(), "first");
1011 EXPECT_EQ(l.get_last(), "xxx");
1012 EXPECT_EQ(l.nappend(string("a"), string("b")), 2u);
1013 EXPECT_EQ(l.ninsert(string("z")), 1u);
1014 EXPECT_EQ(l.size(), 5u);
1015}
1016
1017TEST(LocateFunctions, find_item_needs_a_default_constructor_find_opt_does_not)
1018{
1019 auto is_two = [] (const No_Default & x) { return x.value == 2; };
1020 static_assert(not can_find_item<DynList<No_Default>, decltype(is_two)>); // G12
1022 l.append(No_Default(1));
1023 l.append(No_Default(2));
1024 const auto found = l.find_opt(is_two);
1025 ASSERT_TRUE(found.has_value());
1026 EXPECT_EQ(found->value, 2);
1027 EXPECT_FALSE(l.find_opt([] (const No_Default & x) { return x.value == 9; }).has_value());
1028}
1029
1030/* In the next two tests the containers are instantiated before their item
1031 type is complete. At that point Clang 14 checked the mixin constraints
1032 that depend only on the item type, and cached `false`: the members
1033 vanished, and the cached traits also broke later checks. These tests did
1034 not compile with Clang 14 until those constraints were deferred to the
1035 call. */
1036namespace
1037{
1038 // Item's default member initializer is parsed only when Nested_Items is
1039 // complete, so until then Item is not default-constructible.
1040 struct Nested_Items
1041 {
1042 struct Item
1043 {
1044 int value = 2;
1045 };
1046
1047 Array<Item> array;
1048 DynArray<Item> dynarray;
1049 DynList<Item> list;
1050 };
1051
1052 // The list is instantiated while Recursive_Item is incomplete, and the
1053 // operator == is declared after it.
1054 struct Recursive_Item
1055 {
1056 int value = 2;
1057 DynList<Recursive_Item> children;
1058
1059 bool operator == (const Recursive_Item & o) const { return value == o.value; }
1060 };
1061}
1062
1063TEST(IncompleteItemType, nested_type_with_default_member_initializers)
1064{
1065 // The cached default constructibility also failed the static_asserts of
1066 // Array and DynArray.
1067 Nested_Items n;
1068 n.array.append(Nested_Items::Item());
1069 n.dynarray.append(Nested_Items::Item());
1070 n.list.append(Nested_Items::Item());
1071
1072 auto is_two = [] (const Nested_Items::Item & i) { return i.value == 2; };
1073 EXPECT_TRUE(get<0>(n.array.find_item(is_two)));
1074 EXPECT_TRUE(get<0>(n.dynarray.find_item(is_two)));
1075 EXPECT_TRUE(get<0>(n.list.find_item(is_two)));
1076}
1077
1078TEST(IncompleteItemType, recursive_type)
1079{
1080 // A cached `is_nothrow_destructible` also made the item look not
1081 // destructible, so emplace() vanished too.
1082 Recursive_Item r;
1083 r.children.emplace();
1084 r.children.append(Recursive_Item());
1085
1086 auto is_two = [] (const Recursive_Item & i) { return i.value == 2; };
1087 EXPECT_TRUE(get<0>(r.children.find_item(is_two)));
1088 EXPECT_TRUE(r.children.find_opt(is_two).has_value());
1089 EXPECT_TRUE(r.children.contains(Recursive_Item()));
1090 auto keep_first = [] (Recursive_Item a, const Recursive_Item &) { return a; };
1091 EXPECT_EQ(r.children.reduce(keep_first)->value, 2);
1092}
1093
1094TEST(EqualityMethods, sequences_compare_order_and_repetitions)
1095{
1096 // Stacks and queues used EqualToMethod, a set equality: [1,2] == [2,1]
1097 // and {1,1,2} == {1,2,2} were true (G3).
1098 DynListStack<int> s1, s2, s3, s4;
1099 s1.push(1); s1.push(2);
1100 s2.push(2); s2.push(1);
1101 s3.push(1); s3.push(1); s3.push(2);
1102 s4.push(1); s4.push(2); s4.push(2);
1103 EXPECT_FALSE(s1 == s2);
1104 EXPECT_FALSE(s3 == s4);
1105 EXPECT_TRUE(s1 != s2);
1106
1107 DynListQueue<int> q1, q2;
1108 q1.put(1); q1.put(2);
1109 q2.put(2); q2.put(1);
1110 EXPECT_FALSE(q1 == q2);
1111 q2.get(); q2.put(2); // q2 is now [1, 2]
1112 EXPECT_TRUE(q1 == q2);
1113
1114 // Stacks and queues on arrays: equality used to not even compile
1115 ArrayStack<int> a1, a2;
1116 a1.push(1); a1.push(2);
1117 a2.push(1); a2.push(2);
1118 EXPECT_TRUE(a1 == a2);
1119 a2.push(3);
1120 EXPECT_FALSE(a1 == a2);
1121 FixedStack<int> f1(4), f2(4);
1122 f1.push(1); f2.push(1);
1123 EXPECT_TRUE(f1 == f2);
1124 ArrayQueue<int> aq1, aq2;
1125 aq1.put(1); aq1.put(2);
1126 aq2.put(2); aq2.put(1);
1127 EXPECT_FALSE(aq1 == aq2);
1128 FixedQueue<int> fq1(4), fq2(4);
1129 fq1.put(5); fq2.put(5);
1130 EXPECT_TRUE(fq1 == fq2);
1131}
1132
1133TEST(EqualityMethods, sorted_containers_count_repetitions)
1134{
1135 DynSetTree<int> t1, t2;
1136 t1.insert_dup(1); t1.insert_dup(1); t1.insert_dup(2);
1137 t2.insert_dup(1); t2.insert_dup(2); t2.insert_dup(2);
1138 EXPECT_FALSE(t1 == t2);
1139 t2.remove(2); t2.insert_dup(1);
1140 EXPECT_TRUE(t1 == t2);
1141
1142 DynIntervalTree<int> i1, i2;
1143 i1.append(Interval<int>(1, 2)); i1.append(Interval<int>(1, 2)); i1.append(Interval<int>(3, 4));
1144 i2.append(Interval<int>(1, 2)); i2.append(Interval<int>(3, 4)); i2.append(Interval<int>(3, 4));
1145 EXPECT_FALSE(i1 == i2);
1147 i3.append(Interval<int>(3, 4)); i3.append(Interval<int>(1, 2)); i3.append(Interval<int>(1, 2));
1148 EXPECT_TRUE(i1 == i3);
1149 EXPECT_FALSE(i1 == DynIntervalTree<int>());
1150}
1151
1152TEST(EqualityMethods, hash_sets_keep_set_equality)
1153{
1154 DynSetHash<int> h1, h2;
1155 for (int i : {1, 2, 3})
1156 h1.insert(i);
1157 for (int i : {3, 1, 2})
1158 h2.insert(i);
1159 EXPECT_TRUE(h1 == h2);
1160 h2.remove(3);
1161 EXPECT_FALSE(h1 == h2);
1162}
1163
1164TEST(EqualityMethods, heaps_and_random_sets_have_no_equality)
1165{
1166 // EqualToMethod was inherited but never compiled for them (D2)
1167 static_assert(not has_equality<ArrayHeap<int>>);
1168 static_assert(not has_equality<DynBinHeap<int>>);
1169 static_assert(not has_equality<DynArrayHeap<int>>);
1170 static_assert(not has_equality<Random_Set<int>>);
1171 static_assert(has_equality<DynListStack<int>>);
1172 static_assert(has_equality<ArrayQueue<int>>);
1173}
1174
1175TEST(RandomSet, iterator_traverses_the_items)
1176{
1177 // Random_Set::Iterator derived from DynArray<T>: a container, not an
1178 // iterator, so range-for, take(i, j, step) and each(pos, slice) did not
1179 // compile (G11).
1181 for (int i = 0; i < 10; ++i)
1182 q.put(i);
1183 int sum = 0;
1184 for (const int x : q)
1185 sum += x;
1186 EXPECT_EQ(sum, 45);
1187 size_t n = 0;
1188 for (auto it = q.get_it(); it.has_curr(); it.next_ne())
1189 ++n;
1190 EXPECT_EQ(n, 10u);
1191 EXPECT_EQ(q.take(0, 9, 3).size(), 4u);
1192 size_t visited = 0;
1193 q.each(1, 4, [&visited] (int) { ++visited; });
1194 EXPECT_EQ(visited, 3u);
1195}
1196
1197TEST(ReadOnlyContainers, offer_queries_but_no_modifying_members)
1198{
1199 // DynMatrix, Polygon and DynIntervalTree traverse with constant
1200 // references: the members that modify are not offered, and the queries
1201 // that used to fail to compile now work (G11).
1202 static_assert(not can_modify_each<DynMatrix<int>>);
1203 static_assert(not can_modify_each<DynSkipList<int>>);
1204 static_assert(not can_modify_each<DynIntervalTree<int>>);
1205 static_assert(can_modify_each<DynList<int>>);
1206
1207 DynMatrix<int> m(2, 3);
1208 m.allocate();
1209 for (size_t i = 0; i < 2; ++i)
1210 for (size_t j = 0; j < 3; ++j)
1211 m.write(i, j, int(3 * i + j));
1212 EXPECT_EQ(m.nth(4), 4);
1213 EXPECT_EQ(*m.find_ptr([] (int x) { return x == 5; }), 5);
1214 EXPECT_TRUE(m.contains(2));
1215 EXPECT_EQ(m.take(0, 5, 2).size(), 3u);
1216}
1217
1218namespace
1219{
1222 struct Pair_Map : public FunctionalMethods<Pair_Map, pair<int, string>>,
1223 public MapSequencesMethods<Pair_Map, int, string>
1224 {
1225 DynList<pair<int, string>> items_list;
1226
1227 template <class Op>
1229 bool traverse(Op & op) { return items_list.traverse(op); }
1230
1231 template <class Op>
1233 bool traverse(Op & op) const { return items_list.traverse(op); }
1234
1235 template <class Op>
1237 bool traverse(Op && op) { return items_list.traverse(op); }
1238
1239 template <class Op>
1241 bool traverse(Op && op) const { return items_list.traverse(op); }
1242
1243 string & find(const int & k)
1244 {
1245 auto p = items_list.find_ptr([&k] (const pair<int, string> & e) { return e.first == k; });
1246 ah_domain_error_if(p == nullptr) << "key not found";
1247 return p->second;
1248 }
1249
1250 const string & find(const int & k) const { return const_cast<Pair_Map *>(this)->find(k); }
1251 };
1252}
1253
1255{
1256 // keys(), values_ptr(), items() and items_ptr() did not compile (G14)
1257 Pair_Map m;
1258 m.items_list.append(make_pair(1, string("one")));
1259 m.items_list.append(make_pair(2, string("two")));
1260
1261 EXPECT_EQ(m.keys().get_last(), 2);
1262 EXPECT_EQ(m.values().get_first(), "one");
1263 EXPECT_EQ(m.items().size(), 2u);
1264
1265 *m.values_ptr().get_first() = "uno";
1266 EXPECT_EQ(m(1), "uno");
1267 *m.items_ptr().get_last().second = "dos";
1268 EXPECT_EQ(m(2), "dos");
1269
1270 const Pair_Map & cm = m;
1271 static_assert(is_same_v<decltype(cm.values_ptr()), DynList<const string *>>);
1272 EXPECT_EQ(*cm.items_ptr().get_last().second, "dos");
1273 EXPECT_THROW(m(3), domain_error);
1274}
bool traverse(const Container &c, Operation &op) noexcept(noexcept(c.traverse(op)))
Invoke c.traverse(op) as a free function (lvalue operation).
Definition ah-dry.H:506
INSTANTIATE_TYPED_TEST_SUITE_P(traverses, Container, Ctypes)
REGISTER_TYPED_TEST_SUITE_P(Container, traverse, for_each, find_ptr, find_index_nth, find_item, iterator_operations, nappend, ninsert, nappend_and_ninsert_count_the_items_added, all, exists, maps, map_synonyms, foldl, filter_ops, nth_out_of_range, take_with_step, mutable_drop_needs_remove, find_item_noexcept_for_nothrow_items, queries_reject_modifying_operations, each_with_position_and_slice, functional_operations, unchecked_iteration_matches_the_checked_one)
Types< DynList< int >, DynDlist< int >, DynArray< int >, HashSet< int, ODhashTable >, HashSet< int, OLhashTable >, DynHashTable< int, LhashTable >, DynHashTable< int, LinearHashTable >, DynSetHash< int >, DynSetTree< int, Treap >, DynSetTree< int, Treap_Rk >, DynSetTree< int, Rand_Tree >, DynSetTree< int, Splay_Tree >, DynSetTree< int, Avl_Tree >, DynSetTree< int, Rb_Tree >, Array< int >, ArrayQueue< int >, ArrayStack< int >, DynListQueue< int >, DynListStack< int >, DynArrayHeap< int >, DynBinHeap< int >, FixedQueue< int >, FixedStack< int > > Ctypes
Definition ah-dry.cc:625
TYPED_TEST_SUITE_P(Container)
TYPED_TEST_P(Container, traverse)
Definition ah-dry.cc:94
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
String manipulation utilities.
Zip iterators and functional operations for multiple containers.
Functional programming utilities for Aleph-w containers.
High-level sorting functions for Aleph containers.
size_t size_t int32_t value
Definition ca-c-api.h:116
Queue implemented with a single dynamic array.
T & put(const T &item)
Copy and put an item in the queue.
Stack implemented with simple dynamic array and with bounds verification.
T & push(const T &data)
Push into stack a copy of data
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
Dynamic heap (priority queue) backed by DynArray.
Dynamic heap of elements of type T ordered by a comparison functor.
Dynamic doubly linked list with O(1) size and bidirectional access.
Self-adjusting dynamic hash table.
void remove(Key *key)
Removes a key from the hash table using its pointer.
Key * insert(const Key &key)
Inserts key into the hash set.
High-level interval tree with automatic memory management.
Key & append(const Key &iv)
Append an interval (alias for insert_dup).
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
T get()
Remove the oldest item of the queue.
Dynamic stack of elements of generic type T based on a singly linked list.
T & push(const T &data)
Push an item by copy onto the top of the stack.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & get_first()
Return the first item of the list.
Definition htlist.H:1548
T & append(const T &item)
Definition htlist.H:1362
T & insert(const T &item)
Definition htlist.H:1308
T & get_last()
Return the last item of the list.
Definition htlist.H:1529
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
Dynamic matrix with sparse storage.
Definition tpl_dynMat.H:122
Dynamic set backed by balanced binary search trees with automatic memory management.
size_t remove(const Key &key)
Removes a key from the dynamic set.
Key * insert_dup(const Key &key)
Very simple queue implemented with a contiguous array.
T & put(const T &item) noexcept
Put an item into the queue by copy.
Fixed length stack.
T & push(const T &data) noexcept(std::is_nothrow_copy_assignable_v< T >)
Push a copy of data
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
constexpr bool contains(const Key &key) const noexcept
Alias for has().
Definition hashDry.H:769
void put(const T &item)
Insert an item by copy.
Minimal std::expected-style result type for C++20.
Mixin providing equality comparison for sequence containers.
Definition ah-dry.H:2945
bool equal_to(const Container &r) const
Equality test between this and r.
Definition ah-dry.H:2963
Common methods to the Aleph-w ( ) containers.
Definition ah-dry.H:1235
std::pair< Aleph::DynList< T >, Aleph::DynList< T > > partition(Operation &op) const
Exclusive partition of container according to a filter criterion.
Definition ah-dry.H:2515
void emplace(Args &&... args)
Appends a new element into the container by constructing it from the given args.
Definition ah-dry.H:1292
Aleph::DynList< Aleph::dry_detail::map_result_t< R, Operation &, T > > maps(Operation &op) const
Definition ah-dry.H:1829
Aleph::DynList< Aleph::dry_detail::map_result_t< R, Operation &, T > > map(Operation &op) const
Definition ah-dry.H:1946
bool exists(Operation &op) const
Test for existence in the container of an element satisfying a criterion.
Definition ah-dry.H:1707
void each(Operation &operation) const
Alias of for_each().
Definition ah-dry.H:1507
Aleph::DynList< T > to_dynlist() const
Convert container to DynList.
Definition ah-dry.H:2072
T fold(const T &init, Operation &operation) const
Simplified version of foldl() where the folded type is the same type of elements stored in the contai...
Definition ah-dry.H:2222
Aleph::DynList< T > filter(Operation &operation) const
Filter the elements of a container according to a matching criterion.
Definition ah-dry.H:2356
std::tuple< Aleph::DynList< T >, Aleph::DynList< T > > tpartition(Operation &op) const
Exclusive partition of container according to a filter criterion.
Definition ah-dry.H:2610
Aleph::DynList< Aleph::dry_detail::map_result_t< R, Operation &, T > > map_if(Prop prop, Operation &op) const
Definition ah-dry.H:1990
bool all(Operation &operation) const
Check if all the elements of the container satisfy a condition.
Definition ah-dry.H:1666
Aleph::DynList< T > take(const size_t n) const
Return a list with the first n elements seen in the container during its traversal.
Definition ah-dry.H:2696
size_t nappend(Args &&... args)
Append n variadic items.
Definition ah-dry.H:1379
Acc foldl(const Acc &init, Op &op) const
Fold the elements of the container to a specific result.
Definition ah-dry.H:2145
Aleph::DynList< Aleph::dry_detail::map_result_t< R, Operation &, T > > maps_if(Prop prop, Operation &op) const
Definition ah-dry.H:1889
size_t ninsert(Args &&... args)
Insert n variadic items.
Definition ah-dry.H:1353
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
size_t count_if(Operation &op) const
Count the elements that satisfy a criterion.
Definition ah-dry.H:1772
Acc fold_left(const Acc &init, Op &op) const
Alias for foldl().
Definition ah-dry.H:2186
Aleph::DynList< T > drop(const size_t n) const
Drop the first n elements seen in the container during its traversal.
Definition ah-dry.H:2757
void emplace_ins(Args &&... args)
Definition ah-dry.H:1329
Aleph::DynList< const T * > ptr_filter(Operation &operation) const
Filter the elements of a container according to a matching criterion and return a pointer to the matc...
Definition ah-dry.H:2411
Common sequential searching methods on containers.
Definition ah-dry.H:555
Type & nth(const size_t n)
Return the n-th item of the container.
Definition ah-dry.H:774
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
and std::copy_constructible< T > std::optional< Type > find_opt(Operation &operation) const
Copy of the first item satisfying a criterion, if any.
Definition ah-dry.H:1028
and Aleph::dry_detail::MutablyTraversable< typename Aleph::concepts_detail::defer< Container, Operation >::type, Type > Type * find_ptr(Operation &operation) noexcept(mutable_search_is_noexcept< Operation >())
Find a pointer to an item in the container according to a searching criterion.
Definition ah-dry.H:825
size_t find_index(Operation &operation) const noexcept(const_search_is_noexcept< Operation >())
Find the position of an item in the container according to a searching criterion.
Definition ah-dry.H:921
Common methods to mapping containers.
Definition ah-dry.H:3190
Key * append(const Key &key)
Alias for insert() (copy version).
Definition hashDry.H:733
DynList< Key > keys() const
Returns a list containing all keys in the table.
Definition hashDry.H:1247
auto items() const
Alias for keys().
Definition hashDry.H:1256
f(args...) is a valid call whose result is usable as a condition.
#define TEST(name)
#define N
Definition fib.C:294
bool traverse(Node *root, Op op)
See infix_traverse().
MapOLhash< int, Foo > tbl
Singly linked list implementations with head-tail access.
Freq_Node * pred
Predecessor node in level-order traversal.
Main namespace for Aleph-w library functions.
DynList< typename Container::Item_Type > to_dynlist(const Container &c)
Definition htlist.H:2086
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
static void suffix(Node *root, DynList< Node * > &acc)
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.
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
T foldl(const Container &container, const T &init, Operation operation)
Classic left fold (reduce).
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
bool exists(Container &container, Operation &operation)
Return true if at least one element satisfies a predicate.
DynArray< T > sort(const DynArray< T > &a, Cmp &&cmp=Cmp())
Returns a sorted copy of a DynArray.
Definition ahSort.H:234
T accumulate(Itor beg, Itor end, T initValue)
Accumulate values in a range.
Definition ahAlgo.H:1493
static void prefix(Node *root, DynList< Node * > &acc)
Itor find(const Itor &beg, const Itor &end, const T &value)
Find the first element equal to a value.
Definition ahAlgo.H:230
and
Check uniqueness with explicit hash + equality functors.
bool zip_all(Op &&op, const Cs &...cs)
Return true if op returns true for all tuples and containers have equal length.
Definition ah-zip.H:505
std::pair< First, Second > pair
Alias to std::pair kept for backwards compatibility.
Definition ahPair.H:89
Operation for_each(Itor beg, const Itor &end, Operation op)
Apply an operation to each element in a range.
Definition ahAlgo.H:76
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
Itor::difference_type count_if(Itor beg, const Itor &end, Operation op)
Count elements satisfying a predicate.
Definition ahAlgo.H:100
Container::Item_Type * find_ptr(Container &container, Pred &pred)
Find the first element satisfying pred.
DynList< T > maps(const C &c, Op op)
Classic map operation.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
STL namespace.
Closed interval [low, high].
Container()
Definition ah-dry.cc:81
static constexpr size_t N
Definition ah-dry.cc:78
DynList< int > item_list
Definition ah-dry.cc:80
Ctype c
Definition ah-dry.cc:79
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
void operator()(int &x) const
Definition ah-dry.cc:475
Operations that need to modify the item: queries must reject them.
Definition ah-dry.cc:469
bool operator()(int &x) const
Definition ah-dry.cc:470
Matching criterion that cannot throw.
Definition ah-dry.cc:370
bool operator()(const int &i) const noexcept
Definition ah-dry.cc:372
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
DynList< char > l3
DynList< int > l1
DynList< int > l2
static int * k
Gsl_Compatible_Rng r
Fixed-capacity binary heap and heapsort algorithms.
Circular queue implementations backed by arrays.
Stack implementations backed by dynamic or fixed arrays.
Array-based dynamic binary heap.
Lazy and scalable dynamic array implementation.
Dynamic binary heap with node-based storage.
Dynamic doubly linked list implementation.
Dynamic queue implementation based on linked lists.
Dynamic stack implementation based on linked lists.
Dynamic matrix with lazy allocation.
Dynamic set implementations based on hash tables.
Dynamic set implementations based on balanced binary search trees.
Dynamic ordered set implemented with a Skip List.
Array-based dynamic set.
Unified hash table interface.
Interval tree: augmented BST for overlap/stabbing queries.
Random access queue (bag) with O(1) random pop.
DynList< int > l