Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
olhash.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 <numeric>
40# include <random>
41# include <set>
42
43# include <tpl_olhash.H>
44
45using namespace std;
46using namespace testing;
47using namespace Aleph;
48
49TEST(OLhashTable, Simplest)
50{
52
53 EXPECT_TRUE(tbl.is_empty());
54 EXPECT_EQ(tbl.size(), 0);
55
56 const size_t cap = tbl.capacity();
57 for (size_t i = 0; i < cap; ++i)
58 {
59 EXPECT_EQ(tbl.size(), i);
60 EXPECT_NE(tbl.insert(i), nullptr);
61 EXPECT_EQ(tbl.size(), i + 1);
62 EXPECT_FALSE(tbl.is_empty());
63 }
64
65 for (size_t i = 0; i < tbl.size(); ++i)
66 {
67 ASSERT_NE(tbl.search(i), nullptr);
68 auto ptr = tbl.search(i);
69 EXPECT_EQ(*ptr, i);
70 EXPECT_FALSE(tbl.is_empty());
71 }
72
73 for (size_t i = 0, n = tbl.size(); i < n; ++i)
74 {
75 auto ptr = tbl.search(i);
76 EXPECT_EQ(*ptr, i);
77 tbl.remove(*ptr);
78 EXPECT_EQ(tbl.size(), n - i - 1);
79 EXPECT_EQ(tbl.search(i), nullptr);
80 EXPECT_FALSE(tbl.contains(i));
81 }
82
83 EXPECT_EQ(tbl.size(), 0);
84 EXPECT_TRUE(tbl.is_empty());
85}
86
87struct MyRecord
88{
89 size_t key;
90 string value;
92 MyRecord(size_t k, const string & v) : key(k), value(v) {}
93 MyRecord(size_t k) : key(k) {}
94 struct Eq
95 {
96 bool operator () (const MyRecord & r1, const MyRecord & r2) const noexcept
97 {
98 return r1.key == r2.key;
99 }
100 };
101 bool operator == (const MyRecord & r) const noexcept { return Eq()(*this, r); }
102};
103
104inline size_t my_hash(const MyRecord & r) noexcept
105{
106 return dft_hash_fct(r.key);
107}
108
110{
112
113 EXPECT_EQ(tbl.size(), 0);
114 EXPECT_TRUE(tbl.is_empty());
115
116 for (size_t i = 0; i < 100; ++i)
117 {
118 EXPECT_EQ(tbl.size(), i);
119 tbl.emplace(i, to_string(i));
120 EXPECT_EQ(tbl.size(), i + 1);
121 auto ptr = tbl.search(MyRecord(i));
122 EXPECT_NE(ptr, nullptr);
123 EXPECT_EQ(ptr->key, i);
124 EXPECT_EQ(ptr->value, to_string(i));
125 }
126
127 for (size_t i = 0, n = tbl.size(); i < n; ++i)
128 {
129 auto ptr = tbl.search(i);
130 EXPECT_EQ(*ptr, i);
131 tbl.remove(MyRecord(ptr->key));
132 EXPECT_EQ(tbl.size(), n - i - 1);
133 EXPECT_EQ(tbl.search(i), nullptr);
134 EXPECT_FALSE(tbl.contains(MyRecord(i)));
135 }
136}
137
138TEST(OLhashTable, KeyToBucketRoundTrip)
139{
141 auto *ptr = tbl.insert(5);
142 ASSERT_NE(ptr, nullptr);
143
144 auto *bucket = decltype(tbl)::key_to_bucket(ptr);
145 ASSERT_NE(bucket, nullptr);
146 EXPECT_EQ(bucket->key, 5);
147 EXPECT_EQ(bucket->status, decltype(tbl)::BUSY);
148
149 EXPECT_NO_THROW(tbl.remove(5));
150 EXPECT_EQ(tbl.search(5), nullptr);
151}
152
153// Test that removing a non-existent key throws and preserves table integrity
154TEST(OLhashTable, RemoveNonExistentKeyPreservesTableIntegrity)
155{
157
158 // Insert some elements
159 const int num_elements = 50;
160 for (int i = 0; i < num_elements; ++i)
161 EXPECT_NE(tbl.insert(i * 2), nullptr); // Insert even numbers: 0, 2, 4, ..., 98
162
163 EXPECT_EQ(tbl.size(), num_elements);
164
165 // Try to remove keys that don't exist (odd numbers)
166 // This should throw domain_error BUT NOT corrupt the table
167 for (int i = 0; i < 10; ++i)
168 {
169 int non_existent_key = i * 2 + 1; // Odd numbers: 1, 3, 5, ..., 19
170 EXPECT_THROW(tbl.remove(non_existent_key), std::domain_error);
171 }
172
173 // Verify table size is unchanged
174 EXPECT_EQ(tbl.size(), num_elements)
175 << "Table size should not change after failed remove attempts";
176
177 // Verify all original elements are still findable
178 for (int i = 0; i < num_elements; ++i)
179 {
180 auto ptr = tbl.search(i * 2);
181 EXPECT_NE(ptr, nullptr)
182 << "Element " << i * 2 << " should still be in the table";
183 if (ptr)
184 EXPECT_EQ(*ptr, i * 2);
185 }
186
187 // Verify we can still remove elements normally
188 for (int i = 0; i < num_elements; ++i)
189 {
190 auto ptr = tbl.search(i * 2);
191 ASSERT_NE(ptr, nullptr);
192 EXPECT_NO_THROW(tbl.remove(*ptr));
193 EXPECT_EQ(tbl.size(), num_elements - i - 1);
194 }
195
196 EXPECT_TRUE(tbl.is_empty());
197}
198
199// Test remove with external key (key not from a bucket in the table)
200TEST(OLhashTable, RemoveWithExternalKey)
201{
203
204 // Insert elements
205 for (int i = 0; i < 20; ++i)
206 EXPECT_NE(tbl.insert(i), nullptr);
207
208 EXPECT_EQ(tbl.size(), 20);
209
210 // Remove using external key (not a reference from the table)
211 int external_key = 10;
212 EXPECT_NO_THROW(tbl.remove(external_key));
213 EXPECT_EQ(tbl.size(), 19);
214 EXPECT_EQ(tbl.search(10), nullptr);
215
216 // Verify other elements are intact
217 for (int i = 0; i < 20; ++i)
218 {
219 if (i == 10) continue;
220 EXPECT_NE(tbl.search(i), nullptr) << "Element " << i << " should still exist";
221 }
222}
223
224// Test remove with internal key (reference from the table bucket)
225TEST(OLhashTable, RemoveWithInternalKey)
226{
228
229 // Insert elements
230 for (int i = 0; i < 20; ++i)
231 EXPECT_NE(tbl.insert(i), nullptr);
232
233 EXPECT_EQ(tbl.size(), 20);
234
235 // Remove using internal key (reference from search result)
236 auto ptr = tbl.search(10);
237 ASSERT_NE(ptr, nullptr);
238 EXPECT_NO_THROW(tbl.remove(*ptr)); // *ptr is internal reference
239 EXPECT_EQ(tbl.size(), 19);
240 EXPECT_EQ(tbl.search(10), nullptr);
241}
242
243// Test behavior with many collisions (stress test linear probing)
244TEST(OLhashTable, ManyCollisions)
245{
246 // Use a small table to force many collisions
247 OLhashTable<int> tbl(17); // Small prime
248
249 // Insert enough elements to cause collisions
250 const int num_elements = 15;
251 for (int i = 0; i < num_elements; ++i)
252 EXPECT_NE(tbl.insert(i), nullptr);
253
254 EXPECT_EQ(tbl.size(), num_elements);
255
256 // Verify all elements are findable
257 for (int i = 0; i < num_elements; ++i)
258 EXPECT_NE(tbl.search(i), nullptr) << "Element " << i << " not found";
259
260 // Remove every other element
261 for (int i = 0; i < num_elements; i += 2)
262 {
263 auto ptr = tbl.search(i);
264 ASSERT_NE(ptr, nullptr);
265 tbl.remove(*ptr);
266 }
267
268 // Verify remaining elements are still findable
269 for (int i = 1; i < num_elements; i += 2)
270 EXPECT_NE(tbl.search(i), nullptr) << "Element " << i << " not found after removals";
271
272 // Verify removed elements are gone
273 for (int i = 0; i < num_elements; i += 2)
274 EXPECT_EQ(tbl.search(i), nullptr) << "Element " << i << " should be removed";
275}
276
277// Test that capacity doesn't change after failed removes
278TEST(OLhashTable, RemoveNonExistentDoesNotChangeCapacity)
279{
281
282 // Insert elements
283 for (int i = 0; i < 50; ++i)
284 EXPECT_NE(tbl.insert(i * 2), nullptr); // Even numbers
285
286 const size_t original_capacity = tbl.capacity();
287 const size_t original_size = tbl.size();
288
289 // Try to remove many non-existent keys
290 for (int attempt = 0; attempt < 100; ++attempt)
291 {
292 int non_existent = attempt * 2 + 1; // Odd numbers don't exist
293 EXPECT_THROW(tbl.remove(non_existent), std::domain_error);
294 }
295
296 // Capacity should be unchanged
297 EXPECT_EQ(tbl.capacity(), original_capacity)
298 << "Capacity changed after failed remove attempts";
299
300 // Size should be unchanged
301 EXPECT_EQ(tbl.size(), original_size);
302
303 // All elements should still be findable
304 for (int i = 0; i < 50; ++i)
305 EXPECT_NE(tbl.search(i * 2), nullptr) << "Element " << i * 2 << " not found";
306}
307
308// ============================================================================
309// STRESS TESTS / FUZZING
310// ============================================================================
311
312// Fuzzing test: random operations with oracle verification
313TEST(OLhashTable, Fuzz_RandomOperationsWithOracle)
314{
315 // Use large table to avoid resize
316 OLhashTable<int> tbl(20000);
317 set<int> oracle;
318
319 mt19937 rng(42);
320 uniform_int_distribution<int> key_dist(0, 5000);
321 uniform_int_distribution<int> op_dist(0, 2);
322
323 const int num_operations = 8000;
324
325 for (int i = 0; i < num_operations; ++i)
326 {
327 int key = key_dist(rng);
328 int op = op_dist(rng);
329
330 switch (op)
331 {
332 case 0: // Insert
333 {
334 bool in_oracle = oracle.count(key) > 0;
335 auto ptr = tbl.insert(key);
336 if (ptr != nullptr)
337 {
338 EXPECT_FALSE(in_oracle) << "Insert succeeded but oracle had key " << key;
339 oracle.insert(key);
340 }
341 else
342 {
343 EXPECT_TRUE(in_oracle) << "Insert failed but oracle didn't have key " << key;
344 }
345 break;
346 }
347 case 1: // Remove
348 {
349 bool in_oracle = oracle.count(key) > 0;
350 if (in_oracle)
351 {
352 try
353 {
354 tbl.remove(key);
355 oracle.erase(key);
356 }
357 catch (const domain_error &)
358 {
359 FAIL() << "Remove threw for key " << key << " that was in oracle";
360 }
361 }
362 else
363 {
364 EXPECT_THROW(tbl.remove(key), domain_error);
365 }
366 break;
367 }
368 case 2: // Search
369 {
370 auto ptr = tbl.search(key);
371 bool in_oracle = oracle.count(key) > 0;
372 EXPECT_EQ(ptr != nullptr, in_oracle) << "Search mismatch for key " << key;
373 if (ptr)
374 EXPECT_EQ(*ptr, key);
375 break;
376 }
377 }
378
379 ASSERT_EQ(tbl.size(), oracle.size()) << "Size mismatch at operation " << i;
380 }
381
382 // Final verification
383 for (int key : oracle)
384 ASSERT_NE(tbl.search(key), nullptr) << "Final: key " << key << " missing";
385}
386
387// Stress test: fill and empty completely
388TEST(OLhashTable, Stress_FillAndEmpty)
389{
390 OLhashTable<int> tbl(1000);
391 const size_t target = tbl.capacity() - 1;
392
393 // Fill
394 for (size_t i = 0; i < target; ++i)
395 {
396 auto ptr = tbl.insert(static_cast<int>(i));
397 ASSERT_NE(ptr, nullptr) << "Insert failed at i=" << i;
398 }
399
400 EXPECT_EQ(tbl.size(), target);
401
402 // Verify
403 for (size_t i = 0; i < target; ++i)
404 ASSERT_NE(tbl.search(static_cast<int>(i)), nullptr);
405
406 // Empty in random order
407 vector<int> keys(target);
408 iota(keys.begin(), keys.end(), 0);
409
410 mt19937 rng(123);
411 shuffle(keys.begin(), keys.end(), rng);
412
413 for (size_t i = 0; i < target; ++i)
414 {
415 EXPECT_NO_THROW(tbl.remove(keys[i]));
416 EXPECT_EQ(tbl.size(), target - i - 1);
417 }
418
419 EXPECT_TRUE(tbl.is_empty());
420}
421
422// Stress test: linear probing with forced collisions
423TEST(OLhashTable, Stress_LinearProbingCollisions)
424{
425 // Bad hash that causes collisions
426 auto bad_hash = [](const int &) -> size_t { return 0; };
427
428 OLhashTable<int> tbl(100, bad_hash);
429
430 const int num_elements = 50;
431 for (int i = 0; i < num_elements; ++i)
432 {
433 auto ptr = tbl.insert(i);
434 ASSERT_NE(ptr, nullptr) << "Insert failed at i=" << i;
435 }
436
437 EXPECT_EQ(tbl.size(), num_elements);
438
439 // All elements should be findable
440 for (int i = 0; i < num_elements; ++i)
441 {
442 auto ptr = tbl.search(i);
443 ASSERT_NE(ptr, nullptr) << "Element " << i << " not found";
444 EXPECT_EQ(*ptr, i);
445 }
446
447 // Remove in order
448 for (int i = 0; i < num_elements; ++i)
449 {
450 EXPECT_NO_THROW(tbl.remove(i));
451 EXPECT_EQ(tbl.search(i), nullptr);
452 }
453
454 EXPECT_TRUE(tbl.is_empty());
455}
456
457// Stress test: insert/remove cycles
458TEST(OLhashTable, Stress_InsertRemoveCycles)
459{
461
462 const int cycles = 100;
463 const int elements_per_cycle = 50;
464
465 for (int cycle = 0; cycle < cycles; ++cycle)
466 {
467 for (int i = 0; i < elements_per_cycle; ++i)
468 {
469 int key = cycle * elements_per_cycle + i;
470 ASSERT_NE(tbl.insert(key), nullptr);
471 }
472
473 EXPECT_EQ(tbl.size(), elements_per_cycle);
474
475 for (int i = 0; i < elements_per_cycle; ++i)
476 {
477 int key = cycle * elements_per_cycle + i;
478 EXPECT_NO_THROW(tbl.remove(key));
479 }
480
481 EXPECT_TRUE(tbl.is_empty());
482 }
483}
484
485// Stress test: resize operations
486TEST(OLhashTable, Stress_ResizeOperations)
487{
489
490 set<int> oracle;
491 mt19937 rng(999);
492 uniform_int_distribution<int> key_dist(0, 100000);
493
494 const int num_inserts = 5000;
495 for (int i = 0; i < num_inserts; ++i)
496 {
497 int key = key_dist(rng);
498 auto ptr = tbl.insert(key);
499 if (oracle.count(key) == 0 && ptr != nullptr)
500 oracle.insert(key);
501 }
502
503 EXPECT_EQ(tbl.size(), oracle.size());
504
505 // Verify all survived
506 for (int key : oracle)
507 ASSERT_NE(tbl.search(key), nullptr) << "Key " << key << " lost after resize";
508}
509
510// Fuzz test: interleaved operations
511TEST(OLhashTable, Fuzz_InterleavedOperations)
512{
513 // Use large table to avoid resize
514 OLhashTable<int> tbl(5000);
515 set<int> oracle;
516
517 mt19937 rng(7777);
518 uniform_int_distribution<int> key_dist(0, 1000);
519 uniform_real_distribution<double> prob_dist(0.0, 1.0);
520
521 const int num_ops = 5000;
522
523 for (int i = 0; i < num_ops; ++i)
524 {
525 int key = key_dist(rng);
526 double prob = prob_dist(rng);
527
528 if (prob < 0.4)
529 {
530 auto ptr = tbl.insert(key);
531 if (ptr != nullptr)
532 oracle.insert(key);
533 }
534 else if (prob < 0.6)
535 {
536 if (oracle.count(key))
537 {
538 try
539 {
540 tbl.remove(key);
541 oracle.erase(key);
542 }
543 catch (const domain_error &)
544 {
545 FAIL() << "Remove threw for key " << key << " that was in oracle";
546 }
547 }
548 }
549 else
550 {
551 auto ptr = tbl.search(key);
552 EXPECT_EQ(ptr != nullptr, oracle.count(key) > 0);
553 }
554
555 if (i % 500 == 0)
556 ASSERT_EQ(tbl.size(), oracle.size());
557 }
558
559 EXPECT_EQ(tbl.size(), oracle.size());
560}
561
562// Stress test: with auto-resize enabled
563TEST(OLhashTable, Stress_WithAutoResize)
564{
565 OLhashTable<int> tbl(10); // Small initial size, auto-resize enabled
566 set<int> oracle;
567
568 mt19937 rng(333);
569 uniform_int_distribution<int> key_dist(0, 50000);
570
571 const int num_inserts = 3000;
572 for (int i = 0; i < num_inserts; ++i)
573 {
574 int key = key_dist(rng);
575 auto ptr = tbl.insert(key);
576 if (ptr != nullptr)
577 oracle.insert(key);
578 }
579
580 EXPECT_EQ(tbl.size(), oracle.size());
581
582 for (int key : oracle)
583 {
584 auto ptr = tbl.search(key);
585 ASSERT_NE(ptr, nullptr) << "Key " << key << " lost during resize";
586 }
587}
588
589// ============================================================================
590// DELETED CLEANUP TESTS (Knuth's optimization)
591// ============================================================================
592
593// Helper to count bucket states
595{
596 size_t empty = 0;
597 size_t busy = 0;
598 size_t deleted = 0;
599};
600
601template <typename HashTable>
603{
604 BucketStats stats;
605 for (size_t i = 0; i < tbl.capacity(); ++i)
606 {
607 switch (tbl.table[i].status)
608 {
609 case HashTable::EMPTY: ++stats.empty; break;
610 case HashTable::BUSY: ++stats.busy; break;
611 case HashTable::DELETED: ++stats.deleted; break;
612 }
613 }
614 return stats;
615}
616
617// Test: removing last element in chain should mark as EMPTY, not DELETED
618TEST(OLhashTable, DeletedCleanup_LastInChainBecomesEmpty)
619{
620 // Use bad hash to force all elements into same chain
621 auto bad_hash = [](const int &) -> size_t { return 0; };
622 OLhashTable<int> tbl(100, bad_hash);
623 // what is tested is how removals mark buckets; a shrink would rebuild
624 tbl.set_with_resize(false);
625
626 // Insert elements: they will all collide at index 0
627 // Chain: [0] -> [1] -> [2] -> [3] -> [4]
628 for (int i = 0; i < 5; ++i)
629 ASSERT_NE(tbl.insert(i), nullptr);
630
631 auto before = count_bucket_states(tbl);
632 EXPECT_EQ(before.busy, 5);
633 EXPECT_EQ(before.deleted, 0);
634
635 // Remove last element (4) - should become EMPTY since next is EMPTY
636 tbl.remove(4);
637
638 auto after = count_bucket_states(tbl);
639 EXPECT_EQ(after.busy, 4);
640 EXPECT_EQ(after.deleted, 0) << "Last element should become EMPTY, not DELETED";
641 EXPECT_EQ(after.empty, before.empty + 1);
642
643 // Verify remaining elements are still findable
644 for (int i = 0; i < 4; ++i)
645 EXPECT_NE(tbl.search(i), nullptr) << "Element " << i << " should still exist";
646
647 EXPECT_EQ(tbl.search(4), nullptr);
648}
649
650// Test: backward propagation of EMPTY status
651TEST(OLhashTable, DeletedCleanup_BackwardPropagation)
652{
653 // Use bad hash to force chain
654 auto bad_hash = [](const int &) -> size_t { return 0; };
655 OLhashTable<int> tbl(100, bad_hash);
656 // what is tested is how removals mark buckets; a shrink would rebuild
657 tbl.set_with_resize(false);
658
659 // Insert chain: positions 0,1,2,3,4
660 for (int i = 0; i < 5; ++i)
661 ASSERT_NE(tbl.insert(i), nullptr);
662
663 // Remove middle elements first (they become DELETED)
664 tbl.remove(3); // position 3 -> DELETED (next is BUSY at 4)
665 tbl.remove(2); // position 2 -> DELETED (next is DELETED at 3)
666
667 auto mid_stats = count_bucket_states(tbl);
668 EXPECT_EQ(mid_stats.busy, 3); // 0, 1, 4 are BUSY
669 EXPECT_EQ(mid_stats.deleted, 2); // 2, 3 are DELETED
670
671 // Now remove element 4 (last in chain)
672 // This should trigger backward cleanup: 4->EMPTY, 3->EMPTY, 2->EMPTY
673 tbl.remove(4);
674
675 auto final_stats = count_bucket_states(tbl);
676 EXPECT_EQ(final_stats.busy, 2); // 0, 1 are BUSY
677 EXPECT_EQ(final_stats.deleted, 0) << "All trailing DELETED should become EMPTY";
678
679 // Verify remaining elements
680 EXPECT_NE(tbl.search(0), nullptr);
681 EXPECT_NE(tbl.search(1), nullptr);
682 EXPECT_EQ(tbl.search(2), nullptr);
683 EXPECT_EQ(tbl.search(3), nullptr);
684 EXPECT_EQ(tbl.search(4), nullptr);
685}
686
687// Test: DELETED in middle of chain stays DELETED
688TEST(OLhashTable, DeletedCleanup_MiddleStaysDeleted)
689{
690 auto bad_hash = [](const int &) -> size_t { return 0; };
691 OLhashTable<int> tbl(100, bad_hash);
692 // what is tested is how removals mark buckets; a shrink would rebuild
693 tbl.set_with_resize(false);
694
695 // Insert chain: 0,1,2,3,4
696 for (int i = 0; i < 5; ++i)
697 ASSERT_NE(tbl.insert(i), nullptr);
698
699 // Remove element in middle (2) - should stay DELETED because 3,4 follow
700 tbl.remove(2);
701
702 auto stats = count_bucket_states(tbl);
703 EXPECT_EQ(stats.busy, 4);
704 EXPECT_EQ(stats.deleted, 1) << "Middle element should stay DELETED";
705
706 // All other elements still findable
707 for (int i = 0; i < 5; ++i)
708 {
709 if (i == 2)
710 EXPECT_EQ(tbl.search(i), nullptr);
711 else
712 EXPECT_NE(tbl.search(i), nullptr);
713 }
714}
715
716// Test: no DELETED accumulation after many insert/remove cycles
717TEST(OLhashTable, DeletedCleanup_NoAccumulationAfterCycles)
718{
720
721 // Perform many insert/remove cycles
722 const int cycles = 50;
723 const int elements = 30;
724
725 for (int cycle = 0; cycle < cycles; ++cycle)
726 {
727 // Insert
728 for (int i = 0; i < elements; ++i)
729 tbl.insert(cycle * 1000 + i);
730
731 // Remove all
732 for (int i = 0; i < elements; ++i)
733 tbl.remove(cycle * 1000 + i);
734 }
735
736 // After all cycles, table should be mostly EMPTY with no DELETED
737 auto stats = count_bucket_states(tbl);
738 EXPECT_EQ(stats.busy, 0);
739 EXPECT_EQ(stats.deleted, 0) << "Should have no DELETED after complete removal";
740 EXPECT_TRUE(tbl.is_empty());
741}
742
743// Test: cleanup with wrap-around at table boundary
744TEST(OLhashTable, DeletedCleanup_WrapAround)
745{
746 // Hash function that puts elements near end of table
747 OLhashTable<int> tbl(17); // Prime size
748
749 // Force insertion near end by using specific values
750 // that hash near len-1
751 auto near_end_hash = [](const int &k) -> size_t {
752 return static_cast<size_t>(k + 15); // Will wrap around
753 };
754
755 OLhashTable<int> tbl2(17, near_end_hash);
756
757 // Insert elements that will wrap around
758 for (int i = 0; i < 5; ++i)
759 ASSERT_NE(tbl2.insert(i), nullptr);
760
761 EXPECT_EQ(tbl2.size(), 5);
762
763 // Remove all - should handle wrap-around correctly
764 for (int i = 4; i >= 0; --i)
765 {
766 EXPECT_NO_THROW(tbl2.remove(i));
767 }
768
769 auto stats = count_bucket_states(tbl2);
770 EXPECT_EQ(stats.deleted, 0) << "Wrap-around cleanup should leave no DELETED";
771 EXPECT_TRUE(tbl2.is_empty());
772}
773
774// Stress test: verify no DELETED accumulation with random operations
775TEST(OLhashTable, DeletedCleanup_StressNoAccumulation)
776{
778 // what is tested is how removals mark buckets; a shrink would rebuild
779 tbl.set_with_resize(false);
780 set<int> oracle;
781
782 mt19937 rng(12345);
783 uniform_int_distribution<int> key_dist(0, 200);
784 uniform_real_distribution<double> op_dist(0.0, 1.0);
785
786 const int num_ops = 5000;
787
788 for (int i = 0; i < num_ops; ++i)
789 {
790 int key = key_dist(rng);
791 double op = op_dist(rng);
792
793 if (op < 0.5)
794 {
795 auto ptr = tbl.insert(key);
796 if (ptr) oracle.insert(key);
797 }
798 else if (oracle.count(key))
799 {
800 tbl.remove(key);
801 oracle.erase(key);
802 }
803 }
804
805 auto stats = count_bucket_states(tbl);
806
807 // The number of DELETED should be minimal compared to capacity
808 // With Knuth's cleanup, DELETED only accumulates in middle of chains
809 double deleted_ratio = static_cast<double>(stats.deleted) / tbl.capacity();
810 EXPECT_LT(deleted_ratio, 0.1)
811 << "DELETED ratio should be low with cleanup. Got "
812 << stats.deleted << "/" << tbl.capacity();
813
814 // Verify integrity
815 EXPECT_EQ(tbl.size(), oracle.size());
816 for (int key : oracle)
817 EXPECT_NE(tbl.search(key), nullptr);
818}
819
820// ============================================================================
821// COPY/MOVE SEMANTICS TESTS
822// ============================================================================
823
824TEST(OLhashTable, CopyConstructor)
825{
826 OLhashTable<int> original(100);
827 for (int i = 0; i < 50; ++i)
828 original.insert(i);
829
830 OLhashTable<int> copy(original);
831
832 EXPECT_EQ(copy.size(), original.size());
833 EXPECT_EQ(copy.capacity(), original.capacity());
834
835 // Verify all elements exist in both
836 for (int i = 0; i < 50; ++i)
837 {
838 EXPECT_NE(original.search(i), nullptr);
839 EXPECT_NE(copy.search(i), nullptr);
840 }
841
842 // Modify copy, original should be unchanged
843 copy.remove(25);
844 EXPECT_EQ(copy.search(25), nullptr);
845 EXPECT_NE(original.search(25), nullptr);
846}
847
848TEST(OLhashTable, MoveConstructor)
849{
850 OLhashTable<int> original(100);
851 for (int i = 0; i < 50; ++i)
852 original.insert(i);
853
854 const size_t orig_size = original.size();
855 const size_t orig_cap = original.capacity();
856
857 OLhashTable<int> moved(std::move(original));
858
859 EXPECT_EQ(moved.size(), orig_size);
860 EXPECT_EQ(moved.capacity(), orig_cap);
861
862 // Verify all elements exist in moved
863 for (int i = 0; i < 50; ++i)
864 EXPECT_NE(moved.search(i), nullptr);
865}
866
867TEST(OLhashTable, CopyAssignment)
868{
869 OLhashTable<int> original(100);
870 for (int i = 0; i < 50; ++i)
871 original.insert(i);
872
874 copy.insert(999);
875
876 copy = original;
877
878 EXPECT_EQ(copy.size(), original.size());
879
880 for (int i = 0; i < 50; ++i)
881 EXPECT_NE(copy.search(i), nullptr);
882
883 EXPECT_EQ(copy.search(999), nullptr); // Old element gone
884}
885
886TEST(OLhashTable, MoveAssignment)
887{
888 OLhashTable<int> original(100);
889 for (int i = 0; i < 50; ++i)
890 original.insert(i);
891
892 const size_t orig_size = original.size();
893
894 OLhashTable<int> target(10);
895 target.insert(999);
896
897 target = std::move(original);
898
899 EXPECT_EQ(target.size(), orig_size);
900
901 for (int i = 0; i < 50; ++i)
902 EXPECT_NE(target.search(i), nullptr);
903}
904
905TEST(OLhashTable, SelfAssignment)
906{
908 for (int i = 0; i < 50; ++i)
909 tbl.insert(i);
910
911 tbl = tbl; // Self-assignment
912
913 EXPECT_EQ(tbl.size(), 50);
914 for (int i = 0; i < 50; ++i)
915 EXPECT_NE(tbl.search(i), nullptr);
916}
917
918// ============================================================================
919// DELETED SLOT REUSE TESTS
920// ============================================================================
921
922TEST(OLhashTable, DeletedSlotReuse)
923{
924 auto bad_hash = [](const int &) -> size_t { return 0; };
925 OLhashTable<int> tbl(100, bad_hash);
926 // what is tested is how removals mark buckets; a shrink would rebuild
927 tbl.set_with_resize(false);
928
929 // Insert chain: 0,1,2,3,4 at positions 0,1,2,3,4
930 for (int i = 0; i < 5; ++i)
931 tbl.insert(i);
932
933 // Remove middle element (2) - becomes DELETED
934 tbl.remove(2);
935
936 auto before = count_bucket_states(tbl);
937 EXPECT_EQ(before.deleted, 1);
938
939 // Insert new element - should reuse DELETED slot at position 2
940 tbl.insert(100);
941
942 auto after = count_bucket_states(tbl);
943 EXPECT_EQ(after.deleted, 0) << "DELETED slot should be reused";
944 EXPECT_EQ(after.busy, 5);
945
946 // All elements should be findable
947 EXPECT_NE(tbl.search(0), nullptr);
948 EXPECT_NE(tbl.search(1), nullptr);
949 EXPECT_EQ(tbl.search(2), nullptr); // Was removed
950 EXPECT_NE(tbl.search(3), nullptr);
951 EXPECT_NE(tbl.search(4), nullptr);
952 EXPECT_NE(tbl.search(100), nullptr); // New element
953}
954
955// ============================================================================
956// SEARCH_OR_INSERT AND CONTAINS_OR_INSERT TESTS
957// ============================================================================
958
959TEST(OLhashTable, SearchOrInsert_NewKey)
960{
962
963 auto ptr = tbl.search_or_insert(42);
964 ASSERT_NE(ptr, nullptr);
965 EXPECT_EQ(*ptr, 42);
966 EXPECT_EQ(tbl.size(), 1);
967}
968
969TEST(OLhashTable, SearchOrInsert_ExistingKey)
970{
972 tbl.insert(42);
973
974 auto ptr = tbl.search_or_insert(42);
975 ASSERT_NE(ptr, nullptr);
976 EXPECT_EQ(*ptr, 42);
977 EXPECT_EQ(tbl.size(), 1); // No duplicate
978}
979
980TEST(OLhashTable, ContainsOrInsert_NewKey)
981{
983
984 auto [ptr, existed] = tbl.contains_or_insert(42);
985 ASSERT_NE(ptr, nullptr);
986 EXPECT_EQ(*ptr, 42);
987 EXPECT_FALSE(existed);
988 EXPECT_EQ(tbl.size(), 1);
989}
990
991TEST(OLhashTable, ContainsOrInsert_ExistingKey)
992{
994 tbl.insert(42);
995
996 auto [ptr, existed] = tbl.contains_or_insert(42);
997 ASSERT_NE(ptr, nullptr);
998 EXPECT_EQ(*ptr, 42);
999 EXPECT_TRUE(existed);
1000 EXPECT_EQ(tbl.size(), 1);
1001}
1002
1003// ============================================================================
1004// REHASH TESTS
1005// ============================================================================
1006
1007TEST(OLhashTable, ManualRehash)
1008{
1009 OLhashTable<int> tbl(100);
1010 set<int> oracle;
1011
1012 for (int i = 0; i < 50; ++i)
1013 {
1014 tbl.insert(i);
1015 oracle.insert(i);
1016 }
1017
1018 // Remove half to create DELETED slots
1019 for (int i = 0; i < 50; i += 2)
1020 {
1021 tbl.remove(i);
1022 oracle.erase(i);
1023 }
1024
1025 auto before = count_bucket_states(tbl);
1026 (void)before;
1027 // Some DELETED may exist (those in middle of chains)
1028
1029 // Manual rehash should eliminate all DELETED
1030 tbl.rehash();
1031
1032 auto after = count_bucket_states(tbl);
1033 EXPECT_EQ(after.deleted, 0) << "Rehash should eliminate all DELETED";
1034 EXPECT_EQ(after.busy, oracle.size());
1035
1036 // All remaining elements should be findable
1037 for (int key : oracle)
1038 EXPECT_NE(tbl.search(key), nullptr);
1039}
1040
1042{
1044
1045 for (int i = 0; i < 30; ++i)
1046 tbl.insert(i);
1047
1048 const size_t old_cap = tbl.capacity();
1049 tbl.resize(200);
1050
1051 EXPECT_GT(tbl.capacity(), old_cap);
1052 EXPECT_EQ(tbl.size(), 30);
1053
1054 for (int i = 0; i < 30; ++i)
1055 EXPECT_NE(tbl.search(i), nullptr);
1056}
1057
1058TEST(OLhashTable, ResizeDown)
1059{
1060 OLhashTable<int> tbl(200);
1061
1062 for (int i = 0; i < 30; ++i)
1063 tbl.insert(i);
1064
1065 tbl.resize(50);
1066
1067 EXPECT_EQ(tbl.size(), 30);
1068
1069 for (int i = 0; i < 30; ++i)
1070 EXPECT_NE(tbl.search(i), nullptr);
1071}
1072
1073// ============================================================================
1074// EDGE CASES
1075// ============================================================================
1076
1077TEST(OLhashTable, EmptyTableOperations)
1078{
1079 OLhashTable<int> tbl(100);
1080
1081 EXPECT_TRUE(tbl.is_empty());
1082 EXPECT_EQ(tbl.size(), 0);
1083 EXPECT_EQ(tbl.search(42), nullptr);
1084 EXPECT_FALSE(tbl.has(42));
1085 EXPECT_FALSE(tbl.contains(42));
1086 EXPECT_THROW(tbl.remove(42), std::domain_error);
1087}
1088
1089TEST(OLhashTable, SingleElement)
1090{
1091 OLhashTable<int> tbl(100);
1092
1093 tbl.insert(42);
1094 EXPECT_EQ(tbl.size(), 1);
1095 EXPECT_NE(tbl.search(42), nullptr);
1096
1097 tbl.remove(42);
1098 EXPECT_EQ(tbl.size(), 0);
1099 EXPECT_TRUE(tbl.is_empty());
1100 EXPECT_EQ(tbl.search(42), nullptr);
1101
1102 // Table should be clean (no DELETED for single element at end)
1103 auto stats = count_bucket_states(tbl);
1104 EXPECT_EQ(stats.deleted, 0);
1105}
1106
1107TEST(OLhashTable, DuplicateInsertReturnsNull)
1108{
1109 OLhashTable<int> tbl(100);
1110
1111 auto first = tbl.insert(42);
1112 ASSERT_NE(first, nullptr);
1113
1114 auto second = tbl.insert(42);
1115 EXPECT_EQ(second, nullptr) << "Duplicate insert should return nullptr";
1116
1117 EXPECT_EQ(tbl.size(), 1);
1118}
1119
1120TEST(OLhashTable, HasAndContains)
1121{
1122 OLhashTable<int> tbl(100);
1123
1124 EXPECT_FALSE(tbl.has(42));
1125 EXPECT_FALSE(tbl.contains(42));
1126
1127 tbl.insert(42);
1128
1129 EXPECT_TRUE(tbl.has(42));
1130 EXPECT_TRUE(tbl.contains(42));
1131 EXPECT_FALSE(tbl.has(43));
1132 EXPECT_FALSE(tbl.contains(43));
1133}
1134
1136{
1137 OLhashTable<int> tbl(100);
1138 tbl.insert(42);
1139
1140 EXPECT_NO_THROW({
1141 int& ref = tbl.find(42);
1142 EXPECT_EQ(ref, 42);
1143 });
1144
1145 EXPECT_THROW(tbl.find(999), std::domain_error);
1146}
1147
1148// ============================================================================
1149// ITERATOR TESTS
1150// ============================================================================
1151
1152TEST(OLhashTable, IteratorBasic)
1153{
1154 OLhashTable<int> tbl(100);
1155 set<int> oracle;
1156
1157 for (int i = 0; i < 50; ++i)
1158 {
1159 tbl.insert(i);
1160 oracle.insert(i);
1161 }
1162
1163 set<int> visited;
1164 for (auto it = tbl.get_it(); it.has_curr(); it.next())
1165 visited.insert(it.get_curr());
1166
1167 EXPECT_EQ(visited, oracle);
1168}
1169
1170TEST(OLhashTable, IteratorEmpty)
1171{
1172 OLhashTable<int> tbl(100);
1173
1174 auto it = tbl.get_it();
1175 EXPECT_FALSE(it.has_curr());
1176}
1177
1178TEST(OLhashTable, IteratorSingleElement)
1179{
1180 OLhashTable<int> tbl(100);
1181 tbl.insert(42);
1182
1183 auto it = tbl.get_it();
1184 ASSERT_TRUE(it.has_curr());
1185 EXPECT_EQ(it.get_curr(), 42);
1186
1187 it.next();
1188 EXPECT_FALSE(it.has_curr());
1189}
1190
1191TEST(OLhashTable, IteratorDelete)
1192{
1193 OLhashTable<int> tbl(100);
1194
1195 for (int i = 0; i < 10; ++i)
1196 tbl.insert(i);
1197
1198 // Delete all elements via iterator
1199 auto it = tbl.get_it();
1200 while (it.has_curr())
1201 it.del();
1202
1203 EXPECT_TRUE(tbl.is_empty());
1204}
1205
1206// Iterator::del() hands deallocate_bucket() the bucket of its current key.
1207// With all the keys in one run of buckets, each removal leaves its bucket
1208// marked as the one of a removed key, until the last one empties the run.
1209TEST(OLhashTable, IteratorDeleteEmptiesACollisionRun)
1210{
1211 auto bad_hash = [](const int &) -> size_t { return 0; };
1212 OLhashTable<int> tbl(100, bad_hash);
1213
1214 for (int i = 0; i < 10; ++i)
1215 ASSERT_NE(tbl.insert(i), nullptr);
1216
1217 auto it = tbl.get_it();
1218 for (size_t removed = 1; it.has_curr(); ++removed)
1219 {
1220 it.del();
1221 EXPECT_EQ(tbl.size(), 10 - removed);
1222 EXPECT_EQ(tbl.stats().num_deleted, removed < 10 ? removed : 0);
1223 }
1224
1225 EXPECT_TRUE(tbl.is_empty());
1226 EXPECT_EQ(tbl.stats().num_empty, tbl.capacity());
1227
1228 for (int i = 0; i < 10; ++i)
1229 ASSERT_NE(tbl.insert(i), nullptr);
1230 for (int i = 0; i < 10; ++i)
1231 EXPECT_TRUE(tbl.contains(i)) << i;
1232}
1233
1234// ============================================================================
1235// STATS TEST
1236// ============================================================================
1237
1238TEST(OLhashTable, StatsCorrectness)
1239{
1240 auto bad_hash = [](const int &) -> size_t { return 0; };
1241 OLhashTable<int> tbl(100, bad_hash);
1242
1243 // Insert chain
1244 for (int i = 0; i < 10; ++i)
1245 tbl.insert(i);
1246
1247 // Remove some in middle
1248 tbl.remove(3);
1249 tbl.remove(5);
1250 tbl.remove(7);
1251
1252 auto stats = tbl.stats();
1253
1254 EXPECT_EQ(stats.num_busy, 7);
1255 // Some DELETED may exist depending on cleanup
1256 EXPECT_EQ(stats.num_busy + stats.num_deleted + stats.num_empty, tbl.capacity());
1257}
1258
1259// ============================================================================
1260// FUNCTIONAL METHODS TEST
1261// ============================================================================
1262
1264{
1265 OLhashTable<int> tbl(100);
1266 for (int i = 0; i < 10; ++i)
1267 tbl.insert(i);
1268
1269 int sum = 0;
1270 tbl.for_each([&sum](int x) { sum += x; });
1271
1272 EXPECT_EQ(sum, 45); // 0+1+2+...+9
1273}
1274
1276{
1277 OLhashTable<int> tbl(100);
1278 for (int i = 0; i < 10; ++i)
1279 tbl.insert(i * 2); // Even numbers
1280
1281 EXPECT_TRUE(tbl.all([](int x) { return x % 2 == 0; }));
1282 EXPECT_FALSE(tbl.all([](int x) { return x > 5; }));
1283}
1284
1286{
1287 OLhashTable<int> tbl(100);
1288 for (int i = 0; i < 10; ++i)
1289 tbl.insert(i);
1290
1291 EXPECT_TRUE(tbl.exists([](int x) { return x == 5; }));
1292 EXPECT_FALSE(tbl.exists([](int x) { return x == 100; }));
1293}
1294
1296{
1297 OLhashTable<int> tbl(100);
1298 for (int i = 0; i < 10; ++i)
1299 tbl.insert(i);
1300
1301 auto evens = tbl.filter([](int x) { return x % 2 == 0; });
1302
1303 EXPECT_EQ(evens.size(), 5);
1304}
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 remove(const Key &key)
Remove the key referenced by key.
Definition tpl_olhash.H:672
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
constexpr size_t capacity() const noexcept
Returns the current capacity of the table.
Definition hashDry.H:964
constexpr bool is_empty() const noexcept
Checks if the table is empty.
Definition hashDry.H:959
Key * insert(const Key &key)
Inserts a key into the hash table (copy version).
Definition hashDry.H:507
#define FAIL(msg)
#define TEST(name)
static mt19937 rng
MapOLhash< int, Foo > tbl
Main namespace for Aleph-w library functions.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
void iota(C &container, typename C::Item_Type start)
Fill all elements of a container with unit-step sequential values.
size_t dft_hash_fct(const Key &key) noexcept
Primary default hash: best speed/quality trade-off.
Definition hash-fct.H:1030
auto shuffle(const C< T > &c)
Randomly shuffle a sequence.
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
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
STL namespace.
size_t my_hash(const MyRecord &r) noexcept
Definition olhash.cc:104
BucketStats count_bucket_states(const HashTable &tbl)
Definition olhash.cc:602
size_t deleted
Definition olhash.cc:598
size_t empty
Definition olhash.cc:596
size_t busy
Definition olhash.cc:597
bool operator()(const MyRecord &r1, const MyRecord &r2) const noexcept
Definition odhash.cc:97
MyRecord()
Definition olhash.cc:91
string value
Definition odhash.cc:91
MyRecord(size_t k)
Definition olhash.cc:93
size_t key
Definition odhash.cc:90
bool operator==(const MyRecord &r) const noexcept
Definition odhash.cc:102
MyRecord(size_t k, const string &v)
Definition olhash.cc:92
int keys[]
static int * k
Gsl_Compatible_Rng r
Open addressing hash table with linear probing.