Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
dynarray.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
38#include <gtest/gtest.h>
39
40#include <tpl_dynArray.H>
41#include <ah-unique.H>
42#include <ahFunctional.H>
43
44#include <limits>
45#include <new>
46#include <stdexcept>
47#include <string>
48#include <type_traits>
49#include <utility>
50
51using namespace Aleph;
52using namespace std;
53
54namespace {
55
56TEST(DynArrayBasics, construction_and_size)
57{
58 DynArray<int> arr;
59 EXPECT_TRUE(arr.is_empty());
60 EXPECT_EQ(arr.size(), 0u);
61
62 arr.append(42);
63 EXPECT_EQ(arr.size(), 1u);
64 EXPECT_FALSE(arr.is_empty());
65 EXPECT_EQ(arr.access(0), 42);
66
67 arr.append(7);
68 EXPECT_EQ(arr.size(), 2u);
69 EXPECT_EQ(arr.access(1), 7);
70}
71
72TEST(DynArrayFunctional, ToArrayPreservesOrder)
73{
74 DynArray<int> src;
75 for (int v : {3, 6, 9})
76 src.append(v);
77
78 auto copy = src.to_array();
79
80 ASSERT_EQ(copy.size(), src.size());
81 for (size_t i = 0; i < copy.size(); ++i)
82 EXPECT_EQ(copy(i), src(i));
83}
84
85TEST(DynArrayBasics, default_values_and_touch)
86{
87 DynArray<int> arr;
89
90 arr.reserve(0, 3);
91 ASSERT_EQ(arr.size(), 4u);
92 for (size_t i = 0; i < arr.size(); ++i)
93 EXPECT_EQ(arr.access(i), 123);
94
95 arr.access(2) = 77;
96 EXPECT_EQ(arr.access(2), 77);
97
98 auto & ref = arr.touch(10);
99 ref = 99;
100 EXPECT_EQ(arr.size(), 11u);
101 EXPECT_EQ(arr.access(10), 99);
102}
103
104TEST(DynArrayAlgorithms, InPlaceUnique)
105{
106 DynArray<int> arr;
107 arr.append(1);
108 arr.append(2);
109 arr.append(1);
110 arr.append(3);
111 arr.append(2);
112 arr.append(4);
113 arr.append(4);
114
115 in_place_unique(arr);
116
117 ASSERT_EQ(arr.size(), 4u);
118 EXPECT_EQ(arr.access(0), 1);
119 EXPECT_EQ(arr.access(1), 2);
120 EXPECT_EQ(arr.access(2), 3);
121 EXPECT_EQ(arr.access(3), 4);
122}
123
124TEST(DynArrayErrors, stack_operations_on_empty)
125{
126 DynArray<int> arr;
127
128 EXPECT_THROW(arr.pop(), std::underflow_error);
129 EXPECT_THROW(arr.top(), std::underflow_error);
130 EXPECT_THROW(arr.get_first(), std::underflow_error);
131 EXPECT_THROW(arr.get_last(), std::underflow_error);
132
133 int dummy = 0;
134 EXPECT_THROW(arr.remove(dummy), std::underflow_error);
135}
136
137TEST(DynArrayReserve, invalid_range_throws)
138{
139 DynArray<int> arr;
140 EXPECT_THROW(arr.reserve(5, 4), std::domain_error);
141}
142
143TEST(DynArrayReserve, reserve_and_access)
144{
145 DynArray<int> arr;
146 arr.reserve(5);
147 ASSERT_EQ(arr.size(), 5u);
148 for (size_t i = 0; i < arr.size(); ++i)
149 arr.access(i) = static_cast<int>(i * 2);
150 for (size_t i = 0; i < arr.size(); ++i)
151 EXPECT_EQ(arr.access(i), static_cast<int>(i * 2));
152}
153
154// The constructor refuses a dimension past Max_Dim_Allowed, but touch() and
155// operator[] took an index past it, and reserve() and adjust() began to
156// allocate every block up to it; with 2^61, the directory asked for 32 TiB
157// before it failed. Now they refuse it as the constructor does, before
158// anything grows, and the array is as it was
159TEST(DynArrayReserve, an_index_past_the_limit_is_refused)
160{
161 constexpr size_t max = numeric_limits<size_t>::max();
162 const size_t limit = DynArray<int>::Max_Dim_Allowed;
163 for (const size_t i : {limit, limit + 1, size_t(1) << 61, max - 1, max})
164 {
165 SCOPED_TRACE(i);
166 DynArray<int> arr;
167 arr.append(5);
168 arr.append(6);
169 EXPECT_THROW(arr.reserve(i == max ? max : i + 1), length_error);
170 EXPECT_THROW(arr.reserve(1, i), length_error);
171 EXPECT_THROW((void) arr.touch(i), length_error);
172 EXPECT_THROW(arr[i] = 7, length_error);
173 EXPECT_THROW(arr.adjust(i == max ? max : i + 1), length_error);
174 ASSERT_EQ(arr.size(), 2u);
175 EXPECT_EQ(arr(0), 5);
176 EXPECT_EQ(arr(1), 6);
177
178 arr.append(7); // and it goes on
179 EXPECT_EQ(arr.size(), 3u);
180 EXPECT_EQ(arr(2), 7);
181 }
182 EXPECT_THROW(DynArray<int> too_big(limit + 1), length_error);
183}
184
185TEST(DynArrayIterator, get_it_position)
186{
187 DynArray<int> arr;
188 for (int i = 0; i < 6; ++i)
189 arr.append(i);
190
191 auto it = arr.get_it(3);
192 ASSERT_TRUE(it.has_curr());
193 EXPECT_EQ(it.get_curr(), 3);
194 it.next();
195 EXPECT_EQ(it.get_curr(), 4);
196
197 const auto & carr = arr;
198 auto cit = carr.get_it(5);
199 EXPECT_EQ(cit.get_curr(), 5);
200 EXPECT_THROW(carr.get_it(6), std::out_of_range);
201}
202
203TEST(DynArrayIterator, IsLastRequiresCurrentItem)
204{
206 EXPECT_FALSE(singular.is_last());
207 singular.reset_last();
208 EXPECT_FALSE(singular.has_curr());
209 EXPECT_FALSE(singular.is_last());
210
211 DynArray<int> empty;
212 auto it = empty.get_it();
213 it.reset_last();
214 EXPECT_FALSE(it.has_curr());
215 EXPECT_FALSE(it.is_last());
216
217 empty.append(7);
218 it.reset_last();
219 EXPECT_TRUE(it.has_curr());
220 EXPECT_TRUE(it.is_last());
221 it.end();
222 EXPECT_FALSE(it.is_last());
223}
224
225TEST(DynArrayIterator, CheckedAccessRejectsInvalidPositions)
226{
228 EXPECT_THROW(singular.get_curr(), std::overflow_error);
229 EXPECT_THROW(singular.next(), std::overflow_error);
230 singular.reset_last();
231 EXPECT_THROW(singular.get_curr(), std::underflow_error);
232 EXPECT_THROW(singular.next(), std::overflow_error);
233
234 DynArray<int> arr;
235 auto it = arr.get_it();
236 EXPECT_THROW(it.get_curr(), std::overflow_error);
237 EXPECT_THROW(it.next(), std::overflow_error);
238 it.reset_last();
239 EXPECT_THROW(it.get_curr(), std::underflow_error);
240
241 arr.append(42);
242 it.reset_first();
243 EXPECT_EQ(it.get_curr(), 42);
244 it.next();
245 EXPECT_THROW(it.get_curr(), std::overflow_error);
246 EXPECT_THROW(it.next(), std::overflow_error);
247 it.set_pos(-1);
248 EXPECT_THROW(it.get_curr(), std::underflow_error);
249 it.next();
250 EXPECT_EQ(it.get_curr(), 42);
251}
252
253TEST(DynArrayReserve, adjust_and_cut)
254{
255 DynArray<int> arr;
256 arr.adjust(10);
257 EXPECT_EQ(arr.size(), 10u);
258 arr.cut(3);
259 EXPECT_EQ(arr.size(), 3u);
260 arr.empty();
261 EXPECT_TRUE(arr.is_empty());
262 arr.append(1);
263 arr.append(2);
264 arr.cut(2);
265 EXPECT_EQ(arr.size(), 2u);
266
267 arr.clear();
268 EXPECT_TRUE(arr.is_empty());
269 EXPECT_EQ(arr.size(), 0u);
270
271 arr.append(10);
272 EXPECT_TRUE(arr.contains(10));
273 EXPECT_FALSE(arr.contains(20));
274}
275
276TEST(DynArrayReserve, reserve_invalid_order)
277{
278 DynArray<int> arr;
279 EXPECT_THROW(arr.reserve(4, 3), std::domain_error);
280 EXPECT_EQ(arr.size(), 0u);
281}
282
283TEST(DynArrayReserve, reserve_touch_consistency)
284{
285 DynArray<int> arr;
286 arr.reserve(2, 5);
287 ASSERT_EQ(arr.size(), 6u);
288 arr.touch(20) = 100;
289 EXPECT_EQ(arr.size(), 21u);
290 arr.cut(6);
291 EXPECT_EQ(arr.size(), 6u);
292}
293
294// Default constructor that throws std::bad_alloc once `budget` constructions
295// have succeeded. A negative budget never fails. Used to make a block
296// allocation fail at a chosen point inside DynArray::reserve().
297struct Fails_After_Budget
298{
299 static inline long budget = -1;
300 int value = 0;
301
302 Fails_After_Budget()
303 {
304 if (budget == 0)
305 throw std::bad_alloc();
306 if (budget > 0)
307 --budget;
308 }
309};
310
311// Restores the unlimited budget even if an ASSERT leaves the test early.
312struct Budget_Guard
313{
314 ~Budget_Guard() { Fails_After_Budget::budget = -1; }
315};
316
317TEST(DynArrayReserve, reserve_fills_missing_blocks_of_existing_segment)
318{
319 DynArray<int> arr(4, 2, 2); // segments of 4 blocks of 4 entries
320 arr.touch(0) = 7; // segment 0 exists, but only its block 0
321 ASSERT_EQ(arr.get_num_blocks(), 1u);
322
323 arr.reserve(0, 15); // must allocate blocks 1..3 of the existing segment
324 EXPECT_EQ(arr.get_num_blocks(), 4u);
325 EXPECT_EQ(arr.size(), 16u);
326 for (size_t i = 0; i <= 15; ++i)
327 EXPECT_TRUE(arr.exist(i)) << "entry " << i;
328 EXPECT_EQ(arr.access(0), 7); // existing data is preserved
329}
330
331TEST(DynArrayReserve, failed_reserve_releases_only_what_it_allocated)
332{
333 Budget_Guard guard;
334 // 16 segments of 4 blocks of 4 entries: [0, 47] spans segments 0, 1 and 2.
335 DynArray<Fails_After_Budget> arr(4, 2, 2);
336 const size_t block = arr.get_block_size();
337 ASSERT_EQ(block, 4u);
338
339 arr.touch(0); // segment 0 and its block 0 exist before the reserve
340 ASSERT_EQ(arr.get_num_blocks(), 1u);
341
342 // Blocks 1..3 of segment 0 and block 0 of segment 1 succeed; block 1 of
343 // segment 1 fails, after a whole new segment has been allocated.
344 Fails_After_Budget::budget = static_cast<long>(4 * block);
345 EXPECT_THROW(arr.reserve(0, 47), std::bad_alloc);
346 Fails_After_Budget::budget = -1;
347
348 EXPECT_EQ(arr.get_num_blocks(), 1u);
349 EXPECT_EQ(arr.size(), 1u);
350 for (size_t i = 0; i < block; ++i)
351 EXPECT_TRUE(arr.exist(i)) << "pre-existing entry " << i;
352 for (size_t i = block; i <= 47; ++i)
353 EXPECT_FALSE(arr.exist(i)) << "entry " << i << " was not rolled back";
354
355 arr.reserve(0, 47); // the array remains fully usable
356 EXPECT_EQ(arr.get_num_blocks(), 12u);
357 EXPECT_EQ(arr.size(), 48u);
358 for (size_t i = 0; i <= 47; ++i)
359 EXPECT_TRUE(arr.exist(i));
360}
361
362TEST(DynArrayReserve, failure_on_first_block_releases_new_segment)
363{
364 Budget_Guard guard;
365 DynArray<Fails_After_Budget> arr(4, 2, 2);
366
367 Fails_After_Budget::budget = 0; // the very first block allocation fails
368 EXPECT_THROW(arr.reserve(20, 40), std::bad_alloc);
369 Fails_After_Budget::budget = -1;
370
371 EXPECT_EQ(arr.get_num_blocks(), 0u);
372 EXPECT_EQ(arr.size(), 0u);
373 for (size_t i = 0; i <= 47; ++i)
374 EXPECT_FALSE(arr.exist(i));
375}
376
377TEST(DynArrayReserve, reserve_of_existing_range_constructs_nothing)
378{
379 Budget_Guard guard;
380 DynArray<Fails_After_Budget> arr(4, 2, 2);
381 arr.reserve(0, 47);
382 ASSERT_EQ(arr.get_num_blocks(), 12u);
383
384 Fails_After_Budget::budget = 0; // any element construction would throw
385 EXPECT_NO_THROW(arr.reserve(0, 47));
386 EXPECT_NO_THROW(arr.reserve(5, 30));
387 EXPECT_EQ(arr.get_num_blocks(), 12u);
388 EXPECT_EQ(arr.size(), 48u);
389}
390
391TEST(DynArrayQueueStack, push_pop_fifo_lifo)
392{
393 DynArray<int> arr;
394 for (int i = 0; i < 5; ++i)
395 arr.push(i);
396 EXPECT_EQ(arr.get_first(), 0);
397 EXPECT_EQ(arr.get_last(), 4);
398
399 arr.insert(-1);
400 EXPECT_EQ(arr.get_first(), -1);
401
402 EXPECT_EQ(arr.pop(), 4);
403 EXPECT_EQ(arr.size(), 5u);
404 EXPECT_EQ(arr.top(), arr.get_last());
405}
406
407// An integer gives a lazy logical size only through explicit construction.
408static_assert(std::is_constructible_v<DynArray<int>, size_t>);
409static_assert(not std::is_convertible_v<int, DynArray<int>>);
410static_assert(not std::is_convertible_v<size_t, DynArray<int>>);
411static_assert(std::is_constructible_v<DynArray<int>, size_t, int>);
412
414struct With_Dyn_Array_Member
415{
416 int key = 0;
417 DynArray<int> values;
418};
419
420TEST(DynArrayCtors, DefaultConstructorIsNotExplicit)
421{
422 const DynArray<int> braced = {};
423 EXPECT_TRUE(braced.is_empty());
424
425 const With_Dyn_Array_Member aggregate{7};
426 EXPECT_EQ(aggregate.key, 7);
427 EXPECT_TRUE(aggregate.values.is_empty());
428}
429
430TEST(DynArrayCtors, LazySizeIsCoveredByTheDirectory)
431{
432 const size_t n = size_t{1} << 30;
433 const DynArray<int> lazy(n);
434 EXPECT_EQ(lazy.size(), n);
435 EXPECT_GE(lazy.max_size(), lazy.size());
436 EXPECT_EQ(lazy.get_num_blocks(), 0u);
437 EXPECT_FALSE(lazy.exist(n - 1));
438
439 EXPECT_THROW((void) DynArray<int>(DynArray<int>::Max_Dim_Allowed + 1),
440 std::length_error);
441}
442
443TEST(DynArrayCtors, CountValueAllocatesEveryEntry)
444{
445 const DynArray<int> sevens(5, 7);
446 ASSERT_EQ(sevens.size(), 5u);
447 int sum = 0;
448 sevens.for_each([&sum] (int x) { sum += x; });
449 EXPECT_EQ(sum, 35);
450 for (size_t i = 0; i < sevens.size(); ++i)
451 {
452 EXPECT_TRUE(sevens.exist(i));
453 EXPECT_EQ(sevens.access(i), 7);
454 }
455
456 const DynArray<size_t> same_type(size_t{3}, size_t{8});
457 ASSERT_EQ(same_type.size(), 3u);
458 EXPECT_EQ(same_type.access(2), 8u);
459
460 const DynArray<std::string> strings(2, "ab");
461 ASSERT_EQ(strings.size(), 2u);
462 EXPECT_EQ(strings.access(1), "ab");
463
464 const DynArray<int> none(0, 7);
465 EXPECT_TRUE(none.is_empty());
466}
467
468TEST(DynArrayCopy, CopyKeepsTheLazySizeAndItsOwnDefaultValue)
469{
470 const DynArray<int> lazy(10);
471 const DynArray<int> lazy_copy(lazy);
472 EXPECT_EQ(lazy_copy.size(), 10u);
473 EXPECT_EQ(lazy_copy.get_num_blocks(), 0u);
474
475 auto * src = new DynArray<int>;
477 src->touch(2) = 5;
478 DynArray<int> copy(*src);
479 delete src; // the copy must not refer to the original's default value
480 EXPECT_EQ(copy.access(2), 5);
481 EXPECT_EQ(copy.touch(5000), 42);
482}
483
484TEST(DynArrayCopy, CopyAssignmentReplacesEverything)
485{
486 DynArray<int> dst;
487 for (int i = 1; i <= 10; ++i)
488 dst.append(i);
489
490 DynArray<int> src(10);
492 dst = src;
493 EXPECT_EQ(dst.size(), 10u);
494 EXPECT_FALSE(dst.exist(0)); // no stale value from the previous contents
495 EXPECT_EQ(dst.touch(5000), 42);
496
497 const DynArray<int> & same = dst;
498 dst = same;
499 EXPECT_EQ(dst.size(), 5001u);
500 EXPECT_EQ(dst.access(5000), 42);
501}
502
505struct Copy_Bomb
506{
507 static inline long live = 0;
508 static inline long budget = -1;
509 int value = 0;
510
511 Copy_Bomb() noexcept { ++live; }
512 Copy_Bomb(const Copy_Bomb & other) noexcept : value(other.value) { ++live; }
513 Copy_Bomb(Copy_Bomb && other) noexcept : value(other.value) { ++live; }
514 ~Copy_Bomb() { --live; }
515
516 Copy_Bomb & operator = (const Copy_Bomb & other)
517 {
518 if (budget >= 0 and budget-- == 0)
519 throw std::runtime_error("Copy_Bomb: copy budget exhausted");
520 value = other.value;
521 return *this;
522 }
523
524 Copy_Bomb & operator = (Copy_Bomb && other) noexcept
525 {
526 value = other.value;
527 return *this;
528 }
529};
530
531// The copy constructor delegates to the geometry constructor, so when copying
532// an entry throws, the destructor releases every segment and block allocated
533// so far. The count of live elements shows any block that leaked.
534TEST(DynArrayCopy, ThrowingCopyLeaksNothing)
535{
537 src.touch(10).value = 1; // first block
538 src.touch(9000).value = 2; // a later block, leaving a gap
539 src.touch(1100000).value = 3; // another segment
540 ASSERT_EQ(src.get_num_blocks(), 3u);
541
542 const long live_before = Copy_Bomb::live;
543 const long block = static_cast<long>(src.get_block_size());
544
545 // Each block costs 2 * block assignments: the default fill and the copy.
546 // The first assignment copies the default value itself.
547 for (const long at : {0L, 1L, block - 1, block, block + 5, 2 * block + 7,
548 3 * block + 1, 5 * block})
549 {
550 Copy_Bomb::budget = at;
551 EXPECT_THROW(DynArray<Copy_Bomb> copy(src), std::runtime_error)
552 << "copy did not throw at assignment " << at;
553 Copy_Bomb::budget = -1;
554 EXPECT_EQ(Copy_Bomb::live, live_before)
555 << "elements leaked when throwing at assignment " << at;
556 }
557
558 // Copy assignment gives the strong guarantee: the target is unchanged.
560 dst.touch(3).value = 7;
561 const long live_with_dst = Copy_Bomb::live;
562 Copy_Bomb::budget = block + 3;
563 EXPECT_THROW(dst = src, std::runtime_error);
564 Copy_Bomb::budget = -1;
565 EXPECT_EQ(Copy_Bomb::live, live_with_dst);
566 ASSERT_EQ(dst.size(), 4u);
567 EXPECT_EQ(dst.read(3).value, 7);
568}
569
570// A block is filled with the default value before the array takes it: if a
571// copy of that value throws, the array is as it was. It used to keep the
572// block of a segment that existed, half filled, and to lose that of a new
573// segment, with its items alive. Every writer of an entry goes through it:
574// touch(), reserve() and the three ways of writing through a[i]
575TEST(DynArrayBlocks, ABlockThatCannotBeFilledLeavesTheArrayAsItWas)
576{
577 struct Unlimited
578 {
579 ~Unlimited() { Copy_Bomb::budget = -1; }
580 } unlimited; // even if an ASSERT leaves the test early
581
582 using Writer = void (*)(DynArray<Copy_Bomb> &, size_t);
583 const Writer writers[] = {
584 [] (DynArray<Copy_Bomb> & a, const size_t i) { a.touch(i); },
585 [] (DynArray<Copy_Bomb> & a, const size_t i) { a.reserve(i, i); },
586 [] (DynArray<Copy_Bomb> & a, const size_t i) { a[i] = Copy_Bomb(); },
587 [] (DynArray<Copy_Bomb> & a, const size_t i) { a[i]->value = 1; },
588 [] (DynArray<Copy_Bomb> & a, const size_t i) { a[i] = a[0]; }};
589
590 Copy_Bomb seven;
591 seven.value = 7;
592 size_t w = 0;
593 for (const Writer write : writers)
594 {
595 // An entry of an array without segments, of a segment that exists
596 // and of a new one, and each copy of the filling of its block
597 for (const size_t first : {size_t{0}, size_t{4}, size_t{16}})
598 for (long at = 0; at < 4; ++at)
599 {
600 SCOPED_TRACE(testing::Message() << "writer " << w << ", entry " << first << ", copy " << at);
601 DynArray<Copy_Bomb> a(4, 2, 2); // segments of 4 blocks of 4 entries
603 if (first != 0)
604 a.touch(0);
605 const size_t blocks = a.get_num_blocks(), size = a.size();
606 const long live = Copy_Bomb::live;
607
608 Copy_Bomb::budget = at;
609 EXPECT_THROW(write(a, first), std::runtime_error);
610 Copy_Bomb::budget = -1;
611 EXPECT_EQ(a.get_num_blocks(), blocks);
612 EXPECT_EQ(a.size(), size);
613 EXPECT_EQ(Copy_Bomb::live, live);
614 EXPECT_FALSE(a.exist(first));
615
616 write(a, first); // with every copy allowed, the block is whole
617 EXPECT_EQ(a.get_num_blocks(), blocks + 1);
618 for (size_t i = first + 1; i < first + 4; ++i)
619 EXPECT_EQ(a.access(i).value, 7) << "entry " << i;
620 }
621 ++w;
622 }
623}
624
625// Reading an entry that was never written yields the default value and never
626// allocates memory; a constant array reads through const T &, not a proxy.
627static_assert(std::is_same_v<decltype(std::declval<const DynArray<int> &>()[0]),
628 const int &>);
629
630TEST(DynArrayLazyReads, ReadingUnwrittenEntriesAllocatesNothing)
631{
632 DynArray<int> lazy(10);
633 const DynArray<int> & view = lazy;
634
635 EXPECT_EQ(lazy.read(3), 0);
636 EXPECT_EQ(view[3], 0);
637
638 int sum = 0;
639 lazy.for_each([&sum] (int x) { sum += x; });
640 for (const int x : view)
641 sum += x;
642 EXPECT_EQ(sum, 0);
643
644 EXPECT_EQ(lazy, DynArray<int>(10, 0));
645 EXPECT_EQ(lazy.to_array().size(), 10u);
646 EXPECT_EQ(lazy.get_num_blocks(), 0u);
647
648 EXPECT_THROW((void) lazy.read(10), std::out_of_range);
649 EXPECT_THROW((void) view[10], std::out_of_range);
650}
651
652TEST(DynArrayLazyReads, ReadsUseTheDefaultValue)
653{
654 DynArray<int> lazy(5);
655 lazy.set_default_initial_value(7);
656 EXPECT_EQ(lazy.read(4), 7);
657
658 int sum = 0;
659 lazy.for_each([&sum] (int x) { sum += x; });
660 EXPECT_EQ(sum, 35);
661 EXPECT_EQ(lazy.get_num_blocks(), 0u);
662}
663
664TEST(DynArrayLazyReads, TraversalVisitsGapsBetweenWrittenBlocks)
665{
666 DynArray<int> sparse;
667 sparse.touch(10000) = 1;
668 ASSERT_EQ(sparse.size(), 10001u);
669
670 size_t visited = 0;
671 int sum = 0;
672 sparse.for_each([&] (int x) { ++visited; sum += x; });
673 EXPECT_EQ(visited, 10001u);
674 EXPECT_EQ(sum, 1);
675}
676
677TEST(DynArrayLazyReads, ModifiableAccessAllocatesTheBlock)
678{
679 DynArray<int> lazy(10);
680 lazy[3] += 1;
681 EXPECT_EQ(lazy.read(3), 1);
682 EXPECT_EQ(lazy.get_num_blocks(), 1u);
683
684 DynArray<int> other(10);
685 other[0] = other[5]; // an unwritten right-hand entry reads as the default
686 EXPECT_EQ(other.read(0), 0);
687
688 DynArray<int> queue(3);
689 EXPECT_EQ(queue.get_last(), 0);
690 queue.get_first() = 4;
691 EXPECT_EQ(queue.read(0), 4);
692 EXPECT_EQ(queue.top(), 0);
693}
694
695TEST(DynArrayLazyReads, WritesThroughModifiableTraversalsReachTheArray)
696{
697 // A modifiable traversal or iterator hands out modifiable references, so
698 // the block of an entry never written is allocated first, as a[i] does:
699 // what the operation writes stays in the array. These writes used to go
700 // to a short-lived copy and were lost.
701 DynArray<int> lazy(3);
702 lazy.traverse([] (int & x) { x = 5; return true; });
703 EXPECT_EQ(lazy.read(0), 5);
704 EXPECT_EQ(lazy.read(2), 5);
705 EXPECT_EQ(lazy.get_num_blocks(), 1u);
706
707 DynArray<int> ranged(3);
708 for (auto & x : ranged)
709 x = 6;
710 EXPECT_EQ(ranged.read(1), 6);
711
712 DynArray<int> mutated(3);
713 mutated.mutable_for_each([] (int & x) { x = 7; });
714 EXPECT_EQ(mutated.read(2), 7);
715
716 DynArray<int> iterated(3);
717 for (auto it = iterated.get_it(); it.has_curr(); it.next_ne())
718 it.get_curr_ne() = 8;
719 EXPECT_EQ(iterated.read(0), 8);
720
721 DynArray<int> sliced(5);
722 sliced.each(1, 2, [] (int & x) { x = 9; });
723 EXPECT_EQ(sliced.read(0), 0);
724 EXPECT_EQ(sliced.read(1), 9);
725 EXPECT_EQ(sliced.read(3), 9);
726
727 DynArray<int> written(3, 1); // real entries are modified in place
728 written.traverse([] (int & x) { x = 5; return true; });
729 EXPECT_EQ(written.read(2), 5);
730}
731
732TEST(DynArrayLazyReads, ConstantTraversalsNeverAllocate)
733{
734 DynArray<int> lazy(3);
735 lazy.set_default_initial_value(4);
736 const DynArray<int> & clazy = lazy;
737
738 int sum = 0;
739 clazy.traverse([&sum] (const int & x) { sum += x; return true; });
740 for (const auto & x : clazy)
741 sum += x;
742 for (auto it = clazy.get_it(); it.has_curr(); it.next_ne())
743 sum += it.get_curr_ne();
744 lazy.for_each([&sum] (int x) { sum += x; }); // a query traverses the constant array
745 clazy.each(0, 1, [&sum] (int x) { sum += x; });
746 EXPECT_EQ(sum, 4 * 3 * 5);
747 EXPECT_EQ(lazy.get_num_blocks(), 0u);
748}
749
750TEST(DynArrayLazyReads, StackAndQueueOperationsOnLazyEntries)
751{
752 DynArray<int> lazy(3);
753 lazy.insert(9);
754 ASSERT_EQ(lazy.size(), 4u);
755 EXPECT_EQ(lazy.read(0), 9);
756 EXPECT_EQ(lazy.read(3), 0);
757
758 DynArray<int> popped(3);
759 EXPECT_EQ(popped.pop(), 0);
760 EXPECT_EQ(popped.size(), 2u);
761}
762
763TEST(DynArrayLazyReads, CutDropsTheEntriesItRemoves)
764{
765 DynArray<int> arr;
766 for (int i = 1; i <= 10; ++i)
767 arr.append(i);
768
769 arr.cut(5);
770 arr.touch(9) = 99;
771
772 int expected[] = {1, 2, 3, 4, 5, 0, 0, 0, 0, 99};
773 ASSERT_EQ(arr.size(), 10u);
774 for (size_t i = 0; i < arr.size(); ++i)
775 EXPECT_EQ(arr.read(i), expected[i]) << "at index " << i;
776}
777
778TEST(DynArrayMovedFrom, StaysEmptyAndReusable)
779{
780 DynArray<int> source;
781 source.append(1);
782 DynArray<int> target(std::move(source));
783 ASSERT_EQ(target.read(0), 1);
784
785 EXPECT_TRUE(source.is_empty());
786 EXPECT_FALSE(source.exist(0));
787 EXPECT_EQ(source.test(0), nullptr);
788 EXPECT_TRUE(DynArray<int>(source).is_empty());
789
790 size_t visited = 0;
791 source.for_each([&visited] (int) { ++visited; });
792 EXPECT_EQ(visited, 0u);
793 source.empty();
794 EXPECT_THROW((void) source.read(0), std::out_of_range);
795
796 source.append(2);
797 EXPECT_EQ(source.read(0), 2);
798
799 DynArray<int> by_index(std::move(target));
800 target[4] = 7;
801 EXPECT_EQ(target.size(), 5u);
802 EXPECT_EQ(target.read(4), 7);
803
804 DynArray<int> by_reserve(std::move(by_index));
805 by_index.reserve(3);
806 EXPECT_EQ(by_index.size(), 3u);
807 by_index = by_reserve;
808 EXPECT_EQ(by_index.read(0), 1);
809}
810
811
812// An array that was built and has not written yet has no directory, as
813// one that was moved from: the first write makes it. Whatever built it, an
814// array of size `dim` without a directory reads the default value without
815// allocating a block, is copied, and then writes
816void expect_an_array_that_never_wrote(DynArray<int> & a, const size_t dim, const char * how)
817{
818 SCOPED_TRACE(how);
819 const DynArray<int> & c = a;
820 EXPECT_EQ(c.size(), dim);
821 EXPECT_EQ(c.is_empty(), dim == 0);
822 EXPECT_EQ(c.get_num_blocks(), 0u);
823 EXPECT_FALSE(c.exist(0));
824 EXPECT_EQ(c.test(0), nullptr);
825 EXPECT_THROW((void) c.read(dim), std::out_of_range);
826 if (dim > 0)
827 {
828 EXPECT_EQ(c.read(0), 0);
829 EXPECT_EQ(c.read(dim - 1), 0);
830 EXPECT_EQ(c.nth_ne(dim - 1), 0);
831 }
832 size_t visited = 0;
833 c.for_each([&visited] (const int & item)
834 {
835 EXPECT_EQ(item, 0);
836 ++visited;
837 });
838 EXPECT_EQ(visited, dim);
839 EXPECT_EQ(c.get_num_blocks(), 0u) << "a reader allocated a block";
840
841 const DynArray<int> copy(c);
842 EXPECT_EQ(copy.size(), dim);
843 EXPECT_EQ(copy.get_num_blocks(), 0u);
844
845 a.touch(dim) = 7; // the first write
846 EXPECT_EQ(a.size(), dim + 1);
847 EXPECT_EQ(c.read(dim), 7);
848 EXPECT_EQ(a.get_num_blocks(), 1u);
849 if (dim > 0)
850 EXPECT_EQ(c.read(0), 0);
851 EXPECT_EQ(copy.size(), dim) << "the copy shares nothing with the array";
852}
853
854TEST(DynArrayNeverWritten, EveryWayOfBuildingOneLeavesItUsable)
855{
856 DynArray<int> by_default;
857 expect_an_array_that_never_wrote(by_default, 0, "built by default");
858
859 DynArray<int> empty(size_t{0});
860 expect_an_array_that_never_wrote(empty, 0, "built with size 0");
861
862 DynArray<int> lazy(size_t{5});
863 expect_an_array_that_never_wrote(lazy, 5, "built with a size");
864
865 // a size past the default geometry: its directory, when it is made, is
866 // larger. Its entries are too many to visit them all here
867 const size_t big = by_default.max_size() + 3;
868 DynArray<int> large(big);
869 EXPECT_EQ(large.size(), big);
870 EXPECT_GE(large.max_size(), big);
871 EXPECT_EQ(std::as_const(large).read(big - 1), 0);
872 EXPECT_EQ(DynArray<int>(large).size(), big);
873 EXPECT_EQ(large.get_num_blocks(), 0u);
874 large.touch(big - 1) = 9;
875 EXPECT_EQ(std::as_const(large).read(big - 1), 9);
876 EXPECT_EQ(std::as_const(large).read(0), 0);
877 EXPECT_EQ(large.get_num_blocks(), 1u);
878
879 DynArray<int> with_geometry(4, 4, 4);
880 expect_an_array_that_never_wrote(with_geometry, 0, "built with a geometry");
881
882 const DynArray<int> source(size_t{5});
883 DynArray<int> copied(source);
884 expect_an_array_that_never_wrote(copied, 5, "copied from one that never wrote");
885
886 DynArray<int> assigned;
887 assigned.append(1);
888 assigned = source;
889 expect_an_array_that_never_wrote(assigned, 5, "assigned one that never wrote");
890
891 DynArray<int> moved_from(size_t{5});
892 DynArray<int> taken(std::move(moved_from));
893 expect_an_array_that_never_wrote(taken, 5, "moved from one that never wrote");
894 expect_an_array_that_never_wrote(moved_from, 0, "that was moved from without having written");
895
896 DynArray<int> cut_down(size_t{5});
897 cut_down.cut(2);
898 expect_an_array_that_never_wrote(cut_down, 2, "cut without having written");
899 DynArray<int> emptied(size_t{5});
900 emptied.empty();
901 expect_an_array_that_never_wrote(emptied, 0, "emptied without having written");
902}
903
904// The first write of an array, by each writer
905TEST(DynArrayNeverWritten, EachWriterMakesTheDirectory)
906{
907 DynArray<int> by_append;
908 by_append.append(1);
909 by_append.append(2);
910 EXPECT_EQ(by_append.size(), 2u);
911 EXPECT_EQ(by_append.read(1), 2);
912
913 DynArray<int> by_index;
914 by_index[3] = 4;
915 EXPECT_EQ(by_index.size(), 4u);
916 EXPECT_EQ(by_index.read(3), 4);
917 EXPECT_EQ(by_index.read(0), 0);
918
919 DynArray<int> by_reserve;
920 by_reserve.reserve(10);
921 EXPECT_EQ(by_reserve.size(), 10u);
922 EXPECT_TRUE(by_reserve.exist(9));
923 by_reserve.access(9) = 5;
924 EXPECT_EQ(by_reserve.read(9), 5);
925
926 DynArray<int> by_push;
927 by_push.push(6);
928 EXPECT_EQ(by_push.top(), 6);
929 EXPECT_EQ(by_push.pop(), 6);
930 EXPECT_TRUE(by_push.is_empty());
931
932 // far from the default geometry: the directory is made and grown at once
933 DynArray<int> far;
934 const size_t index = far.max_size() + 7;
935 far.touch(index) = 8;
936 EXPECT_EQ(far.size(), index + 1);
937 EXPECT_EQ(far.read(index), 8);
938 EXPECT_EQ(far.read(0), 0);
939
940 // the default value that is set before the first write
941 DynArray<int> with_default(size_t{3});
942 with_default.set_default_initial_value(42);
943 EXPECT_EQ(std::as_const(with_default).read(2), 42);
944 with_default.touch(1) = 1;
945 EXPECT_EQ(with_default.read(0), 42);
946 EXPECT_EQ(with_default.read(1), 1);
947}
948
949// Two arrays swap what they have: the one that never wrote takes the
950// entries of the other, which is left without a directory, and writes again
951TEST(DynArrayNeverWritten, SwapsWithOneThatWrote)
952{
953 DynArray<int> written;
954 for (int i = 0; i < 10; ++i)
955 written.append(i);
956 DynArray<int> never(size_t{3});
957 never.swap(written);
958 EXPECT_EQ(never.size(), 10u);
959 EXPECT_EQ(never.read(9), 9);
960 expect_an_array_that_never_wrote(written, 3, "after the swap");
961
962 DynArray<int> a, b(size_t{2});
963 a.swap(b);
964 expect_an_array_that_never_wrote(a, 2, "of two that never wrote, the first");
965 expect_an_array_that_never_wrote(b, 0, "of two that never wrote, the second");
966}
967
969std::string long_string(const char c)
970{
971 return std::string(40, c);
972}
973
976struct Failing_Slot
977{
978 static inline int constructions_left = -1;
979 std::string value;
980
983 {
984 if (constructions_left == 0)
985 throw std::bad_alloc();
986 if (constructions_left > 0)
988 }
989
991 explicit Failing_Slot(std::string v) : value(std::move(v)) {}
992};
993
994// The argument of insert() may be an entry of the array itself. The gap
995// that insert() opens used to overwrite it before it was read.
996
997TEST(DynArrayInsert, OwnEntryKeepsItsValue)
998{
1000 for (int i : {10, 20, 30})
1001 a.append(i);
1002
1003 EXPECT_EQ(a.insert(a.access(1)), 20);
1004 ASSERT_EQ(a.size(), 4u);
1005 const int expected[] = {20, 10, 20, 30};
1006 for (size_t i = 0; i < 4; ++i)
1007 EXPECT_EQ(a.read(i), expected[i]);
1008}
1009
1010TEST(DynArrayInsert, OwnMovedEntryKeepsItsValue)
1011{
1013 for (char c : {'a', 'b', 'c'})
1014 a.append(long_string(c));
1015
1016 EXPECT_EQ(a.insert(std::move(a.access(2))), long_string('c'));
1017 ASSERT_EQ(a.size(), 4u);
1018 EXPECT_EQ(a.read(1), long_string('a'));
1019 EXPECT_EQ(a.read(2), long_string('b'));
1020}
1021
1022TEST(DynArrayInsert, FailedAllocationLeavesTheArrayAndTheArgumentUntouched)
1023{
1024 DynArray<Failing_Slot> a(2, 2, 2); // blocks of four entries
1025 for (char c : {'a', 'b', 'c', 'd'})
1027 ASSERT_EQ(a.size(), a.get_block_size()); // the next entry needs a block
1028
1029 Failing_Slot x(long_string('x'));
1030 Failing_Slot::constructions_left = 0; // the new block cannot be built
1031 EXPECT_THROW(a.insert(x), std::bad_alloc);
1032 EXPECT_THROW(a.insert(std::move(x)), std::bad_alloc);
1034
1035 EXPECT_EQ(x.value, long_string('x'));
1036 ASSERT_EQ(a.size(), 4u);
1037 for (size_t i = 0; i < 4; ++i)
1038 EXPECT_EQ(a.read(i).value, long_string(static_cast<char>('a' + i)));
1039
1040 EXPECT_EQ(a.insert(std::move(x)).value, long_string('x'));
1041 EXPECT_EQ(a.read(1).value, long_string('a'));
1042}
1043
1044
1045// The geometry helpers were noexcept, so the overflow_error documented by
1046// the geometry constructor called std::terminate.
1047static_assert(not noexcept(DynArray<int>::compute_sizes(size_t{})));
1048
1049TEST(DynArrayGeometry, OversizedGeometryThrowsOverflowError)
1050{
1051 // 2^(40 + 20 + 10) entries do not fit in a size_t.
1052 EXPECT_THROW((DynArray<int>(40, 20, 10)), std::overflow_error);
1053 EXPECT_THROW((void) DynArray<int>::compute_sizes(numeric_limits<size_t>::max()),
1054 std::overflow_error);
1055
1056 // 2^63 is the largest dimension that a geometry can hold.
1057 const auto [d, s, b] = DynArray<int>::compute_sizes(size_t(1) << 63);
1058 EXPECT_EQ(d + s + b, 63u);
1059}
1060
1061
1064struct Counted_Default
1065{
1066 static inline long defaults = 0;
1067 static inline bool failing = false;
1068 int value = 0;
1069
1070 Counted_Default()
1071 {
1072 if (failing)
1073 throw std::bad_alloc();
1074 ++defaults;
1075 }
1076 explicit Counted_Default(int v) noexcept : value(v) {}
1077};
1078
1079TEST(DynArrayIterator, CreatingIteratorsConstructsNoItem)
1080{
1081 // The iterator kept a default-constructed T for unwritten entries, and
1082 // its constructors were noexcept: a throwing default constructor called
1083 // std::terminate. The copy is now built only when an unwritten entry is
1084 // read.
1085 static_assert(std::is_nothrow_default_constructible_v<DynArray<Counted_Default>::Iterator>);
1087 a.append(Counted_Default(1));
1088 a.append(Counted_Default(2));
1089
1090 const long before = Counted_Default::defaults;
1091 Counted_Default::failing = true;
1092 {
1093 auto it = a.get_it();
1094 EXPECT_TRUE(it.has_curr());
1095 EXPECT_EQ(it.get_curr().value, 1);
1097 EXPECT_FALSE(end.has_curr());
1098 int sum = 0;
1099 for (const auto & item : a)
1100 sum += item.value;
1101 EXPECT_EQ(sum, 3);
1102 }
1103 Counted_Default::failing = false;
1104 EXPECT_EQ(Counted_Default::defaults, before);
1105}
1106
1107TEST(DynArrayIterator, UnwrittenEntryOnConstantAndModifiableArrays)
1108{
1109 DynArray<int> a(2, 2, 2); // blocks of four entries
1111 a.touch(9) = 3; // entries 0 to 7 are in blocks never allocated
1112
1113 // On a constant array the iterator never allocates: an entry never
1114 // written is the default value, at an address that stays valid.
1115 const DynArray<int> & ca = a;
1116 auto cit = ca.get_it();
1117 const int & first = cit.get_curr();
1118 EXPECT_EQ(first, 7);
1119 cit.next();
1120 EXPECT_EQ(&cit.get_curr(), &first);
1121 EXPECT_EQ(a.test(0), nullptr);
1122
1123 // On a modifiable array get_curr() hands out the entry itself, allocating
1124 // its block as a[i] does, so writing through it writes the array.
1125 auto it = a.get_it();
1126 int & entry = it.get_curr();
1127 EXPECT_EQ(&entry, a.test(0));
1128 entry = 100;
1129 EXPECT_EQ(a.read(0), 100);
1130 it.next();
1131 EXPECT_EQ(it.get_curr(), 7); // same block, filled with the default value
1132 EXPECT_EQ(a.size(), 10u);
1133}
1134
1135
1138DynArray<int> array_with_unwritten_blocks()
1139{
1140 DynArray<int> a(2, 2, 2);
1142 a.touch(9) = 0;
1143 return a;
1144}
1145
1146// The traversal hands out an entry never written as a short-lived copy of
1147// the default value. nth(), nth_ne() and find_ptr(), inherited from
1148// LocateFunctions, kept its address: they returned a dangling reference.
1149
1150TEST(DynArrayLocate, NthOfAnUnwrittenEntryIsTheEntry)
1151{
1152 DynArray<int> a = array_with_unwritten_blocks();
1153 const DynArray<int> & ca = a;
1154
1155 EXPECT_EQ(ca.nth(1), 7); // a constant read allocates nothing
1156 EXPECT_EQ(ca.nth_ne(5), 7);
1157 EXPECT_EQ(a.test(1), nullptr);
1158 EXPECT_EQ(a.test(5), nullptr);
1159 EXPECT_THROW((void) ca.nth(10), std::out_of_range);
1160
1161 int & x = a.nth(3); // a modifiable access allocates, as a[i]
1162 EXPECT_EQ(&x, a.test(3));
1163 EXPECT_EQ(x, 7);
1164 x = 30;
1165 EXPECT_EQ(a.read(3), 30);
1166
1167 int & y = a.nth_ne(6);
1168 EXPECT_EQ(&y, a.test(6));
1169 EXPECT_EQ(y, 7);
1170 EXPECT_THROW((void) a.nth(10), std::out_of_range);
1171 EXPECT_EQ(a.size(), 10u);
1172}
1173
1174TEST(DynArrayLocate, FindPtrOfAnUnwrittenEntryPointsIntoTheArray)
1175{
1176 DynArray<int> a = array_with_unwritten_blocks();
1177 const DynArray<int> & ca = a;
1178 auto is_seven = [] (int i) { return i == 7; };
1179
1180 const int * c = ca.find_ptr(is_seven); // entry 0, never written
1181 ASSERT_NE(c, nullptr);
1182 EXPECT_EQ(*c, 7);
1183 EXPECT_EQ(a.test(0), nullptr); // a constant search allocates nothing
1184
1185 int * p = a.find_ptr(is_seven);
1186 ASSERT_NE(p, nullptr);
1187 EXPECT_EQ(p, a.test(0)); // the entry itself, now allocated
1188 *p = 1;
1189 EXPECT_EQ(a.read(0), 1);
1190
1191 EXPECT_EQ(a.find_ptr([] (int i) { return i == 42; }), nullptr);
1192 EXPECT_EQ(ca.find_ptr([] (int i) { return i == 42; }), nullptr);
1193 EXPECT_EQ(*a.find_ptr([] (int i) { return i == 0; }), 0); // entry 9
1194}
1195
1197template <class A, class Op>
1198constexpr bool can_find_item = requires (A & a, Op & op) { a.find_item(op); };
1199
1201constexpr auto is_seven_criterion = [] (const int & i) { return i == 7; };
1202
1203TEST(DynArrayLocate, FindItemOfAnUnwrittenEntryCopiesTheDefaultValue)
1204{
1205 DynArray<int> a = array_with_unwritten_blocks();
1206 const auto [found, item] = a.find_item([] (int i) { return i == 7; });
1207 EXPECT_TRUE(found);
1208 EXPECT_EQ(item, 7);
1209 EXPECT_EQ(a.test(0), nullptr); // find_item() returns a copy: no allocation
1210
1211 // find_item() is a query: its criterion receives each entry as a
1212 // constant reference, so a criterion that modifies it does not compile.
1213 auto scribble = [] (int & i) { const bool match = i == 7; i = -1; return match; };
1214 static_assert(not can_find_item<DynArray<int>, decltype(scribble)>);
1215 static_assert(can_find_item<DynArray<int>, decltype(is_seven_criterion)>);
1216
1217 const auto [missing, dflt] = std::as_const(a).find_item([] (int i) { return i == 42; });
1218 EXPECT_FALSE(missing);
1219 EXPECT_EQ(dflt, 0);
1220}
1221
1222// G1: the traversal and the iterator handed out short-lived copies of the
1223// entries never written, and these functions kept their addresses. The
1224// constant ones now point to the default value, which lives as long as the
1225// array; the modifiable ones to the entries themselves, now allocated.
1226TEST(DynArrayLocate, AddressesOfUnwrittenEntriesStayValid)
1227{
1228 DynArray<int> a = array_with_unwritten_blocks(); // entries 0 to 7 never written
1229 const DynArray<int> & ca = a;
1230
1231 // Entries 0 to 7 read as the default value; entry 8 shares the block of
1232 // entry 9, allocated and filled with the default value.
1233 const auto ptrs = ca.ptr_filter([] (int x) { return x == 7; });
1234 ASSERT_EQ(ptrs.size(), 9u);
1235 size_t i = 0;
1236 ptrs.for_each([&ca, &a, &i] (const int * p)
1237 {
1238 EXPECT_EQ(*p, 7);
1239 EXPECT_EQ(p, i < 8 ? &ca.read(0) : a.test(8));
1240 ++i;
1241 });
1242
1243 const int * lo = Aleph::min_ptr(ca);
1244 const int * hi = Aleph::max_ptr(ca);
1245 ASSERT_NE(lo, nullptr);
1246 ASSERT_NE(hi, nullptr);
1247 EXPECT_EQ(*lo, 0); // entry 9
1248 EXPECT_EQ(*hi, 7);
1249 const auto [mn, mx] = Aleph::minmax_ptr(ca);
1250 EXPECT_EQ(*mn, 0);
1251 EXPECT_EQ(*mx, 7);
1252
1253 int sum = 0;
1254 Aleph::pointers_list(ca).for_each([&sum] (const int * p) { sum += *p; });
1255 EXPECT_EQ(sum, 9 * 7 + 0);
1256 EXPECT_EQ(a.test(0), nullptr); // the constant reads allocated nothing
1257
1258 // Modifiable pointers refer to the entries, whose blocks are allocated
1259 auto seven = [] (int x) { return x == 7; };
1260 int * p = Aleph::find_ptr(a, seven);
1261 ASSERT_NE(p, nullptr);
1262 EXPECT_EQ(p, a.test(0));
1263 const auto mutable_ptrs = Aleph::pointers_list(a);
1264 EXPECT_EQ(mutable_ptrs.get_first(), a.test(0));
1265 *mutable_ptrs.get_last() = 42; // entry 9
1266 EXPECT_EQ(a.read(9), 42);
1267}
1268
1269// F4: these members were noexcept although they copy, swap or
1270// default-construct a T, which may throw.
1271struct Throwing_Copy
1272{
1273 int value = 0;
1274 Throwing_Copy() = default;
1275 Throwing_Copy(const Throwing_Copy & o) : value(o.value) {}
1276 Throwing_Copy(Throwing_Copy && o) : value(o.value) {}
1277 Throwing_Copy & operator = (const Throwing_Copy & o) { value = o.value; return *this; }
1278 Throwing_Copy & operator = (Throwing_Copy && o) { value = o.value; return *this; }
1279};
1280
1281TEST(DynArrayNoexcept, DependsOnT)
1282{
1283 static_assert(std::is_nothrow_move_constructible_v<DynArray<int>>);
1284 static_assert(std::is_nothrow_move_assignable_v<DynArray<int>>);
1285 static_assert(std::is_nothrow_swappable_v<DynArray<int>>);
1286 static_assert(noexcept(std::declval<DynArray<int> &>().set_default_initial_value(0)));
1287
1288 static_assert(not std::is_nothrow_move_constructible_v<DynArray<Throwing_Copy>>);
1289 static_assert(not std::is_nothrow_move_assignable_v<DynArray<Throwing_Copy>>);
1290 static_assert(not noexcept(std::declval<DynArray<Throwing_Copy> &>().swap(
1291 std::declval<DynArray<Throwing_Copy> &>())));
1292 static_assert(not noexcept(std::declval<DynArray<Throwing_Copy> &>().set_default_initial_value(
1293 std::declval<const Throwing_Copy &>())));
1294
1296 a.append(Throwing_Copy());
1297 a.swap(b);
1298 EXPECT_EQ(b.size(), 1u);
1299}
1300
1301// cut() resets the entries that leave the last kept block, which assigns a
1302// T and may throw. A cut that fails must leave the array as it was: it used
1303// to release the blocks above first and keep the old dimension.
1304struct Assignment_Throws
1305{
1306 static inline int assignments_left = -1; // negative: never throws
1307
1308 int value = 0;
1309
1310 Assignment_Throws() = default;
1311 Assignment_Throws(const int v) : value(v) {}
1312 Assignment_Throws(const Assignment_Throws &) = default;
1313 Assignment_Throws & operator = (const Assignment_Throws & o)
1314 {
1315 if (assignments_left == 0)
1316 throw std::runtime_error("assignment");
1317 if (assignments_left > 0)
1318 --assignments_left;
1319 value = o.value;
1320 return *this;
1321 }
1322};
1323
1324TEST(DynArrayCut, a_cut_that_fails_releases_nothing_and_keeps_the_dimension)
1325{
1326 DynArray<Assignment_Throws> a(4, 4, 2); // blocks of four entries
1327 for (int i = 0; i < 12; ++i)
1328 a.touch(i) = Assignment_Throws(i + 1);
1329
1330 // cut(6) resets the entries 6 and 7 of the second block and releases the
1331 // third one; the second reset throws.
1332 Assignment_Throws::assignments_left = 1;
1333 EXPECT_THROW(a.cut(6), std::runtime_error);
1334 Assignment_Throws::assignments_left = -1;
1335
1336 EXPECT_EQ(a.size(), 12u);
1337 for (size_t i = 0; i < 12; ++i)
1338 ASSERT_TRUE(a.exist(i)) << i; // no block was released
1339 for (int i = 0; i < 6; ++i)
1340 EXPECT_EQ(a.access(i).value, i + 1);
1341 for (int i = 8; i < 12; ++i)
1342 EXPECT_EQ(a.access(i).value, i + 1); // the third block is intact
1343
1344 // The cut can be retried, and growing again shows unwritten entries.
1345 a.cut(6);
1346 EXPECT_EQ(a.size(), 6u);
1347 EXPECT_FALSE(a.exist(8));
1348 for (int i = 0; i < 6; ++i)
1349 EXPECT_EQ(a.access(i).value, i + 1);
1350 a.touch(11);
1351 EXPECT_EQ(a.size(), 12u);
1352 for (size_t i = 6; i < 12; ++i)
1353 EXPECT_EQ(a.read(i).value, 0) << i;
1354
1355 // A cut inside one block has nothing to release.
1356 Assignment_Throws::assignments_left = 0;
1357 EXPECT_THROW(a.cut(10), std::runtime_error);
1358 Assignment_Throws::assignments_left = -1;
1359 EXPECT_EQ(a.size(), 12u);
1360 EXPECT_TRUE(a.exist(11));
1361}
1362
1363// pop() and remove() take one entry out through the same code. The entry is
1364// reset only when its block stays, and a block is released only when nothing
1365// is reset, so a reset that throws leaves the dimension and the blocks as
1366// they were, whatever the position of the last entry in its block.
1367TEST(DynArrayCut, a_pop_or_a_remove_that_fails_keeps_the_dimension)
1368{
1369 const auto make = [] (const int n)
1370 {
1371 DynArray<Assignment_Throws> a(4, 4, 2); // blocks of four entries
1372 for (int i = 0; i < n; ++i)
1373 a.touch(i) = Assignment_Throws(i + 1);
1374 return a;
1375 };
1376
1377 for (int n = 5; n <= 12; ++n)
1378 {
1379 // The last entry is reset unless it is the first one of its block,
1380 // whose block is released instead.
1381 const bool resets = (n - 1) % 4 != 0;
1382 const auto size_after = static_cast<size_t>(resets ? n : n - 1);
1383
1384 auto a = make(n);
1385 Assignment_Throws::assignments_left = 0;
1386 if (resets)
1387 EXPECT_THROW((void) a.pop(), std::runtime_error) << n;
1388 else
1389 EXPECT_EQ(a.pop().value, n);
1390 Assignment_Throws::assignments_left = -1;
1391
1392 ASSERT_EQ(a.size(), size_after) << n;
1393 for (size_t i = 0; i < a.size(); ++i)
1394 {
1395 ASSERT_TRUE(a.exist(i)) << n << " " << i;
1396 EXPECT_EQ(a.access(i).value, static_cast<int>(i) + 1) << n;
1397 }
1398
1399 // remove() swaps the entry with the last one, which assigns twice, and
1400 // then shrinks: the swap is done when the reset throws.
1401 auto b = make(n);
1402 Assignment_Throws::assignments_left = 2;
1403 if (resets)
1404 EXPECT_THROW(b.remove(b.access(0)), std::runtime_error) << n;
1405 else
1406 EXPECT_NO_THROW(b.remove(b.access(0))) << n;
1407 Assignment_Throws::assignments_left = -1;
1408
1409 ASSERT_EQ(b.size(), size_after) << n;
1410 for (size_t i = 0; i < b.size(); ++i)
1411 ASSERT_TRUE(b.exist(i)) << n << " " << i;
1412 EXPECT_EQ(b.access(0).value, n);
1413 if (resets)
1414 EXPECT_EQ(b.access(b.size() - 1).value, 1) << n; // pop() completes the removal
1415 }
1416}
1417
1418} // namespace
Deduplicate sequential Aleph containers in-place.
Functional programming utilities for Aleph-w containers.
static string long_string(const char c)
A string too long for the small-string buffer.
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
Iterator on the items of array.
void reset_last() noexcept
Reset the iterator to the last item.
bool is_last() const noexcept
Check whether the current item is the last item.
void next()
Advance one position, from the last item to the end if needed.
bool has_curr() const noexcept
Check whether the iterator refers to an item.
T & get_curr() const
Return the current item.
void each(Operation &operation) const
Alias of for_each(); see FunctionalMethods::for_each().
void set_default_initial_value(const T &value) noexcept(std::is_nothrow_copy_assignable_v< T >)
Set the default value.
T * test(const size_t i) const noexcept
Test if the i-th entry es writable,.
size_t get_block_size() const noexcept
Return the block size.
void swap(DynArray< T > &array) noexcept(std::is_nothrow_swappable_v< T >)
Swap in constant time array with this
T & top()
Return a modifiable reference to the last item of stack.
void push(const T &data)
See append(const T & data).
void adjust(const size_t dim)
Set a new dimension.
Iterator get_it()
Iterator on the modifiable array, positioned on entry 0.
void cut(const size_t new_dim=0)
Cut the array to a new dimension; that is, it reduces the dimension of array and frees the remaining ...
const T & read(const size_t i) const
Read entry i without allocating memory.
Array< T > to_array() const
Copy contents into Aleph::Array (requires copyable elements).
T & insert(const T &item)
Insert a copy of item at the beginning of the array.
size_t get_num_blocks() const noexcept
Return the number of blocks consumed by the array.
void clear() noexcept
Empties the container.
T * find_ptr(Operation &operation)
Return a pointer to the first entry satisfying a criterion.
T & touch(const size_t i)
Touch the entry i.
size_t size() const noexcept
Return the current dimension of array.
T & access(const size_t i) noexcept
Fast access without checking allocation and bound_min_clock checking.
T & nth(const size_t n)
Return a modifiable reference to entry n.
T & get_first()
Return a modifiable reference to the first item of array (as if this was a queue)
T & nth_ne(const size_t n)
Return a modifiable reference to entry n without checking n.
T pop()
Remove the last item of array (as if this was a stack)
static void compute_sizes(const size_t n, size_t &d, size_t &s, size_t &b)
Given a dimension n, it proposes values for the directory, segment and block sizes.
size_t max_size() const noexcept
Return the maximum allowed dimension (or the maximum number of elements that could have the array tre...
bool traverse(Operation &operation) const noexcept(Aleph::NothrowPredicateWith< Operation &, const T & >)
Traverse a constant array and execute a conditioned operation, which must have the signature:
bool exist(const size_t i) const
Return true if the i-th entry is accessible.
T & get_last()
Return a modifiable reference to the last item of array (as if this was a queue)
T & append()
Allocate a new entry to the end of array.
bool is_empty() const noexcept
Return true if the array is empty.
void empty() noexcept
Empty the array.
void reserve(const size_t l, const size_t r)
Allocate a range of entries.
void remove(T &item)
Given a valid reference to an item in the array, it removes it and decrease the dimension.
Minimal std::expected-style result type for C++20.
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
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
bool contains(const Type &item) const
Test if an item is present in the container using equality.
Definition ah-dry.H:1074
and std::default_initializable< T > and std::copy_constructible< T > std::tuple< bool, Type > find_item(Operation &operation) const noexcept(find_item_is_noexcept< Operation >())
Safe sequential searching of an item matching a criterion.
Definition ah-dry.H:983
#define TEST(name)
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_dim_function > > dim(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4130
static mpfr_t y
Definition mpfr_mul_d.c:3
Compiler_SSA_Block & block(Compiler_SSA_Function &function, const Compiler_SSA_Block_Id id)
Definition SSA.H:636
constexpr size_t Unlimited
Alias for Search_Unlimited.
Main namespace for Aleph-w library functions.
void in_place_unique(Container &c, Compare cmp={})
Remove duplicates in-place preserving first occurrence order.
Definition ah-unique.H:74
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
Definition ahTypes.H:123
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
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
and
Check uniqueness with explicit hash + equality functors.
and PredicateWith< Cmp &, const typename Container::Item_Type &, functional_detail::get_curr_cref_t< Container > > std::pair< const typename Container::Item_Type *, const typename Container::Item_Type * > minmax_ptr(const Container &container, Cmp cmp=Cmp())
Find both min and max elements in a single pass.
DynList< typename Container::Item_Type * > pointers_list(Container &c)
Create a list of pointers to items in a container.
Container::Item_Type * find_ptr(Container &container, Pred &pred)
Find the first element satisfying pred.
bool none(const Container &container, Operation &operation)
Return true if no element satisfies operation.
const Container::Item_Type * min_ptr(const Container &container, Cmp cmp=Cmp())
Find the minimum element in a container.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
STL namespace.
Element whose default construction, that of every slot of a new buffer, can fail as an allocation doe...
static int constructions_left
Failing_Slot()
Fail at the configured default construction.
void test()
Definition test-comb.C:40
Lazy and scalable dynamic array implementation.