Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
item_copies_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
39// keys() and values() of the maps took each pair by value, which copied its
40// key and its value, and then copied the one that they return: three copies
41// where one was needed. ranks() and pair_ranks() of a list, and the copy
42// constructor and assignment of a Random_Set, copied each item twice. These
43// tests count the copies that such functions make: one for each item of the
44// new container, and none of the items that it does not hold.
45
46#include <gtest/gtest.h>
47
48#include <ah-convert.H>
49#include <ah-dry-mixin.H>
50#include <ahSort.H>
51#include <htlist.H>
52#include <tpl_array.H>
53#include <tpl_dynDlist.H>
54#include <tpl_dynMapOhash.H>
55#include <tpl_dynMapTree.H>
56#include <tpl_dynSetHash.H>
57#include <tpl_flat_map.H>
58#include <tpl_random_queue.H>
59
60using namespace Aleph;
61
62namespace
63{
64 // An item that counts its copies and its moves, those of an item that
65 // holds a value: the arrays fill their blocks with copies of a default
66 // item, which hold none
67 struct Counted
68 {
69 static inline long copies = 0;
70 static inline long moves = 0;
71
72 int v = -1;
73
74 Counted() = default;
75 explicit Counted(const int x) noexcept : v(x) {}
76
77 Counted(const Counted & o) : v(o.v) { copies += v >= 0 ? 1 : 0; }
78 Counted(Counted && o) noexcept : v(o.v) { moves += v >= 0 ? 1 : 0; }
79
80 Counted & operator=(const Counted & o)
81 {
82 v = o.v;
83 copies += v >= 0 ? 1 : 0;
84 return *this;
85 }
86
87 Counted & operator=(Counted && o) noexcept
88 {
89 v = o.v;
90 moves += v >= 0 ? 1 : 0;
91 return *this;
92 }
93
94 bool operator<(const Counted & o) const noexcept { return v < o.v; }
95 bool operator==(const Counted & o) const noexcept { return v == o.v; }
96 };
97
98 // For the hash tables whose key is a Counted
99 size_t aleph_hash_value(const Counted & c) noexcept
100 {
101 return static_cast<size_t>(c.v) * 0x9E3779B97F4A7C15ull;
102 }
103
104 // A container made of the mixins of ah-dry-mixin.H, for KeysMixin::keys()
105 class Mixed : public TraverseMixin<Mixed, Counted>,
106 public FunctionalMixin<Mixed, Counted>,
107 public KeysMixin<Mixed, Counted>
108 {
109 Array<Counted> data;
110
111 public:
112 using Item_Type = Counted;
113
114 void append(const Counted & c) { data.append(c); }
115
116 class Iterator
117 {
118 const Array<Counted> * items = nullptr;
119 size_t pos = 0;
120
121 public:
122 Iterator() = default;
123 Iterator(const Mixed & c) : items(&c.data) {}
124
125 [[nodiscard]] bool has_curr() const noexcept { return pos < items->size(); }
126 [[nodiscard]] Counted & get_curr() const { return const_cast<Counted &>((*items)(pos)); }
127 void next() { ++pos; }
128 void next_ne() noexcept { ++pos; }
129 };
130
131 [[nodiscard]] Iterator get_it() const { return Iterator(*this); }
132 };
133
134 template <class Map>
135 class MapCopies : public ::testing::Test
136 {};
137
138 using Maps = ::testing::Types<DynMapAvlTree<int, Counted>, DynMapRbTree<int, Counted>,
144 TYPED_TEST_SUITE(MapCopies, Maps);
145
146 // The same maps, with the counted item as their key
147 template <class Map>
148 class MapKeyCopies : public ::testing::Test
149 {};
150
151 using Maps_By_Counted = ::testing::Types<DynMapAvlTree<Counted, int>, DynMapRbTree<Counted, int>,
157 TYPED_TEST_SUITE(MapKeyCopies, Maps_By_Counted);
158}
159
160TYPED_TEST(MapCopies, KeysCopyNoValueAndValuesCopyEachValueOnce)
161{
162 constexpr int n = 20;
163 TypeParam m;
164 for (int i = 0; i < n; ++i)
165 (void) m.insert(i, Counted(i));
166
167 Counted::copies = Counted::moves = 0;
168 const auto keys = m.keys();
169 EXPECT_EQ(keys.size(), static_cast<size_t>(n));
170 EXPECT_EQ(Counted::copies, 0);
171 EXPECT_EQ(Counted::moves, 0);
172
173 // each value is copied into the list, and not copied and then moved
174 Counted::copies = Counted::moves = 0;
175 const auto values = m.values();
176 EXPECT_EQ(values.size(), static_cast<size_t>(n));
177 EXPECT_EQ(Counted::copies, n);
178 EXPECT_EQ(Counted::moves, 0);
179 int sum = 0;
180 values.for_each([&sum] (const Counted & c) { sum += c.v; });
181 EXPECT_EQ(sum, n * (n - 1) / 2);
182}
183
184TYPED_TEST(MapKeyCopies, KeysCopyEachKeyOnceAndMoveNone)
185{
186 constexpr int n = 20;
187 TypeParam m;
188 for (int i = 0; i < n; ++i)
189 (void) m.insert(Counted(i), i);
190
191 Counted::copies = Counted::moves = 0;
192 const auto keys = m.keys();
193 EXPECT_EQ(keys.size(), static_cast<size_t>(n));
194 EXPECT_EQ(Counted::copies, n);
195 EXPECT_EQ(Counted::moves, 0);
196 int sum = 0;
197 keys.for_each([&sum] (const Counted & c) { sum += c.v; });
198 EXPECT_EQ(sum, n * (n - 1) / 2);
199}
200
201// The list that a container gives of its items copies each one into the
202// list: the function that maps() applies returns a reference to the item,
203// and not a copy that maps() would then move
204TEST(ItemCopies, TheListOfTheItemsOfAContainerCopiesEachOnceAndMovesNone)
205{
206 constexpr int n = 10;
207 DynList<Counted> list;
208 DynDlist<Counted> dlist;
209 Array<Counted> array;
210 Mixed mixed;
211 for (int i = 0; i < n; ++i)
212 {
213 list.append(Counted(i));
214 dlist.append(Counted(i));
215 array.append(Counted(i));
216 mixed.append(Counted(i));
217 }
218
219 auto expect_one_copy = [n] (const char * what, auto && make)
220 {
221 Counted::copies = Counted::moves = 0;
222 const auto items = make();
223 EXPECT_EQ(items.size(), static_cast<size_t>(n)) << what;
224 EXPECT_EQ(Counted::copies, n) << what;
225 EXPECT_EQ(Counted::moves, 0) << what;
226 int sum = 0;
227 items.for_each([&sum] (const Counted & c) { sum += c.v; });
228 EXPECT_EQ(sum, n * (n - 1) / 2) << what;
229 };
230 expect_one_copy("DynList::items()", [&list] { return list.items(); });
231 expect_one_copy("DynList::keys()", [&list] { return list.keys(); });
232 expect_one_copy("DynDlist::items()", [&dlist] { return dlist.items(); });
233 expect_one_copy("to_dynlist(DynDlist)", [&dlist] { return to_dynlist(dlist); });
234 expect_one_copy("to_DynList(Array)", [&array] { return to_DynList(array); });
235 expect_one_copy("KeysMixin::keys()", [&mixed] { return mixed.keys(); });
236 expect_one_copy("KeysMixin::items()", [&mixed] { return mixed.items(); });
237}
238
239TEST(ItemCopies, TheRanksOfAListCopyEachItemOnce)
240{
241 DynList<Counted> list;
242 DynDlist<Counted> dlist;
243 for (const int v : {5, 3, 8, 1, 9, 2})
244 {
245 list.append(Counted(v));
246 dlist.append(Counted(v));
247 }
248 const size_t expected[] = {3, 2, 4, 0, 5, 1};
249
250 Counted::copies = 0;
251 const auto r1 = ranks(list);
252 EXPECT_EQ(Counted::copies, 6);
253 Counted::copies = 0;
254 const auto r2 = ranks(dlist);
255 EXPECT_EQ(Counted::copies, 6);
256 Counted::copies = 0;
257 const auto p1 = pair_ranks(list);
258 EXPECT_EQ(Counted::copies, 6);
259 Counted::copies = 0;
260 const auto p2 = pair_ranks(dlist);
261 EXPECT_EQ(Counted::copies, 6);
262
263 for (size_t i = 0; i < 6; ++i)
264 {
265 EXPECT_EQ(r1(i), expected[i]);
266 EXPECT_EQ(r2(i), expected[i]);
267 EXPECT_EQ(p1(i).second, expected[i]);
268 EXPECT_EQ(p2(i).second, expected[i]);
269 }
270 EXPECT_EQ(p1(0).first, Counted(5));
271 EXPECT_EQ(p2(5).first, Counted(2));
272}
273
274TEST(ItemCopies, ACopyOfARandomSetCopiesEachItemOnce)
275{
277 for (int i = 0; i < 10; ++i)
278 s.append(Counted(i));
279
280 Counted::copies = 0;
282 EXPECT_EQ(Counted::copies, 10);
283 EXPECT_EQ(copy.size(), 10u);
284
285 Random_Set<Counted> assigned;
286 assigned.append(Counted(99));
287 Counted::copies = 0;
288 assigned = s;
289 EXPECT_EQ(Counted::copies, 10);
290 EXPECT_EQ(assigned.size(), 10u);
291}
Conversion utilities between Aleph-w and STL container types.
CRTP Mixins for container functionality (DRY principle).
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
High-level sorting functions for Aleph containers.
TYPED_TEST_SUITE(ArcHeapLifecycle, ArcHeapKinds)
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
Dynamic doubly linked list with O(1) size and bidirectional access.
T & append(const T &item)
Append a copied item at the end of the list.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
Dynamic map implemented with a classic binary search tree.
Dynamic map implemented with a randomized BST.
Dynamic map implemented with a red-black tree.
Dynamic map implemented with a splay tree.
Dynamic map implemented with a ranked treap.
Dynamic map implemented with a treap.
Ordered map stored as two parallel sorted contiguous arrays.
CRTP Mixin providing functional programming operations.
CRTP Mixin for extracting keys from set-like containers.
T & append(const T &item)
Insert randomly an item by copy.
size_t size() const
Return the number of items in the queue.
CRTP Mixin providing traversal operations.
Minimal std::expected-style result type for C++20.
DynList< Key > keys() const
Returns a list containing all keys in the table.
Definition hashDry.H:1247
Key * insert(const Key &key)
Inserts a key into the hash table (copy version).
Definition hashDry.H:507
#define TEST(name)
Singly linked list implementations with head-tail access.
TYPED_TEST(MapCopies, KeysCopyNoValueAndValuesCopyEachValueOnce)
Main namespace for Aleph-w library functions.
DynList< typename Container::Item_Type > to_dynlist(const Container &c)
Definition htlist.H:2086
DynList< T > to_DynList(const Array< T > &a)
Convert an Array to a DynList.
Definition ah-convert.H:148
T Item_Type
Type of elements from the first container.
Definition ah-zip.H:161
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
auto pair_ranks(const Array< T > &c)
Computes (value, rank) pairs for each element in an Array.
Definition ahSort.H:759
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
size_t aleph_hash_value(const AdversarialTranspositionKey< StateKey > &key) noexcept
Definition Negamax.H:134
auto get_curr() const
Return the current tuple (bounds-checked).
Definition ah-zip.H:192
bool has_curr() const noexcept
Return true if all underlying iterators are positioned on a valid item.
Definition ah-zip.H:173
Array< size_t > ranks(const Array< T > &array)
Computes the rank of each element in an Array.
Definition ahSort.H:696
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
void next_ne() noexcept(noexcept(std::declval< Aleph::const_iterator_t< HeadC > & >().next_ne()) and noexcept(std::declval< ZipIterator< TailC... > & >().next_ne()))
Advance all underlying iterators (unchecked variant).
Definition ah-zip.H:252
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Open addressing hash map using double hashing.
Open addressing hash map using linear probing.
Counted & operator=(const Counted &other)
static int moves
static int copies
Counted(int v=0)
Aleph::DynList< T > items() const
Return a list of all the elements of a container sorted by traversal order.
Definition ah-dry.H:2904
Aleph::DynList< T > keys() const
See items().
Definition ah-dry.H:2916
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
int keys[]
Dynamic array container with automatic resizing.
Dynamic doubly linked list implementation.
Dynamic map with open hashing.
Dynamic key-value map based on balanced binary search trees.
Dynamic set implementations based on hash tables.
Sorted-array map (Aleph::FlatMap), a cache-friendly ordered map.
Random access queue (bag) with O(1) random pop.