Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
hash-it.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
37# include <gtest/gtest.h>
38
39# include <ahFunctional.H>
40# include <ahSort.H>
41# include <tpl_dynMapOhash.H>
42# include <tpl_dynSetHash.H>
43# include <tpl_olhash.H>
44# include <tpl_odhash.H>
45# include <tpl_lhash.H>
46# include <tpl_dynLhash.H>
47# include <tpl_hash.H>
48# include <algorithm>
49# include <deque>
50# include <stdexcept>
51# include <functional>
52# include <map>
53# include <ostream>
54# include <random>
55# include <set>
56# include <type_traits>
57# include <utility>
58# include <vector>
59
60using namespace std;
61using namespace testing;
62using namespace Aleph;
63
65
66constexpr size_t N = 1000;
67
68template <class HashTbl>
69struct OHashTest : public ::testing::Test
70{
71 HashTbl tbl;
74 : tbl(N), items(range(static_cast<size_t>(0), N - 1))
75 {
76 items.for_each([this](auto i)
77 { tbl.emplace(i, to_string(i)); });
78 }
79};
80
81template <class HashTbl>
82struct EmptyOHashTest : public ::testing::Test
83{
84 HashTbl tbl;
85};
86
88(OHashTest);
89
92
94{
95 TypeParam tbl = this->tbl;
96 auto it = tbl.get_it();
97 ASSERT_FALSE(it.has_curr());
98 ASSERT_THROW(it.get_curr(), std::overflow_error);
99 ASSERT_THROW(it.next(), std::overflow_error);
100}
101
102TYPED_TEST_P(OHashTest, Without_exception)
103{
104 TypeParam tbl = this->tbl;
105
106 ASSERT_EQ(tbl.size(), N);
107
108 auto it = tbl.get_it();
109 EXPECT_NO_THROW(it.get_curr());
110 EXPECT_NO_THROW(it.next());
111 EXPECT_NO_THROW(it.reset_first());
113 for (; it.has_curr(); it.next_ne())
114 l.append(it.get_curr_ne());
115 EXPECT_FALSE(it.has_curr());
116 auto ll = l.maps<size_t>([](auto &p)
117 { return p.first; });
118 EXPECT_EQ(sort(ll), this->items);
119
120 l.empty();
121 EXPECT_NO_THROW(it.reset_last());
122 for (; it.has_curr(); it.prev_ne())
123 l.append(it.get_curr_ne());
124 ll = l.maps<size_t>([](auto &p)
125 { return p.first; });
126 EXPECT_EQ(sort(ll), this->items);
127}
128
130(EmptyOHashTest, With_exception);
132(OHashTest, Without_exception);
133
135 Types<MapODhash<size_t, string>,
139 >;
140
142(Empty, EmptyOHashTest, HashTypes);
144(NoEmpty, OHashTest, HashTypes);
145
146TEST(OLhashTable, DoubleHashCtorAndOps)
147{
149 11,
150 Aleph::dft_hash_fct<int>,
151 Aleph::dft_hash_fct<int>,
155 false);
156
157 EXPECT_TRUE(tbl.is_empty());
158 ASSERT_NE(tbl.insert(42), nullptr);
159 ASSERT_NE(tbl.insert(7), nullptr);
160 EXPECT_NE(tbl.search(42), nullptr);
161
162 auto stats = tbl.stats();
163 EXPECT_EQ(stats.num_busy, static_cast<size_t>(2));
164}
165
166TEST(OLhashTable, KeyToBucketRoundTrip)
167{
169 auto *ptr = tbl.insert(5);
170 ASSERT_NE(ptr, nullptr);
171
172 auto *bucket = decltype(tbl)::key_to_bucket(ptr);
173 ASSERT_NE(bucket, nullptr);
174 EXPECT_EQ(bucket->key, 5);
175 // bucket must be within table range
176 EXPECT_NO_THROW(tbl.remove(5));
177}
178
179TEST(OLhashTable, RemoveThrowsOnMissingKey)
180{
182 tbl.insert(1);
183 EXPECT_THROW(tbl.remove(2), std::domain_error);
184}
185
186TEST(OLhashTable, InsertRejectsDuplicate)
187{
188 OLhashTable<int> tbl(5, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
190 auto *p1 = tbl.insert(10);
191 ASSERT_NE(p1, nullptr);
192 auto *p2 = tbl.insert(10);
193 EXPECT_EQ(p2, nullptr); // duplicate rejected
194 EXPECT_EQ(tbl.size(), static_cast<size_t>(1));
195}
196
197TEST(OLhashTable, RemovePtrMarksDeleted)
198{
199 OLhashTable<int> tbl(11, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
201 auto *p = tbl.insert(5);
202 ASSERT_NE(p, nullptr);
203 // remove_ptr is protected; exercise via remove(key) for coverage
204 EXPECT_NO_THROW(tbl.remove(5));
205 EXPECT_EQ(tbl.size(), static_cast<size_t>(0));
206 EXPECT_THROW(tbl.remove(5), std::domain_error);
207}
208
209TEST(OLhashTable, NoResizeFillAndSearchMiss)
210{
211 OLhashTable<int> tbl(5, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
213 for (int i = 0; i < 4; ++i)
214 ASSERT_NE(tbl.insert(i), nullptr);
215 EXPECT_EQ(tbl.insert(4), nullptr); // full: one bucket stays empty
216 EXPECT_EQ(tbl.size(), static_cast<size_t>(4));
217 EXPECT_EQ(tbl.search(42), nullptr); // miss should terminate
218}
219
220TEST(OLhashTable, StatsWithDeletedAndBusy)
221{
222 auto constant_hash = [] (const int &) noexcept -> size_t { return 0u; };
226 auto *p1 = tbl.insert(1);
227 auto *p2 = tbl.insert(2);
228 auto *p3 = tbl.insert(3);
229 ASSERT_NE(p1, nullptr);
230 ASSERT_NE(p2, nullptr);
231 ASSERT_NE(p3, nullptr);
232
233 tbl.remove_ptr(p2); // mark one as deleted
234
235 auto stats = tbl.stats();
236 EXPECT_EQ(stats.num_busy, static_cast<size_t>(2));
237 EXPECT_EQ(stats.num_deleted, static_cast<size_t>(1));
238 EXPECT_EQ(stats.num_busy + stats.num_deleted + stats.num_empty,
239 static_cast<size_t>(tbl.capacity()));
240 EXPECT_GE(stats.max_len, static_cast<size_t>(1));
241}
242
243TEST(OLhashTable, RehashKeepsElements)
244{
246 Aleph::dft_hash_fct<int>,
248 /*lower*/0.25f,
249 /*upper*/0.5f,
250 /*with_resize*/true);
251 for (int i = 0; i < 10; ++i)
252 ASSERT_NE(tbl.insert(i), nullptr);
253
254 for (int i = 0; i < 10; ++i)
255 EXPECT_NE(tbl.search(i), nullptr);
256 EXPECT_EQ(tbl.size(), static_cast<size_t>(10));
257}
258
259TEST(OLhashTable, ConstantHashCollisionsNoResize)
260{
261 auto const_hash = [](int) { return static_cast<size_t>(0); };
264 for (int i = 0; i < 4; ++i)
265 ASSERT_NE(tbl.insert(i), nullptr);
266 EXPECT_EQ(tbl.insert(4), nullptr); // full: one bucket stays empty
267
268 for (int i = 0; i < 4; ++i)
269 EXPECT_NE(tbl.search(i), nullptr);
270
271 auto stats = tbl.stats();
272 EXPECT_EQ(stats.num_busy, static_cast<size_t>(4));
273 EXPECT_GE(stats.max_len, static_cast<size_t>(4)); // long collision chain
274}
275
276TEST(OLhashTable, RehashAfterDeletesPreservesLiveKeys)
277{
279 Aleph::dft_hash_fct<int>,
281 /*lower*/0.25f,
282 /*upper*/0.5f,
283 /*with_resize*/true);
284 for (int i = 0; i < 6; ++i)
285 ASSERT_NE(tbl.insert(i), nullptr);
286
287 // Remove some keys to create DELETED slots
288 tbl.remove(1);
289 tbl.remove(3);
290
291 // Insert more keys to force resize
292 for (int i = 10; i < 16; ++i)
293 ASSERT_NE(tbl.insert(i), nullptr);
294
295 // Live keys must remain accessible
296 for (int i : {0, 2, 4, 5, 10, 11, 12, 13, 14, 15})
297 EXPECT_NE(tbl.search(i), nullptr);
298}
299
300TEST(OLhashTable, SearchOrInsertBehavior)
301{
303 auto *p1 = tbl.search_or_insert(1);
304 ASSERT_NE(p1, nullptr);
305 auto *p2 = tbl.search_or_insert(1); // should return existing
306 EXPECT_EQ(p1, p2);
307 EXPECT_EQ(tbl.size(), static_cast<size_t>(1));
308}
309
310TEST(OLhashTable, CopyMoveAndSwap)
311{
312 OLhashTable<int> a(7, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
314 a.insert(1);
315 a.insert(2);
316
317 // copy ctor
318 OLhashTable<int> b = a;
319 EXPECT_EQ(b.size(), a.size());
320 EXPECT_NE(b.search(1), nullptr);
321 EXPECT_NE(b.search(2), nullptr);
322
323 // move ctor
324 OLhashTable<int> c = std::move(b);
325 EXPECT_EQ(c.size(), static_cast<size_t>(2));
326 EXPECT_NE(c.search(1), nullptr);
327 // moved-from state is unspecified; ensure it is still usable
328 b.insert(5);
329 EXPECT_NE(b.search(5), nullptr);
330
331 // swap
332 OLhashTable<int> d(3, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
334 d.insert(99);
335 a.swap(d);
336 EXPECT_NE(a.search(99), nullptr);
337 EXPECT_EQ(d.search(99), nullptr);
338
339 // copy assignment
340 OLhashTable<int> e(2);
341 e.insert(42);
342 e = c; // c has 1 and 2
343 EXPECT_NE(e.search(1), nullptr);
344 EXPECT_NE(e.search(2), nullptr);
345 EXPECT_EQ(e.size(), static_cast<size_t>(2));
346
347 // move assignment
348 OLhashTable<int> f(2);
349 f.insert(77);
350 f = std::move(e);
351 EXPECT_NE(f.search(1), nullptr);
352 EXPECT_NE(f.search(2), nullptr);
353 f.insert(88); // moved-from e should still be usable indirectly via f
354}
355
356TEST(OLhashTable, StatsExtremes)
357{
358 OLhashTable<int> tbl_empty(5);
359 auto stats_empty = tbl_empty.stats();
360 EXPECT_EQ(stats_empty.num_busy, static_cast<size_t>(0));
361 EXPECT_EQ(stats_empty.num_deleted, static_cast<size_t>(0));
362 // num_empty may be greater than len due to lens counting, so only busy/deleted are validated
363
364 auto const_hash = [](int) { return static_cast<size_t>(0); };
365 OLhashTable<int> tbl_full(5, const_hash, Aleph::equal_to<int>(),
367 for (int i = 0; i < 5; ++i)
368 (void) tbl_full.insert(i); // the last one does not fit
369 auto stats_full = tbl_full.stats();
370 EXPECT_EQ(stats_full.num_busy, static_cast<size_t>(4));
371 EXPECT_EQ(stats_full.num_empty, static_cast<size_t>(1));
372 EXPECT_EQ(stats_full.num_deleted, static_cast<size_t>(0));
373 EXPECT_FALSE(std::isnan(stats_full.avg));
374 EXPECT_FALSE(std::isnan(stats_full.var));
375}
376
377TEST(OLhashTable, CleanTableLeavesEmpty)
378{
380 tbl.insert(1);
381 tbl.insert(2);
382 tbl.clean_table();
383 EXPECT_EQ(tbl.size(), static_cast<size_t>(0));
384 EXPECT_EQ(tbl.search(1), nullptr);
385}
386
387TEST(OLhashTable, InsertFailsWhenFullNoResize)
388{
389 OLhashTable<int> tbl(3, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
391 ASSERT_NE(tbl.insert(1), nullptr);
392 ASSERT_NE(tbl.insert(2), nullptr);
393 // Two keys fill three buckets, since one must stay empty
394 EXPECT_EQ(tbl.insert(3), nullptr);
395 // With a full table and no resize, inserting a duplicate returns nullptr
396 EXPECT_EQ(tbl.insert(2), nullptr);
397 EXPECT_EQ(tbl.size(), static_cast<size_t>(2));
398}
399
400TEST(OLhashTable, ResizeIncreasesCapacity)
401{
402 // Small upper alpha to force rehash quickly
404 Aleph::dft_hash_fct<int>,
406 /*lower*/0.1f,
407 /*upper*/0.4f,
408 /*with_resize*/true);
409 const auto cap0 = tbl.capacity();
410 for (int i = 0; i < 10; ++i)
411 tbl.insert(i);
412 EXPECT_GE(tbl.capacity(), cap0); // puede no crecer si el alpha no se supera
413 for (int i = 0; i < 10; ++i)
414 EXPECT_NE(tbl.search(i), nullptr);
415}
416
417TEST(OLhashTable, DeletedSlotIsReused)
418{
419 OLhashTable<int> tbl(5, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
421 tbl.insert(1);
422 tbl.insert(2);
423 tbl.remove(1); // leaves a DELETED slot
424 EXPECT_EQ(tbl.size(), static_cast<size_t>(1));
425 tbl.insert(3); // should reuse the slot if applicable
426 EXPECT_NE(tbl.search(2), nullptr);
427 EXPECT_NE(tbl.search(3), nullptr);
428 EXPECT_EQ(tbl.size(), static_cast<size_t>(2));
429}
430
431TEST(ODhashTable, RemoveMissingInFullTableDoesNotHang)
432{
433 // Small table without resize to force search without finding EMPTY
435 Aleph::dft_hash_fct<int>,
436 Aleph::snd_hash_fct<int>,
440 /*with_resize*/false);
441 for (int i = 0; i < 4; ++i)
442 ASSERT_NE(tbl.insert(i), nullptr);
443 EXPECT_EQ(tbl.insert(4), nullptr); // full: one bucket stays empty
444
445 // Missing key must throw in finite time (no infinite loop)
446 EXPECT_THROW(tbl.remove(99), std::domain_error);
447}
448
449TEST(ODhashTable, DuplicateInsertAndSearchOrInsert)
450{
452 auto *p1 = tbl.insert(10);
453 ASSERT_NE(p1, nullptr);
454 auto *p2 = tbl.insert(10);
455 EXPECT_EQ(p2, nullptr); // duplicate rejected
456
457 auto *p3 = tbl.search_or_insert(10);
458 EXPECT_EQ(p3, p1); // returns the existing one
459 EXPECT_EQ(tbl.size(), static_cast<size_t>(1));
460}
461
462TEST(ODhashTable, CopyMoveAssignAndSwap)
463{
464 ODhashTable<int> a(7);
465 a.insert(1);
466 a.insert(2);
467
468 ODhashTable<int> b = a; // copy ctor
469 EXPECT_EQ(b.size(), a.size());
470 EXPECT_NE(b.search(1), nullptr);
471
472 ODhashTable<int> c = std::move(b); // move ctor
473 EXPECT_EQ(c.size(), static_cast<size_t>(2));
474
475 ODhashTable<int> d(3);
476 d.insert(99);
477 c.swap(d);
478 EXPECT_NE(c.search(99), nullptr);
479 EXPECT_EQ(d.search(99), nullptr);
480
481 ODhashTable<int> e(2);
482 e.insert(77);
483 e = c; // copy assign
484 EXPECT_NE(e.search(99), nullptr);
485 EXPECT_EQ(e.size(), c.size());
486
487 ODhashTable<int> f(2);
488 f = std::move(e); // move assign
489 EXPECT_NE(f.search(99), nullptr);
490 f.insert(5); // usable after move
491}
492
493TEST(ODhashTable, StatsWithBusyDeletedEmpty)
494{
495 ODhashTable<int> tbl(7, Aleph::dft_hash_fct<int>, Aleph::snd_hash_fct<int>,
498 tbl.insert(1);
499 tbl.insert(2);
500 tbl.insert(3);
501 tbl.remove(2); // leaves DELETED and rehash clears probe_counters
502 auto stats = tbl.stats();
503 EXPECT_EQ(stats.num_busy, static_cast<size_t>(2));
504 EXPECT_GE(stats.num_deleted, static_cast<size_t>(0)); // may compact
505}
506
507TEST(ODhashTable, CustomSecondHashSetter)
508{
510 auto h2 = [](int k) { return static_cast<size_t>(k * 13); };
512 EXPECT_TRUE(tbl.insert(1));
513 EXPECT_NE(tbl.search(1), nullptr);
514}
515
516TEST(ODhashTable, StatsAvgVarFinite)
517{
519 for (int i = 0; i < 5; ++i)
520 tbl.insert(i);
521 auto stats = tbl.stats();
522 EXPECT_FALSE(std::isnan(stats.avg));
523 EXPECT_FALSE(std::isnan(stats.var));
524}
525TEST(ODhashTable, StatsControlledProbes)
526{
528 // Force the second hash to be constant to lengthen the probe chain
529 auto const_h2 = +[](int) { return static_cast<size_t>(0); };
530 tbl.set_second_hash_fct(const_h2);
531 // Insert keys that collide in the first hash by modulo
532 tbl.insert(0); // i_fst=0
533 tbl.insert(7); // i_fst=0 -> BUSY, i_snd=0 -> BUSY, linear probe
534 tbl.insert(14); // i_fst=0 -> BUSY, i_snd=0 -> BUSY, linear probe
535 auto stats = tbl.stats();
536 EXPECT_EQ(stats.num_busy, static_cast<size_t>(3));
537 EXPECT_GE(stats.max_len, static_cast<size_t>(1));
538}
539
540TEST(ODhashTable, RehashWithResizeKeepsElements)
541{
543 Aleph::dft_hash_fct<int>,
544 Aleph::snd_hash_fct<int>,
546 /*lower*/0.25f,
547 /*upper*/0.5f,
548 /*with_resize*/true);
549 const auto cap0 = tbl.capacity();
550 for (int i = 0; i < 10; ++i)
551 tbl.insert(i);
552 EXPECT_GE(tbl.capacity(), cap0);
553 for (int i = 0; i < 10; ++i)
554 EXPECT_NE(tbl.search(i), nullptr);
555}
556
557TEST(ODhashTable, LinearProbePathCovered)
558{
560 tbl.insert(0);
561 tbl.insert(5);
562 tbl.insert(10);
563 EXPECT_NE(tbl.search(10), nullptr); // traverses linear probe
564}
565
566TEST(ODhashTable, IteratorCollectsAllKeys)
567{
569 std::set<int> inserted;
570 for (int i = 0; i < 7; ++i)
571 {
572 tbl.insert(i * 2);
573 inserted.insert(i * 2);
574 }
575 auto it = tbl.get_it();
576 std::set<int> iterated;
577 for (; it.has_curr(); it.next_ne())
578 iterated.insert(it.get_curr());
579 EXPECT_EQ(iterated, inserted);
580}
581
582// ============================================================================
583// LhashTable tests
584// ============================================================================
585
586TEST(LhashTable, BusySlotsAfterLastRemoval)
587{
588 auto const_hash = +[](const int &) { return static_cast<size_t>(0); };
591 true, true);
592
593 using Bucket = LhashBucket<int>;
594 auto * b = new Bucket(1);
595 ASSERT_NE(tbl.insert(b), nullptr);
596 EXPECT_EQ(tbl.size(), 1u);
597 EXPECT_EQ(tbl.get_num_busy_slots(), 1u);
598
599 auto * removed = tbl.remove(b);
600 ASSERT_NE(removed, nullptr);
601 delete removed;
602
603 EXPECT_EQ(tbl.size(), 0u);
604 EXPECT_EQ(tbl.get_num_busy_slots(), 0u);
605 EXPECT_DOUBLE_EQ(tbl.current_alpha(), 0.0);
606}
607
608TEST(LhashTable, ShrinksWhenLoadFallsBelowLowerAlpha)
609{
610 LhashTable<int> tbl(500, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
611 0.9f, 10.0f, true, true);
612
613 using Bucket = LhashBucket<int>;
614 auto * b1 = new Bucket(1);
615 auto * b2 = new Bucket(2);
616 auto * b3 = new Bucket(3);
617
618 ASSERT_NE(tbl.insert(b1), nullptr);
619 ASSERT_NE(tbl.insert(b2), nullptr);
620 ASSERT_NE(tbl.insert(b3), nullptr);
621
622 const auto old_cap = tbl.capacity();
623 auto * removed = tbl.remove(b1);
624 ASSERT_NE(removed, nullptr);
625 delete removed;
626
627 EXPECT_LT(tbl.capacity(), old_cap);
628 EXPECT_EQ(tbl.size(), 2u);
629
630 delete tbl.remove(b2);
631 delete tbl.remove(b3);
632}
633
634TEST(LhashTable, IteratorDelRemovesAllCollidingBuckets)
635{
636 auto const_hash = +[](const int &) { return static_cast<size_t>(1); };
639 true, true);
640 using Bucket = LhashBucket<int>;
641 for (int k : {1, 2, 3})
642 ASSERT_NE(tbl.insert(new Bucket(k)), nullptr);
643
644 for (LhashTable<int>::Iterator it(tbl); it.has_curr(); )
645 {
646 auto * removed = it.del();
647 delete removed;
648 }
649
650 EXPECT_EQ(tbl.size(), 0u);
651 EXPECT_EQ(tbl.get_num_busy_slots(), 0u);
652}
653
654TEST(LhashTable, SearchOrInsertReturnsExisting)
655{
657 using Bucket = LhashBucket<int>;
658
659 auto * b1 = new Bucket(42);
660 ASSERT_NE(tbl.insert(b1), nullptr);
661
662 auto * b2 = new Bucket(42);
663 auto * found = tbl.search_or_insert(b2);
664 EXPECT_EQ(found, b1);
665 delete b2;
666
667 delete tbl.remove(b1);
668}
669
670TEST(LhashTable, MoveSemanticsPreserveContent)
671{
672 using Bucket = LhashBucket<int>;
673 LhashTable<int> src(5);
674 auto * b1 = new Bucket(1);
675 auto * b2 = new Bucket(2);
676 src.insert(b1);
677 src.insert(b2);
678
679 LhashTable<int> dst(std::move(src));
680 EXPECT_TRUE(src.is_empty());
681 EXPECT_EQ(dst.size(), 2u);
682 EXPECT_NE(dst.search(1), nullptr);
683 EXPECT_NE(dst.search(2), nullptr);
684
685 delete dst.remove(b1);
686 delete dst.remove(b2);
687}
688
689TEST(LhashTable, InsertRejectsDuplicateAndSearchFinds)
690{
692 using Bucket = LhashBucket<int>;
693
694 auto * b1 = new Bucket(7);
695 ASSERT_NE(tbl.insert(b1), nullptr);
696 EXPECT_EQ(tbl.size(), 1u);
697
698 auto * b2 = new Bucket(7);
699 EXPECT_EQ(tbl.insert(b2), nullptr);
700 delete b2;
701
702 auto * found = tbl.search(7);
703 EXPECT_EQ(found, b1);
704
705 delete tbl.remove(b1);
706}
707
708TEST(LhashTable, SearchNextReturnsNullWhenNoDuplicateKey)
709{
710 auto const_hash = +[](const int &) { return static_cast<size_t>(3); };
713 true, true);
714 using Bucket = LhashBucket<int>;
715 auto * b1 = new Bucket(1);
716 auto * b2 = new Bucket(2);
717 auto * b3 = new Bucket(3);
718 tbl.insert(b1);
719 tbl.insert(b2);
720 tbl.insert(b3);
721
722 auto * first = tbl.search(1);
723 ASSERT_NE(first, nullptr);
724 EXPECT_EQ(tbl.search_next(first), nullptr);
725
726 delete tbl.remove(b1);
727 delete tbl.remove(b2);
728 delete tbl.remove(b3);
729}
730
731TEST(LhashTable, IteratorBoundsThrow)
732{
734 using Bucket = LhashBucket<int>;
735 tbl.insert(new Bucket(1));
736 tbl.insert(new Bucket(2));
737
739 it.reset_last();
740 ASSERT_TRUE(it.has_curr());
741 it.next();
742 EXPECT_THROW(it.get_curr(), std::overflow_error);
743 EXPECT_THROW(it.next(), std::overflow_error);
744
745 it.reset_first();
746 ASSERT_TRUE(it.has_curr());
747 it.prev();
748 EXPECT_THROW(it.get_curr(), std::underflow_error);
749 EXPECT_THROW(it.prev(), std::underflow_error);
750
751 // cleanup
752 for (LhashTable<int>::Iterator clean(tbl); clean.has_curr(); )
753 delete clean.del();
754}
755
756TEST(LhashTable, EmptyResetsCountersAndBuckets)
757{
758 LhashTable<int> tbl(11, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
760 true, true);
761 using Bucket = LhashBucket<int>;
762 for (int k : {1, 2, 3})
763 tbl.insert(new Bucket(k));
764
765 tbl.empty();
766
767 EXPECT_EQ(tbl.size(), 0u);
768 EXPECT_EQ(tbl.get_num_busy_slots(), 0u);
769 EXPECT_DOUBLE_EQ(tbl.current_alpha(), 0.0);
770}
771
772TEST(LhashTable, RemoveAllBucketsFalseKeepsOwnership)
773{
774 // remove_all_buckets = false should not delete user buckets on destruction
775 auto const_hash = +[](const int &) { return static_cast<size_t>(0); };
776 auto * b = new LhashBucket<int>(10);
777 {
780 /*remove_all_buckets*/false, /*with_resize*/true);
781 tbl.insert(b);
782 EXPECT_EQ(tbl.size(), 1u);
783 }
784 // if destructor deleted b, this would UAF; we delete manually
785 delete b;
786}
787
788TEST(LhashTable, SwapExchangesState)
789{
790 using Bucket = LhashBucket<int>;
791 LhashTable<int> a(7);
792 LhashTable<int> b(3);
793 auto * b1 = new Bucket(1);
794 auto * b2 = new Bucket(2);
795 auto * b3 = new Bucket(3);
796 auto * bx = new Bucket(99);
797 a.insert(b1);
798 a.insert(b2);
799 a.insert(b3);
800 b.insert(bx);
801
802 const auto cap_a = a.capacity();
803 const auto cap_b = b.capacity();
804
805 a.swap(b);
806
807 EXPECT_EQ(a.size(), 1u);
808 EXPECT_EQ(b.size(), 3u);
809 EXPECT_EQ(a.capacity(), cap_b);
810 EXPECT_EQ(b.capacity(), cap_a);
811 EXPECT_NE(a.search(99), nullptr);
812 EXPECT_NE(b.search(1), nullptr);
813
814 delete a.remove(bx);
815 delete b.remove(b1);
816 delete b.remove(b2);
817 delete b.remove(b3);
818}
819
820TEST(LhashTable, SetHashFunctionChangesDistribution)
821{
822 using Bucket = LhashBucket<int>;
823 LhashTable<int> tbl(101);
824 for (int k : {1, 2, 102}) // 1 and 102 collide with modulo 101
825 tbl.insert(new Bucket(k));
826 const size_t busy_before = tbl.get_num_busy_slots();
827
828 tbl.set_hash_fct(+[](const int & k) { return static_cast<size_t>(k * 2); });
829 tbl.resize(101); // force rehash with new hash function
830
831 EXPECT_LE(tbl.get_num_busy_slots(), 3u);
832 EXPECT_NE(tbl.search(1), nullptr);
833 EXPECT_NE(tbl.search(2), nullptr);
834 EXPECT_NE(tbl.search(102), nullptr);
835 EXPECT_NE(tbl.get_num_busy_slots(), busy_before);
836
837 delete tbl.remove(tbl.search(1));
838 delete tbl.remove(tbl.search(2));
839 delete tbl.remove(tbl.search(102));
840}
841
842TEST(LhashTable, NoResizeModeKeepsCapacity)
843{
844 LhashTable<int> tbl(11, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
846 true, false);
847 using Bucket = LhashBucket<int>;
848 const auto cap = tbl.capacity();
849 for (int k = 0; k < 50; ++k)
850 tbl.insert(new Bucket(k));
851
852 EXPECT_EQ(tbl.capacity(), cap);
853
854 for (LhashTable<int>::Iterator it(tbl); it.has_curr(); )
855 delete it.del();
856}
857
858TEST(LhashTable, SetWithResizeTurnsResizingOnAndOff)
859{
860 LhashTable<int> tbl(11, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
862 true, false);
863 using Bucket = LhashBucket<int>;
864 EXPECT_FALSE(tbl.get_with_resize());
865 for (int k = 0; k < 50; ++k)
866 ASSERT_NE(tbl.insert(new Bucket(k)), nullptr) << "key " << k;
867 EXPECT_EQ(tbl.capacity(), 11u);
868
869 // turned on, the next insertion grows it
870 tbl.set_with_resize(true);
871 EXPECT_TRUE(tbl.get_with_resize());
872 ASSERT_NE(tbl.insert(new Bucket(50)), nullptr);
873 const size_t grown = tbl.capacity();
874 EXPECT_GT(grown, 11u);
875
876 // turned off, removals do not shrink it
877 tbl.set_with_resize(false);
878 for (int k = 0; k < 45; ++k)
879 delete tbl.remove(tbl.search(k));
880 EXPECT_EQ(tbl.capacity(), grown);
881
882 // and turned on again, they do
883 tbl.set_with_resize(true);
884 delete tbl.remove(tbl.search(45));
885 EXPECT_LT(tbl.capacity(), grown);
886 for (int k = 46; k <= 50; ++k)
887 EXPECT_NE(tbl.search(k), nullptr) << "key " << k;
888
889 for (LhashTable<int>::Iterator it(tbl); it.has_curr(); )
890 delete it.del();
891}
892
893// The sets and maps over chained tables copied every table as resizing.
894TEST(DynSetLhash, CopyKeepsWhetherTheTableResizes)
895{
896 DynSetLhash<int> original;
897 for (int k = 0; k < 20; ++k)
898 original.insert(k);
899 original.set_with_resize(false);
900
901 DynSetLhash<int> copy(original);
902 EXPECT_FALSE(copy.get_with_resize());
903 EXPECT_EQ(copy.size(), 20u);
904
905 DynSetLinHash<int> lin_original;
906 lin_original.insert(1);
907 lin_original.set_with_resize(false);
908 DynSetLinHash<int> lin_copy(lin_original);
909 EXPECT_FALSE(lin_copy.get_with_resize());
910 EXPECT_TRUE(lin_copy.contains(1));
911}
912
913TEST(LhashTable, CustomComparatorActsAsEquality)
914{
915 struct ModCmp
916 {
917 bool operator()(int a, int b) const { return (a % 10) == (b % 10); }
918 };
919 using Bucket = LhashBucket<int>;
920 auto const_hash = +[](const int &) { return static_cast<size_t>(0); };
921 LhashTable<int, ModCmp> tbl(11, const_hash, ModCmp(),
924 true, true);
925 auto * b1 = new Bucket(10);
926 auto * b2 = new Bucket(20);
927 ASSERT_NE(tbl.insert(b1), nullptr);
928 EXPECT_EQ(tbl.insert(b2), nullptr); // treated as equal keys
929 EXPECT_EQ(tbl.size(), 1u);
930
931 delete tbl.remove(b1);
932 delete b2;
933}
934
935TEST(LhashTable, CurrentAlphaNonZero)
936{
937 using Bucket = LhashBucket<int>;
938 LhashTable<int> tbl(101);
939 tbl.insert(new Bucket(1));
940 tbl.insert(new Bucket(2));
941 EXPECT_GT(tbl.current_alpha(), 0.0);
942 for (LhashTable<int>::Iterator it(tbl); it.has_curr(); )
943 delete it.del();
944}
945
946static_assert(!std::is_copy_constructible_v<LhashTable<int>>,
947 "LhashTable should not be copy constructible");
948static_assert(!std::is_copy_assignable_v<LhashTable<int>>,
949 "LhashTable should not be copy assignable");
950
951// ---------------------------------------------------------------------------
952// What rules a table travels with its keys
953// ---------------------------------------------------------------------------
954
955namespace
956{
957 size_t first_hash_a(const long & k) noexcept
958 {
959 return static_cast<size_t>(k) * 2654435761u;
960 }
961
962 size_t first_hash_b(const long & k) noexcept
963 {
964 return static_cast<size_t>(k) * 40503u + 17;
965 }
966
967 size_t second_hash_a(const long & k) noexcept
968 {
969 return static_cast<size_t>(k) + 7;
970 }
971
972 size_t second_hash_b(const long & k) noexcept
973 {
974 return static_cast<size_t>(k) * 3 + 11;
975 }
976
977 // An equality that says which table it was given to.
978 struct Tagged_Equal
979 {
980 int tag = 0;
981
982 bool operator()(const long & x, const long & y) const noexcept
983 {
984 return x == y;
985 }
986 };
987
988 // Everything that rules a table, apart from its keys and its capacity.
989 struct Table_Config
990 {
991 size_t first_hash = 0; // the hash function, applied to a fixed key
992 size_t second_hash = 0; // the second one, in the table that has two
993 int cmp_tag = 0;
994 float lower_alpha = 0;
995 float upper_alpha = 0;
996
997 bool operator==(const Table_Config &) const = default;
998
999 friend std::ostream & operator<<(std::ostream & out,
1000 const Table_Config & c)
1001 {
1002 return out << "{hash " << c.first_hash << ", second hash "
1003 << c.second_hash << ", comparator " << c.cmp_tag
1004 << ", thresholds " << c.lower_alpha << '/' << c.upper_alpha
1005 << '}';
1006 }
1007 };
1008
1009 constexpr long Config_Probe_Key = 12345;
1010
1011 // The two configurations that the tests tell apart. Capacity `len` is
1012 // not part of them: each test chooses it.
1013 const Table_Config config_a = {first_hash_a(Config_Probe_Key),
1014 second_hash_a(Config_Probe_Key), 1,
1015 0.10f, 0.40f};
1016 const Table_Config config_b = {first_hash_b(Config_Probe_Key),
1017 second_hash_b(Config_Probe_Key), 2,
1018 0.25f, 0.90f};
1019
1020 using Linear_Probing = OLhashTable<long, Tagged_Equal>;
1021 using Double_Hashing = ODhashTable<long, Tagged_Equal>;
1022 using Chained = DynSetLhash<long, Tagged_Equal>;
1023 using Linear_Hashing = DynSetLinHash<long, Tagged_Equal>;
1024
1025 // How to build each table with configuration a or b, and how to read
1026 // its configuration back.
1027 template <class Table> struct Config_Of;
1028
1029 template <> struct Config_Of<Linear_Probing>
1030 {
1031 static Linear_Probing make(const bool a, const size_t len)
1032 {
1033 return a ? Linear_Probing(len, first_hash_a, Tagged_Equal{1},
1034 0.10f, 0.40f, true)
1035 : Linear_Probing(len, first_hash_b, Tagged_Equal{2},
1036 0.25f, 0.90f, true);
1037 }
1038
1039 static size_t second_hash(const Linear_Probing &, const bool a)
1040 {
1041 return a ? config_a.second_hash : config_b.second_hash; // it has none
1042 }
1043 };
1044
1045 template <> struct Config_Of<Double_Hashing>
1046 {
1047 static Double_Hashing make(const bool a, const size_t len)
1048 {
1049 return a ? Double_Hashing(len, first_hash_a, second_hash_a,
1050 Tagged_Equal{1}, 0.10f, 0.40f, true)
1051 : Double_Hashing(len, first_hash_b, second_hash_b,
1052 Tagged_Equal{2}, 0.25f, 0.90f, true);
1053 }
1054
1055 static size_t second_hash(const Double_Hashing & table, bool)
1056 {
1057 return table.get_second_hash_fct()(Config_Probe_Key);
1058 }
1059 };
1060
1061 template <class Table> struct Config_Of_Chained
1062 {
1063 static Table make(const bool a, const size_t len)
1064 {
1065 return a ? Table(len, first_hash_a, Tagged_Equal{1}, 0.10f, 0.40f)
1066 : Table(len, first_hash_b, Tagged_Equal{2}, 0.25f, 0.90f);
1067 }
1068
1069 static size_t second_hash(const Table &, const bool a)
1070 {
1071 return a ? config_a.second_hash : config_b.second_hash; // it has none
1072 }
1073 };
1074
1075 template <> struct Config_Of<Chained> : Config_Of_Chained<Chained> {};
1076
1077 template <>
1078 struct Config_Of<Linear_Hashing> : Config_Of_Chained<Linear_Hashing> {};
1079
1080 // `like_a` only says which second hash to report for the tables that
1081 // have a single hash function.
1082 template <class Table>
1083 Table_Config config_of(const Table & table, const bool like_a)
1084 {
1085 return {table.get_hash_fct()(Config_Probe_Key),
1086 Config_Of<Table>::second_hash(table, like_a),
1087 table.get_compare().tag,
1088 table.get_lower_alpha(), table.get_upper_alpha()};
1089 }
1090
1091 template <class Table>
1092 void insert_keys(Table & table, const long from, const long to)
1093 {
1094 for (long k = from; k < to; ++k)
1095 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
1096 }
1097
1098 template <class Table>
1099 ::testing::AssertionResult holds(const Table & table, long from, long to)
1100 {
1101 if (table.size() != static_cast<size_t>(to - from))
1102 return ::testing::AssertionFailure()
1103 << "size is " << table.size() << ", expected " << to - from;
1104 for (long k = from; k < to; ++k)
1105 if (not table.contains(k))
1106 return ::testing::AssertionFailure() << "key " << k << " not found";
1107 return ::testing::AssertionSuccess();
1108 }
1109
1110 template <class Table>
1111 struct HashTableConfiguration : public ::testing::Test {};
1112
1113 using Configured_Tables = ::testing::Types<Linear_Probing, Double_Hashing,
1114 Chained, Linear_Hashing>;
1115 TYPED_TEST_SUITE(HashTableConfiguration, Configured_Tables);
1116
1117 TYPED_TEST(HashTableConfiguration, ConstructionKeepsWhatItWasGiven)
1118 {
1119 const auto a = Config_Of<TypeParam>::make(true, 101);
1120 const auto b = Config_Of<TypeParam>::make(false, 101);
1121
1122 EXPECT_EQ(config_of(a, true), config_a);
1123 EXPECT_EQ(config_of(b, false), config_b);
1124 }
1125
1126 TYPED_TEST(HashTableConfiguration, CopyConstructionCopiesTheConfiguration)
1127 {
1128 auto source = Config_Of<TypeParam>::make(true, 101);
1129 insert_keys(source, 0, 40);
1130
1131 const TypeParam copy(source);
1132
1133 EXPECT_EQ(config_of(copy, true), config_a);
1134 EXPECT_TRUE(holds(copy, 0, 40));
1135 EXPECT_EQ(config_of(source, true), config_a);
1136 EXPECT_TRUE(holds(source, 0, 40));
1137 }
1138
1139 // The target is larger than the source needs. The open addressing tables
1140 // used to keep their own array in this case, and with it their own hash
1141 // function, comparator and thresholds.
1142 TYPED_TEST(HashTableConfiguration, CopyAssignmentToALargerTable)
1143 {
1144 auto source = Config_Of<TypeParam>::make(true, 101);
1145 insert_keys(source, 0, 40);
1146 auto target = Config_Of<TypeParam>::make(false, 1009);
1147 insert_keys(target, 500, 520);
1148
1149 target = source;
1150
1151 EXPECT_EQ(config_of(target, true), config_a);
1152 EXPECT_TRUE(holds(target, 0, 40));
1153 EXPECT_EQ(config_of(source, true), config_a);
1154 EXPECT_TRUE(holds(source, 0, 40));
1155
1156 insert_keys(target, 40, 400); // it keeps working with what it was given
1157 EXPECT_TRUE(holds(target, 0, 400));
1158 }
1159
1160 TYPED_TEST(HashTableConfiguration, CopyAssignmentToASmallerTable)
1161 {
1162 auto source = Config_Of<TypeParam>::make(true, 1009);
1163 insert_keys(source, 0, 400);
1164 auto target = Config_Of<TypeParam>::make(false, 11);
1165 insert_keys(target, 500, 505);
1166
1167 target = source;
1168
1169 EXPECT_EQ(config_of(target, true), config_a);
1170 EXPECT_TRUE(holds(target, 0, 400));
1171 EXPECT_TRUE(holds(source, 0, 400));
1172 }
1173
1174 TYPED_TEST(HashTableConfiguration, SelfCopyAssignmentChangesNothing)
1175 {
1176 auto table = Config_Of<TypeParam>::make(true, 101);
1177 insert_keys(table, 0, 40);
1178 const auto & same = table;
1179
1180 table = same;
1181
1182 EXPECT_EQ(config_of(table, true), config_a);
1183 EXPECT_TRUE(holds(table, 0, 40));
1184 }
1185
1186 TYPED_TEST(HashTableConfiguration, MoveConstructionCarriesTheConfiguration)
1187 {
1188 auto source = Config_Of<TypeParam>::make(true, 101);
1189 insert_keys(source, 0, 40);
1190
1191 TypeParam target(std::move(source));
1192
1193 EXPECT_EQ(config_of(target, true), config_a);
1194 EXPECT_TRUE(holds(target, 0, 40));
1195
1196 // The source is empty, keeps its configuration and can be used again.
1197 EXPECT_TRUE(source.is_empty());
1198 EXPECT_EQ(source.size(), 0u);
1199 EXPECT_FALSE(source.contains(7));
1200 EXPECT_EQ(config_of(source, true), config_a);
1201 insert_keys(source, 100, 300);
1202 EXPECT_TRUE(holds(source, 100, 300));
1203 EXPECT_TRUE(holds(target, 0, 40));
1204 }
1205
1206 TYPED_TEST(HashTableConfiguration, MoveAssignmentCarriesTheConfiguration)
1207 {
1208 auto source = Config_Of<TypeParam>::make(true, 101);
1209 insert_keys(source, 0, 40);
1210 auto target = Config_Of<TypeParam>::make(false, 1009);
1211 insert_keys(target, 500, 520);
1212
1213 target = std::move(source);
1214
1215 EXPECT_EQ(config_of(target, true), config_a);
1216 EXPECT_TRUE(holds(target, 0, 40));
1217
1218 insert_keys(target, 40, 400);
1219 EXPECT_TRUE(holds(target, 0, 400));
1220 }
1221
1222 TYPED_TEST(HashTableConfiguration, SwapExchangesTheConfiguration)
1223 {
1224 auto a = Config_Of<TypeParam>::make(true, 101);
1225 insert_keys(a, 0, 40);
1226 auto b = Config_Of<TypeParam>::make(false, 1009);
1227 insert_keys(b, 500, 520);
1228
1229 a.swap(b);
1230
1231 EXPECT_EQ(config_of(a, false), config_b);
1232 EXPECT_TRUE(holds(a, 500, 520));
1233 EXPECT_EQ(config_of(b, true), config_a);
1234 EXPECT_TRUE(holds(b, 0, 40));
1235
1236 insert_keys(a, 520, 900);
1237 insert_keys(b, 40, 400);
1238 EXPECT_TRUE(holds(a, 500, 900));
1239 EXPECT_TRUE(holds(b, 0, 400));
1240 }
1241
1242 TYPED_TEST(HashTableConfiguration, SwapWithAnEmptyTable)
1243 {
1244 auto a = Config_Of<TypeParam>::make(true, 101);
1245 insert_keys(a, 0, 40);
1246 auto b = Config_Of<TypeParam>::make(false, 11);
1247
1248 a.swap(b);
1249
1250 EXPECT_EQ(config_of(a, false), config_b);
1251 EXPECT_TRUE(a.is_empty());
1252 EXPECT_EQ(config_of(b, true), config_a);
1253 EXPECT_TRUE(holds(b, 0, 40));
1254 }
1255
1256 // The resizing policy of the open addressing tables has no accessor: it
1257 // shows in whether a table grows as it fills up. One bucket is left
1258 // free: a table that does not resize must not be given more keys than
1259 // it has buckets.
1260 template <class Table> bool grows_when_filled(Table & table)
1261 {
1262 const size_t capacity = table.capacity();
1263 for (long k = 0;
1264 table.capacity() == capacity and table.size() + 1 < capacity; ++k)
1265 (void) table.insert(1000000 + k);
1266 return table.capacity() != capacity;
1267 }
1268
1269 template <class Table>
1270 struct OpenTableResizingPolicy : public ::testing::Test
1271 {
1272 // The sources of the tests have a few keys, so that assigning one of
1273 // them to a table with fewer buckets than that cannot keep the array
1274 // of the target.
1275 static constexpr long Num_Keys = 6;
1276
1277 static Table fixed_size(const size_t len, const long num_keys = 0)
1278 {
1279 auto make = [len] ()
1280 {
1281 if constexpr (std::is_same_v<Table, Linear_Probing>)
1282 return Table(len, first_hash_a, Tagged_Equal{1}, 0.10f, 0.40f,
1283 false);
1284 else
1285 return Table(len, first_hash_a, second_hash_a, Tagged_Equal{1},
1286 0.10f, 0.40f, false);
1287 };
1288 Table table = make();
1289 insert_keys(table, 0, num_keys);
1290 return table;
1291 }
1292
1293 static Table resizable(const size_t len, const long num_keys = 0)
1294 {
1295 Table table = Config_Of<Table>::make(false, len);
1296 insert_keys(table, 0, num_keys);
1297 return table;
1298 }
1299 };
1300
1301 using Open_Tables = ::testing::Types<Linear_Probing, Double_Hashing>;
1302 TYPED_TEST_SUITE(OpenTableResizingPolicy, Open_Tables);
1303
1304 TYPED_TEST(OpenTableResizingPolicy, IsWhatTheConstructorWasGiven)
1305 {
1306 auto fixed = this->fixed_size(11, this->Num_Keys);
1307 auto resizable = this->resizable(11, this->Num_Keys);
1308
1309 EXPECT_FALSE(grows_when_filled(fixed));
1310 EXPECT_TRUE(grows_when_filled(resizable));
1311 }
1312
1313 TYPED_TEST(OpenTableResizingPolicy, IsCopied)
1314 {
1315 const auto fixed = this->fixed_size(11, this->Num_Keys);
1316 const auto resizable = this->resizable(11, this->Num_Keys);
1317
1318 TypeParam fixed_copy(fixed);
1319 TypeParam resizable_copy(resizable);
1320 EXPECT_FALSE(grows_when_filled(fixed_copy));
1321 EXPECT_TRUE(grows_when_filled(resizable_copy));
1322
1323 // By assignment, to a target with fewer buckets than the source has
1324 // keys and to one with plenty of them.
1325 for (const size_t len : {size_t(5), size_t(1009)})
1326 {
1327 auto to_fixed = this->resizable(len);
1328 to_fixed = fixed;
1329 EXPECT_FALSE(grows_when_filled(to_fixed)) << "capacity " << len;
1330
1331 auto to_resizable = this->fixed_size(len);
1332 to_resizable = resizable;
1333 EXPECT_TRUE(grows_when_filled(to_resizable)) << "capacity " << len;
1334 }
1335 }
1336
1337 TYPED_TEST(OpenTableResizingPolicy, IsMoved)
1338 {
1339 auto fixed = this->fixed_size(11, this->Num_Keys);
1340 auto resizable = this->resizable(11, this->Num_Keys);
1341
1342 TypeParam from_fixed(std::move(fixed));
1343 TypeParam from_resizable(std::move(resizable));
1344
1345 auto to_fixed = this->resizable(101);
1346 to_fixed = std::move(from_fixed);
1347 EXPECT_FALSE(grows_when_filled(to_fixed));
1348
1349 auto to_resizable = this->fixed_size(101);
1350 to_resizable = std::move(from_resizable);
1351 EXPECT_TRUE(grows_when_filled(to_resizable));
1352 }
1353
1354 TYPED_TEST(OpenTableResizingPolicy, IsSwapped)
1355 {
1356 auto a = this->fixed_size(11, this->Num_Keys);
1357 auto b = this->resizable(11, this->Num_Keys);
1358
1359 a.swap(b);
1360
1361 EXPECT_TRUE(grows_when_filled(a));
1362 EXPECT_FALSE(grows_when_filled(b));
1363 }
1364
1365 // -------------------------------------------------------------------------
1366 // An open addressing table after a move took its buckets
1367 // -------------------------------------------------------------------------
1368
1369 template <class Table>
1370 struct OpenTableAfterMove : public ::testing::Test
1371 {
1372 // A table with keys [0, 40) whose buckets are then taken by a move.
1373 // `resizes` is the resizing policy of the table.
1374 static Table emptied_by_a_move(const bool resizes = true)
1375 {
1376 auto make = [resizes] ()
1377 {
1378 if constexpr (std::is_same_v<Table, OLhashTable<long>>)
1379 return Table(101, first_hash_a, Aleph::equal_to<long>(),
1380 0.10f, 0.40f, resizes);
1381 else
1382 return Table(101, first_hash_a, second_hash_a,
1383 Aleph::equal_to<long>(), 0.10f, 0.40f, resizes);
1384 };
1385 Table source = make();
1386 insert_keys(source, 0, 40);
1387 Table target(std::move(source));
1388 EXPECT_TRUE(holds(target, 0, 40));
1389 return source;
1390 }
1391 };
1392
1393 using Plain_Open_Tables =
1394 ::testing::Types<OLhashTable<long>, ODhashTable<long>>;
1395 TYPED_TEST_SUITE(OpenTableAfterMove, Plain_Open_Tables);
1396
1397 // The keys do not change address: the buckets are taken, not copied.
1398 TYPED_TEST(OpenTableAfterMove, TheTargetHasTheVeryBucketsOfTheSource)
1399 {
1400 static_assert(std::is_nothrow_move_constructible_v<TypeParam>);
1401
1402 TypeParam source;
1403 insert_keys(source, 0, 1000);
1404 const size_t capacity = source.capacity();
1405 std::vector<const long *> where;
1406 for (long k = 0; k < 1000; ++k)
1407 where.push_back(source.search(k));
1408
1409 TypeParam target(std::move(source));
1410
1411 EXPECT_EQ(target.capacity(), capacity);
1412 ASSERT_TRUE(holds(target, 0, 1000));
1413 for (long k = 0; k < 1000; ++k)
1414 ASSERT_EQ(std::as_const(target).search(k), where[k]) << "key " << k;
1415
1416 EXPECT_EQ(source.size(), 0u);
1417 EXPECT_EQ(source.capacity(), 0u);
1418 }
1419
1420 TYPED_TEST(OpenTableAfterMove, TheSourceAnswersAsAnEmptyTable)
1421 {
1422 TypeParam source = this->emptied_by_a_move();
1423
1424 EXPECT_EQ(source.size(), 0u);
1425 EXPECT_EQ(source.capacity(), 0u);
1426 EXPECT_TRUE(source.is_empty());
1427 EXPECT_EQ(source.current_alpha(), 0.0f);
1428
1429 EXPECT_EQ(source.search(7), nullptr);
1430 EXPECT_EQ(std::as_const(source).search(7), nullptr);
1431 EXPECT_FALSE(source.has(7));
1432 EXPECT_FALSE(source.contains(7));
1433 EXPECT_THROW((void) source.find(7), std::domain_error);
1434 EXPECT_THROW(source.remove(7), std::domain_error);
1435
1436 EXPECT_TRUE(source.keys().is_empty());
1437 size_t visited = 0;
1438 source.for_each([&visited] (const long &) { ++visited; });
1439 for ([[maybe_unused]] const long & key : source)
1440 ++visited;
1441 EXPECT_EQ(visited, 0u);
1442
1443 typename TypeParam::Iterator it(source);
1444 EXPECT_FALSE(it.has_curr());
1445 EXPECT_THROW(it.del(), std::overflow_error);
1446 it.reset_last();
1447 EXPECT_FALSE(it.has_curr());
1448
1449 const auto stats = source.stats();
1450 EXPECT_EQ(stats.num_busy, 0u);
1451 EXPECT_EQ(stats.num_empty, 0u);
1452 EXPECT_EQ(stats.num_deleted, 0u);
1453 EXPECT_EQ(stats.max_len, 0u);
1454 EXPECT_EQ(stats.avg, 0.0f); // not the 0/0 of averaging over no bucket
1455 EXPECT_EQ(stats.var, 0.0f);
1456
1457 source.rehash();
1458 EXPECT_EQ(source.capacity(), 0u);
1459 EXPECT_EQ(source.resize(0), 0u);
1460 EXPECT_EQ(source.capacity(), 0u);
1461 }
1462
1463 TYPED_TEST(OpenTableAfterMove, TheSourceGetsBucketsWithItsFirstInsertion)
1464 {
1465 {
1466 TypeParam source = this->emptied_by_a_move();
1467 ASSERT_NE(source.insert(7), nullptr);
1468 EXPECT_EQ(source.capacity(), Primes::DefaultPrime);
1469 EXPECT_TRUE(holds(source, 7, 8));
1470 insert_keys(source, 8, 2000);
1471 EXPECT_TRUE(holds(source, 7, 2000));
1472 source.remove(7);
1473 EXPECT_TRUE(holds(source, 8, 2000));
1474 }
1475 {
1476 TypeParam source = this->emptied_by_a_move();
1477 long key = 7;
1478 ASSERT_NE(source.insert(std::move(key)), nullptr);
1479 EXPECT_TRUE(holds(source, 7, 8));
1480 }
1481 {
1482 TypeParam source = this->emptied_by_a_move();
1483 const long * stored = source.search_or_insert(7);
1484 ASSERT_NE(stored, nullptr);
1485 EXPECT_EQ(source.search_or_insert(7), stored);
1486 EXPECT_TRUE(holds(source, 7, 8));
1487 }
1488 {
1489 TypeParam source = this->emptied_by_a_move();
1490 const auto first = source.contains_or_insert(7);
1491 ASSERT_NE(first.first, nullptr);
1492 EXPECT_FALSE(first.second);
1493 EXPECT_TRUE(source.contains_or_insert(7).second);
1494 EXPECT_TRUE(holds(source, 7, 8));
1495 }
1496 {
1497 TypeParam source = this->emptied_by_a_move();
1498 EXPECT_EQ(source[7], 7);
1499 EXPECT_TRUE(holds(source, 7, 8));
1500 }
1501 }
1502
1503 // A table that does not resize gets buckets all the same; otherwise it
1504 // could never hold a key again.
1505 TYPED_TEST(OpenTableAfterMove, ATableThatDoesNotResizeGetsBucketsToo)
1506 {
1507 TypeParam source = this->emptied_by_a_move(false);
1508
1509 ASSERT_NE(source.insert(7), nullptr);
1510 EXPECT_EQ(source.capacity(), Primes::DefaultPrime);
1511 insert_keys(source, 8, 50);
1512 EXPECT_TRUE(holds(source, 7, 50));
1513 EXPECT_FALSE(grows_when_filled(source));
1514 }
1515
1516 TYPED_TEST(OpenTableAfterMove, TheSourceCanBeResizedAndCleared)
1517 {
1518 {
1519 TypeParam source = this->emptied_by_a_move();
1520 EXPECT_EQ(source.resize(17), 17u);
1521 EXPECT_EQ(source.capacity(), 17u);
1522 EXPECT_TRUE(source.is_empty());
1523 insert_keys(source, 0, 10);
1524 EXPECT_TRUE(holds(source, 0, 10));
1525 }
1526 {
1527 TypeParam source = this->emptied_by_a_move();
1528 source.clear();
1529 EXPECT_EQ(source.capacity(), Primes::DefaultPrime);
1530 EXPECT_TRUE(source.is_empty());
1531 insert_keys(source, 0, 10);
1532 EXPECT_TRUE(holds(source, 0, 10));
1533 }
1534 }
1535
1536 TYPED_TEST(OpenTableAfterMove, TheSourceCanBeCopiedMovedAndAssigned)
1537 {
1538 {
1539 const TypeParam source = this->emptied_by_a_move();
1540 TypeParam copy(source);
1541 EXPECT_TRUE(copy.is_empty());
1542 EXPECT_EQ(copy.get_hash_fct()(Config_Probe_Key),
1543 first_hash_a(Config_Probe_Key));
1544 insert_keys(copy, 0, 10);
1545 EXPECT_TRUE(holds(copy, 0, 10));
1546 EXPECT_TRUE(source.is_empty());
1547 }
1548 {
1549 TypeParam source = this->emptied_by_a_move();
1550 TypeParam moved(std::move(source));
1551 EXPECT_TRUE(moved.is_empty());
1552 insert_keys(moved, 0, 10);
1553 insert_keys(source, 20, 30);
1554 EXPECT_TRUE(holds(moved, 0, 10));
1555 EXPECT_TRUE(holds(source, 20, 30));
1556 }
1557 {
1558 const TypeParam source = this->emptied_by_a_move();
1559 TypeParam target;
1560 insert_keys(target, 100, 150);
1561 target = source;
1562 EXPECT_TRUE(target.is_empty());
1563 insert_keys(target, 0, 10);
1564 EXPECT_TRUE(holds(target, 0, 10));
1565 }
1566 {
1567 TypeParam source = this->emptied_by_a_move();
1568 TypeParam other;
1569 insert_keys(other, 100, 150);
1570 source = other;
1571 EXPECT_TRUE(holds(source, 100, 150));
1572 EXPECT_TRUE(holds(other, 100, 150));
1573 }
1574 {
1575 TypeParam source = this->emptied_by_a_move();
1576 TypeParam other;
1577 insert_keys(other, 100, 150);
1578 source = std::move(other);
1579 EXPECT_TRUE(holds(source, 100, 150));
1580 insert_keys(other, 0, 10);
1581 EXPECT_TRUE(holds(other, 0, 10));
1582 }
1583 {
1584 TypeParam source = this->emptied_by_a_move();
1585 TypeParam other;
1586 insert_keys(other, 100, 150);
1587 source.swap(other);
1588 EXPECT_TRUE(holds(source, 100, 150));
1589 EXPECT_TRUE(other.is_empty());
1590 insert_keys(other, 0, 10);
1591 EXPECT_TRUE(holds(other, 0, 10));
1592 }
1593 }
1594
1595 // -------------------------------------------------------------------------
1596 // A copy assignment that fails midway
1597 // -------------------------------------------------------------------------
1598
1599 // A key whose copies can be made to throw.
1600 struct Fragile_Key
1601 {
1602 // How many copies still succeed. Negative: none fails.
1603 static inline long copies_before_failure = -1;
1604
1605 long value = 0;
1606
1607 Fragile_Key() = default;
1608
1609 Fragile_Key(const long v) : value(v) {}
1610
1611 Fragile_Key(const Fragile_Key & other) : value(other.value)
1612 {
1613 may_throw();
1614 }
1615
1616 Fragile_Key & operator=(const Fragile_Key & other)
1617 {
1618 may_throw();
1619 value = other.value;
1620 return *this;
1621 }
1622
1623 Fragile_Key(Fragile_Key &&) noexcept = default;
1624
1625 Fragile_Key & operator=(Fragile_Key &&) noexcept = default;
1626
1627 bool operator==(const Fragile_Key &) const = default;
1628
1629 static void may_throw()
1630 {
1631 if (copies_before_failure == 0)
1632 throw std::runtime_error("no copy");
1633 if (copies_before_failure > 0)
1634 --copies_before_failure;
1635 }
1636 };
1637
1638 size_t fragile_hash(const Fragile_Key & key) noexcept
1639 {
1640 return first_hash_a(key.value);
1641 }
1642
1643 size_t fragile_second_hash(const Fragile_Key & key) noexcept
1644 {
1645 return second_hash_a(key.value);
1646 }
1647
1648 // While it lives, copying a key throws after `successful` copies.
1649 struct Failing_Copies
1650 {
1651 explicit Failing_Copies(const long successful = 0)
1652 {
1653 Fragile_Key::copies_before_failure = successful;
1654 }
1655
1656 ~Failing_Copies() { Fragile_Key::copies_before_failure = -1; }
1657 };
1658
1659 template <class Table>
1660 struct HashTableCopyThatThrows : public ::testing::Test
1661 {
1662 static Table make(const long from, const long to)
1663 {
1664 auto empty_table = [] ()
1665 {
1666 if constexpr (std::is_same_v<Table, ODhashTable<Fragile_Key>>)
1667 return Table(101, fragile_hash, fragile_second_hash);
1668 else
1669 return Table(101, fragile_hash);
1670 };
1671 Table table = empty_table();
1672 for (long k = from; k < to; ++k)
1673 EXPECT_NE(table.insert(Fragile_Key(k)), nullptr) << "key " << k;
1674 return table;
1675 }
1676
1677 static ::testing::AssertionResult holds_keys(const Table & table,
1678 const long from,
1679 const long to)
1680 {
1681 if (table.size() != static_cast<size_t>(to - from))
1682 return ::testing::AssertionFailure()
1683 << "size is " << table.size() << ", expected " << to - from;
1684 for (long k = from; k < to; ++k)
1685 if (not table.contains(Fragile_Key(k)))
1686 return ::testing::AssertionFailure() << "key " << k << " not found";
1687 return ::testing::AssertionSuccess();
1688 }
1689 };
1690
1691 using Fragile_Tables = ::testing::Types<OLhashTable<Fragile_Key>,
1695 TYPED_TEST_SUITE(HashTableCopyThatThrows, Fragile_Tables);
1696
1697 // The assignment used to empty the target before it copied the first
1698 // key.
1699 TYPED_TEST(HashTableCopyThatThrows, AssignmentKeepsTheTarget)
1700 {
1701 const TypeParam source = this->make(0, 30);
1702 TypeParam target = this->make(100, 110);
1703
1704 {
1705 Failing_Copies failing;
1706 EXPECT_THROW(target = source, std::runtime_error);
1707 }
1708
1709 EXPECT_TRUE(this->holds_keys(target, 100, 110));
1710 EXPECT_TRUE(this->holds_keys(source, 0, 30));
1711
1712 target = source;
1713 EXPECT_TRUE(this->holds_keys(target, 0, 30));
1714 }
1715
1716 TYPED_TEST(HashTableCopyThatThrows, ConstructionReleasesWhatItBuilt)
1717 {
1718 const TypeParam source = this->make(0, 30);
1719
1720 {
1721 Failing_Copies failing;
1722 EXPECT_THROW(TypeParam copy(source), std::runtime_error);
1723 }
1724
1725 EXPECT_TRUE(this->holds_keys(source, 0, 30));
1726 }
1727
1728 // -------------------------------------------------------------------------
1729 // Changing the hash function of a table that has keys
1730 // -------------------------------------------------------------------------
1731
1732 TEST(OpenTableHashFunction, RehashPlacesTheKeysWithTheNewFunction)
1733 {
1734 {
1735 OLhashTable<long> table(101, first_hash_a);
1736 insert_keys(table, 0, 60);
1737 table.set_hash_fct(first_hash_b);
1738 table.rehash();
1739 EXPECT_TRUE(holds(table, 0, 60));
1740 insert_keys(table, 60, 300);
1741 EXPECT_TRUE(holds(table, 0, 300));
1742 }
1743 {
1744 ODhashTable<long> table(101, first_hash_a, second_hash_a);
1745 insert_keys(table, 0, 60);
1746 table.set_hash_fct(first_hash_b);
1747 table.set_second_hash_fct(second_hash_b);
1748 table.rehash();
1749 EXPECT_TRUE(holds(table, 0, 60));
1750 for (long k = 0; k < 60; k += 2)
1751 table.remove(k);
1752 insert_keys(table, 60, 300);
1753 for (long k = 1; k < 60; k += 2)
1754 EXPECT_TRUE(table.contains(k)) << "key " << k;
1755 EXPECT_EQ(table.size(), 270u);
1756 }
1757 }
1758
1759 // -------------------------------------------------------------------------
1760 // Hash functions given as lambdas without captures
1761 // -------------------------------------------------------------------------
1762
1763 // With every parameter given, a lambda without captures fitted both the
1764 // constructor that takes a std::function and the one that takes a
1765 // function pointer, and the call did not compile.
1766 TEST(OpenTableConstruction, TakesLambdasWithoutCaptures)
1767 {
1768 auto plus_ten = [] (const long & k) { return static_cast<size_t>(k) + 10; };
1769 auto plus_twenty = [] (const long & k)
1770 {
1771 return static_cast<size_t>(k) + 20;
1772 };
1774
1775 OLhashTable<long> one(11, plus_ten, eq, 0.1f, 0.5f, true);
1776 EXPECT_EQ(one.get_hash_fct()(1), 11u);
1777 insert_keys(one, 0, 100);
1778 EXPECT_TRUE(holds(one, 0, 100));
1779
1780 OLhashTable<long> two(11, plus_ten, plus_twenty, eq, 0.1f, 0.5f, true);
1781 EXPECT_EQ(two.get_hash_fct()(1), 11u);
1782
1783 OLhashTable<long> with_a_function(11, plus_ten, second_hash_a, eq,
1784 0.1f, 0.5f, true);
1785 EXPECT_EQ(with_a_function.get_hash_fct()(1), 11u);
1786
1787 const OLhashTable<long>::Hash_Fct stored = plus_twenty;
1788 OLhashTable<long> with_a_stored_one(11, stored, plus_ten, eq,
1789 0.1f, 0.5f, true);
1790 EXPECT_EQ(with_a_stored_one.get_hash_fct()(1), 21u);
1791
1792 ODhashTable<long> twice(11, plus_ten, plus_twenty, eq, 0.1f, 0.5f, true);
1793 EXPECT_EQ(twice.get_hash_fct()(1), 11u);
1794 EXPECT_EQ(twice.get_second_hash_fct()(1), 21u);
1795 insert_keys(twice, 0, 100);
1796 EXPECT_TRUE(holds(twice, 0, 100));
1797
1798 HashSet<long, OLhashTable> set(11, plus_ten, eq, 0.1f, 0.5f, true);
1799 EXPECT_EQ(set.get_hash_fct()(1), 11u);
1800 }
1801
1802 // The calls that already compiled keep choosing the same function.
1803 TEST(OpenTableConstruction, OtherHashFunctionsAreTakenAsBefore)
1804 {
1805 long bias = 30;
1806 auto capturing = [bias] (const long & k)
1807 {
1808 return static_cast<size_t>(k + bias);
1809 };
1810 auto plus_ten = [] (const long & k) { return static_cast<size_t>(k) + 10; };
1811 const OLhashTable<long>::Hash_Fct stored = capturing;
1813 const size_t a = first_hash_a(1), b = first_hash_b(1);
1814 const size_t sa = second_hash_a(1);
1815
1816 using OL = OLhashTable<long>;
1817 EXPECT_EQ(OL(11, first_hash_a, eq, 0.1f, 0.5f, true).get_hash_fct()(1), a);
1818 EXPECT_EQ(OL(11, &first_hash_b, eq, 0.1f, 0.5f, true).get_hash_fct()(1), b);
1819 EXPECT_EQ(OL(11, +plus_ten, eq, 0.1f, 0.5f, true).get_hash_fct()(1), 11u);
1820 EXPECT_EQ(OL(11, capturing, eq, 0.1f, 0.5f, true).get_hash_fct()(1), 31u);
1821 EXPECT_EQ(OL(11, stored, eq, 0.1f, 0.5f, true).get_hash_fct()(1), 31u);
1822 EXPECT_EQ(OL(11, plus_ten).get_hash_fct()(1), 11u);
1823 EXPECT_EQ(OL(11, plus_ten, eq, 0.1f, 0.5f).get_hash_fct()(1), 11u);
1824 EXPECT_EQ(OL(11, first_hash_a, first_hash_b, eq, 0.1f, 0.5f, true)
1825 .get_hash_fct()(1), a);
1826 EXPECT_EQ(OL(11, stored, stored, eq, 0.1f, 0.5f, true).get_hash_fct()(1),
1827 31u);
1828 EXPECT_EQ(OL(11, capturing, first_hash_b, eq, 0.1f, 0.5f, true)
1829 .get_hash_fct()(1), 31u);
1830 EXPECT_EQ(OL(11, first_hash_a, capturing, eq, 0.1f, 0.5f, true)
1831 .get_hash_fct()(1), a);
1832 EXPECT_EQ(OL(11, first_hash_b, plus_ten, eq, 0.1f, 0.5f, true)
1833 .get_hash_fct()(1), b);
1834
1835 using OD = ODhashTable<long>;
1836 const OD plain(11, first_hash_a, second_hash_a, eq, 0.1f, 0.5f, true);
1837 EXPECT_EQ(plain.get_hash_fct()(1), a);
1838 EXPECT_EQ(plain.get_second_hash_fct()(1), sa);
1839 const OD lambda_first(11, plus_ten, second_hash_a, eq, 0.1f, 0.5f, true);
1840 EXPECT_EQ(lambda_first.get_hash_fct()(1), 11u);
1841 EXPECT_EQ(lambda_first.get_second_hash_fct()(1), sa);
1842 const OD lambda_second(11, first_hash_a, plus_ten, eq, 0.1f, 0.5f, true);
1843 EXPECT_EQ(lambda_second.get_hash_fct()(1), a);
1844 EXPECT_EQ(lambda_second.get_second_hash_fct()(1), 11u);
1845 const OD with_defaults(11, plus_ten, plus_ten);
1846 EXPECT_EQ(with_defaults.get_second_hash_fct()(1), 11u);
1847 }
1848
1849 // -------------------------------------------------------------------------
1850 // An insertion that throws leaves an open addressing table as it was
1851 // -------------------------------------------------------------------------
1852
1853 // A key with copy operations only, as many older classes are. Moving it
1854 // copies it, so swapping two of them can throw.
1855 struct Copy_Only_Key
1856 {
1857 long value = 0;
1858
1859 Copy_Only_Key() = default;
1860
1861 Copy_Only_Key(const long v) : value(v) {}
1862
1863 Copy_Only_Key(const Copy_Only_Key & other) : value(other.value)
1864 {
1865 Fragile_Key::may_throw();
1866 }
1867
1868 Copy_Only_Key & operator=(const Copy_Only_Key & other)
1869 {
1870 Fragile_Key::may_throw();
1871 value = other.value;
1872 return *this;
1873 }
1874
1875 bool operator==(const Copy_Only_Key &) const = default;
1876 };
1877
1878 static_assert(noexcept(std::swap(std::declval<Fragile_Key &>(),
1879 std::declval<Fragile_Key &>())));
1880 static_assert(not noexcept(std::swap(std::declval<Copy_Only_Key &>(),
1881 std::declval<Copy_Only_Key &>())));
1882
1883 // Hash functions that send many keys to the same buckets, so that the
1884 // insertions go through the buckets of removed keys and, in the double
1885 // hashing table, through its three kinds of probe.
1886 template <class Key> size_t crowded_hash(const Key & key) noexcept
1887 {
1888 return static_cast<size_t>(key.value) % 7;
1889 }
1890
1891 template <class Key> size_t crowded_second_hash(const Key & key) noexcept
1892 {
1893 return static_cast<size_t>(key.value) % 5;
1894 }
1895
1896 // A key of value 1000 b + s has its first probe in bucket b and its
1897 // second one in bucket s, so that a test can place each key.
1898 long value_of(const long k) noexcept { return k; }
1899
1900 template <class Key> long value_of(const Key & key) noexcept
1901 {
1902 return key.value;
1903 }
1904
1905 template <class Key> size_t chosen_hash(const Key & key) noexcept
1906 {
1907 return static_cast<size_t>(value_of(key) / 1000);
1908 }
1909
1910 template <class Key> size_t chosen_second_hash(const Key & key) noexcept
1911 {
1912 return static_cast<size_t>(value_of(key) % 1000);
1913 }
1914
1915 // A table of 101 buckets, with an upper threshold of 0.9, whose buckets
1916 // [1, 1 + removed) are marked as the ones of removed keys: they held keys
1917 // whose first probe was there, and the key stored after them, the only
1918 // one left, has a probe sequence that goes through all of them. The
1919 // table resizes itself, but not while the keys are removed: with one key
1920 // left, the removals would shrink it.
1921 template <class Table> Table with_removed_keys(const long removed)
1922 {
1923 using Key = typename Table::Key_Type;
1924 Table table = [] ()
1925 {
1926 if constexpr (requires (Table & t) { t.get_second_hash_fct(); })
1927 return Table(101, chosen_hash<Key>, chosen_second_hash<Key>,
1928 Aleph::equal_to<Key>(), 0.05f, 0.9f, true);
1929 else
1930 return Table(101, chosen_hash<Key>, Aleph::equal_to<Key>(),
1931 0.05f, 0.9f, true);
1932 }();
1933 for (long b = 1; b <= removed; ++b)
1934 EXPECT_NE(table.insert(Key(1000*b + 999)), nullptr) << "bucket " << b;
1935 EXPECT_NE(table.insert(Key(1000 + 2)), nullptr); // probes 1, 2 and on
1936 table.set_with_resize(false);
1937 for (long b = 1; b <= removed; ++b)
1938 table.remove(Key(1000*b + 999));
1939 table.set_with_resize(true);
1940 EXPECT_EQ(table.size(), 1u);
1941 EXPECT_EQ(table.stats().num_deleted, static_cast<size_t>(removed));
1942 return table;
1943 }
1944
1945 template <class Table> struct OpenTableInsertionThatThrows
1946 : public ::testing::Test
1947 {
1948 using Key = typename Table::Key_Type;
1949
1950 static Table make(const size_t len, const float upper_alpha,
1951 const bool resizes)
1952 {
1953 if constexpr (requires (Table & t) { t.get_second_hash_fct(); })
1954 return Table(len, crowded_hash<Key>, crowded_second_hash<Key>,
1955 Aleph::equal_to<Key>(), 0.05f, upper_alpha, resizes);
1956 else
1957 return Table(len, crowded_hash<Key>, Aleph::equal_to<Key>(),
1958 0.05f, upper_alpha, resizes);
1959 }
1960
1961 // Keys [0, 20) without six of them, whose buckets are left behind.
1962 static Table with_keys_and_removals(const bool resizes)
1963 {
1964 Table table = make(31, 0.95f, resizes);
1965 for (long k = 0; k < 20; ++k)
1966 EXPECT_NE(table.insert(Key(k)), nullptr) << "key " << k;
1967 for (const long k : {1L, 4L, 7L, 10L, 13L, 16L})
1968 table.remove(Key(k));
1969 return table;
1970 }
1971
1972 static std::vector<long> keys_of(const Table & table)
1973 {
1974 std::vector<long> keys;
1975 table.for_each([&keys] (const Key & key) { keys.push_back(key.value); });
1976 std::sort(keys.begin(), keys.end());
1977 return keys;
1978 }
1979
1980 // What the probes depend on: the state of every bucket and, in the
1981 // double hashing table, how many probe sequences go through it. In
1982 // these tests every removed key's bucket lies on the probe sequence of
1983 // a key still stored, so undoing an insertion must restore them all.
1984 static std::vector<std::pair<int, unsigned>> probes_of(const Table & table)
1985 {
1986 std::vector<std::pair<int, unsigned>> state;
1987 for (size_t i = 0; i < table.capacity(); ++i)
1988 if constexpr (requires { table.table[0].probe_counter; })
1989 state.emplace_back(table.table[i].status,
1990 table.table[i].probe_counter);
1991 else
1992 state.emplace_back(table.table[i].status, 0u);
1993 return state;
1994 }
1995 };
1996
1997 using Tables_With_Fragile_Keys =
1998 ::testing::Types<OLhashTable<Fragile_Key>, ODhashTable<Fragile_Key>>;
1999 TYPED_TEST_SUITE(OpenTableInsertionThatThrows, Tables_With_Fragile_Keys);
2000
2001 // The bucket was marked as busy before the key was copied into it. When
2002 // the copy threw, the table kept one entry more, holding whatever the
2003 // bucket had: a key by default or one that had been removed.
2004 TYPED_TEST(OpenTableInsertionThatThrows, KeyCopyThatThrowsLeavesNoEntry)
2005 {
2006 for (const bool resizes : {false, true})
2007 {
2008 TypeParam table = this->with_keys_and_removals(resizes);
2009 const auto keys = this->keys_of(table);
2010 const auto probes = this->probes_of(table);
2011 const size_t capacity = table.capacity();
2012 ASSERT_EQ(keys.size(), 14u);
2013
2014 for (long k = 0; k < 60; ++k)
2015 for (int operation = 0; operation < 4; ++operation)
2016 {
2017 const Fragile_Key key(k);
2018 const bool present = table.contains(key);
2019 bool threw = false;
2020 {
2021 Failing_Copies failing;
2022 try
2023 {
2024 switch (operation)
2025 {
2026 case 0: (void) table.insert(key); break;
2027 case 1: (void) table.search_or_insert(key); break;
2028 case 2: (void) table.contains_or_insert(key); break;
2029 default: (void) table[key]; break;
2030 }
2031 }
2032 catch (const std::runtime_error &)
2033 {
2034 threw = true;
2035 }
2036 }
2037 // a key that is already there is not copied
2038 ASSERT_EQ(threw, not present)
2039 << "key " << k << ", operation " << operation;
2040 ASSERT_EQ(this->keys_of(table), keys)
2041 << "key " << k << ", operation " << operation;
2042 ASSERT_EQ(table.size(), keys.size());
2043 ASSERT_EQ(table.capacity(), capacity);
2044 ASSERT_EQ(this->probes_of(table), probes)
2045 << "key " << k << ", operation " << operation;
2046 }
2047
2048 // and the table goes on working
2049 for (long k = 0; k < 28; ++k)
2050 {
2051 const bool present = table.contains(Fragile_Key(k));
2052 EXPECT_EQ(table.insert(Fragile_Key(k)) != nullptr, not present)
2053 << "key " << k;
2054 }
2055 for (long k = 0; k < 28; ++k)
2056 EXPECT_TRUE(table.contains(Fragile_Key(k))) << "key " << k;
2057 for (long k = 0; k < 28; ++k)
2058 table.remove(Fragile_Key(k));
2059 EXPECT_TRUE(table.is_empty());
2060 }
2061 }
2062
2063 // The key is stored and then the table grows, which copies the key once
2064 // more and asks for memory. If that failed, the insertion threw and the
2065 // key stayed in the table.
2066 TYPED_TEST(OpenTableInsertionThatThrows, GrowthThatFailsTakesTheKeyOutAgain)
2067 {
2068 for (int operation = 0; operation < 5; ++operation)
2069 {
2070 TypeParam table = this->make(11, 0.5f, true);
2071 for (long k = 0; k < 5; ++k)
2072 ASSERT_NE(table.insert(Fragile_Key(k)), nullptr);
2073 ASSERT_EQ(table.capacity(), 11u); // the sixth key makes it grow
2074 const auto keys = this->keys_of(table);
2075 const auto probes = this->probes_of(table);
2076
2077 const Fragile_Key key(5);
2078 {
2079 // the copy into the bucket succeeds; the one made to grow fails
2080 Failing_Copies failing(operation == 4 ? 0 : 1);
2081 switch (operation)
2082 {
2083 case 0:
2084 EXPECT_THROW((void) table.insert(key), std::runtime_error);
2085 break;
2086 case 1:
2087 EXPECT_THROW((void) table.search_or_insert(key),
2088 std::runtime_error);
2089 break;
2090 case 2:
2091 EXPECT_THROW((void) table.contains_or_insert(key),
2092 std::runtime_error);
2093 break;
2094 case 3:
2095 EXPECT_THROW((void) table[key], std::runtime_error);
2096 break;
2097 default: // moved in: the only copy is the one made to grow
2098 EXPECT_THROW((void) table.insert(Fragile_Key(5)),
2099 std::runtime_error);
2100 break;
2101 }
2102 }
2103
2104 EXPECT_EQ(this->keys_of(table), keys) << "operation " << operation;
2105 EXPECT_EQ(table.size(), 5u) << "operation " << operation;
2106 EXPECT_EQ(table.capacity(), 11u) << "operation " << operation;
2107 EXPECT_FALSE(table.contains(key)) << "operation " << operation;
2108 EXPECT_EQ(this->probes_of(table), probes)
2109 << "operation " << operation;
2110
2111 ASSERT_NE(table.insert(key), nullptr);
2112 EXPECT_GT(table.capacity(), 11u);
2113 for (long k = 0; k < 6; ++k)
2114 EXPECT_TRUE(table.contains(Fragile_Key(k))) << "key " << k;
2115 }
2116 }
2117
2118 // A search that reaches an empty bucket stops there. An insertion that
2119 // threw left the bucket it had reserved as the one of a removed key, so
2120 // a few of them could use up the empty buckets of a table far from full.
2121 TYPED_TEST(OpenTableInsertionThatThrows, FailuresDoNotUseUpEmptyBuckets)
2122 {
2123 TypeParam table = this->make(11, 0.35f, true);
2124 for (const long k : {1L, 3L, 5L})
2125 ASSERT_NE(table.insert(Fragile_Key(k)), nullptr);
2126 ASSERT_EQ(table.capacity(), 11u); // a fourth key makes it grow
2127 const auto probes = this->probes_of(table);
2128 const size_t empty = table.stats().num_empty;
2129
2130 // each key goes to an empty bucket that a busy one follows
2131 for (const long k : {0L, 2L, 4L})
2132 {
2133 const Fragile_Key key(k);
2134 {
2135 Failing_Copies failing; // the copy into the bucket fails
2136 EXPECT_THROW((void) table.insert(key), std::runtime_error)
2137 << "key " << k;
2138 }
2139 {
2140 Failing_Copies failing(1); // the copy made to grow fails
2141 EXPECT_THROW((void) table.insert(key), std::runtime_error)
2142 << "key " << k;
2143 }
2144 }
2145
2146 EXPECT_EQ(table.size(), 3u);
2147 EXPECT_EQ(table.capacity(), 11u);
2148 EXPECT_EQ(table.stats().num_empty, empty);
2149 EXPECT_EQ(this->probes_of(table), probes);
2150 }
2151
2152 // When the buckets of removed keys take the table to its upper threshold
2153 // and the keys are few, the insertion rebuilds it in place, which copies
2154 // the key once more. If that copy fails, the key is taken out again.
2155 TYPED_TEST(OpenTableInsertionThatThrows, RebuildInPlaceThatFailsTakesTheKeyOutAgain)
2156 {
2157 // 60 removed keys' buckets and 30 keys: 90 buckets in use of 101
2158 TypeParam table = with_removed_keys<TypeParam>(60);
2159 for (long b = 62; b < 91; ++b)
2160 ASSERT_NE(table.insert(Fragile_Key(1000*b + 999)), nullptr);
2161 ASSERT_EQ(table.stats().num_deleted, 60u);
2162 const auto keys = this->keys_of(table);
2163 const auto probes = this->probes_of(table);
2164
2165 // the 91st bucket in use takes the table over 0.9, with 31 keys
2166 const Fragile_Key key(1000*91 + 999);
2167 {
2168 // the copy into the bucket succeeds; the one made to rebuild fails
2169 Failing_Copies failing(1);
2170 EXPECT_THROW((void) table.insert(key), std::runtime_error);
2171 }
2172 EXPECT_EQ(this->keys_of(table), keys);
2173 EXPECT_EQ(this->probes_of(table), probes);
2174 EXPECT_EQ(table.capacity(), 101u);
2175 EXPECT_FALSE(table.contains(key));
2176
2177 ASSERT_NE(table.insert(key), nullptr);
2178 EXPECT_EQ(table.capacity(), 101u);
2179 EXPECT_EQ(table.stats().num_deleted, 0u);
2180 EXPECT_EQ(table.size(), 31u);
2181 }
2182
2183 // A removed key's bucket that no probe sequence goes through is not
2184 // needed. When a failed insertion had reserved one, it is left empty,
2185 // and so are the unneeded removed keys' buckets right before it.
2186 TEST(OLhashTable, FailedInsertionClearsRemovedMarksNoOneNeeds)
2187 {
2188 OLhashTable<Fragile_Key> table(11, crowded_hash<Fragile_Key>,
2190 0.95f, false);
2191 for (const long k : {1L, 2L, 3L})
2192 ASSERT_NE(table.insert(Fragile_Key(k)), nullptr);
2193 table.remove(Fragile_Key(1));
2194 table.remove(Fragile_Key(2));
2195 ASSERT_EQ(table.stats().num_deleted, 2u);
2196
2197 {
2198 const Fragile_Key key(9); // its probe sequence starts at bucket 2
2199 Failing_Copies failing;
2200 EXPECT_THROW((void) table.insert(key), std::runtime_error);
2201 }
2202
2203 EXPECT_EQ(table.size(), 1u);
2204 EXPECT_TRUE(table.contains(Fragile_Key(3)));
2205 EXPECT_EQ(table.stats().num_deleted, 0u);
2206 EXPECT_EQ(table.stats().num_empty, 10u);
2207 }
2208
2209 // Real insertions and removals mixed with insertions that fail, checked
2210 // against a std::set.
2211 TYPED_TEST(OpenTableInsertionThatThrows, FailuresDoNotDisturbTheTable)
2212 {
2213 TypeParam table = this->make(11, 0.7f, true);
2214 std::set<long> oracle;
2215 std::mt19937 rng(20261013);
2216
2217 auto check = [&] (const int step)
2218 {
2219 ASSERT_EQ(table.size(), oracle.size()) << "step " << step;
2220 for (long k = 0; k < 150; ++k)
2221 ASSERT_EQ(table.contains(Fragile_Key(k)), oracle.count(k) == 1)
2222 << "key " << k << ", step " << step;
2223 };
2224
2225 for (int step = 0; step < 20000; ++step)
2226 {
2227 const long k = static_cast<long>(rng() % 150);
2228 const Fragile_Key key(k);
2229 switch (rng() % 5)
2230 {
2231 case 0: // a real insertion
2232 EXPECT_EQ(table.insert(key) != nullptr, oracle.insert(k).second);
2233 break;
2234 case 1: // a real removal
2235 if (oracle.erase(k) == 1)
2236 table.remove(key);
2237 else
2238 EXPECT_THROW(table.remove(key), std::domain_error);
2239 break;
2240 case 2: // the copy into the bucket fails
2241 {
2242 Failing_Copies failing;
2243 try
2244 {
2245 EXPECT_EQ(table.search_or_insert(key) != nullptr, true);
2246 EXPECT_EQ(oracle.count(k), 1u); // it was already there
2247 }
2248 catch (const std::runtime_error &)
2249 {
2250 EXPECT_EQ(oracle.count(k), 0u);
2251 }
2252 }
2253 break;
2254 default: // the copy made to grow fails, when the table grows
2255 {
2256 Failing_Copies failing(1);
2257 try
2258 {
2259 if (table.insert(key) != nullptr)
2260 oracle.insert(k);
2261 }
2262 catch (const std::runtime_error &)
2263 {
2264 EXPECT_EQ(oracle.count(k), 0u);
2265 }
2266 }
2267 break;
2268 }
2269 if (step % 500 == 0)
2270 check(step);
2271 }
2272 check(20000);
2273
2274 for (const long k : oracle)
2275 table.remove(Fragile_Key(k));
2276 EXPECT_TRUE(table.is_empty());
2277 }
2278
2279 template <class Table> struct OpenTableWithCopyOnlyKeys
2280 : public OpenTableInsertionThatThrows<Table> {};
2281
2282 using Tables_With_Copy_Only_Keys =
2283 ::testing::Types<OLhashTable<Copy_Only_Key>, ODhashTable<Copy_Only_Key>>;
2284 TYPED_TEST_SUITE(OpenTableWithCopyOnlyKeys, Tables_With_Copy_Only_Keys);
2285
2286 // A smaller table that cannot be built, here because copying a key into
2287 // it fails, leaves the table as it was: the key stays removed, and
2288 // neither remove() nor remove_ptr() throws.
2289 TYPED_TEST(OpenTableWithCopyOnlyKeys, ShrinkThatFailsKeepsTheCapacity)
2290 {
2291 using Key = typename TypeParam::Key_Type;
2292 TypeParam table = this->make(11, 0.95f, true);
2293 for (long k = 0; k < 1000; ++k)
2294 ASSERT_NE(table.insert(Key(k)), nullptr) << "key " << k;
2295 const size_t grown = table.capacity();
2296
2297 {
2298 Failing_Copies failing;
2299 for (long k = 0; k < 990; ++k)
2300 if (k % 2 == 0)
2301 ASSERT_NO_THROW(table.remove(Key(k))) << "key " << k;
2302 else
2303 ASSERT_NO_THROW(table.remove_ptr(table.search(Key(k)))) << "key " << k;
2304 }
2305 EXPECT_EQ(table.capacity(), grown);
2306 EXPECT_EQ(this->keys_of(table).size(), 10u);
2307 for (long k = 990; k < 1000; ++k)
2308 EXPECT_TRUE(table.contains(Key(k))) << "key " << k;
2309
2310 // once the keys can be copied, the next removal shrinks it
2311 table.remove(Key(990));
2312 EXPECT_LT(table.capacity(), grown);
2313 for (long k = 991; k < 1000; ++k)
2314 EXPECT_TRUE(table.contains(Key(k))) << "key " << k;
2315 }
2316
2317 // The insertions that take the key by rvalue swap it into the bucket. A
2318 // swap that can throw could leave both the table and the argument
2319 // broken, so such a key is copied, and the copy that fails is undone.
2320 TYPED_TEST(OpenTableWithCopyOnlyKeys, MovedInKeyThatThrowsLeavesNoEntry)
2321 {
2322 for (const bool resizes : {false, true})
2323 {
2324 TypeParam table = this->with_keys_and_removals(resizes);
2325 const auto keys = this->keys_of(table);
2326 const auto probes = this->probes_of(table);
2327
2328 for (long k = 0; k < 60; ++k)
2329 for (int operation = 0; operation < 3; ++operation)
2330 {
2331 Copy_Only_Key key(k);
2332 const bool present = table.contains(key);
2333 bool threw = false;
2334 {
2335 Failing_Copies failing;
2336 try
2337 {
2338 switch (operation)
2339 {
2340 case 0: (void) table.insert(std::move(key)); break;
2341 case 1:
2342 (void) table.search_or_insert(std::move(key));
2343 break;
2344 default:
2345 (void) table.contains_or_insert(std::move(key));
2346 break;
2347 }
2348 }
2349 catch (const std::runtime_error &)
2350 {
2351 threw = true;
2352 }
2353 }
2354 ASSERT_EQ(threw, not present)
2355 << "key " << k << ", operation " << operation;
2356 ASSERT_EQ(key.value, k) << "the argument was not touched";
2357 ASSERT_EQ(this->keys_of(table), keys)
2358 << "key " << k << ", operation " << operation;
2359 ASSERT_EQ(this->probes_of(table), probes)
2360 << "key " << k << ", operation " << operation;
2361 }
2362
2363 for (long k = 20; k < 28; ++k)
2364 EXPECT_NE(table.insert(Copy_Only_Key(k)), nullptr) << "key " << k;
2365 for (long k = 20; k < 28; ++k)
2366 EXPECT_TRUE(table.contains(Copy_Only_Key(k))) << "key " << k;
2367 }
2368 }
2369
2370 // Growing places the keys in new buckets, and such keys are copied there.
2371 // A copy that failed halfway left the table with the keys placed so far:
2372 // the others were lost, and the old buckets leaked.
2373 TYPED_TEST(OpenTableWithCopyOnlyKeys, GrowthThatFailsHalfwayLeavesTheTable)
2374 {
2375 // the key is copied into its bucket and once more before growing; the
2376 // next 6 copies place the 6 keys in the new buckets
2377 for (size_t successful = 2; successful < 8; ++successful)
2378 {
2379 TypeParam table = this->make(11, 0.5f, true);
2380 for (long k = 0; k < 5; ++k)
2381 ASSERT_NE(table.insert(Copy_Only_Key(k)), nullptr);
2382 ASSERT_EQ(table.capacity(), 11u); // the sixth key makes it grow
2383 const auto keys = this->keys_of(table);
2384 const auto probes = this->probes_of(table);
2385
2386 const Copy_Only_Key key(5);
2387 {
2388 Failing_Copies failing(successful);
2389 EXPECT_THROW((void) table.insert(key), std::runtime_error)
2390 << successful << " copies";
2391 }
2392
2393 EXPECT_EQ(this->keys_of(table), keys) << successful << " copies";
2394 EXPECT_EQ(table.size(), 5u) << successful << " copies";
2395 EXPECT_EQ(table.capacity(), 11u) << successful << " copies";
2396 EXPECT_EQ(this->probes_of(table), probes) << successful << " copies";
2397
2398 ASSERT_NE(table.insert(key), nullptr);
2399 EXPECT_GT(table.capacity(), 11u);
2400 for (long k = 0; k < 6; ++k)
2401 EXPECT_TRUE(table.contains(Copy_Only_Key(k))) << "key " << k;
2402 }
2403 }
2404
2405 // rehash() and resize() place the keys in new buckets the same way.
2406 TYPED_TEST(OpenTableWithCopyOnlyKeys, RebuildThatFailsLeavesTheTable)
2407 {
2408 TypeParam table = this->with_keys_and_removals(false);
2409 const auto keys = this->keys_of(table);
2410 const auto probes = this->probes_of(table);
2411 const size_t capacity = table.capacity();
2412 const size_t larger = Primes::next_prime(2 * capacity);
2413
2414 for (size_t successful = 0; successful < keys.size(); ++successful)
2415 {
2416 {
2417 Failing_Copies failing(successful);
2418 EXPECT_THROW(table.rehash(), std::runtime_error) << successful;
2419 }
2420 ASSERT_EQ(this->keys_of(table), keys) << successful;
2421 ASSERT_EQ(this->probes_of(table), probes) << successful;
2422 ASSERT_EQ(table.capacity(), capacity) << successful;
2423
2424 {
2425 Failing_Copies failing(successful);
2426 EXPECT_THROW((void) table.resize(larger), std::runtime_error)
2427 << successful;
2428 }
2429 ASSERT_EQ(this->keys_of(table), keys) << successful;
2430 ASSERT_EQ(this->probes_of(table), probes) << successful;
2431 ASSERT_EQ(table.capacity(), capacity) << successful;
2432 }
2433
2434 table.rehash();
2435 EXPECT_EQ(this->keys_of(table), keys);
2436 EXPECT_EQ(table.stats().num_deleted, 0u);
2437 EXPECT_EQ(table.resize(larger), larger);
2438 EXPECT_EQ(this->keys_of(table), keys);
2439 }
2440
2441 // -------------------------------------------------------------------------
2442 // A table that does not resize itself is full with capacity() - 1 keys
2443 // -------------------------------------------------------------------------
2444
2445 template <class Table> struct OpenTableWithoutResizing
2446 : public ::testing::Test
2447 {
2448 static Table make(const size_t len)
2449 {
2450 if constexpr (requires (Table & t) { t.get_second_hash_fct(); })
2451 return Table(len, Aleph::dft_hash_ptr_fct<long>,
2452 Aleph::snd_hash_ptr_fct<long>, Aleph::equal_to<long>(),
2454 else
2455 return Table(len, Aleph::dft_hash_ptr_fct<long>, Aleph::equal_to<long>(),
2457 }
2458
2459 // Inserts keys 0, 1, 2... until the table refuses one, and returns how
2460 // many it took.
2461 static size_t fill(Table & table)
2462 {
2463 size_t taken = 0;
2464 for (long k = 0; k < 1000 and table.insert(k) != nullptr; ++k)
2465 ++taken;
2466 return taken;
2467 }
2468 };
2469
2470 using Open_Tables_Of_Longs =
2471 ::testing::Types<OLhashTable<long>, ODhashTable<long>>;
2472 TYPED_TEST_SUITE(OpenTableWithoutResizing, Open_Tables_Of_Longs);
2473
2474 // A search that misses stops at an empty bucket, so the table keeps one.
2475 // It used to take a key in every bucket, and the double hashing table
2476 // then failed an assertion on the next insertion.
2477 TYPED_TEST(OpenTableWithoutResizing, KeepsOneBucketEmpty)
2478 {
2479 TypeParam table = this->make(11);
2480 ASSERT_EQ(table.capacity(), 11u);
2481
2482 EXPECT_EQ(this->fill(table), 10u);
2483 EXPECT_EQ(table.size(), 10u);
2484 EXPECT_EQ(table.capacity(), 11u);
2485 EXPECT_EQ(table.stats().num_empty, 1u);
2486
2487 const long absent = 500;
2488 EXPECT_EQ(table.insert(absent), nullptr);
2489 EXPECT_EQ(table.insert(long(absent)), nullptr);
2490 EXPECT_FALSE(table.contains(absent));
2491 EXPECT_EQ(table.size(), 10u);
2492
2493 // a removal makes room for one key
2494 table.remove(3L);
2495 EXPECT_NE(table.insert(absent), nullptr);
2496 EXPECT_EQ(table.insert(3L), nullptr);
2497 EXPECT_EQ(table.size(), 10u);
2498 EXPECT_EQ(table.stats().num_busy, 10u);
2499 }
2500
2501 // A full table still finds the keys it has, and refuses the others.
2502 // operator[] dereferenced the null pointer that it got for a new key.
2503 TYPED_TEST(OpenTableWithoutResizing, FullTableFindsItsKeysAndRefusesNewOnes)
2504 {
2505 TypeParam table = this->make(11);
2506 ASSERT_EQ(this->fill(table), 10u);
2507 const long present = 3, absent = 500;
2508 long * const stored = table.search(present);
2509 ASSERT_NE(stored, nullptr);
2510
2511 EXPECT_EQ(table.search_or_insert(present), stored);
2512 EXPECT_EQ(table.search_or_insert(long(present)), stored);
2513 EXPECT_EQ(table.contains_or_insert(present),
2514 std::make_pair(stored, true));
2515 EXPECT_EQ(table.contains_or_insert(long(present)),
2516 std::make_pair(stored, true));
2517 EXPECT_EQ(&table[present], stored);
2518
2519 EXPECT_EQ(table.search_or_insert(absent), nullptr);
2520 EXPECT_EQ(table.search_or_insert(long(absent)), nullptr);
2521 EXPECT_EQ(table.contains_or_insert(absent),
2522 std::make_pair(static_cast<long *>(nullptr), false));
2523 EXPECT_EQ(table.contains_or_insert(long(absent)),
2524 std::make_pair(static_cast<long *>(nullptr), false));
2525 EXPECT_THROW((void) table[absent], std::overflow_error);
2526
2527 EXPECT_EQ(table.size(), 10u);
2528 EXPECT_FALSE(table.contains(absent));
2529 }
2530
2531 template <class Map> struct OpenMapWithoutResizing : public ::testing::Test
2532 {};
2533
2534 using Open_Maps = ::testing::Types<MapOLhash<long, int>, MapODhash<long, int>>;
2535 TYPED_TEST_SUITE(OpenMapWithoutResizing, Open_Maps);
2536
2537 // The maps over open tables index through search_or_insert() too.
2538 TYPED_TEST(OpenMapWithoutResizing, SubscriptOnAFullMapThrows)
2539 {
2540 TypeParam map(11, Aleph::dft_hash_ptr_fct<long>,
2541 Aleph::snd_hash_ptr_fct<long>, Aleph::equal_to<long>(),
2543 for (long k = 0; k < 10; ++k)
2544 ASSERT_NE(map.insert(k, static_cast<int>(k)), nullptr) << "key " << k;
2545 EXPECT_EQ(map.insert(10L, 10), nullptr); // full
2546
2547 map[3L] = 30;
2548 const long present = 4;
2549 map[present] = 40;
2550 EXPECT_EQ(map.find(3L), 30);
2551 EXPECT_EQ(map.find(4L), 40);
2552
2553 const long absent = 500;
2554 EXPECT_THROW((void) map[absent], std::overflow_error);
2555 EXPECT_THROW((void) map[501L], std::overflow_error);
2556 EXPECT_EQ(map.size(), 10u);
2557 EXPECT_FALSE(map.contains(absent));
2558 }
2559
2560 template <class Map> struct OpenMapShrinking : public ::testing::Test
2561 {};
2562
2563 TYPED_TEST_SUITE(OpenMapShrinking, Open_Maps);
2564
2565 // The maps remove through the remove() of their table, which did not
2566 // shrink it.
2567 TYPED_TEST(OpenMapShrinking, RemoveShrinksTheMap)
2568 {
2569 TypeParam map(11, Aleph::dft_hash_ptr_fct<long>,
2570 Aleph::snd_hash_ptr_fct<long>, Aleph::equal_to<long>(),
2572 for (long k = 0; k < 1000; ++k)
2573 ASSERT_NE(map.insert(k, static_cast<int>(k)), nullptr) << "key " << k;
2574 const size_t grown = map.capacity();
2575
2576 for (long k = 0; k < 990; ++k)
2577 map.remove(k);
2578
2579 EXPECT_LT(map.capacity(), grown / 4);
2580 EXPECT_EQ(map.size(), 10u);
2581 for (long k = 990; k < 1000; ++k)
2582 EXPECT_EQ(map.find(k), static_cast<int>(k)) << "key " << k;
2583 }
2584
2585 // -------------------------------------------------------------------------
2586 // Shrinking leaves the keys under the upper threshold
2587 // -------------------------------------------------------------------------
2588
2589 template <class Table> struct OpenTableShrinking : public ::testing::Test
2590 {
2591 static Table make(const size_t len, const float lower, const float upper)
2592 {
2593 if constexpr (requires (Table & t) { t.get_second_hash_fct(); })
2594 return Table(len, Aleph::dft_hash_ptr_fct<long>,
2595 Aleph::snd_hash_ptr_fct<long>, Aleph::equal_to<long>(),
2596 lower, upper, true);
2597 else
2598 return Table(len, Aleph::dft_hash_ptr_fct<long>, Aleph::equal_to<long>(),
2599 lower, upper, true);
2600 }
2601 };
2602
2603 TYPED_TEST_SUITE(OpenTableShrinking, Open_Tables_Of_Longs);
2604
2605 // With a lower threshold over one half, a table of half the capacity may
2606 // not hold the keys. remove_ptr() removed the key and then resize()
2607 // threw std::overflow_error. Now the table waits until the keys fit.
2608 TYPED_TEST(OpenTableShrinking, KeysFitInTheSmallerTable)
2609 {
2610 TypeParam table = this->make(101, 0.6f, 0.9f);
2611 for (long k = 0; k < 60; ++k)
2612 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
2613 ASSERT_EQ(table.capacity(), 101u);
2614
2615 for (long k = 0; k < 55; ++k)
2616 {
2617 ASSERT_NO_THROW(table.remove_ptr(table.search(k))) << "key " << k;
2618 ASSERT_FALSE(table.contains(k)) << "key " << k;
2619 ASSERT_EQ(table.size(), static_cast<size_t>(59 - k));
2620 ASSERT_LT(table.current_alpha(), 0.9f) << "key " << k;
2621 ASSERT_LT(table.size(), table.capacity()) << "key " << k;
2622 }
2623
2624 EXPECT_LT(table.capacity(), 101u); // it shrank once the keys fitted
2625 for (long k = 55; k < 60; ++k)
2626 EXPECT_TRUE(table.contains(k)) << "key " << k;
2627 }
2628
2629 // A smaller table where the keys leave exactly one bucket empty is good
2630 // enough: 6 keys fit in 7 buckets under 0.9.
2631 TYPED_TEST(OpenTableShrinking, ShrinksWhenTheKeysLeaveOneBucketEmpty)
2632 {
2633 TypeParam table = this->make(11, 0.6f, 0.9f);
2634 for (long k = 0; k < 7; ++k)
2635 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
2636 ASSERT_EQ(table.capacity(), 11u);
2637
2638 table.remove_ptr(table.search(0L));
2639
2640 EXPECT_EQ(table.capacity(), 7u);
2641 EXPECT_EQ(table.size(), 6u);
2642 EXPECT_EQ(table.stats().num_empty, 1u);
2643 for (long k = 1; k < 7; ++k)
2644 EXPECT_TRUE(table.contains(k)) << "key " << k;
2645 }
2646
2647 // With the default thresholds the table still shrinks as before.
2648 TYPED_TEST(OpenTableShrinking, DefaultThresholdsStillShrink)
2649 {
2650 TypeParam table = this->make(11, hash_default_lower_alpha,
2652 for (long k = 0; k < 1000; ++k)
2653 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
2654 const size_t grown = table.capacity();
2655
2656 for (long k = 0; k < 990; ++k)
2657 table.remove_ptr(table.search(k));
2658
2659 EXPECT_LT(table.capacity(), grown / 4);
2660 EXPECT_EQ(table.size(), 10u);
2661 for (long k = 990; k < 1000; ++k)
2662 EXPECT_TRUE(table.contains(k)) << "key " << k;
2663 }
2664
2665 // Only remove_ptr() shrank the table; remove() left it as large as it
2666 // had grown.
2667 TYPED_TEST(OpenTableShrinking, RemoveShrinksTooWhileTheTableResizes)
2668 {
2669 TypeParam table = this->make(11, hash_default_lower_alpha,
2671 for (long k = 0; k < 1000; ++k)
2672 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
2673 const size_t grown = table.capacity();
2674
2675 // turned off, the table keeps its capacity and its keys do not move
2676 table.set_with_resize(false);
2677 EXPECT_FALSE(table.get_with_resize());
2678 for (long k = 0; k < 900; ++k)
2679 table.remove(k);
2680 EXPECT_EQ(table.capacity(), grown);
2681
2682 table.set_with_resize(true);
2683 EXPECT_TRUE(table.get_with_resize());
2684 for (long k = 900; k < 990; ++k)
2685 table.remove(k);
2686 EXPECT_LT(table.capacity(), grown / 4);
2687 EXPECT_EQ(table.size(), 10u);
2688 for (long k = 990; k < 1000; ++k)
2689 EXPECT_TRUE(table.contains(k)) << "key " << k;
2690 }
2691
2692 // With a lower threshold over one half, remove() also waits until the
2693 // keys fit in the smaller table.
2694 TYPED_TEST(OpenTableShrinking, RemoveWaitsUntilTheKeysFit)
2695 {
2696 TypeParam table = this->make(101, 0.6f, 0.9f);
2697 for (long k = 0; k < 60; ++k)
2698 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
2699 ASSERT_EQ(table.capacity(), 101u);
2700
2701 for (long k = 0; k < 55; ++k)
2702 {
2703 ASSERT_NO_THROW(table.remove(k)) << "key " << k;
2704 ASSERT_EQ(table.size(), static_cast<size_t>(59 - k));
2705 ASSERT_LT(table.current_alpha(), 0.9f) << "key " << k;
2706 ASSERT_LT(table.size(), table.capacity()) << "key " << k;
2707 }
2708
2709 EXPECT_LT(table.capacity(), 101u);
2710 for (long k = 55; k < 60; ++k)
2711 EXPECT_TRUE(table.contains(k)) << "key " << k;
2712 }
2713
2714 // The del() of an iterator does not shrink the table, which would leave
2715 // the iterator on buckets that are gone.
2716 TYPED_TEST(OpenTableShrinking, IteratorDelDoesNotShrink)
2717 {
2718 TypeParam table = this->make(11, hash_default_lower_alpha,
2720 for (long k = 0; k < 1000; ++k)
2721 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
2722 const size_t grown = table.capacity();
2723
2724 auto it = table.get_it();
2725 for (size_t deleted = 0; deleted < 990; ++deleted)
2726 {
2727 ASSERT_TRUE(it.has_curr());
2728 it.del();
2729 }
2730
2731 EXPECT_EQ(table.capacity(), grown);
2732 EXPECT_EQ(table.size(), 10u);
2733 }
2734
2735 // A table built without resizing grows once it is turned on: the change
2736 // applies from the next insertion.
2737 TYPED_TEST(OpenTableShrinking, TurningResizingOnLetsAFullTableGrow)
2738 {
2739 TypeParam table = this->make(11, hash_default_lower_alpha,
2741 EXPECT_TRUE(table.get_with_resize());
2742 table.set_with_resize(false);
2743 for (long k = 0; k < 10; ++k)
2744 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
2745 EXPECT_EQ(table.insert(10L), nullptr); // full
2746
2747 table.set_with_resize(true);
2748 ASSERT_NE(table.insert(10L), nullptr);
2749 EXPECT_GT(table.capacity(), 11u);
2750 for (long k = 0; k <= 10; ++k)
2751 EXPECT_TRUE(table.contains(k)) << "key " << k;
2752 }
2753
2754 // -------------------------------------------------------------------------
2755 // The buckets of removed keys count as used
2756 // -------------------------------------------------------------------------
2757
2758 // A removed key's bucket stays marked while a search may have to go
2759 // through it, so it is not empty. Those buckets did not count to grow or
2760 // fill the table: insertions and removals could leave it without an empty
2761 // bucket, where the searches stop, far from its upper threshold.
2762
2763 size_t colliding_hash(const long & k) noexcept
2764 {
2765 return static_cast<size_t>(k);
2766 }
2767
2768 size_t colliding_second_hash(const long & k) noexcept
2769 {
2770 return static_cast<size_t>(k / 7 + k % 5);
2771 }
2772
2773 template <class Table> struct OpenTableRemovedKeys : public ::testing::Test
2774 {
2775 static Table make(const size_t len, const bool resizes)
2776 {
2777 if constexpr (requires (Table & t) { t.get_second_hash_fct(); })
2778 return Table(len, colliding_hash, colliding_second_hash,
2779 Aleph::equal_to<long>(), 0.05f, 0.9f, resizes);
2780 else
2781 return Table(len, colliding_hash, Aleph::equal_to<long>(),
2782 0.05f, 0.9f, resizes);
2783 }
2784
2785 // Whether the buckets in use, those of removed keys included, are
2786 // under the upper threshold of 0.9, computed as the table does.
2787 static bool under_threshold(const Table & table)
2788 {
2789 const auto stats = table.stats();
2790 return 1.0f*(stats.num_busy + stats.num_deleted)/table.capacity() < 0.9f;
2791 }
2792
2793 static ::testing::AssertionResult holds(const Table & table,
2794 const std::set<long> & keys)
2795 {
2796 if (table.size() != keys.size())
2797 return ::testing::AssertionFailure()
2798 << "size is " << table.size() << ", expected " << keys.size();
2799 for (const long k : keys)
2800 if (not table.contains(k))
2801 return ::testing::AssertionFailure() << "key " << k << " not found";
2802 return ::testing::AssertionSuccess();
2803 }
2804 };
2805
2806 TYPED_TEST_SUITE(OpenTableRemovedKeys, Open_Tables_Of_Longs);
2807
2808 // Insertions and removals of a few keys that collide a lot, in small
2809 // tables. Both tables used to end without empty buckets.
2810 TYPED_TEST(OpenTableRemovedKeys, ResizingTableStaysUnderItsThreshold)
2811 {
2812 std::mt19937 rng(20261018);
2813 for (int trial = 0; trial < 300; ++trial)
2814 {
2815 TypeParam table = this->make(11, true);
2816 std::set<long> keys;
2817 for (int step = 0; step < 300; ++step)
2818 {
2819 const long k = static_cast<long>(rng() % 200);
2820 if (keys.count(k) == 0)
2821 {
2822 ASSERT_NE(table.insert(k), nullptr);
2823 keys.insert(k);
2824 }
2825 else
2826 {
2827 table.remove(k);
2828 keys.erase(k);
2829 }
2830 ASSERT_GT(table.stats().num_empty, 0u)
2831 << "trial " << trial << ", step " << step;
2832 ASSERT_TRUE(this->under_threshold(table))
2833 << "trial " << trial << ", step " << step;
2834 }
2835 ASSERT_TRUE(this->holds(table, keys)) << "trial " << trial;
2836 }
2837 }
2838
2839 // A table that does not resize itself is never rebuilt by itself, so
2840 // that the pointers to its keys stay valid: it keeps its capacity, takes
2841 // keys until it holds capacity() - 1, and never moves one.
2842 TYPED_TEST(OpenTableRemovedKeys, FixedTableNeverMovesItsKeys)
2843 {
2844 std::mt19937 rng(20261018);
2845 for (int trial = 0; trial < 300; ++trial)
2846 {
2847 TypeParam table = this->make(11, false);
2848 std::map<long, long *> keys; // and where each one is
2849 for (int step = 0; step < 300; ++step)
2850 {
2851 const long k = static_cast<long>(rng() % 200);
2852 if (keys.count(k) == 0)
2853 {
2854 long * const stored = table.insert(k);
2855 const bool full = keys.size() == 10;
2856 ASSERT_EQ(stored == nullptr, full)
2857 << "trial " << trial << ", step " << step;
2858 if (not full)
2859 keys[k] = stored;
2860 }
2861 else
2862 {
2863 table.remove(k);
2864 keys.erase(k);
2865 ASSERT_EQ(table.search(k), nullptr);
2866 }
2867 ASSERT_EQ(table.capacity(), 11u);
2868 ASSERT_EQ(table.size(), keys.size());
2869 for (const auto & [key, where] : keys)
2870 ASSERT_EQ(table.search(key), where)
2871 << "key " << key << " moved, trial " << trial << ", step " << step;
2872 }
2873 }
2874 }
2875
2876 // 60 removed keys' buckets and 30 keys put 90 buckets in use, of 101.
2877 // The next key takes them over 0.9 with 31 keys, under half of it, and
2878 // the table is rebuilt in place.
2879 TYPED_TEST(OpenTableRemovedKeys, RebuildsInPlaceWhileTheKeysAreFew)
2880 {
2881 TypeParam table = with_removed_keys<TypeParam>(60);
2882 std::set<long> keys = {1002};
2883 for (long b = 62; b <= 91; ++b)
2884 {
2885 ASSERT_EQ(table.stats().num_deleted, 60u) << "bucket " << b;
2886 ASSERT_NE(table.insert(1000*b + 999), nullptr) << "bucket " << b;
2887 keys.insert(1000*b + 999);
2888 }
2889
2890 EXPECT_EQ(table.capacity(), 101u);
2891 EXPECT_EQ(table.stats().num_deleted, 0u);
2892 EXPECT_TRUE(this->holds(table, keys));
2893 }
2894
2895 // With 40 removed keys' buckets it takes 51 keys, over half of the
2896 // threshold, to get there: the table doubles.
2897 TYPED_TEST(OpenTableRemovedKeys, GrowsWhenTheKeysAreMany)
2898 {
2899 TypeParam table = with_removed_keys<TypeParam>(40);
2900 std::set<long> keys = {1002};
2901 for (long b = 42; b <= 91; ++b)
2902 {
2903 ASSERT_EQ(table.capacity(), 101u) << "bucket " << b;
2904 ASSERT_NE(table.insert(1000*b + 999), nullptr) << "bucket " << b;
2905 keys.insert(1000*b + 999);
2906 }
2907
2908 EXPECT_GT(table.capacity(), 101u);
2909 EXPECT_EQ(table.stats().num_deleted, 0u);
2910 EXPECT_TRUE(this->holds(table, keys));
2911 }
2912
2913 // Each key replaces the oldest one, so that the removed keys' buckets
2914 // are left behind, followed by busy ones. With 30 keys the linear probing
2915 // table is rebuilt in place, again and again; with 60 it doubles.
2916 TEST(OLhashTable, RemovedKeysRebuildItInPlaceWhileTheKeysAreFew)
2917 {
2918 for (const size_t num_keys : {size_t(30), size_t(60)})
2919 {
2920 OLhashTable<long> table(101, colliding_hash, Aleph::equal_to<long>(),
2921 0.05f, 0.9f, true);
2922 std::deque<long> order;
2923 size_t rebuilt_in_place = 0;
2924 for (long k = 0; k < 3000; ++k)
2925 {
2926 const size_t capacity = table.capacity();
2927 const size_t deleted = table.stats().num_deleted;
2928 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
2929 if (table.capacity() == capacity and deleted > 1
2930 and table.stats().num_deleted == 0)
2931 ++rebuilt_in_place;
2932 order.push_back(k);
2933 if (order.size() > num_keys)
2934 {
2935 table.remove(order.front());
2936 order.pop_front();
2937 }
2938 const auto stats = table.stats();
2939 ASSERT_LT(1.0f*(stats.num_busy + stats.num_deleted)/table.capacity(),
2940 0.9f) << "key " << k;
2941 }
2942
2943 EXPECT_EQ(table.size(), num_keys);
2944 for (const long k : order)
2945 EXPECT_TRUE(table.contains(k)) << "key " << k;
2946 if (num_keys == 30)
2947 {
2948 EXPECT_GT(rebuilt_in_place, 1u);
2949 EXPECT_EQ(table.capacity(), 101u);
2950 }
2951 else
2952 EXPECT_GT(table.capacity(), 101u);
2953 }
2954 }
2955
2956 // -------------------------------------------------------------------------
2957 // The iterator deletes the last key
2958 // -------------------------------------------------------------------------
2959
2960 template <class Table> struct OpenTableIteratorDel : public ::testing::Test
2961 {};
2962
2963 TYPED_TEST_SUITE(OpenTableIteratorDel, Open_Tables_Of_Longs);
2964
2965 // Deleting the last key in bucket order, with other keys before it, went
2966 // on looking for the next busy bucket past the end of the array.
2967 TYPED_TEST(OpenTableIteratorDel, DeletingTheLastKeyLeavesTheIteratorAtTheEnd)
2968 {
2969 // the keys go to buckets 2 and 9 of 11
2970 TypeParam table = OpenTableRemovedKeys<TypeParam>::make(11, false);
2971 ASSERT_NE(table.insert(2L), nullptr);
2972 ASSERT_NE(table.insert(9L), nullptr);
2973
2974 auto it = table.get_it();
2975 ASSERT_EQ(it.get_curr(), 2L);
2976 it.next();
2977 ASSERT_EQ(it.get_curr(), 9L);
2978 it.del();
2979
2980 EXPECT_FALSE(it.has_curr());
2981 EXPECT_EQ(table.size(), 1u);
2982 EXPECT_FALSE(table.contains(9L));
2983 it.prev();
2984 ASSERT_TRUE(it.has_curr());
2985 EXPECT_EQ(it.get_curr(), 2L);
2986 }
2987
2988 // -------------------------------------------------------------------------
2989 // Random operations on small open addressing tables, against an oracle
2990 // -------------------------------------------------------------------------
2991
2992 template <class Table> struct OpenTableRandomOperations : public ::testing::Test
2993 {
2994 static Table make(const size_t len, const float lower, const float upper,
2995 const bool resizes)
2996 {
2997 if constexpr (requires (Table & t) { t.get_second_hash_fct(); })
2998 return Table(len, colliding_hash, colliding_second_hash,
2999 Aleph::equal_to<long>(), lower, upper, resizes);
3000 else
3001 return Table(len, colliding_hash, Aleph::equal_to<long>(),
3002 lower, upper, resizes);
3003 }
3004 };
3005
3006 TYPED_TEST_SUITE(OpenTableRandomOperations, Open_Tables_Of_Longs);
3007
3008 // Every way of inserting and removing, with the resizing turned on and
3009 // off at random, on tables of a few buckets where most keys collide and
3010 // the buckets of removed keys may take all the empty ones. After each
3011 // step the table holds the oracle's keys. While it does not resize
3012 // itself, its capacity and the places of its keys stay, and it refuses a
3013 // new key only when full. While it resizes itself, an insertion of a new
3014 // key leaves its buckets in use under the upper threshold, and a removal
3015 // shrinks it to the prime after half its capacity exactly when the keys
3016 // fit there.
3017 TYPED_TEST(OpenTableRandomOperations, AgreesWithAnOracle)
3018 {
3019 const std::pair<float, float> thresholds[] =
3020 {{0.05f, 0.9f}, {0.25f, 0.9f}, {0.6f, 0.9f}, {0.85f, 0.9f}, {0.01f, 0.99f}};
3021 const size_t lens[] = {2, 3, 5, 7, 11, 13};
3022 std::mt19937 rng(20261021);
3023 for (int trial = 0; trial < 400; ++trial)
3024 {
3025 const auto [lower, upper] = thresholds[rng() % 5];
3026 TypeParam table = this->make(lens[rng() % 6], lower, upper,
3027 rng() % 2 == 0);
3028 std::set<long> oracle;
3029 std::map<long, const long *> places; // kept while it does not resize
3030 for (int step = 0; step < 300; ++step)
3031 {
3032 const auto where = [&] { return ::testing::Message()
3033 << "trial " << trial << ", step " << step; };
3034 const long k = static_cast<long>(rng() % 40);
3035 const unsigned op = rng() % 10;
3036 const bool resizes = table.get_with_resize();
3037 const size_t capacity = table.capacity();
3038 const bool present = oracle.count(k) > 0;
3039 const bool full = table.size() + 1 == capacity;
3040
3041 if (op < 4) // an insertion, of one of four kinds
3042 {
3043 long * stored = nullptr;
3044 bool found = false;
3045 if (op == 0)
3046 stored = table.insert(k);
3047 else if (op == 1)
3048 {
3049 long copy = k;
3050 stored = table.insert(std::move(copy));
3051 }
3052 else if (op == 2)
3053 {
3054 stored = table.search_or_insert(k);
3055 found = present and stored != nullptr;
3056 }
3057 else
3058 std::tie(stored, found) = table.contains_or_insert(k);
3059
3060 if (present)
3061 {
3062 if (op < 2)
3063 ASSERT_EQ(stored, nullptr) << where();
3064 else
3065 {
3066 ASSERT_NE(stored, nullptr) << where();
3067 ASSERT_TRUE(found) << where();
3068 }
3069 }
3070 else if (full and not resizes)
3071 {
3072 ASSERT_EQ(stored, nullptr) << where();
3073 ASSERT_FALSE(found) << where();
3074 }
3075 else
3076 {
3077 ASSERT_NE(stored, nullptr) << where();
3078 ASSERT_FALSE(found) << where();
3079 ASSERT_EQ(*stored, k) << where();
3080 oracle.insert(k);
3081 if (not resizes)
3082 places[k] = stored;
3083 else // an insertion rebuilds the table at the threshold
3084 {
3085 const auto stats = table.stats();
3086 ASSERT_LT(1.0f*(stats.num_busy + stats.num_deleted)
3087 /table.capacity(), upper) << where();
3088 }
3089 }
3090 }
3091 else if (op < 8) // a removal, by key or by pointer
3092 {
3093 if (not present)
3094 {
3095 if (op < 6)
3096 {
3097 ASSERT_THROW(table.remove(k), std::domain_error) << where();
3098 }
3099 ASSERT_EQ(table.capacity(), capacity) << where();
3100 }
3101 else
3102 {
3103 if (op < 6)
3104 table.remove(k);
3105 else
3106 table.remove_ptr(table.search(k));
3107 oracle.erase(k);
3108 places.erase(k);
3109
3110 const size_t n = oracle.size();
3111 const size_t smaller = Primes::next_prime(capacity / 2 + 1);
3112 const bool shrinks = resizes and 1.0f*n/capacity < lower
3113 and n < smaller and 1.0f*n/smaller < upper;
3114 ASSERT_EQ(table.capacity(), shrinks ? smaller : capacity)
3115 << where();
3116 }
3117 }
3118 else if (op == 8 and rng() % 4 == 0) // turn the resizing over
3119 {
3120 table.set_with_resize(not resizes);
3121 ASSERT_EQ(table.get_with_resize(), not resizes);
3122 if (resizes) // turned off: the keys stay from now on
3123 {
3124 places.clear();
3125 for (const long key : oracle)
3126 places[key] = table.search(key);
3127 }
3128 }
3129
3130 ASSERT_EQ(table.size(), oracle.size()) << where();
3131 ASSERT_LT(table.size(), table.capacity()) << where();
3132 for (long key = 0; key < 40; ++key)
3133 ASSERT_EQ(table.contains(key), oracle.count(key) > 0)
3134 << "key " << key << ", " << where();
3135 if (not table.get_with_resize() and not resizes)
3136 {
3137 ASSERT_EQ(table.capacity(), capacity) << where();
3138 for (const auto & [key, at] : places)
3139 ASSERT_EQ(table.search(key), at)
3140 << "key " << key << " moved, " << where();
3141 }
3142 }
3143
3144 std::set<long> listed;
3145 table.for_each([&listed] (const long key) { listed.insert(key); });
3146 EXPECT_EQ(listed, oracle) << "trial " << trial;
3147 }
3148 }
3149
3150 // -------------------------------------------------------------------------
3151 // Paths that no test went through
3152 // -------------------------------------------------------------------------
3153
3154 template <class Table> struct OpenTableEdges : public ::testing::Test
3155 {
3156 static Table fixed(const size_t len)
3157 {
3158 return OpenTableRandomOperations<Table>::make(len, 0.05f, 0.9f, false);
3159 }
3160 };
3161
3162 TYPED_TEST_SUITE(OpenTableEdges, Open_Tables_Of_Longs);
3163
3164 // A linear probing table that does not resize itself may lose all its
3165 // empty buckets to removed keys (with double hashing, a bucket that no
3166 // probe sequence goes through becomes empty). Turned on, the next
3167 // insertion rebuilds it in place, as its keys are few.
3168 TEST(OLhashTable, TurningResizingOnRebuildsATableWithoutEmptyBuckets)
3169 {
3170 OLhashTable<long> table(11, colliding_hash, Aleph::equal_to<long>(),
3171 0.05f, 0.9f, false);
3172 for (long k = 0; k < 10; ++k) // key k in bucket k
3173 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
3174 table.remove(0L);
3175 ASSERT_NE(table.insert(10L), nullptr); // no empty bucket left
3176 for (const long k : {1L, 2L, 3L, 4L, 5L, 6L})
3177 table.remove(k);
3178 ASSERT_EQ(table.stats().num_empty, 0u);
3179 ASSERT_EQ(table.size(), 4u);
3180
3181 table.set_with_resize(true);
3182 ASSERT_NE(table.insert(1000L), nullptr);
3183 EXPECT_EQ(table.capacity(), 11u); // rebuilt in place: the keys are few
3184 EXPECT_EQ(table.stats().num_deleted, 0u);
3185 EXPECT_GT(table.stats().num_empty, 0u);
3186 for (const long k : {7L, 8L, 9L, 10L, 1000L})
3187 EXPECT_TRUE(table.contains(k)) << "key " << k;
3188 }
3189
3190 // A search that misses goes through every bucket of a table without
3191 // empty buckets, and remove() then throws; search_or_insert() and
3192 // contains_or_insert() take the first removed key's bucket they met.
3193 TEST(OLhashTable, TableWithoutEmptyBuckets)
3194 {
3195 OLhashTable<long> table(11, colliding_hash, Aleph::equal_to<long>(),
3196 0.05f, 0.9f, false);
3197 for (long k = 0; k < 10; ++k)
3198 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
3199 table.remove(0L); // bucket 0 marked
3200 ASSERT_NE(table.insert(10L), nullptr); // bucket 10: no empty one left
3201 table.remove(5L); // and bucket 5 marked
3202 ASSERT_EQ(table.stats().num_empty, 0u);
3203 ASSERT_EQ(table.size(), 9u);
3204
3205 EXPECT_THROW(table.remove(22L), std::domain_error); // starts at bucket 0
3206 EXPECT_THROW(table.remove(21L), std::domain_error); // starts at bucket 10
3207
3208 long * const p = table.search_or_insert(21L); // goes around to bucket 0
3209 ASSERT_NE(p, nullptr);
3210 EXPECT_EQ(*p, 21L);
3211 EXPECT_EQ(table.size(), 10u); // full
3212 EXPECT_EQ(table.search_or_insert(43L), nullptr);
3213 EXPECT_EQ(table.contains_or_insert(43L).first, nullptr);
3214
3215 table.remove(7L); // bucket 7 marked, still no empty bucket
3216 ASSERT_EQ(table.stats().num_empty, 0u);
3217 auto [q, found] = table.contains_or_insert(32L); // bucket 5
3218 ASSERT_NE(q, nullptr);
3219 EXPECT_FALSE(found);
3220 EXPECT_EQ(*q, 32L);
3221 for (const long k : {1L, 2L, 3L, 4L, 6L, 8L, 9L, 10L, 21L, 32L})
3222 EXPECT_TRUE(table.contains(k)) << "key " << k;
3223 EXPECT_FALSE(table.contains(7L));
3224 }
3225
3226 // resize() refuses a capacity without room for the keys and an empty
3227 // bucket, and leaves the table as it was.
3228 TYPED_TEST(OpenTableEdges, ResizeRefusesTooFewBuckets)
3229 {
3230 TypeParam table = this->fixed(11);
3231 for (long k = 0; k < 7; ++k)
3232 ASSERT_NE(table.insert(k), nullptr);
3233 EXPECT_THROW(table.resize(7), std::overflow_error);
3234 EXPECT_THROW(table.resize(5), std::overflow_error);
3235 EXPECT_EQ(table.capacity(), 11u);
3236 EXPECT_EQ(table.size(), 7u);
3237 EXPECT_EQ(table.resize(0), 11u);
3238 EXPECT_EQ(table.resize(8), 8u); // 7 keys and an empty bucket
3239 for (long k = 0; k < 7; ++k)
3240 EXPECT_TRUE(table.contains(k)) << "key " << k;
3241 }
3242
3243 // remove_ptr() refuses a pointer that does not point into the table, or
3244 // to a bucket whose key was removed already. The double hashing table
3245 // took them: in a release build, removing a stale pointer again lost
3246 // other keys.
3247 TYPED_TEST(OpenTableEdges, RemovePtrRefusesForeignAndStalePointers)
3248 {
3249 TypeParam table = this->fixed(11);
3250 long * const p = table.insert(3L);
3251 ASSERT_NE(table.insert(4L), nullptr);
3252 long outside = 3;
3253 EXPECT_THROW(table.remove_ptr(&outside), std::invalid_argument);
3254
3255 table.remove_ptr(p);
3256 EXPECT_THROW(table.remove_ptr(p), std::domain_error);
3257 EXPECT_EQ(table.size(), 1u);
3258
3259 TypeParam other(std::move(table)); // table is left without buckets
3260 EXPECT_THROW(table.remove_ptr(&outside), std::invalid_argument);
3261 EXPECT_TRUE(other.contains(4L));
3262 }
3263
3264 // The bounds of the iterator.
3265 TYPED_TEST(OpenTableEdges, IteratorBounds)
3266 {
3267 TypeParam table = this->fixed(11);
3268 for (const long k : {2L, 5L, 9L})
3269 ASSERT_NE(table.insert(k), nullptr);
3270
3271 auto it = table.get_it();
3272 EXPECT_EQ(it.get_pos(), 0);
3273 const auto & const_it = it;
3274 EXPECT_EQ(const_it.get_curr(), 2L);
3275 it.prev(); // before the first one
3276 EXPECT_FALSE(it.has_curr());
3277 EXPECT_EQ(it.get_pos(), -1);
3278 EXPECT_THROW(it.get_curr(), std::underflow_error);
3279 EXPECT_THROW(it.prev(), std::underflow_error);
3280
3281 it.reset_last();
3282 EXPECT_EQ(it.get_curr(), 9L);
3283 EXPECT_EQ(it.get_pos(), 2);
3284 it.next(); // past the last one
3285 EXPECT_FALSE(it.has_curr());
3286 EXPECT_THROW(it.get_curr(), std::overflow_error);
3287 EXPECT_THROW(it.next(), std::overflow_error);
3288 }
3289
3290 // remove() of a key inside the table that was removed already.
3291 TEST(ODhashTable, RemoveOfAKeyThatWasRemovedThrows)
3292 {
3293 ODhashTable<long> table(11, colliding_hash, colliding_second_hash,
3294 Aleph::equal_to<long>(), 0.05f, 0.9f, false);
3295 for (long k = 0; k < 5; ++k)
3296 ASSERT_NE(table.insert(k * 11), nullptr); // all start at bucket 0
3297 long & second = *table.search(11L);
3298 table.remove(second);
3299 EXPECT_THROW(table.remove(second), std::domain_error);
3300 EXPECT_EQ(table.size(), 4u);
3301 }
3302
3303 // values_ptr() and items_ptr() of the maps over open tables.
3304 TYPED_TEST(OpenMapShrinking, ValuesAndItemsByPointer)
3305 {
3306 TypeParam map(11, Aleph::dft_hash_ptr_fct<long>,
3307 Aleph::snd_hash_ptr_fct<long>, Aleph::equal_to<long>(),
3309 for (long k = 0; k < 5; ++k)
3310 ASSERT_NE(map.insert(k, static_cast<int>(10 * k)), nullptr);
3311
3312 std::set<int> values;
3313 map.values_ptr().for_each([&values] (int * v) { values.insert(*v); });
3314 EXPECT_EQ(values, (std::set<int>{0, 10, 20, 30, 40}));
3315
3316 std::set<long> keys;
3317 map.items_ptr().for_each([&keys] (auto * item)
3318 {
3319 keys.insert(item->first);
3320 item->second += 1;
3321 });
3322 EXPECT_EQ(keys, (std::set<long>{0, 1, 2, 3, 4}));
3323 EXPECT_EQ(map.find(3L), 31);
3324 }
3325
3326 // -------------------------------------------------------------------------
3327 // Random operations on small chained tables, against an oracle
3328 // -------------------------------------------------------------------------
3329
3330 // Number of non-empty lists, counted
3331 template <class Table> size_t busy_lists(const Table & table)
3332 {
3333 const auto stats = table.stats();
3334 return table.capacity() - (stats.lens.size() > 0 ? stats.lens(0) : 0);
3335 }
3336
3337 // Insertions, also through search_or_insert(), and removals, with the
3338 // resizing turned on and off at random. After each step the table holds
3339 // the oracle's keys and counts its busy lists right. While it does not
3340 // resize itself, its capacity stays. While it does, an insertion that
3341 // takes the load to the upper threshold doubles it to the next prime of
3342 // the table until the keys are under that threshold (after turning the
3343 // resizing on, more than once), and a removal that takes it under the
3344 // lower one halves it,
3345 // if that gives a smaller table where the keys stay under the upper one.
3346 // Before, with a lower threshold over half the upper one, such a removal
3347 // shrank the table and resize() grew it back at once.
3348 TEST(LhashTable, RandomOperationsAgreeWithAnOracle)
3349 {
3350 using Bucket = LhashBucket<long>;
3351 const std::pair<float, float> thresholds[] =
3352 {{0.25f, 0.9f}, {0.5f, 2.0f}, {0.01f, 0.99f}, {0.85f, 0.9f}};
3353 std::mt19937 rng(20261021);
3354 for (int trial = 0; trial < 200; ++trial)
3355 {
3356 const auto [lower, upper] = thresholds[rng() % 4];
3357 const bool resizing = rng() % 2 == 0;
3358 LhashTable<long> table(1 + rng() % 13, colliding_hash,
3359 Aleph::equal_to<long>(), lower, upper, true,
3360 resizing);
3361 std::map<long, Bucket *> oracle;
3362 for (int step = 0; step < 300; ++step)
3363 {
3364 const auto where = [&] { return ::testing::Message()
3365 << "trial " << trial << ", step " << step; };
3366 const long k = static_cast<long>(rng() % 60);
3367 const unsigned op = rng() % 9;
3368 const bool resizes = table.get_with_resize();
3369 const size_t capacity = table.capacity();
3370 const bool present = oracle.count(k) > 0;
3371
3372 if (op < 4)
3373 {
3374 auto * bucket = new Bucket(k);
3375 Bucket * stored = op < 2 ? table.insert(bucket)
3376 : table.search_or_insert(bucket);
3377 if (present)
3378 {
3379 ASSERT_EQ(stored, op < 2 ? nullptr : oracle[k]) << where();
3380 delete bucket;
3381 }
3382 else
3383 {
3384 ASSERT_EQ(stored, bucket) << where();
3385 oracle[k] = bucket;
3386 // resize() places the keys again with insert(), which
3387 // grows the new table too while they do not fit
3388 const auto load = [&] (const size_t c)
3389 { return static_cast<float>(1.0*oracle.size()/c); };
3390 size_t expected = capacity;
3391 if (resizes and load(capacity) >= upper)
3392 do
3394 while (load(expected) >= upper);
3395 ASSERT_EQ(table.capacity(), expected) << where();
3396 }
3397 }
3398 else if (op < 8)
3399 {
3400 if (present)
3401 {
3402 delete table.remove(oracle[k]);
3403 oracle.erase(k);
3404 const size_t n = oracle.size();
3405 const size_t smaller = Primes::next_prime(capacity/2);
3406 const bool shrinks = resizes
3407 and static_cast<float>(1.0*n/capacity) < lower
3408 and smaller < capacity and 1.0f*n/smaller < upper;
3409 ASSERT_EQ(table.capacity(), shrinks ? smaller : capacity)
3410 << where();
3411 }
3412 }
3413 else if (rng() % 4 == 0)
3414 table.set_with_resize(not resizes);
3415
3416 ASSERT_EQ(table.size(), oracle.size()) << where();
3417 ASSERT_EQ(table.get_num_busy_slots(), busy_lists(table)) << where();
3418 for (long key = 0; key < 60; ++key)
3419 ASSERT_EQ(table.search(key),
3420 oracle.count(key) ? oracle[key] : nullptr)
3421 << "key " << key << ", " << where();
3422 }
3423 for (auto & [key, bucket] : oracle)
3424 delete table.remove(bucket);
3425 }
3426 }
3427
3428 // The bounds of the iterator of a chained table, and resize(0).
3429 TEST(LhashTable, IteratorBoundsAndResizeZero)
3430 {
3431 using Bucket = LhashBucket<long>;
3432 LhashTable<long> table(11, colliding_hash, Aleph::equal_to<long>(),
3434 true, false);
3435 LhashTable<long>::Iterator empty_it(table);
3436 EXPECT_FALSE(empty_it.has_curr());
3437 empty_it.reset_last(); // an empty table has no last one
3438 EXPECT_FALSE(empty_it.has_curr());
3439
3440 for (const long k : {2L, 5L, 9L})
3441 ASSERT_NE(table.insert(new Bucket(k)), nullptr);
3442 EXPECT_EQ(table.resize(0), 11u);
3443
3445 EXPECT_EQ(it.get_curr()->get_key(), 2L);
3446 it.prev(); // before the first one
3447 EXPECT_FALSE(it.has_curr());
3448 EXPECT_THROW(it.prev(), std::underflow_error);
3449 it.reset_last();
3450 EXPECT_EQ(it.get_curr()->get_key(), 9L);
3451 it.next(); // past the last one
3452 EXPECT_FALSE(it.has_curr());
3453 EXPECT_THROW(it.next(), std::overflow_error);
3454
3455 for (LhashTable<long>::Iterator del(table); del.has_curr(); )
3456 delete del.del();
3457 }
3458
3459 // A map over a chained or a linear hash table: values and items by
3460 // pointer, and a move into itself.
3461 template <class Map> struct DynMapHashTables : public ::testing::Test {};
3462
3463 using Dyn_Hash_Maps = ::testing::Types<DynMapHash<long, int>,
3465 TYPED_TEST_SUITE(DynMapHashTables, Dyn_Hash_Maps);
3466
3467 TYPED_TEST(DynMapHashTables, ValuesAndItemsByPointerAndSelfMove)
3468 {
3469 TypeParam map;
3470 for (long k = 0; k < 5; ++k)
3471 map.insert(k, static_cast<int>(10 * k));
3472
3473 std::set<int> values;
3474 map.values_ptr().for_each([&values] (int * v) { values.insert(*v); });
3475 EXPECT_EQ(values, (std::set<int>{0, 10, 20, 30, 40}));
3476
3477 std::set<long> keys;
3478 map.items_ptr().for_each([&keys] (auto * item)
3479 {
3480 keys.insert(item->first);
3481 item->second += 1;
3482 });
3483 EXPECT_EQ(keys, (std::set<long>{0, 1, 2, 3, 4}));
3484 EXPECT_EQ(map.find(3L), 31);
3485
3486 TypeParam & same = map;
3487 map = std::move(same);
3488 EXPECT_EQ(map.size(), 5u);
3489 EXPECT_EQ(map.find(4L), 41);
3490 }
3491} // namespace
3492
3493// A move of the table left the other one without lists and took its hash
3494// function, so that a search in it divided by zero. The move constructor
3495// copies the function now, and a table without lists finds nothing and
3496// takes buckets again
3497TEST(LhashTable, TheTableThatWasMovedFromTakesBucketsAgain)
3498{
3499 using Bucket = LhashBucket<int>;
3500 LhashTable<int> src(5);
3501 for (int i = 0; i < 20; ++i)
3502 ASSERT_NE(src.insert(new Bucket(i)), nullptr);
3503 const size_t capacity = src.capacity();
3504 Bucket * const where = src.search(7);
3505
3506 LhashTable<int> dst(std::move(src));
3507 ASSERT_EQ(dst.size(), 20u);
3508 EXPECT_EQ(dst.capacity(), capacity);
3509 EXPECT_EQ(dst.search(7), where); // the very bucket
3510 EXPECT_EQ(src.size(), 0u);
3511 EXPECT_EQ(src.capacity(), 0u);
3512 EXPECT_EQ(src.current_alpha(), 0.0f);
3513 EXPECT_EQ(src.search(3), nullptr);
3514 EXPECT_FALSE(src.contains(3));
3515 EXPECT_FALSE(LhashTable<int>::Iterator(src).has_curr());
3516
3517 ASSERT_NE(src.insert(new Bucket(3)), nullptr); // its first bucket
3518 EXPECT_EQ(src.capacity(), Primes::DefaultPrime);
3519 EXPECT_NE(src.search(3), nullptr);
3520 EXPECT_EQ(src.search(4), nullptr);
3521
3522 src = std::move(dst); // the move assignment
3523 EXPECT_EQ(src.size(), 20u);
3524 EXPECT_EQ(src.search(7), where);
3525 EXPECT_EQ(dst.size(), 0u);
3526 EXPECT_EQ(dst.capacity(), 0u);
3527 Bucket * const mine = new Bucket(8);
3528 EXPECT_EQ(dst.search_or_insert(mine), mine);
3529 EXPECT_EQ(dst.search(8), mine);
3530 EXPECT_EQ(dst.resize(31), 31u);
3531 EXPECT_EQ(dst.search(8), mine);
3532}
3533
3534namespace
3535{
3536 // Two hash functions that count their calls
3537 size_t first_hash_calls = 0;
3538 size_t second_hash_calls = 0;
3539
3540 size_t first_counted_hash(const int & k) noexcept
3541 {
3542 ++first_hash_calls;
3543 return static_cast<size_t>(k);
3544 }
3545
3546 size_t second_counted_hash(const int & k) noexcept
3547 {
3548 ++second_hash_calls;
3549 return static_cast<size_t>(k) * 31u;
3550 }
3551}
3552
3553// The move constructor copies the hash function, so that the table that
3554// it moves from goes on with its own
3555TEST(LhashTable, TheTableThatWasMovedFromKeepsItsHashFunction)
3556{
3557 using Bucket = LhashBucket<int>;
3558 LhashTable<int> src(11, first_counted_hash);
3559 for (int i = 0; i < 20; ++i)
3560 ASSERT_NE(src.insert(new Bucket(i)), nullptr);
3561
3562 LhashTable<int> dst(std::move(src));
3563 first_hash_calls = second_hash_calls = 0;
3564 for (int i = 0; i < 20; ++i)
3565 ASSERT_NE(dst.search(i), nullptr);
3566 EXPECT_EQ(first_hash_calls, 20u);
3567
3568 first_hash_calls = 0;
3569 ASSERT_NE(src.insert(new Bucket(7)), nullptr);
3570 EXPECT_NE(src.search(7), nullptr);
3571 EXPECT_EQ(first_hash_calls, 2u); // one for the insertion and one for the search
3572}
3573
3574// The move assignment copies no function: the two tables swap what rules
3575// them, so that the one that was moved from goes on with the hash function
3576// that the other one had
3577TEST(LhashTable, AMoveAssignmentSwapsWhatRulesTheTables)
3578{
3579 using Bucket = LhashBucket<int>;
3580 LhashTable<int> src(11, first_counted_hash);
3581 LhashTable<int> dst(11, second_counted_hash);
3582 for (int i = 0; i < 20; ++i)
3583 ASSERT_NE(src.insert(new Bucket(i)), nullptr);
3584 ASSERT_NE(dst.insert(new Bucket(100)), nullptr); // the assignment frees it
3585
3586 dst = std::move(src);
3587 ASSERT_EQ(dst.size(), 20u);
3588 EXPECT_EQ(dst.search(100), nullptr);
3589 EXPECT_EQ(src.size(), 0u);
3590 EXPECT_EQ(src.capacity(), 0u);
3591
3592 first_hash_calls = second_hash_calls = 0;
3593 for (int i = 0; i < 20; ++i)
3594 ASSERT_NE(dst.search(i), nullptr); // with the function that put them there
3595 EXPECT_EQ(first_hash_calls, 20u);
3596 EXPECT_EQ(second_hash_calls, 0u);
3597
3598 ASSERT_NE(src.insert(new Bucket(7)), nullptr); // with the one that dst had
3599 EXPECT_NE(src.search(7), nullptr);
3600 EXPECT_EQ(second_hash_calls, 2u);
3601 EXPECT_EQ(first_hash_calls, 20u);
3602}
3603
3604// A table that does not own its buckets does not free them when it is
3605// assigned another one, nor does it count them any more: the table that
3606// was moved from, which takes what ruled this one, is left empty
3607TEST(LhashTable, AMoveAssignmentOfATableThatDoesNotOwnItsBucketsLeavesTheOtherEmpty)
3608{
3609 using Bucket = LhashBucket<int>;
3610 LhashTable<int> src(11, first_counted_hash);
3611 for (int i = 0; i < 5; ++i)
3612 ASSERT_NE(src.insert(new Bucket(i)), nullptr);
3613
3614 Bucket * const mine[3] = {new Bucket(100), new Bucket(101), new Bucket(102)};
3615 LhashTable<int> dst(11, second_counted_hash, Aleph::equal_to<int>(),
3617 false, true);
3618 for (Bucket * bucket : mine)
3619 ASSERT_NE(dst.insert(bucket), nullptr);
3620 ASSERT_EQ(dst.size(), 3u);
3621
3622 dst = std::move(src);
3623 for (Bucket * bucket : mine) // they were never of the table
3624 delete bucket;
3625
3626 ASSERT_EQ(dst.size(), 5u);
3627 for (int i = 0; i < 5; ++i)
3628 EXPECT_NE(dst.search(i), nullptr);
3629 EXPECT_EQ(dst.search(100), nullptr);
3630 EXPECT_EQ(src.size(), 0u);
3631 EXPECT_TRUE(src.is_empty());
3632 EXPECT_EQ(src.capacity(), 0u);
3633 EXPECT_EQ(src.search(100), nullptr);
3634}
3635
3636namespace
3637{
3638 // A comparator that can be copied and not moved, which EqualityComparator
3639 // admits and std::swap() does not take. Its number tells the copies apart.
3640 struct Copied_Not_Moved_Eq
3641 {
3642 int id = 0;
3643
3644 Copied_Not_Moved_Eq() = default;
3645
3646 Copied_Not_Moved_Eq(const Copied_Not_Moved_Eq &) = default;
3647
3648 Copied_Not_Moved_Eq & operator = (const Copied_Not_Moved_Eq &) = default;
3649
3650 Copied_Not_Moved_Eq(Copied_Not_Moved_Eq &&) = delete;
3651
3652 bool operator () (int a, int b) const noexcept { return a == b; }
3653 };
3654
3655 static_assert(EqualityComparator<Copied_Not_Moved_Eq, int>);
3656 static_assert(not std::is_move_constructible_v<Copied_Not_Moved_Eq>);
3657
3658 // MSVC builds a class through a constructor that it inherits with a
3659 // function of its own, which moves the arguments to the constructor of
3660 // the base. LhashTable and LhashTableVtl inherit those of GenLhashTable,
3661 // and DynLhashTable and DynSetLhash are built through them: with a
3662 // comparator whose move constructor is deleted, none of them can be
3663 // built there (C2280). GCC, Clang and clang-cl initialize the parameters
3664 // from the arguments, and the tests below are theirs
3665# if !defined(_MSC_VER) || defined(__clang__)
3666
3667 // swap() and the move assignment of a table of chained lists swap a
3668 // comparator that cannot be moved, and the table that was moved from
3669 // takes keys again
3670 template <class Table>
3671 void expect_that_the_comparators_are_swapped()
3672 {
3673 using Bucket = typename Table::Bucket;
3674 Table a, b;
3675 a.get_compare().id = 1;
3676 b.get_compare().id = 2;
3677 ASSERT_NE(a.insert(new Bucket(1)), nullptr);
3678 ASSERT_NE(b.insert(new Bucket(2)), nullptr);
3679 ASSERT_NE(b.insert(new Bucket(3)), nullptr);
3680
3681 a.swap(b);
3682 EXPECT_EQ(a.get_compare().id, 2);
3683 EXPECT_EQ(b.get_compare().id, 1);
3684 ASSERT_EQ(a.size(), 2u);
3685 ASSERT_EQ(b.size(), 1u);
3686 EXPECT_NE(a.search(3), nullptr);
3687 EXPECT_NE(b.search(1), nullptr);
3688
3689 a = std::move(b); // frees the keys 2 and 3
3690 EXPECT_EQ(a.get_compare().id, 1);
3691 EXPECT_EQ(b.get_compare().id, 2);
3692 ASSERT_EQ(a.size(), 1u);
3693 EXPECT_NE(a.search(1), nullptr);
3694 EXPECT_EQ(b.size(), 0u);
3695 EXPECT_EQ(b.capacity(), 0u);
3696
3697 ASSERT_NE(b.insert(new Bucket(5)), nullptr);
3698 EXPECT_NE(b.search(5), nullptr);
3699 }
3700
3701# endif // the tables that MSVC cannot build with such a comparator
3702}
3703
3704# if !defined(_MSC_VER) || defined(__clang__) // see above
3705
3706// The move assignment swaps the two tables, and std::swap() asks for a
3707// comparator that can be moved: with this one, it did not compile
3708TEST(LhashTable, AComparatorThatCannotBeMovedIsSwappedThroughItsCopies)
3709{
3710 expect_that_the_comparators_are_swapped<LhashTable<int, Copied_Not_Moved_Eq>>();
3711 expect_that_the_comparators_are_swapped<LhashTableVtl<int, Copied_Not_Moved_Eq>>();
3712}
3713
3714TEST(DynLhashTable, AComparatorThatCannotBeMovedIsSwappedThroughItsCopies)
3715{
3717 a.get_compare().id = 1;
3718 b.get_compare().id = 2;
3719 ASSERT_NE(a.insert(1, 10), nullptr);
3720 ASSERT_NE(b.insert(2, 20), nullptr);
3721 ASSERT_NE(b.insert(3, 30), nullptr);
3722
3723 a.swap(b);
3724 EXPECT_EQ(a.get_compare().id, 2);
3725 EXPECT_EQ(b.get_compare().id, 1);
3726 ASSERT_NE(a.search(3), nullptr);
3727 EXPECT_EQ(*a.search(3), 30);
3728
3729 a = std::move(b);
3730 EXPECT_EQ(a.get_compare().id, 1);
3731 EXPECT_EQ(b.get_compare().id, 2);
3732 ASSERT_NE(a.search(1), nullptr);
3733 EXPECT_EQ(*a.search(1), 10);
3734 EXPECT_EQ(b.size(), 0u);
3735 ASSERT_NE(b.insert(5, 50), nullptr);
3736 EXPECT_NE(b.search(5), nullptr);
3737}
3738
3739TEST(DynSetLhash, AComparatorThatCannotBeMovedIsSwappedThroughItsCopies)
3740{
3742 Set a, b;
3743 a.get_compare().id = 1;
3744 b.get_compare().id = 2;
3745 ASSERT_NE(a.insert(1), nullptr);
3746 ASSERT_NE(b.insert(2), nullptr);
3747 ASSERT_NE(b.insert(3), nullptr);
3748
3749 a.swap(b);
3750 EXPECT_EQ(a.get_compare().id, 2);
3751 EXPECT_EQ(b.get_compare().id, 1);
3752 EXPECT_NE(a.search(3), nullptr);
3753
3754 a = std::move(b);
3755 EXPECT_EQ(a.get_compare().id, 1);
3756 EXPECT_EQ(b.get_compare().id, 2);
3757 EXPECT_NE(a.search(1), nullptr);
3758 EXPECT_EQ(b.size(), 0u);
3759 ASSERT_NE(b.insert(5), nullptr);
3760 EXPECT_NE(b.search(5), nullptr);
3761
3762 Set c(std::move(a));
3763 EXPECT_EQ(c.get_compare().id, 1);
3764 EXPECT_NE(c.search(1), nullptr);
3765}
3766
3767# endif // the tables that MSVC cannot build with such a comparator
3768
3769// The other tables with the same comparator: they are swapped, moved and
3770// move assigned with it, as the tables of chained lists. The raw
3771// LinearHashTable has no moves of its own and cannot be copied
3772TEST(HashTables, TheyAreMovedWithAComparatorThatCannotBeMoved)
3773{
3774 auto check_table = [] (auto a)
3775 {
3776 using Table = decltype(a);
3777 Table b;
3778 a.get_compare().id = 1;
3779 b.get_compare().id = 2;
3780 ASSERT_NE(a.insert(1), nullptr);
3781 ASSERT_NE(b.insert(2), nullptr);
3782
3783 a.swap(b);
3784 EXPECT_EQ(a.get_compare().id, 2);
3785 EXPECT_EQ(b.get_compare().id, 1);
3786 EXPECT_NE(a.search(2), nullptr);
3787 EXPECT_NE(b.search(1), nullptr);
3788
3789 Table c(std::move(a));
3790 EXPECT_EQ(c.get_compare().id, 2);
3791 EXPECT_NE(c.search(2), nullptr);
3792
3793 b = std::move(c);
3794 EXPECT_EQ(b.get_compare().id, 2);
3795 EXPECT_NE(b.search(2), nullptr);
3796 };
3800
3801 auto check_map = [] (auto a)
3802 {
3803 using Map = decltype(a);
3804 ASSERT_NE(a.insert(1, 10), nullptr);
3805 Map b(std::move(a));
3806 ASSERT_NE(b.search(1), nullptr);
3807 Map c;
3808 c = std::move(b);
3809 c.swap(a);
3810 ASSERT_NE(a.search(1), nullptr);
3811 EXPECT_EQ(a.search(1)->second, 10);
3812 };
3815# if !defined(_MSC_VER) || defined(__clang__) // its table is a LhashTable: see above
3817# endif
3818}
Functional programming utilities for Aleph-w containers.
High-level sorting functions for Aleph containers.
TYPED_TEST_SUITE(ArcHeapLifecycle, ArcHeapKinds)
TYPED_TEST(ArcHeapLifecycle, ClearNullsTheHandles)
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
bool contains(const Key &key) const noexcept
Return true if the key exists in the table.
Key * insert(const Key &key)
Inserts key into the hash set.
Dynamic hash table mapping keys to records with separate chaining.
Record * search(const Key &key)
Search for a key in the table.
void swap(DynLhashTable &table) noexcept
Swap contents with another table.
Record * insert(const Key &key, const Record &record)
Insert a key-record pair into the table.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
void empty() noexcept
empty the list
Definition htlist.H:1576
Bucket * remove(Bucket *bucket) noexcept
Removes bucket from the table.
Definition tpl_lhash.H:587
Bucket * insert(Bucket *bucket)
Inserts bucket into the table and returns its address if the key is not already in the table; otherwi...
Definition tpl_lhash.H:503
bool contains(const Key &key) const noexcept
Checks if a key exists in the table.
Definition tpl_lhash.H:382
float current_alpha() const noexcept
return the current table load; zero for a table without lists
Definition tpl_lhash.H:479
const size_t & size() const noexcept
Returns the number of elements contained in the table.
Definition tpl_lhash.H:697
Bucket * search_or_insert(Bucket *bucket)
Definition tpl_lhash.H:529
const size_t & capacity() const noexcept
Returns the table capacity.
Definition tpl_lhash.H:694
void swap(GenLhashTable &other) noexcept
Swaps this table with other in constant time.
Definition tpl_lhash.H:276
Bucket * search(const Key &key) const noexcept
Search in the table for a bucket with key.
Definition tpl_lhash.H:555
constexpr bool is_empty() const noexcept
Definition tpl_lhash.H:703
size_t resize(const size_t new_size)
Resizes the table to new_size lists and places every bucket again.
Definition tpl_lhash.H:627
Generic linear hash table.
const size_t & capacity() const noexcept
Returns the table capacity.
void swap(GenLinearHashTable &other) noexcept
Swaps this table with other in constant time.
DynArray< BucketList > table
Cmp & get_compare() noexcept
const size_t & size() const noexcept
Returns the number of elements in the table.
Bucket * remove(Bucket *bucket) noexcept
Removes bucket from the table, without freeing it.
BucketType< Key > Bucket
The bucket type.
bool contains(const Key &key) const noexcept
Checks if a key exists in the table.
Bucket * insert(Bucket *bucket)
Insert bucket in the table.
Hash_Fct get_hash_fct() const noexcept
Bucket * search_or_insert(Bucket *bucket)
void set_hash_fct(Hash_Fct fct)
Sets the hash function of an empty table.
Bucket * search(const Key &key) const noexcept
Search for key in the linear hash table.
size_t resize(size_t) noexcept
Provided for generic programming compatibility.
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Open addressing hash table with double hashing collision resolution.
Definition tpl_odhash.H:193
void set_second_hash_fct(Hash_Fct fct)
Sets the hash function of the second probe.
Definition tpl_odhash.H:750
void swap(ODhashTable &other) noexcept
Swaps this table with other in constant time.
Definition tpl_odhash.H:470
Key * search(const Key &key) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition tpl_odhash.H:657
Open addressing hash table with linear probing collision resolution.
Definition tpl_olhash.H:175
Key * search(const Key &key) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition tpl_olhash.H:449
void swap(OLhashTable &other) noexcept
Swaps this table with other in constant time.
Definition tpl_olhash.H:362
Stats stats() const
Definition tpl_olhash.H:706
Minimal std::expected-style result type for C++20.
Aleph::DynList< Aleph::dry_detail::map_result_t< R, Operation &, T > > maps(Operation &op) const
Definition ah-dry.H:1829
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
constexpr float get_upper_alpha() const noexcept
Returns the upper load factor threshold.
Definition hashDry.H:1564
void set_with_resize(const bool with_resize) noexcept
Turns the automatic resizing on or off.
Definition hashDry.H:1580
Stats stats() const
Computes statistics about chain length distribution.
Definition hashDry.H:1470
constexpr bool get_with_resize() const noexcept
Returns whether the table resizes itself.
Definition hashDry.H:1569
constexpr float get_lower_alpha() const noexcept
Returns the lower load factor threshold.
Definition hashDry.H:1559
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
Key * insert(const Key &key)
Inserts a key into the hash table (copy version).
Definition hashDry.H:507
#define TEST(name)
static mt19937 rng
pair< size_t, string > P
Types< MapODhash< size_t, string >, MapOLhash< size_t, string >, DynMapLinHash< size_t, string >, DynMapHash< size_t, string > > HashTypes
REGISTER_TYPED_TEST_CASE_P(EmptyOHashTest, With_exception)
TYPED_TEST_P(EmptyOHashTest, With_exception)
Definition hash-it.cc:93
INSTANTIATE_TYPED_TEST_CASE_P(Empty, EmptyOHashTest, HashTypes)
TYPED_TEST_CASE_P(OHashTest)
::testing::Types< OLhashTable< long >, ODhashTable< long > > Open_Tables
MapOLhash< int, Foo > tbl
Table::Bucket Bucket
Definition lin-hash.cc:57
LinearHashTable< int > Table
Definition lin-hash.cc:56
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
bool eq(const C1 &c1, const C2 &c2, Eq e=Eq())
Check equality of two containers using a predicate.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
const float hash_default_upper_alpha
Definition hash-dry.C:40
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
void fill(Itor beg, const Itor &end, const T &value)
Fill a range with a value.
Definition ahAlgo.H:707
bool contains(const std::string_view &str, const std::string_view &substr)
Check if substr appears inside str.
DynArray< T > sort(const DynArray< T > &a, Cmp &&cmp=Cmp())
Returns a sorted copy of a DynArray.
Definition ahSort.H:234
and
Check uniqueness with explicit hash + equality functors.
bool has_curr() const noexcept
Return true if all underlying iterators are positioned on a valid item.
Definition ah-zip.H:173
std::pair< First, Second > pair
Alias to std::pair kept for backwards compatibility.
Definition ahPair.H:89
Fw_Itor remove(Fw_Itor __first, const Fw_Itor &__last, const T &__value)
Remove elements equal to a value.
Definition ahAlgo.H:962
Itor1 search(Itor1 beg, const Itor1 &end, Itor2 searchBeg, const Itor2 &searchEnd, BinaryPredicate op=BinaryPredicate())
Search for a subrange within a range.
Definition ahAlgo.H:309
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
Container< T > range(const T start, const T end, const T step=1)
Generate a range of values [start, end] with a given step.
const float hash_default_lower_alpha
Definition hash-dry.C:38
std::ostream & operator<<(std::ostream &osObject, const Field< T > &rightOp)
Definition ahField.H:121
const unsigned long DefaultPrime
Default prime number used when no specific size is requested.
Definition primes.C:381
unsigned long next_prime(unsigned long n)
Find a prime >= n in the database, for hash table sizing.
Definition primes.C:383
STL namespace.
Hash-based dynamic set (defined in tpl_dynSetHash.H).
Generic hash table with collision resolution by separate chaining and buckets without virtual destruc...
Definition tpl_lhash.H:1008
Open addressing hash map using double hashing.
Open addressing hash map using linear probing.
HashTbl tbl
Definition hash-it.cc:84
HashTbl tbl
DynList< size_t > items
Definition hash-it.cc:72
OHashTest()
Definition hash-it.cc:73
bool check(GT &g)
int keys[]
ValueArg< size_t > num_keys
Definition testHash.C:50
static int * k
Dynamic hash table mapping keys to records with separate chaining.
Dynamic map with open hashing.
Dynamic set implementations based on hash tables.
Unified hash table interface.
Hash tables with collision resolution by separate chaining.
Open addressing hash table with double hashing.
Open addressing hash table with linear probing.
DynList< int > l