Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ah-dry-mixin_test.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 <stdexcept>
42#include <vector>
43#include <string>
44#include <htlist.H>
45#include <ah-dry-mixin.H>
46#include <tpl_array.H>
47#include <tpl_dynArray.H>
48
49using namespace std;
50using namespace Aleph;
51
52// =============================================================================
53// Test Container using CRTP Mixins
54// =============================================================================
55
57template <typename T>
58class MixinVector : public TraverseMixin<MixinVector<T>, T>,
59 public LocateMixin<MixinVector<T>, T>,
60 public FunctionalMixin<MixinVector<T>, T>,
61 public KeysMixin<MixinVector<T>, T>
62{
63 std::vector<T> data;
64
65public:
66 using Item_Type = T;
67
68 MixinVector() = default;
69 MixinVector(std::initializer_list<T> init) : data(init) {}
70
71 void append(const T & item) { data.push_back(item); }
72 void insert(const T & item) { data.insert(data.begin(), item); }
73 size_t size() const noexcept { return data.size(); }
74 bool is_empty() const noexcept { return data.empty(); }
75
76 // Iterator compatible with Aleph requirements
78 {
80 size_t pos;
81
82 public:
83 Iterator() : container(nullptr), pos(0) {}
84 Iterator(const MixinVector & c) : container(&c), pos(0) {}
85
86 bool has_curr() const noexcept { return pos < container->data.size(); }
87 T & get_curr() const { return const_cast<T&>(container->data[pos]); }
88 void next() { ++pos; }
89 void next_ne() noexcept { ++pos; }
90 };
91
92 Iterator get_it() const { return Iterator(*this); }
93
94 // For testing equality
95 bool operator==(const MixinVector & other) const { return data == other.data; }
96};
97
98
99// =============================================================================
100// TraverseMixin Tests
101// =============================================================================
102
103TEST(TraverseMixin, BasicTraverse)
104{
105 MixinVector<int> v = {1, 2, 3, 4, 5};
106
107 int sum = 0;
108 bool completed = v.traverse([&sum](int x) {
109 sum += x;
110 return true;
111 });
112
113 EXPECT_TRUE(completed);
114 EXPECT_EQ(sum, 15);
115}
116
117TEST(TraverseMixin, TraverseEarlyStop)
118{
119 MixinVector<int> v = {1, 2, 3, 4, 5};
120
121 int sum = 0;
122 bool completed = v.traverse([&sum](int x) {
123 if (x > 3) return false;
124 sum += x;
125 return true;
126 });
127
128 EXPECT_FALSE(completed);
129 EXPECT_EQ(sum, 6); // 1 + 2 + 3
130}
131
132TEST(TraverseMixin, TraverseEmpty)
133{
135
136 bool completed = v.traverse([](int) { return true; });
137 EXPECT_TRUE(completed);
138}
139
140// A constant container hands out constant items. An operation that takes a
141// modifiable reference must be rejected by the constraint of traverse(), and
142// of the constant members that ask it (all()), instead of failing inside
143// their body.
144template <class C, class Op>
145concept TraversesWith = requires(C & c, Op & op) { c.template traverse<Op>(op); };
146
147template <class C, class Op>
148concept TraversesWithTemporary = requires(C & c) { c.traverse(Op()); };
149
150template <class C, class Op>
151concept TestsAllWith = requires(C & c, Op & op) { c.template all<Op>(op); };
152
153struct TakesModifiableItem { bool operator () (int & x) const { return x > 0; } };
154struct TakesConstantItem { bool operator () (const int & x) const { return x > 0; } };
155
156TEST(TraverseMixin, ConstantContainerRejectsModifyingOperation)
157{
158 using V = MixinVector<int>;
159
164
168
170 static_assert(not TestsAllWith<V, TakesModifiableItem>);
171
172 V v = {1, 2, 3};
173 EXPECT_TRUE(v.traverse([] (int & x) { x *= 2; return true; }));
174
175 const V & cv = v;
176 int sum = 0;
177 EXPECT_TRUE(cv.traverse([&sum] (const int & x) { sum += x; return true; }));
178 EXPECT_EQ(sum, 12);
179 TakesConstantItem positive;
180 EXPECT_TRUE(cv.traverse(positive));
181 EXPECT_TRUE(cv.all(positive));
182}
183
184
185// =============================================================================
186// FunctionalMixin Tests
187// =============================================================================
188
190{
191 MixinVector<int> v = {1, 2, 3};
192
193 int sum = 0;
194 v.for_each([&sum](int x) { sum += x; });
195
196 EXPECT_EQ(sum, 6);
197}
198
199TEST(FunctionalMixin, MutableForEach)
200{
201 MixinVector<int> v = {1, 2, 3};
202
203 v.mutable_for_each([](int& x) { x *= 2; });
204
205 int sum = 0;
206 v.for_each([&sum](int x) { sum += x; });
207 EXPECT_EQ(sum, 12); // 2 + 4 + 6
208}
209
210TEST(FunctionalMixin, AllPredicate)
211{
212 MixinVector<int> v = {2, 4, 6, 8};
213
214 EXPECT_TRUE(v.all([](int x) { return x % 2 == 0; }));
215 EXPECT_FALSE(v.all([](int x) { return x > 5; }));
216}
217
219{
221 // Vacuous truth
222 EXPECT_TRUE(v.all([](int) { return false; }));
223}
224
225TEST(FunctionalMixin, ExistsPredicate)
226{
227 MixinVector<int> v = {1, 3, 5, 6, 7};
228
229 EXPECT_TRUE(v.exists([](int x) { return x % 2 == 0; })); // 6
230 EXPECT_FALSE(v.exists([](int x) { return x > 100; }));
231}
232
234{
236 EXPECT_FALSE(v.exists([](int) { return true; }));
237}
238
240{
241 MixinVector<int> v = {1, 2, 3};
242
243 auto squared = v.maps<int>([](int x) { return x * x; });
244
245 EXPECT_EQ(squared.size(), 3);
246
247 int expected[] = {1, 4, 9};
248 int i = 0;
249 squared.for_each([&](int x) { EXPECT_EQ(x, expected[i++]); });
250}
251
252TEST(FunctionalMixin, MapsTypeConversion)
253{
254 MixinVector<int> v = {1, 2, 3};
255
256 auto strs = v.maps<string>([](int x) { return to_string(x); });
257
258 EXPECT_EQ(strs.size(), 3);
259
260 string expected[] = {"1", "2", "3"};
261 int i = 0;
262 strs.for_each([&](const string& s) { EXPECT_EQ(s, expected[i++]); });
263}
264
265// Without an operation, maps() copies the items and maps<R>() converts each
266// one to R. The default operation had its two types exchanged: an item went
267// to R, back to its own type and to R again, which is not the same value
268// for every item, and did not compile for an R from which the type of the
269// items is not built. And it was noexcept: a copy that threw ended the
270// program.
271namespace
272{
273 // Counts its constructions from an int, to which it converts back
274 struct Counted_From_Int
275 {
276 static inline int built = 0;
277 int v;
278 Counted_From_Int(const int x) : v(x) { ++built; }
279 operator int () const { return v; }
280 };
281
282 struct Meters
283 {
284 double v;
285 };
286
287 // Built from Meters, and Meters is not built from it
288 struct Feet
289 {
290 double v;
291 explicit Feet(const Meters & m) : v(m.v * 3.28084) {}
292 };
293
294 struct Copy_May_Throw
295 {
296 static inline bool fail = false;
297 int v = 0;
298 Copy_May_Throw() = default;
299 Copy_May_Throw(const int x) : v(x) {}
300 Copy_May_Throw(const Copy_May_Throw & c) : v(c.v)
301 {
302 if (fail)
303 throw std::runtime_error("the copy fails");
304 }
305 Copy_May_Throw & operator = (const Copy_May_Throw &) = default;
306 };
307
308 // An item that counts its copies and its moves
309 struct Counted_Item
310 {
311 static inline int copies = 0, moves = 0;
312 int v = 0;
313 Counted_Item() = default;
314 Counted_Item(const int x) : v(x) {}
315 Counted_Item(const Counted_Item & c) : v(c.v) { ++copies; }
316 Counted_Item(Counted_Item && c) noexcept : v(c.v) { ++moves; }
317 Counted_Item & operator = (const Counted_Item &) = default;
318 };
319
320 // An item that counts its copies and has no move: its rvalues are copied
321 struct Counted_Copy
322 {
323 static inline int copies = 0;
324 int v = 0;
325 Counted_Copy() = default;
326 Counted_Copy(const int x) : v(x) {}
327 Counted_Copy(const Counted_Copy & c) : v(c.v) { ++copies; }
328 Counted_Copy & operator = (const Counted_Copy &) = default;
329 };
330
331 // A container for a result that takes its items by rvalue alone
332 template <typename T>
333 struct Only_Rvalues
334 {
335 DynList<T> items;
336 void append(T && item) { items.append(std::move(item)); }
337 };
338
339 template <class C, class R>
340 concept Maps_To = requires (const C & c) { c.template maps<R>(); };
341
342 // Asking whether a container maps without operation to a type is an
343 // answer, also when its items do not convert to the type
344 static_assert(Maps_To<MixinVector<int>, double>);
345 static_assert(Maps_To<MixinVector<Meters>, Meters>);
346 static_assert(Maps_To<MixinVector<Meters>, Feet>);
347 static_assert(not Maps_To<MixinVector<Feet>, Meters>);
348 static_assert(not Maps_To<MixinVector<Meters>, int>);
349}
350
351TEST(FunctionalMixin, MapsWithoutOperationCopiesTheItems)
352{
353 MixinVector<int> v = {3, 1, 2};
354
355 const DynList<int> copy = v.maps();
356 EXPECT_EQ(copy, build_dynlist<int>(3, 1, 2));
357 EXPECT_EQ(v.maps<int>(), copy);
358 EXPECT_TRUE(MixinVector<int>().maps().is_empty());
359}
360
361TEST(FunctionalMixin, MapsWithoutOperationConvertsEachItemOnce)
362{
363 MixinVector<int> v = {3, 1, 2};
364 Counted_From_Int::built = 0;
365 const DynList<Counted_From_Int> counted = v.maps<Counted_From_Int>();
366 EXPECT_EQ(Counted_From_Int::built, 3);
367 EXPECT_EQ(counted.maps<int>([] (const Counted_From_Int & c) { return c.v; }), build_dynlist<int>(3, 1, 2));
368
369 // the largest 64-bit integer is not a double, and the nearest one, 2^63,
370 // is not a 64-bit integer: there is no way back from it
371 MixinVector<long long> big = {std::numeric_limits<long long>::max(), 5, -7};
372 EXPECT_EQ(big.maps<double>(), build_dynlist<double>(9223372036854775808.0, 5.0, -7.0));
373
374 MixinVector<double> halves = {3.75, -0.5};
375 EXPECT_EQ(halves.maps<int>(), build_dynlist<int>(3, 0));
376
377 MixinVector<Meters> lengths = {Meters{1.0}, Meters{2.0}};
378 const DynList<Feet> feet = lengths.maps<Feet>();
379 EXPECT_EQ(feet.maps<double>([] (const Feet & f) { return f.v; }), build_dynlist<double>(3.28084, 6.56168));
380}
381
382// The copy of maps() without operation took each item twice: the default
383// operation built a copy, and the container moved it, or copied it again
384// when the item has no move
385TEST(FunctionalMixin, MapsWithoutOperationCopiesEachItemOnce)
386{
389 for (int i = 0; i < 5; ++i)
390 {
391 v.append(Counted_Item(i));
392 w.append(Counted_Copy(i));
393 }
394
395 Counted_Item::copies = Counted_Item::moves = 0;
396 const DynList<Counted_Item> items = v.maps();
397 EXPECT_EQ(Counted_Item::copies, 5);
398 EXPECT_EQ(Counted_Item::moves, 0);
399 EXPECT_EQ(items.maps<int>([] (const Counted_Item & c) { return c.v; }), build_dynlist<int>(0, 1, 2, 3, 4));
400
401 Counted_Item::copies = Counted_Item::moves = 0;
402 EXPECT_EQ(v.maps<Counted_Item>().size(), 5u);
403 EXPECT_EQ(Counted_Item::copies, 5);
404 EXPECT_EQ(Counted_Item::moves, 0);
405
406 Counted_Copy::copies = 0;
407 const DynList<Counted_Copy> copies = w.maps();
408 EXPECT_EQ(Counted_Copy::copies, 5);
409 EXPECT_EQ(copies.maps<int>([] (const Counted_Copy & c) { return c.v; }), build_dynlist<int>(0, 1, 2, 3, 4));
410}
411
412// maps() copies the item itself into a container that takes it so. One
413// whose append() takes only an rvalue is given what the default operation
414// builds, as before: maps() into it did not compile with the copy alone
415TEST(FunctionalMixin, MapsWithoutOperationIntoAContainerOfRvalues)
416{
417 MixinVector<int> v = {3, 1, 2};
418 const Only_Rvalues<int> same = v.maps<void, Only_Rvalues>();
419 EXPECT_EQ(same.items, build_dynlist<int>(3, 1, 2));
420 const Only_Rvalues<int> named = v.maps<int, Only_Rvalues>();
421 EXPECT_EQ(named.items, build_dynlist<int>(3, 1, 2));
422 const Only_Rvalues<double> wide = v.maps<double, Only_Rvalues>();
423 EXPECT_EQ(wide.items, build_dynlist<double>(3.0, 1.0, 2.0));
424
426 for (int i = 0; i < 5; ++i)
427 items.append(Counted_Item(i));
428 Counted_Item::copies = Counted_Item::moves = 0;
429 const Only_Rvalues<Counted_Item> moved = items.maps<void, Only_Rvalues>();
430 EXPECT_EQ(Counted_Item::copies, 5);
431 EXPECT_EQ(Counted_Item::moves, 5);
432 EXPECT_EQ(moved.items.size(), 5u);
433}
434
435TEST(FunctionalMixin, MapsWithoutOperationLetsACopyThrow)
436{
438 for (int i = 0; i < 5; ++i)
439 v.append(Copy_May_Throw(i));
440
441 Copy_May_Throw::fail = true;
442 EXPECT_THROW((void) v.maps(), std::runtime_error);
443 EXPECT_THROW((void) v.maps<Copy_May_Throw>(), std::runtime_error);
444 Copy_May_Throw::fail = false;
445 EXPECT_EQ(v.maps().size(), 5u);
446}
447
449{
450 MixinVector<int> v = {1, 2, 3, 4, 5, 6};
451
452 auto evens = v.filter([](int x) { return x % 2 == 0; });
453
454 EXPECT_EQ(evens.size(), 3);
455
456 int expected[] = {2, 4, 6};
457 int i = 0;
458 evens.for_each([&](int x) { EXPECT_EQ(x, expected[i++]); });
459}
460
462{
463 MixinVector<int> v = {1, 3, 5, 7};
464
465 auto evens = v.filter([](int x) { return x % 2 == 0; });
466 EXPECT_TRUE(evens.is_empty());
467}
468
470{
471 MixinVector<int> v = {1, 2, 3, 4, 5};
472
473 int sum = v.foldl<int>(0, [](int acc, int x) { return acc + x; });
474 EXPECT_EQ(sum, 15);
475
476 int product = v.foldl<int>(1, [](int acc, int x) { return acc * x; });
477 EXPECT_EQ(product, 120);
478}
479
481{
483
484 int result = v.foldl<int>(42, [](int acc, int x) { return acc + x; });
485 EXPECT_EQ(result, 42);
486}
487
489{
490 MixinVector<int> v = {1, 2, 3, 4, 5, 6};
491
492 auto [evens, odds] = v.partition([](int x) { return x % 2 == 0; });
493
494 EXPECT_EQ(evens.size(), 3);
495 EXPECT_EQ(odds.size(), 3);
496
497 int expected_evens[] = {2, 4, 6};
498 int expected_odds[] = {1, 3, 5};
499
500 int i = 0;
501 evens.for_each([&](int x) { EXPECT_EQ(x, expected_evens[i++]); });
502
503 i = 0;
504 odds.for_each([&](int x) { EXPECT_EQ(x, expected_odds[i++]); });
505}
506
508{
509 MixinVector<int> v = {1, 2, 3, 4, 5};
510 EXPECT_EQ(v.length(), 5);
511
512 MixinVector<int> empty;
513 EXPECT_EQ(empty.length(), 0);
514}
515
517{
518 MixinVector<int> v = {1, 2, 3, 4, 5};
519
520 auto reversed = v.rev();
521
522 EXPECT_EQ(reversed.size(), 5);
523
524 int expected[] = {5, 4, 3, 2, 1};
525 int i = 0;
526 reversed.for_each([&](int x) { EXPECT_EQ(x, expected[i++]); });
527}
528
530{
531 MixinVector<int> v = {1, 2, 3, 4, 5};
532
533 auto first3 = v.take(3);
534 EXPECT_EQ(first3.size(), 3);
535
536 int expected[] = {1, 2, 3};
537 int i = 0;
538 first3.for_each([&](int x) { EXPECT_EQ(x, expected[i++]); });
539
540 auto all = v.take(100);
541 EXPECT_EQ(all.size(), 5);
542}
543
545{
546 MixinVector<int> v = {1, 2, 3, 4, 5};
547
548 auto last3 = v.drop(2);
549 EXPECT_EQ(last3.size(), 3);
550
551 int expected[] = {3, 4, 5};
552 int i = 0;
553 last3.for_each([&](int x) { EXPECT_EQ(x, expected[i++]); });
554
555 auto empty = v.drop(100);
556 EXPECT_TRUE(empty.is_empty());
557}
558
559
560// =============================================================================
561// LocateMixin Tests
562// =============================================================================
563
565{
566 MixinVector<int> v = {10, 20, 30, 40, 50};
567
568 EXPECT_EQ(v.nth(0), 10);
569 EXPECT_EQ(v.nth(2), 30);
570 EXPECT_EQ(v.nth(4), 50);
571
572 EXPECT_THROW(v.nth(5), std::out_of_range);
573 EXPECT_THROW(v.nth(100), std::out_of_range);
574}
575
576TEST(LocateMixin, NthWithLargestIndexThrows)
577{
578 // The check compared the count with n + 1, which overflows to zero for
579 // n == SIZE_MAX: on an empty container nth() returned a null reference.
580 constexpr size_t largest = std::numeric_limits<size_t>::max();
581 MixinVector<int> empty;
582 EXPECT_THROW((void) empty.nth(largest), std::out_of_range);
583 EXPECT_THROW((void) empty.nth(0), std::out_of_range);
584
585 MixinVector<int> v = {10, 20, 30};
586 EXPECT_THROW((void) v.nth(largest), std::out_of_range);
587}
588
590{
591 MixinVector<int> v = {10, 20, 30};
592
593 EXPECT_EQ(v.nth_ne(0), 10);
594 EXPECT_EQ(v.nth_ne(1), 20);
595 EXPECT_EQ(v.nth_ne(2), 30);
596}
597
598TEST(LocateMixin, NthModify)
599{
600 MixinVector<int> v = {10, 20, 30};
601
602 v.nth(1) = 25;
603 EXPECT_EQ(v.nth(1), 25);
604}
605
607{
608 MixinVector<int> v = {1, 2, 3, 4, 5};
609
610 int* p = v.find_ptr([](int x) { return x == 3; });
611 ASSERT_NE(p, nullptr);
612 EXPECT_EQ(*p, 3);
613
614 int* not_found = v.find_ptr([](int x) { return x == 100; });
615 EXPECT_EQ(not_found, nullptr);
616}
617
618TEST(LocateMixin, FindPtrModify)
619{
620 MixinVector<int> v = {1, 2, 3, 4, 5};
621
622 int* p = v.find_ptr([](int x) { return x == 3; });
623 ASSERT_NE(p, nullptr);
624 *p = 30;
625
626 EXPECT_EQ(v.nth(2), 30);
627}
628
630{
631 MixinVector<int> v = {1, 2, 3, 4, 5};
632
633 auto [found, item] = v.find_item([](int x) { return x > 3; });
634 EXPECT_TRUE(found);
635 EXPECT_EQ(item, 4);
636
637 auto [not_found, default_val] = v.find_item([](int x) { return x > 100; });
638 EXPECT_FALSE(not_found);
639}
640
641
642// =============================================================================
643// KeysMixin Tests
644// =============================================================================
645
647{
648 MixinVector<int> v = {1, 2, 3};
649
650 auto k = v.keys();
651 EXPECT_EQ(k.size(), 3);
652}
653
655{
656 MixinVector<string> v = {"a", "b", "c"};
657
658 auto items = v.items();
659 EXPECT_EQ(items.size(), 3);
660}
661
662
663// =============================================================================
664// Chained Operations Tests
665// =============================================================================
666
667TEST(ChainedOps, FilterThenMap)
668{
669 MixinVector<int> v = {1, 2, 3, 4, 5, 6};
670
671 // Filter evens, then square them
672 auto evens = v.filter([](int x) { return x % 2 == 0; });
673 auto squared = evens.maps<int>([](int x) { return x * x; });
674
675 EXPECT_EQ(squared.size(), 3);
676
677 int expected[] = {4, 16, 36};
678 int i = 0;
679 squared.for_each([&](int x) { EXPECT_EQ(x, expected[i++]); });
680}
681
682TEST(ChainedOps, MapThenFold)
683{
684 MixinVector<int> v = {1, 2, 3, 4, 5};
685
686 // Square then sum
687 auto squared = v.maps<int>([](int x) { return x * x; });
688 int sum = squared.foldl<int>(0, [](int acc, int x) { return acc + x; });
689
690 EXPECT_EQ(sum, 1 + 4 + 9 + 16 + 25);
691}
692
693
694// =============================================================================
695// Complex Type Tests
696// =============================================================================
697
698struct Person
699{
700 string name;
701 int age;
702};
703
704TEST(ComplexTypes, StructOperations)
705{
706 MixinVector<Person> people;
707 people.append({"Alice", 30});
708 people.append({"Bob", 25});
709 people.append({"Charlie", 35});
710
711 // Find oldest
712 Person* oldest = people.find_ptr([](const Person& p) {
713 return p.age >= 35;
714 });
715 ASSERT_NE(oldest, nullptr);
716 EXPECT_EQ(oldest->name, "Charlie");
717
718 // Get ages
719 auto ages = people.maps<int>([](const Person& p) { return p.age; });
720 int sum = ages.foldl<int>(0, [](int acc, int a) { return acc + a; });
721 EXPECT_EQ(sum, 90);
722
723 // Filter by age
724 auto over27 = people.filter([](const Person& p) { return p.age > 27; });
725 EXPECT_EQ(over27.size(), 2);
726}
727
728
729// =============================================================================
730// Aggregation Tests (sum, product, min, max)
731// =============================================================================
732
734{
735 MixinVector<int> v = {1, 2, 3, 4, 5};
736 EXPECT_EQ(v.sum(), 15);
737 EXPECT_EQ(v.sum(10), 25); // with initial value
738}
739
741{
743 EXPECT_EQ(v.sum(), 0);
744 EXPECT_EQ(v.sum(100), 100);
745}
746
748{
749 MixinVector<string> v = {"Hello", " ", "World"};
750 EXPECT_EQ(v.sum(), "Hello World");
751 EXPECT_EQ(v.sum(string("Prefix: ")), "Prefix: Hello World");
752}
753
755{
756 MixinVector<int> v = {1, 2, 3, 4, 5};
757 EXPECT_EQ(v.product(1), 120);
758 EXPECT_EQ(v.product(2), 240);
759}
760
761TEST(FunctionalMixin, ProductEmpty)
762{
764 EXPECT_EQ(v.product(1), 1);
765 EXPECT_EQ(v.product(0), 0);
766}
767
769{
770 MixinVector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
771
772 const int* min_ptr = v.min();
773 ASSERT_NE(min_ptr, nullptr);
774 EXPECT_EQ(*min_ptr, 1);
775}
776
778{
780 EXPECT_EQ(v.min(), nullptr);
781}
782
784{
785 MixinVector<int> v = {42};
786 ASSERT_NE(v.min(), nullptr);
787 EXPECT_EQ(*v.min(), 42);
788}
789
791{
792 MixinVector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
793
794 const int* max_ptr = v.max();
795 ASSERT_NE(max_ptr, nullptr);
796 EXPECT_EQ(*max_ptr, 9);
797}
798
800{
802 EXPECT_EQ(v.max(), nullptr);
803}
804
806{
807 MixinVector<int> v = {42};
808 ASSERT_NE(v.max(), nullptr);
809 EXPECT_EQ(*v.max(), 42);
810}
811
812TEST(FunctionalMixin, MinByCustomComparator)
813{
814 MixinVector<string> v = {"apple", "pie", "a", "banana"};
815
816 const string* shortest = v.min_by([](const string& a, const string& b) {
817 return a.length() < b.length();
818 });
819
820 ASSERT_NE(shortest, nullptr);
821 EXPECT_EQ(*shortest, "a");
822}
823
824TEST(FunctionalMixin, MaxByCustomComparator)
825{
826 MixinVector<string> v = {"apple", "pie", "a", "banana"};
827
828 const string* longest = v.max_by([](const string& a, const string& b) {
829 return a.length() < b.length();
830 });
831
832 ASSERT_NE(longest, nullptr);
833 EXPECT_EQ(*longest, "banana");
834}
835
836TEST(FunctionalMixin, MinMaxWithNegatives)
837{
838 MixinVector<int> v = {-5, 3, -10, 7, 0};
839
840 EXPECT_EQ(*v.min(), -10);
841 EXPECT_EQ(*v.max(), 7);
842}
843
844
845// =============================================================================
846// Search and Counting Tests (contains, none, count_if)
847// =============================================================================
848
850{
851 MixinVector<int> v = {1, 2, 3, 4, 5};
852
853 EXPECT_TRUE(v.has_value(3));
854 EXPECT_TRUE(v.has_value(1));
855 EXPECT_TRUE(v.has_value(5));
856 EXPECT_FALSE(v.has_value(0));
857 EXPECT_FALSE(v.has_value(6));
858 EXPECT_FALSE(v.has_value(100));
859}
860
861TEST(FunctionalMixin, HasValueEmpty)
862{
864 EXPECT_FALSE(v.has_value(1));
865}
866
867TEST(FunctionalMixin, HasValueStrings)
868{
869 MixinVector<string> v = {"apple", "banana", "cherry"};
870
871 EXPECT_TRUE(v.has_value("banana"));
872 EXPECT_FALSE(v.has_value("Banana")); // case sensitive
873 EXPECT_FALSE(v.has_value("grape"));
874}
875
877{
878 MixinVector<int> v = {2, 4, 6, 8, 10};
879
880 EXPECT_TRUE(v.none([](int x) { return x % 2 != 0; })); // no odds
881 EXPECT_FALSE(v.none([](int x) { return x > 5; })); // some > 5
882}
883
885{
887 EXPECT_TRUE(v.none([](int) { return true; })); // vacuously true
888}
889
890TEST(FunctionalMixin, NoneLValuePredicate)
891{
892 MixinVector<int> v = {2, 4, 6};
893
894 auto is_odd = [](int x) { return x % 2 != 0; };
895 EXPECT_TRUE(v.none(is_odd));
896}
897
899{
900 MixinVector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
901
902 EXPECT_EQ(v.count_if([](int x) { return x % 2 == 0; }), 5); // evens
903 EXPECT_EQ(v.count_if([](int x) { return x > 5; }), 5); // > 5
904 EXPECT_EQ(v.count_if([](int x) { return x > 100; }), 0); // none
905 EXPECT_EQ(v.count_if([](int) { return true; }), 10); // all
906}
907
908TEST(FunctionalMixin, CountIfEmpty)
909{
911 EXPECT_EQ(v.count_if([](int) { return true; }), 0);
912}
913
914
915// =============================================================================
916// First/Last Element Tests
917// =============================================================================
918
920{
921 MixinVector<int> v = {10, 20, 30};
922
923 const int* ptr = v.first();
924 ASSERT_NE(ptr, nullptr);
925 EXPECT_EQ(*ptr, 10);
926}
927
929{
931 EXPECT_EQ(v.first(), nullptr);
932}
933
935{
936 MixinVector<int> v = {10, 20, 30};
937 EXPECT_EQ(v.first_or(-1), 10);
938
939 MixinVector<int> empty;
940 EXPECT_EQ(empty.first_or(-1), -1);
941}
942
944{
945 MixinVector<int> v = {10, 20, 30};
946
947 const int* ptr = v.last();
948 ASSERT_NE(ptr, nullptr);
949 EXPECT_EQ(*ptr, 30);
950}
951
953{
955 EXPECT_EQ(v.last(), nullptr);
956}
957
959{
960 MixinVector<int> v = {10, 20, 30};
961 EXPECT_EQ(v.last_or(-1), 30);
962
963 MixinVector<int> empty;
964 EXPECT_EQ(empty.last_or(-1), -1);
965}
966
967TEST(FunctionalMixin, FirstLastSingleElement)
968{
969 MixinVector<int> v = {42};
970
971 EXPECT_EQ(*v.first(), 42);
972 EXPECT_EQ(*v.last(), 42);
973 EXPECT_EQ(v.first_or(-1), 42);
974 EXPECT_EQ(v.last_or(-1), 42);
975}
976
977
978// =============================================================================
979// Enumeration and Indexing Tests
980// =============================================================================
981
983{
984 MixinVector<string> v = {"a", "b", "c"};
985
986 auto enumerated = v.enumerate();
987 EXPECT_EQ(enumerated.size(), 3);
988
989 size_t expected_idx = 0;
990 string expected_vals[] = {"a", "b", "c"};
991 enumerated.for_each([&](const std::pair<size_t, string>& p) {
992 EXPECT_EQ(p.first, expected_idx);
993 EXPECT_EQ(p.second, expected_vals[expected_idx]);
994 ++expected_idx;
995 });
996}
997
998TEST(FunctionalMixin, EnumerateEmpty)
999{
1001 auto enumerated = v.enumerate();
1002 EXPECT_TRUE(enumerated.is_empty());
1003}
1004
1006{
1007 MixinVector<int> v = {10, 20, 30, 40, 50};
1008
1009 EXPECT_EQ(v.find_index([](int x) { return x == 30; }), 2);
1010 EXPECT_EQ(v.find_index([](int x) { return x > 35; }), 3); // first > 35 is 40
1011 EXPECT_EQ(v.find_index([](int x) { return x > 100; }), v.size());
1012}
1013
1014TEST(FunctionalMixin, FindIndexEmpty)
1015{
1017 EXPECT_EQ(v.find_index([](int) { return true; }), 0u); // empty: size()
1018}
1019
1021{
1022 MixinVector<int> v = {10, 20, 30, 40, 50};
1023
1024 EXPECT_EQ(v.index_of(10), 0);
1025 EXPECT_EQ(v.index_of(30), 2);
1026 EXPECT_EQ(v.index_of(50), 4);
1027 EXPECT_EQ(v.index_of(99), v.size());
1028}
1029
1030TEST(FunctionalMixin, IndexOfStrings)
1031{
1032 MixinVector<string> v = {"apple", "banana", "cherry"};
1033
1034 EXPECT_EQ(v.index_of("banana"), 1);
1035 EXPECT_EQ(v.index_of("grape"), v.size());
1036}
1037
1038
1039// =============================================================================
1040// Combined Operations with New Methods
1041// =============================================================================
1042
1043TEST(ChainedOps, SumAfterFoldl)
1044{
1045 MixinVector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
1046
1047 // Sum of evens using filter + foldl (since filter returns DynList)
1048 auto evens = v.filter([](int x) { return x % 2 == 0; });
1049 int sum = evens.foldl<int>(0, [](int acc, int x) { return acc + x; });
1050 EXPECT_EQ(sum, 2 + 4 + 6 + 8 + 10);
1051
1052 // Direct sum on MixinVector
1053 EXPECT_EQ(v.sum(), 55);
1054}
1055
1056TEST(ChainedOps, MinMaxOnMixinVector)
1057{
1058 MixinVector<int> v = {1, 3, 5, 7, 9}; // odds only
1059
1060 EXPECT_EQ(*v.min(), 1);
1061 EXPECT_EQ(*v.max(), 9);
1062}
1063
1064TEST(ChainedOps, EnumerateThenCountElements)
1065{
1066 MixinVector<string> v = {"a", "bb", "ccc", "dd"};
1067
1068 auto enumerated = v.enumerate();
1069 EXPECT_EQ(enumerated.size(), 4);
1070
1071 // Count even indices using the mixin's count_if
1072 // (enumerated is DynList, so we verify via foldl)
1073 int even_count = enumerated.foldl<int>(0, [](int acc, const std::pair<size_t, string>& p) {
1074 return acc + (p.first % 2 == 0 ? 1 : 0);
1075 });
1076 EXPECT_EQ(even_count, 2); // indices 0 and 2
1077}
1078
1079
1080// =============================================================================
1081// Stress Tests
1082// =============================================================================
1083
1084TEST(StressTest, LargeContainer)
1085{
1086 constexpr size_t N = 10000;
1088
1089 for (size_t i = 0; i < N; ++i)
1090 v.append(i);
1091
1092 // Sum using foldl
1093 size_t sum = v.foldl<size_t>(0, [](size_t acc, size_t x) { return acc + x; });
1094 EXPECT_EQ(sum, N * (N - 1) / 2);
1095
1096 // Sum using sum()
1097 EXPECT_EQ(v.sum(), N * (N - 1) / 2);
1098
1099 // Count evens
1100 auto evens = v.filter([](size_t x) { return x % 2 == 0; });
1101 EXPECT_EQ(evens.size(), N / 2);
1102
1103 // count_if
1104 EXPECT_EQ(v.count_if([](size_t x) { return x % 2 == 0; }), N / 2);
1105
1106 // All positive
1107 EXPECT_TRUE(v.all([](size_t x) { return x < N; }));
1108
1109 // Min/Max
1110 EXPECT_EQ(*v.min(), 0);
1111 EXPECT_EQ(*v.max(), N - 1);
1112
1113 // has_value
1114 EXPECT_TRUE(v.has_value(N / 2));
1115 EXPECT_FALSE(v.has_value(N));
1116
1117 // first/last
1118 EXPECT_EQ(*v.first(), 0);
1119 EXPECT_EQ(*v.last(), N - 1);
1120}
1121
1122TEST(StressTest, LargeEnumerate)
1123{
1124 constexpr size_t N = 1000;
1126
1127 for (size_t i = 0; i < N; ++i)
1128 v.append(static_cast<int>(i * 2));
1129
1130 auto enumerated = v.enumerate();
1131 EXPECT_EQ(enumerated.size(), N);
1132
1133 // Verify all indices are correct
1134 size_t idx = 0;
1135 enumerated.for_each([&idx](const std::pair<size_t, int>& p) {
1136 EXPECT_EQ(p.first, idx);
1137 EXPECT_EQ(p.second, static_cast<int>(idx * 2));
1138 ++idx;
1139 });
1140}
1141
1142
1143// =============================================================================
1144// Constraint Tests - verify methods are properly constrained
1145// =============================================================================
1146
1147// Type without arithmetic operators
1149{
1151 // No operator+, operator*, operator<, operator==
1152};
1153
1154TEST(ConstraintTest, MethodsWithoutConstraintsWork)
1155{
1157 v.append({1});
1158 v.append({2});
1159 v.append({3});
1160
1161 // These should compile - they don't require operators
1162 EXPECT_EQ(v.length(), 3);
1163 EXPECT_NE(v.first(), nullptr);
1164 EXPECT_NE(v.last(), nullptr);
1165 EXPECT_EQ(v.first()->value, 1);
1166 EXPECT_EQ(v.last()->value, 3);
1167
1168 auto enumerated = v.enumerate();
1169 EXPECT_EQ(enumerated.size(), 3);
1170
1171 // count_if with custom predicate works
1172 EXPECT_EQ(v.count_if([](const NoOpType& x) { return x.value > 1; }), 2);
1173
1174 // find_index with custom predicate works
1175 EXPECT_EQ(v.find_index([](const NoOpType& x) { return x.value == 2; }), 1);
1176
1177 // The following would NOT compile (correctly!) due to requires constraints:
1178 // v.sum(); // requires operator+
1179 // v.product({0}); // requires operator*
1180 // v.min(); // requires operator<
1181 // v.max(); // requires operator<
1182 // v.has_value({1}); // requires operator==
1183 // v.index_of({1}); // requires operator==
1184}
1185
1186// Type with only equality
1188{
1190 bool operator==(const EqOnlyType& other) const { return value == other.value; }
1191};
1192
1193TEST(ConstraintTest, EqualityOnlyType)
1194{
1196 v.append({1});
1197 v.append({2});
1198 v.append({3});
1199
1200 // has_value and index_of work (require operator==)
1201 EXPECT_TRUE(v.has_value({2}));
1202 EXPECT_FALSE(v.has_value({99}));
1203 EXPECT_EQ(v.index_of({2}), 1);
1204
1205 // The following would NOT compile:
1206 // v.sum(); // requires operator+
1207 // v.min(); // requires operator<
1208}
1209
1210// Type with only less-than
1212{
1214 bool operator<(const LtOnlyType& other) const { return value < other.value; }
1215};
1216
1217TEST(ConstraintTest, LessThanOnlyType)
1218{
1220 v.append({3});
1221 v.append({1});
1222 v.append({2});
1223
1224 // min and max work (require operator<)
1225 EXPECT_EQ(v.min()->value, 1);
1226 EXPECT_EQ(v.max()->value, 3);
1227
1228 // The following would NOT compile:
1229 // v.sum(); // requires operator+
1230 // v.has_value({1}); // requires operator==
1231}
1232
1233
1234// =============================================================================
1235// Advanced Transformation Tests (unique, intersperse)
1236// =============================================================================
1237
1239{
1240 MixinVector<int> v = {1, 1, 2, 2, 2, 3, 1, 1};
1241
1242 auto u = v.unique();
1243 EXPECT_EQ(u.size(), 4);
1244
1245 int expected[] = {1, 2, 3, 1};
1246 int i = 0;
1247 u.for_each([&](int x) { EXPECT_EQ(x, expected[i++]); });
1248}
1249
1251{
1253 auto u = v.unique();
1254 EXPECT_TRUE(u.is_empty());
1255}
1256
1257TEST(FunctionalMixin, UniqueSingleElement)
1258{
1259 MixinVector<int> v = {42};
1260 auto u = v.unique();
1261 EXPECT_EQ(u.size(), 1);
1262
1263 // Verify first element via iteration
1264 int first_val = 0;
1265 u.traverse([&first_val](int x) { first_val = x; return false; });
1266 EXPECT_EQ(first_val, 42);
1267}
1268
1269TEST(FunctionalMixin, UniqueNoDuplicates)
1270{
1271 MixinVector<int> v = {1, 2, 3, 4, 5};
1272 auto u = v.unique();
1273 EXPECT_EQ(u.size(), 5);
1274}
1275
1277{
1278 MixinVector<string> v = {"a", "A", "b", "B", "c"};
1279
1280 auto u = v.unique_by([](const string& a, const string& b) {
1281 return tolower(a[0]) == tolower(b[0]);
1282 });
1283
1284 EXPECT_EQ(u.size(), 3); // "a", "b", "c"
1285}
1286
1288{
1289 MixinVector<int> v = {1, 2, 3};
1290
1291 auto i = v.intersperse(0);
1292 EXPECT_EQ(i.size(), 5); // 1, 0, 2, 0, 3
1293
1294 int expected[] = {1, 0, 2, 0, 3};
1295 int idx = 0;
1296 i.for_each([&](int x) { EXPECT_EQ(x, expected[idx++]); });
1297}
1298
1299TEST(FunctionalMixin, IntersperseEmpty)
1300{
1302 auto i = v.intersperse(0);
1303 EXPECT_TRUE(i.is_empty());
1304}
1305
1306TEST(FunctionalMixin, IntersperseSingleElement)
1307{
1308 MixinVector<int> v = {42};
1309 auto i = v.intersperse(0);
1310 EXPECT_EQ(i.size(), 1);
1311
1312 // Verify first element via iteration
1313 int first_val = 0;
1314 i.traverse([&first_val](int x) { first_val = x; return false; });
1315 EXPECT_EQ(first_val, 42);
1316}
1317
1318TEST(FunctionalMixin, IntersperseStrings)
1319{
1320 MixinVector<string> v = {"a", "b", "c"};
1321 auto i = v.intersperse(string("-"));
1322 EXPECT_EQ(i.size(), 5);
1323}
1324
1325
1326// =============================================================================
1327// Chunking and Windowing Tests
1328// =============================================================================
1329
1331{
1332 MixinVector<int> v = {1, 2, 3, 4, 5};
1333
1334 auto chunks = v.chunk(2);
1335 EXPECT_EQ(chunks.size(), 3); // {1,2}, {3,4}, {5}
1336
1337 // Verify first chunk size via iteration
1338 size_t first_chunk_size = 0;
1339 chunks.traverse([&first_chunk_size](const auto& c) {
1340 first_chunk_size = c.size();
1341 return false;
1342 });
1343 EXPECT_EQ(first_chunk_size, 2);
1344}
1345
1346TEST(FunctionalMixin, ChunkExactDivision)
1347{
1348 MixinVector<int> v = {1, 2, 3, 4, 5, 6};
1349
1350 auto chunks = v.chunk(2);
1351 EXPECT_EQ(chunks.size(), 3); // {1,2}, {3,4}, {5,6}
1352}
1353
1355{
1357 auto chunks = v.chunk(2);
1358 EXPECT_TRUE(chunks.is_empty());
1359}
1360
1361TEST(FunctionalMixin, ChunkSizeZero)
1362{
1363 MixinVector<int> v = {1, 2, 3};
1364 auto chunks = v.chunk(0);
1365 EXPECT_TRUE(chunks.is_empty());
1366}
1367
1368TEST(FunctionalMixin, ChunkLargerThanContainer)
1369{
1370 MixinVector<int> v = {1, 2};
1371 auto chunks = v.chunk(10);
1372 EXPECT_EQ(chunks.size(), 1); // single chunk with all elements
1373}
1374
1376{
1377 MixinVector<int> v = {1, 2, 3, 4, 5};
1378
1379 auto windows = v.sliding(3);
1380 EXPECT_EQ(windows.size(), 3); // {1,2,3}, {2,3,4}, {3,4,5}
1381
1382 // Verify each window has 3 elements
1383 windows.for_each([](const auto& w) { EXPECT_EQ(w.size(), 3); });
1384}
1385
1386TEST(FunctionalMixin, SlidingWithStep)
1387{
1388 MixinVector<int> v = {1, 2, 3, 4, 5, 6};
1389
1390 auto windows = v.sliding(2, 2);
1391 EXPECT_EQ(windows.size(), 3); // {1,2}, {3,4}, {5,6}
1392}
1393
1394TEST(FunctionalMixin, SlidingEmpty)
1395{
1397 auto windows = v.sliding(2);
1398 EXPECT_TRUE(windows.is_empty());
1399}
1400
1401TEST(FunctionalMixin, SlidingSizeZero)
1402{
1403 MixinVector<int> v = {1, 2, 3};
1404 auto windows = v.sliding(0);
1405 EXPECT_TRUE(windows.is_empty());
1406}
1407
1408TEST(FunctionalMixin, SlidingLargerThanContainer)
1409{
1410 MixinVector<int> v = {1, 2};
1411 auto windows = v.sliding(3);
1412 EXPECT_TRUE(windows.is_empty());
1413}
1414
1415
1416// =============================================================================
1417// Conversion Tests (to_vector, join)
1418// =============================================================================
1419
1421{
1422 MixinVector<int> v = {1, 2, 3, 4, 5};
1423
1424 std::vector<int> vec = v.to_vector();
1425 EXPECT_EQ(vec.size(), 5);
1426 EXPECT_EQ(vec[0], 1);
1427 EXPECT_EQ(vec[4], 5);
1428}
1429
1430TEST(FunctionalMixin, ToVectorEmpty)
1431{
1433 std::vector<int> vec = v.to_vector();
1434 EXPECT_TRUE(vec.empty());
1435}
1436
1438{
1439 MixinVector<int> v = {1, 2, 3, 4, 5};
1440
1441 DynList<int> list = v.to_dynlist();
1442 EXPECT_EQ(list.size(), 5);
1443
1444 // Verify order is preserved
1445 auto it = list.get_it();
1446 EXPECT_EQ(it.get_curr(), 1);
1447 it.next_ne();
1448 EXPECT_EQ(it.get_curr(), 2);
1449}
1450
1451TEST(FunctionalMixin, ToDynlistEmpty)
1452{
1454 DynList<int> list = v.to_dynlist();
1455 EXPECT_TRUE(list.is_empty());
1456}
1457
1458TEST(FunctionalMixin, ToDynlistRoundTrip)
1459{
1460 // to_vector -> to_dynlist -> verify same content
1461 MixinVector<int> v = {10, 20, 30};
1462
1463 std::vector<int> vec = v.to_vector();
1464 DynList<int> list = v.to_dynlist();
1465
1466 // Both should have same size and content
1467 EXPECT_EQ(vec.size(), list.size());
1468
1469 size_t i = 0;
1470 list.for_each([&vec, &i](int x) {
1471 EXPECT_EQ(x, vec[i++]);
1472 });
1473}
1474
1476{
1477 MixinVector<int> v = {1, 2, 3};
1478
1479 string s = v.join(string(", "));
1480 EXPECT_EQ(s, "1, 2, 3");
1481}
1482
1483TEST(FunctionalMixin, JoinSingleElement)
1484{
1485 MixinVector<int> v = {42};
1486 string s = v.join(string("-"));
1487 EXPECT_EQ(s, "42");
1488}
1489
1491{
1493 string s = v.join(string(", "));
1494 EXPECT_EQ(s, "");
1495}
1496
1498{
1499 MixinVector<string> v = {"a", "b", "c"};
1500
1501 string s = v.join_str("-");
1502 EXPECT_EQ(s, "a-b-c");
1503}
1504
1505TEST(FunctionalMixin, JoinStrEmpty)
1506{
1508 string s = v.join_str("-");
1509 EXPECT_EQ(s, "");
1510}
1511
1512
1513// =============================================================================
1514// Zip Tests
1515// =============================================================================
1516
1518{
1519 MixinVector<int> a = {1, 2, 3};
1521 b.append("a");
1522 b.append("b");
1523 b.append("c");
1524
1525 auto zipped = a.zip_with(b);
1526 EXPECT_EQ(zipped.size(), 3);
1527
1528 // Verify pairs
1529 auto it = zipped.get_it();
1530 EXPECT_EQ(it.get_curr().first, 1);
1531 EXPECT_EQ(it.get_curr().second, "a");
1532}
1533
1534TEST(FunctionalMixin, ZipWithDifferentLengths)
1535{
1536 MixinVector<int> a = {1, 2, 3, 4, 5};
1537 MixinVector<int> b = {10, 20};
1538
1539 auto zipped = a.zip_with(b);
1540 EXPECT_EQ(zipped.size(), 2); // stops at shorter
1541}
1542
1543TEST(FunctionalMixin, ZipWithEmpty)
1544{
1545 MixinVector<int> a = {1, 2, 3};
1547
1548 auto zipped = a.zip_with(b);
1549 EXPECT_TRUE(zipped.is_empty());
1550}
1551
1552TEST(FunctionalMixin, ZipWithBothEmpty)
1553{
1556
1557 auto zipped = a.zip_with(b);
1558 EXPECT_TRUE(zipped.is_empty());
1559}
1560
1561
1562// =============================================================================
1563// Combined Advanced Operations
1564// =============================================================================
1565
1566TEST(ChainedOps, UniqueVerify)
1567{
1568 MixinVector<int> v = {1, 1, 2, 2, 3};
1569
1570 auto unique_result = v.unique();
1571 EXPECT_EQ(unique_result.size(), 3); // 1, 2, 3
1572
1573 // Verify values via iteration
1574 int expected[] = {1, 2, 3};
1575 int idx = 0;
1576 unique_result.for_each([&](int x) { EXPECT_EQ(x, expected[idx++]); });
1577}
1578
1579TEST(ChainedOps, ChunkAndSum)
1580{
1581 MixinVector<int> v = {1, 2, 3, 4, 5, 6};
1582
1583 auto chunks = v.chunk(2);
1584 // Each chunk: {1,2}, {3,4}, {5,6} -> sums: 3, 7, 11
1585
1586 int total = 0;
1587 chunks.for_each([&total](const Aleph::DynList<int>& chunk) {
1588 total += chunk.foldl<int>(0, [](int acc, int x) { return acc + x; });
1589 });
1590 EXPECT_EQ(total, 21);
1591}
1592
1593
1594// =============================================================================
1595// Tests with DynList (Real Aleph Container) - uses existing methods
1596// =============================================================================
1597
1598TEST(DynListIntegration, ExistingMethodsWork)
1599{
1600 // DynList uses legacy ahDry.H macros, so only test existing methods
1602 for (int i = 1; i <= 5; ++i)
1603 list.append(i);
1604
1605 // foldl exists in DynList
1606 int sum = list.foldl<int>(0, [](int acc, int x) { return acc + x; });
1607 EXPECT_EQ(sum, 15);
1608
1609 // filter exists
1610 auto evens = list.filter([](int x) { return x % 2 == 0; });
1611 EXPECT_EQ(evens.size(), 2);
1612
1613 // all exists
1614 EXPECT_TRUE(list.all([](int x) { return x <= 5; }));
1615
1616 // exists works
1617 EXPECT_TRUE(list.exists([](int x) { return x == 3; }));
1618}
1619
1620
1621// =============================================================================
1622// EqualSequenceMethod Tests
1623// Exercises equal_to(), operator==, and operator!= on Array<T> and DynArray<T>,
1624// both of which inherit EqualSequenceMethod via CRTP.
1625// =============================================================================
1626
1627// Helper: build an Array<int> from an initializer list.
1628static Array<int> make_array(std::initializer_list<int> vals)
1629{
1630 Array<int> a;
1631 for (int v : vals)
1632 a.append(v);
1633 return a;
1634}
1635
1636// Helper: build a DynArray<int> from an initializer list.
1637static DynArray<int> make_dynarray(std::initializer_list<int> vals)
1638{
1639 DynArray<int> a;
1640 for (int v : vals)
1641 a.append(v);
1642 return a;
1643}
1644
1645TEST(EqualSequenceMethod, SizeMismatchReturnsFalse)
1646{
1647 // Containers with different sizes must compare unequal regardless of content.
1648 const Array<int> a3 = make_array({1, 2, 3});
1649 const Array<int> a2 = make_array({1, 2});
1650
1651 EXPECT_FALSE(a3.equal_to(a2));
1652 EXPECT_FALSE(a2.equal_to(a3));
1653 EXPECT_FALSE(a3 == a2);
1654 EXPECT_TRUE(a3 != a2);
1655
1656 const DynArray<int> d3 = make_dynarray({1, 2, 3});
1657 const DynArray<int> d2 = make_dynarray({1, 2});
1658
1659 EXPECT_FALSE(d3.equal_to(d2));
1660 EXPECT_FALSE(d2.equal_to(d3));
1661 EXPECT_FALSE(d3 == d2);
1662 EXPECT_TRUE(d3 != d2);
1663}
1664
1665TEST(EqualSequenceMethod, SelfComparisonReturnsTrue)
1666{
1667 // equal_to(self) must return true via the identity fast-path.
1668 const Array<int> a = make_array({10, 20, 30});
1669 EXPECT_TRUE(a.equal_to(a));
1670 EXPECT_TRUE(a == a);
1671 EXPECT_FALSE(a != a);
1672
1673 const DynArray<int> d = make_dynarray({10, 20, 30});
1674 EXPECT_TRUE(d.equal_to(d));
1675 EXPECT_TRUE(d == d);
1676 EXPECT_FALSE(d != d);
1677}
1678
1679TEST(EqualSequenceMethod, SameElementsDifferentOrderReturnsFalse)
1680{
1681 // Same multiset, different traversal order → unequal (order-sensitive).
1682 const Array<int> a1 = make_array({1, 2, 3});
1683 const Array<int> a2 = make_array({3, 2, 1});
1684
1685 EXPECT_FALSE(a1.equal_to(a2));
1686 EXPECT_FALSE(a1 == a2);
1687 EXPECT_TRUE(a1 != a2);
1688
1689 const DynArray<int> d1 = make_dynarray({1, 2, 3});
1690 const DynArray<int> d2 = make_dynarray({3, 2, 1});
1691
1692 EXPECT_FALSE(d1.equal_to(d2));
1693 EXPECT_FALSE(d1 == d2);
1694 EXPECT_TRUE(d1 != d2);
1695}
1696
1697TEST(EqualSequenceMethod, DuplicateMultiplicityDifferenceReturnsFalse)
1698{
1699 // Same elements but different duplicate counts → unequal.
1700 const Array<int> a1 = make_array({1, 1, 2}); // two 1s
1701 const Array<int> a2 = make_array({1, 2, 2}); // two 2s
1702
1703 EXPECT_FALSE(a1.equal_to(a2));
1704 EXPECT_FALSE(a1 == a2);
1705 EXPECT_TRUE(a1 != a2);
1706
1707 const DynArray<int> d1 = make_dynarray({5, 5, 7});
1708 const DynArray<int> d2 = make_dynarray({5, 7, 7});
1709
1710 EXPECT_FALSE(d1.equal_to(d2));
1711 EXPECT_FALSE(d1 == d2);
1712 EXPECT_TRUE(d1 != d2);
1713}
1714
1715TEST(EqualSequenceMethod, EqualContainersReturnTrue)
1716{
1717 // Sanity-check the positive case: identical content → equal.
1718 const Array<int> a1 = make_array({4, 5, 6});
1719 const Array<int> a2 = make_array({4, 5, 6});
1720
1721 EXPECT_TRUE(a1.equal_to(a2));
1722 EXPECT_TRUE(a1 == a2);
1723 EXPECT_FALSE(a1 != a2);
1724
1725 const DynArray<int> d1 = make_dynarray({4, 5, 6});
1726 const DynArray<int> d2 = make_dynarray({4, 5, 6});
1727
1728 EXPECT_TRUE(d1.equal_to(d2));
1729 EXPECT_TRUE(d1 == d2);
1730 EXPECT_FALSE(d1 != d2);
1731}
1732
1733TEST(EqualSequenceMethod, EmptyContainersAreEqual)
1734{
1735 const Array<int> a1, a2;
1736 EXPECT_TRUE(a1.equal_to(a2));
1737 EXPECT_TRUE(a1 == a2);
1738 EXPECT_FALSE(a1 != a2);
1739
1740 const DynArray<int> d1, d2;
1741 EXPECT_TRUE(d1.equal_to(d2));
1742 EXPECT_TRUE(d1 == d2);
1743 EXPECT_FALSE(d1 != d2);
1744}
1745
1747{
1748 // Array
1749 Array<int> a1 = {10};
1750 Array<int> a2 = {10};
1751 Array<int> a3 = {20};
1752
1753 EXPECT_TRUE(a1.equal_to(a1)); // Self
1754 EXPECT_TRUE(a1.equal_to(a2)); // Equal
1755 EXPECT_FALSE(a1.equal_to(a3)); // Not equal value
1756 EXPECT_TRUE(a1 != a3);
1757
1758 // DynArray
1759 DynArray<int> d1 = {10};
1760 DynArray<int> d2 = {10};
1761 DynArray<int> d3 = {20};
1762
1763 EXPECT_TRUE(d1 == d2);
1764 EXPECT_FALSE(d1 == d3);
1765}
1766
1768{
1769 constexpr size_t N = 10000;
1770 Array<int> a1, a2;
1771 DynArray<int> d1, d2;
1772
1773 for (size_t i = 0; i < N; ++i)
1774 {
1775 a1.append(i);
1776 a2.append(i);
1777 d1.append(i);
1778 d2.append(i);
1779 }
1780
1781 EXPECT_TRUE(a1 == a2);
1782 EXPECT_TRUE(d1 == d2);
1783 EXPECT_TRUE(a1.equal_to(a2));
1784 EXPECT_TRUE(d1.equal_to(d2));
1785 EXPECT_FALSE(a1 != a2);
1786 EXPECT_FALSE(d1 != d2);
1787
1788 // Differ at one position
1789 a2(N/2) = -1;
1790 d2(N/2) = -1;
1791
1792 EXPECT_FALSE(a1 == a2);
1793 EXPECT_FALSE(d1 == d2);
1794 EXPECT_FALSE(a1.equal_to(a2));
1795 EXPECT_FALSE(d1.equal_to(d2));
1796 EXPECT_TRUE(a1 != a2);
1797 EXPECT_TRUE(d1 != d2);
1798}
1799
CRTP Mixins for container functionality (DRY principle).
static DynArray< int > make_dynarray(std::initializer_list< int > vals)
static Array< int > make_array(std::initializer_list< int > vals)
long double w
Definition btreepic.C:153
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
T & append()
Allocate a new entry to the end of array.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
CRTP Mixin providing functional programming operations.
size_t count_if(Predicate pred) const
Count elements satisfying a predicate.
Container< Type > drop(const size_t n) const
Skip the first n elements.
Container< std::pair< size_t, Type > > enumerate() const
Enumerate elements with their indices.
Container< Container< Type > > chunk(size_t n) const
Split into chunks of fixed size.
DynListType to_dynlist() const
Convert container to DynList.
std::pair< DynList< Type >, DynList< Type > > partition(Operation &op) const
Partition elements by a predicate.
auto mutable_for_each(Operation &operation) -> decltype(self())
Apply an operation to each element (mutable).
const Type * min_by(Compare cmp) const
Find the minimum element using a custom comparator.
const Type * max() const
Find the maximum element.
Container< Type > unique_by(EqPred eq) const
Remove consecutive duplicates using a custom equality predicate.
bool none(Predicate &pred) const
Check if no element satisfies a predicate.
Container< Type > rev() const
Create a reversed copy.
Acc foldl(const Acc &init, std::function< Acc(const Acc &, const Type &)> operation) const
Left fold (reduce) with initial value.
bool exists(Operation &operation) const
Test if any element satisfies a predicate.
Container< Container< Type > > sliding(size_t size, size_t step=1) const
Create sliding windows of fixed size.
Container< Type > take(const size_t n) const
Take the first n elements.
std::string join_str(const std::string &sep=", ") const
Join string elements with separator.
Container< Type > unique() const
Remove consecutive duplicate elements.
const Type * first() const
Get the first element.
Container< std::pair< Type, typename Other::Item_Type > > zip_with(const Other &other) const
Zip with another container.
Type last_or(const Type &default_val) const
Get the last element or a default value.
Container< concepts_detail::map_result_t< R, Operation &, Type > > maps(Operation &operation) const
auto for_each(Operation &operation) const -> decltype(self())
Apply an operation to each element (read-only).
bool has_value(const Type &val) const
Check if container has a value.
StringType join(const StringType &sep=StringType{", "}) const
Join elements into a string with separator.
size_t index_of(const Type &val) const
Find the index of a specific value.
Type product(const Type &init) const
Compute the product of all elements.
bool all(Operation &operation) const
Test if all elements satisfy a predicate.
size_t length() const noexcept
Count the number of elements.
Type sum(const Type &init=Type{}) const
Compute the sum of all elements.
size_t find_index(Predicate pred) const
Find the index of the first element satisfying a predicate.
std::vector< Type > to_vector() const
Convert to std::vector.
const Type * max_by(Compare cmp) const
Find the maximum element using a custom comparator.
Container< Type > intersperse(const Type &sep) const
Intersperse a separator between elements.
Type first_or(const Type &default_val) const
Get the first element or a default value.
DynList< Type > filter(Operation &operation) const
Filter elements by a predicate.
const Type * last() const
Get the last element.
const Type * min() const
Find the minimum element.
constexpr bool is_empty() const noexcept
Definition htlist.H:434
CRTP Mixin for extracting keys from set-like containers.
Container< Type > items() const
Alias for keys().
Container< Type > keys() const
Extract all keys as a list.
CRTP Mixin providing element location operations.
std::tuple< bool, Type > find_item(Operation &operation)
Find element with success flag.
Type * find_ptr(Operation &operation)
Find the first element satisfying a predicate.
Type & nth(const size_t n)
Access the n-th element (bounds-checked).
Type & nth_ne(const size_t n) noexcept
Access the n-th element (unchecked).
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
CRTP Mixin providing traversal operations.
bool traverse(Operation &operation) const
Traverse all elements, applying an operation to each.
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
Aleph::DynList< Aleph::dry_detail::map_result_t< R, Operation &, T > > maps(Operation &op) const
Definition ah-dry.H:1829
bool exists(Operation &op) const
Test for existence in the container of an element satisfying a criterion.
Definition ah-dry.H:1707
Aleph::DynList< T > filter(Operation &operation) const
Filter the elements of a container according to a matching criterion.
Definition ah-dry.H:2356
bool all(Operation &operation) const
Check if all the elements of the container satisfy a condition.
Definition ah-dry.H:1666
Acc foldl(const Acc &init, Op &op) const
Fold the elements of the container to a specific result.
Definition ah-dry.H:2145
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
Iterator(const MixinVector &c)
const MixinVector * container
bool has_curr() const noexcept
Simple test container using std::vector internally but with Aleph mixins.
void insert(const T &item)
Iterator get_it() const
bool operator==(const MixinVector &other) const
void append(const T &item)
std::vector< T > data
MixinVector()=default
MixinVector(std::initializer_list< T > init)
size_t size() const noexcept
bool is_empty() const noexcept
#define TEST(name)
#define N
Definition fib.C:294
Singly linked list implementations with head-tail access.
Main namespace for Aleph-w library functions.
std::string tolower(const char *str)
Convert a C std::string to lower-case.
bool completed() const noexcept
Return true if all underlying iterators are finished.
Definition ah-zip.H:183
const Container::Item_Type * max_ptr(const Container &container, Cmp cmp=Cmp())
Find the maximum element in a container.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
T product(const Container &container, const T &init=T{1})
Compute product of all elements.
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
static std::atomic< bool > init
Definition hash-fct.C:54
const Container::Item_Type * min_ptr(const Container &container, Cmp cmp=Cmp())
Find the minimum element in a container.
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.
#define is_odd(x)
Definition ran_array.c:30
Represents a missing value.
bool operator==(const EqOnlyType &other) const
bool operator<(const LtOnlyType &other) const
bool operator()(const int &x) const
bool operator()(int &x) const
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
size_t V
static int * k
Dynamic array container with automatic resizing.
Lazy and scalable dynamic array implementation.