Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_odhash.H
Go to the documentation of this file.
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
106# ifndef TPL_ODHASH_H
107# define TPL_ODHASH_H
108
109# include <iostream>
110# include <cstddef>
111# include <cstdint>
112
113# include <primes.H>
114# include <dlink.H>
115# include <tpl_dynArray.H>
116# include <array_it.H>
117# include <ahDry.H>
118# include <utility>
119# include <hash-dry.H>
120# include <hashDry.H>
121# include <hash-fct.H>
122# include <ah-errors.H>
123# include <ah-concepts.H>
124
125using namespace Aleph;
126
127namespace Aleph
128{
129# ifdef N
130# define NBACKUP N
131# undef N
132# endif
133
134# ifdef M
135# define MBACKUP M
136# undef M
137# endif
138
139
184 template <typename Key, class Cmp = Aleph::equal_to<Key>>
187 : public OhashCommon<ODhashTable<Key, Cmp>, Key>,
188 public GenericTraverse<ODhashTable<Key, Cmp>>,
189 public LocateFunctions<ODhashTable<Key, Cmp>, Key>,
190 public FunctionalMethods<ODhashTable<Key, Cmp>, Key>,
191 public EqualToMethod<ODhashTable<Key, Cmp>>,
192 public StlAlephIterator<ODhashTable<Key, Cmp>>
193 {
194 friend class OhashCommon<ODhashTable<Key, Cmp>, Key>;
195
196 public:
197 using Key_Type = Key;
198
199 using Item_Type = Key;
200
201 using Hash_Fct = std::function<size_t(const Key &)>;
202
203 using Hash_Fct_Ptr = size_t (*)(const Key &);
204
206
208
209 struct Bucket
210 {
211 Key key;
212 unsigned char status = EMPTY; // status EMPTY, DELETED o BUSY
213 unsigned char probe_type = NO_PROBED; // FIRST_PROBE SECOND_PROBE LINEAR_PROBE
214 unsigned int probe_counter = 0;
215
216 Bucket() noexcept(std::is_nothrow_default_constructible_v<Key>)
218 { /* empty */
219 }
220
221 void reset() noexcept // put all as when constructed
222 {
223 status = EMPTY;
225 probe_counter = 0;
226 }
227
228 [[nodiscard]] constexpr bool valid() const noexcept
229 {
230 return (status == EMPTY or status == DELETED or status == BUSY) and
233 }
234
235 friend std::ostream &operator <<(std::ostream & out, const Bucket & bucket)
236 {
237 std::string status_str;
238 switch (bucket.status)
239 {
240 case EMPTY: status_str = "EMPTY";
241 break;
242 case BUSY: status_str = "BUSY";
243 break;
244 case DELETED: status_str = "DELETED";
245 break;
246 }
247 std::string probe_type_str;
248 switch (bucket.probe_type)
249 {
250 case NO_PROBED: probe_type_str = "NO_PROBED";
251 break;
252 case FIRST_PROBE: probe_type_str = "FIRST_PROBE";
253 break;
254 case SECOND_PROBE: probe_type_str = "SECOND_PROBE";
255 break;
256 case LINEAR_PROBE: probe_type_str = "LINEAR_PROBE";
257 break;
258 }
259 return out << "Bucket at " << &bucket << '\n'
260 << "status = " << status_str << '\n'
261 << "probe_type = " << probe_type_str << '\n'
262 << "probe_counter = " << bucket.probe_counter;
263 }
264 };
265
266 Bucket *table = nullptr; //bucket arrangement
267 Hash_Fct hash_fct = nullptr; // first hash function
268 Hash_Fct second_hash_fct = nullptr; // second hash function
269
271
272 protected:
273 size_t len; // table size
276
277 private:
278 size_t N; // number of buckets occupied
280 size_t deleted_buckets = 0; // buckets marked as the ones of removed keys
281
282 Bucket * allocate_bucket(Bucket & bucket, unsigned char probe_type) noexcept
283 {
284 assert(bucket.status != BUSY);
285
286 if (bucket.status == DELETED)
288 ++N;
289 bucket.status = BUSY;
290 bucket.probe_type = probe_type;
291 ++bucket.probe_counter;
292
293 return &bucket;
294 }
295
296 void decrease_probe_counter(Bucket *bucket) noexcept
297 {
298 assert(bucket->status == BUSY or bucket->status == DELETED);
299
300 --bucket->probe_counter;
301 if (bucket->probe_counter == 0) // <mark EMPTY on the bucket?
302 {
303 // only a removed key's bucket: a busy one counts its own key
304 assert(bucket->status == DELETED);
306 bucket->status = EMPTY;
307 }
308 }
309
310 void deallocate_bucket(Bucket *bucket) noexcept
311 {
312 deallocate_bucket_with_record(bucket, [](Bucket *) {});
313 }
314
319 void undo_allocate_bucket(Bucket *bucket, const Key & key) noexcept
320 {
321 release_bucket(bucket, key, [](Bucket *) {});
322 }
323
324 size_t index_forward(size_t & i) const noexcept
325 {
326 assert(i < len);
327 if (++i == len)
328 i = 0;
329 return i;
330 }
331
332 size_t index_backward(size_t & i) const noexcept
333 {
334 assert(i < len);
335 if (i-- == 0)
336 i = len - 1;
337 return i;
338 }
339
340 [[nodiscard]] bool is_valid_bucket(Bucket *bucket) const noexcept
341 {
342 if (table == nullptr)
343 return false;
344
345 const auto begin = reinterpret_cast<std::uintptr_t>(&table[0]);
346 const auto end = reinterpret_cast<std::uintptr_t>(&table[len]);
347 const auto addr = reinterpret_cast<std::uintptr_t>(bucket);
348
349 if (addr < begin or addr >= end)
350 return false;
351
352 const auto offset_with_base =
353 static_cast<std::ptrdiff_t>(addr - begin);
354 return offset_with_base % sizeof(*bucket) == 0;
355 }
356
357 [[nodiscard]] size_t bucket_to_index(Bucket *bucket) const noexcept
358 {
359 assert(is_valid_bucket(bucket));
360 return bucket - &table[0];
361 }
362
364 [[nodiscard]] bool is_key_in_table(const Key & key) const noexcept
365 {
366 if (table == nullptr)
367 return false;
368
369 const auto addr = reinterpret_cast<std::uintptr_t>(&key);
370 const auto table_begin = reinterpret_cast<std::uintptr_t>(&table[0]);
371 const auto table_end = reinterpret_cast<std::uintptr_t>(&table[len]);
372
373 if (addr < table_begin or addr >= table_end)
374 return false;
375
376 constexpr auto key_offset = offsetof(Bucket, key);
377 return ((addr - table_begin - key_offset) % sizeof(Bucket)) == 0;
378 }
379
381 [[nodiscard]] Bucket * key_in_table_to_bucket(const Key & key) noexcept
382 {
383 assert(is_key_in_table(key));
384 return key_to_bucket(const_cast<Key *>(&key));
385 }
386
389 template <typename RecordBucket>
391 RecordBucket && record_bucket) noexcept
392 {
393 release_bucket(bucket, bucket->key,
394 std::forward<RecordBucket>(record_bucket));
395 }
396
403 template <typename RecordBucket>
404 void release_bucket(Bucket *bucket, const Key & key,
405 RecordBucket && record_bucket) noexcept
406 {
407 assert(bucket->status == BUSY);
408
409 bucket->status = DELETED;
411
412 const size_t i_fst = hash_fct(key) % len;
413 if (&table[i_fst] == bucket)
414 {
415 assert(table[i_fst].probe_type == FIRST_PROBE);
416 }
417 else
418 {
419 const size_t i_snd = second_hash_fct(key) % len;
420 if (&table[i_snd] == bucket)
421 {
422 assert(table[i_snd].probe_type == SECOND_PROBE);
423 record_bucket(&table[i_fst]);
425 }
426 else
427 {
428 record_bucket(&table[i_fst]);
430 record_bucket(&table[i_snd]);
432 size_t i = i_snd;
433 for (index_forward(i); &table[i] != bucket; index_forward(i))
434 {
435 assert(table[i].status != EMPTY);
436 record_bucket(&table[i]);
438 }
439 assert(table[i].probe_type == LINEAR_PROBE);
440 }
441 }
442
444 --N;
445 }
446
447 public:
448 [[nodiscard]] static Bucket * key_to_bucket(Key *rec) noexcept
449 {
450 const auto base = reinterpret_cast<std::uintptr_t>(rec);
451 const auto offset = offsetof(Bucket, key);
452 return reinterpret_cast<Bucket *>(base - offset);
453 }
454
455 [[nodiscard]] constexpr const Cmp &get_compare() const noexcept { return cmp; }
456
457 [[nodiscard]] constexpr Cmp &get_compare() noexcept { return cmp; }
458
470 void swap(ODhashTable & other) noexcept
471 {
472 std::swap(table, other.table);
473 std::swap(hash_fct, other.hash_fct);
474 std::swap(second_hash_fct, other.second_hash_fct);
476 std::swap(N, other.N);
477 std::swap(len, other.len);
478 std::swap(lower_alpha, other.lower_alpha);
479 std::swap(upper_alpha, other.upper_alpha);
480 std::swap(with_resize, other.with_resize);
481 std::swap(deleted_buckets, other.deleted_buckets);
482 }
483
484 protected:
485 ODhashTable(const size_t l, Hash_Fct fst_hash_fct,
486 Hash_Fct snd_hash_fct, Cmp cpm_fct,
487 const float lower, const float upper, const bool resize)
488 : table(nullptr), hash_fct(fst_hash_fct),
490 len(hash_dry_detail::prime_table_len<Bucket>(l)),
491 lower_alpha(lower), upper_alpha(upper),
492 N(0), with_resize(resize)
493 {
494 table = new Bucket[len];
495 }
496
497 public:
525
526 using Base::contains;
527
529 Hash_Fct_Ptr first_hash_fct = Aleph::dft_hash_ptr_fct<Key>,
530 Hash_Fct_Ptr second_hash_fct = Aleph::snd_hash_ptr_fct<Key>,
531 Cmp cmp = Cmp(),
534 bool with_resize = true)
535 : ODhashTable(len, Hash_Fct(first_hash_fct), Hash_Fct(second_hash_fct),
537
555 template <typename H1, typename H2>
556 requires (std::is_convertible_v<H1, Hash_Fct_Ptr>
557 and std::is_convertible_v<H2, Hash_Fct_Ptr>
558 and (std::is_class_v<std::remove_cvref_t<H1>>
559 or std::is_class_v<std::remove_cvref_t<H2>>))
560 ODhashTable(size_t len, H1 && first_hash_fct, H2 && second_hash_fct,
561 Cmp cmp, float lower_alpha, float upper_alpha,
562 bool with_resize)
564 Hash_Fct(static_cast<Hash_Fct_Ptr>(first_hash_fct)),
567
570 {
571 if (table != nullptr)
572 delete [] table;
573 }
574
586 : ODhashTable(other.len == 0 ? Primes::DefaultPrime : other.len,
587 other.hash_fct, other.second_hash_fct, other.cmp,
588 other.lower_alpha, other.upper_alpha, other.with_resize)
589 {
590 assert(table != nullptr);
591 this->copy_from_table(other);
592 }
593
609 ODhashTable(ODhashTable && other) noexcept
610 : table(other.table), hash_fct(other.hash_fct),
611 second_hash_fct(other.second_hash_fct), cmp(other.cmp),
612 len(other.len),
613 lower_alpha(other.lower_alpha), upper_alpha(other.upper_alpha),
614 N(other.N), with_resize(other.with_resize),
615 deleted_buckets(other.deleted_buckets)
616 {
617 other.table = nullptr;
618 other.N = 0;
619 other.len = 0;
620 other.deleted_buckets = 0;
621 }
622
624
637 {
638 if (this == &other)
639 return *this;
640
641 ODhashTable tmp(other);
642 swap(tmp);
643
644 return *this;
645 }
646
648 {
649 swap(other);
650 return *this;
651 }
652
654
657 [[nodiscard]] Key * search(const Key & key) noexcept
658 {
659 return const_cast<Key *>(std::as_const(*this).search(key));
660 }
661
664 [[nodiscard]] const Key * search(const Key & key) const noexcept
665 {
666 if (len == 0) [[unlikely]]
667 return nullptr; // the storage was taken by a move
668
669 const size_t i_fst = hash_fct(key) % len; // 1st probe (1st hash function)
670 if (table[i_fst].status == EMPTY) [[unlikely]]
671 return nullptr;
672
673 if (table[i_fst].status == BUSY and cmp(table[i_fst].key, key)) [[likely]]
674 {
675 assert(table[i_fst].probe_type == FIRST_PROBE);
676 assert(table[i_fst].probe_counter > 0);
677 return &table[i_fst].key;
678 }
679
680 // Early exit: if BUSY with different key and probe_counter == 1,
681 // no other key with this first hash can exist in the table
682 if (table[i_fst].status == BUSY and table[i_fst].probe_counter == 1)
683 return nullptr;
684
685 const size_t i_snd = second_hash_fct(key) % len; // 2nd probe
686
687 // If both hashes collide to same index, skip directly to linear probing
688 if (i_fst == i_snd) [[unlikely]]
689 goto linear_probe;
690
691 if (table[i_snd].status == EMPTY)
692 return nullptr;
693
694 if (table[i_snd].status == BUSY and cmp(table[i_snd].key, key))
695 {
696 assert(table[i_snd].probe_type == SECOND_PROBE);
697 assert(table[i_snd].probe_counter > 0);
698 return &table[i_snd].key;
699 }
700
701 // Early exit: if BUSY with different key and probe_counter == 1,
702 // no other key passed through this bucket
703 if (table[i_snd].status == BUSY and table[i_snd].probe_counter == 1)
704 return nullptr;
705
706 linear_probe:
707 size_t i = i_snd;
708 // Linear polling from index of 2nd hash function
709 for (size_t count = 0; count < len; ++count)
710 {
711 index_forward(i);
712 // Prefetch next bucket for better cache performance
713 __builtin_prefetch(&table[(i + 1 < len) ? i + 1 : 0], 0, 1);
714 switch (table[i].status)
715 {
716 case EMPTY:
717 assert(table[i].probe_counter == 0);
718 return nullptr;
719 case BUSY:
720 assert(table[i].probe_counter > 0);
721 if (cmp(table[i].key, key)) [[unlikely]]
722 {
723 assert(table[i].probe_type == LINEAR_PROBE);
724 return &table[i].key;
725 }
726 break;
727 case DELETED:
728 assert(table[i].probe_counter > 0);
729 break;
730 default: AH_ERROR("ODhashTable search: inconsistent bucket status");
731 }
732 }
733
734 return nullptr;
735 }
736
737 [[nodiscard]] constexpr Hash_Fct get_second_hash_fct() const noexcept { return second_hash_fct; }
738
751 {
752 Hash_Fct old = std::move(second_hash_fct);
753 second_hash_fct = std::move(fct);
754 if (N == 0)
755 return;
756
757 try
758 {
759 this->rehash();
760 }
761 catch (...)
762 {
763 second_hash_fct = std::move(old);
764 throw;
765 }
766 }
767
773
774 private:
775 Bucket * allocate_bucket(const Key & key) noexcept
776 {
777 assert(N < len);
778
779 const size_t i_fst = hash_fct(key) % len;
780
781 // EMPTY at first probe: safe to insert, no collision chain
782 if (table[i_fst].status == EMPTY)
783 return allocate_bucket(table[i_fst], FIRST_PROBE);
784
785 // BUSY at first probe: check for duplicate
786 if (table[i_fst].status == BUSY && cmp(table[i_fst].key, key))
787 return nullptr;
788
789 const size_t i_snd = second_hash_fct(key) % len;
790
791 // EMPTY at second probe: safe to insert if first wasn't the key
792 if (table[i_snd].status == EMPTY)
793 {
794 // If first was DELETED, use it; otherwise use second
795 if (table[i_fst].status == DELETED)
796 return allocate_bucket(table[i_fst], FIRST_PROBE);
797 ++table[i_fst].probe_counter;
798 return allocate_bucket(table[i_snd], SECOND_PROBE);
799 }
800
801 // BUSY at second probe: check for duplicate
802 if (table[i_snd].status == BUSY && cmp(table[i_snd].key, key))
803 return nullptr;
804
805 // Need to do linear probing - search for duplicate and find insertion point
806 Bucket *candidate = nullptr;
807 size_t candidate_idx = 0;
808
809 // Check if first or second are candidates (DELETED)
810 if (table[i_fst].status == DELETED)
811 {
812 candidate = &table[i_fst];
813 candidate_idx = 0; // Marker: use first probe slot
814 }
815 else if (table[i_snd].status == DELETED)
816 {
817 candidate = &table[i_snd];
818 candidate_idx = 1; // Marker: use second probe slot
819 }
820
821 size_t i = i_snd;
822 for (size_t c = 0; c < len; ++c)
823 {
824 index_forward(i);
825 // Prefetch next bucket for better cache performance
826 __builtin_prefetch(&table[(i + 1 < len) ? i + 1 : 0], 0, 1);
827
828 if (table[i].status == EMPTY)
829 {
830 // End of collision chain - no duplicate, insert
831 if (candidate)
832 {
833 // Insert at the first DELETED slot found
834 if (candidate_idx == 0) // First probe slot
835 return allocate_bucket(*candidate, FIRST_PROBE);
836 if (candidate_idx == 1) // Second probe slot
837 {
838 ++table[i_fst].probe_counter;
839 return allocate_bucket(*candidate, SECOND_PROBE);
840 }
841 // Linear probe slot - need to update all counters
842 ++table[i_fst].probe_counter;
843 ++table[i_snd].probe_counter;
844 size_t j = i_snd;
845 for (size_t k = 0; k < candidate_idx - 2; ++k)
846 {
847 index_forward(j);
848 ++table[j].probe_counter;
849 }
850 return allocate_bucket(*candidate, LINEAR_PROBE);
851 }
852 // No DELETED found, insert at this EMPTY slot
853 ++table[i_fst].probe_counter;
854 ++table[i_snd].probe_counter;
855 // Increment probe_counter for all buckets between i_snd and i (exclusive)
856 size_t j = i_snd;
857 for (size_t k = 0; k < c; ++k)
858 {
859 index_forward(j);
860 ++table[j].probe_counter;
861 }
863 }
864
865 if (table[i].status == BUSY && cmp(table[i].key, key))
866 return nullptr; // Duplicate found
867
868 if (table[i].status == DELETED && candidate == nullptr)
869 {
870 candidate = &table[i];
871 candidate_idx = c + 2; // Store position (2 = after first and second)
872 }
873 }
874
875 // Table full, but might have a DELETED slot
876 if (candidate)
877 {
878 if (candidate_idx == 0)
879 return allocate_bucket(*candidate, FIRST_PROBE);
880 if (candidate_idx == 1)
881 {
882 ++table[i_fst].probe_counter;
883 return allocate_bucket(*candidate, SECOND_PROBE);
884 }
885 ++table[i_fst].probe_counter;
886 ++table[i_snd].probe_counter;
887 size_t j = i_snd;
888 for (size_t k = 0; k < candidate_idx - 2; ++k)
889 {
890 index_forward(j);
891 ++table[j].probe_counter;
892 }
893 return allocate_bucket(*candidate, LINEAR_PROBE);
894 }
895
896 return nullptr;
897 }
898
899 // search key. If found return (bucket_ptr, true), otherwise allocates and
900 // returns (new_bucket_ptr, false)
901 std::tuple<Bucket *, bool> hard_allocate_bucket(const Key & key) noexcept
902 {
903 assert(N < len);
904
905 Bucket *candidate = nullptr;
906 size_t candidate_linear_steps = 0; // How many linear steps to reach candidate
907
908 const size_t i_fst = hash_fct(key) % len;
909 switch (table[i_fst].status)
910 {
911 case EMPTY:
912 return {allocate_bucket(table[i_fst], FIRST_PROBE), false};
913 case DELETED:
914 candidate = &table[i_fst];
915 // candidate at FIRST_PROBE, no linear steps needed
916 break;
917 case BUSY:
918 if (cmp(table[i_fst].key, key))
919 return {&table[i_fst], true}; // found existing
920 break;
921 }
922
923 const size_t i_snd = second_hash_fct(key) % len;
924 switch (table[i_snd].status)
925 {
926 case EMPTY:
927 if (candidate) // candidate is at i_fst (FIRST_PROBE)
928 return {allocate_bucket(*candidate, FIRST_PROBE), false};
929 ++table[i_fst].probe_counter;
930 return {allocate_bucket(table[i_snd], SECOND_PROBE), false};
931 case DELETED:
932 if (candidate == nullptr)
933 {
934 candidate = &table[i_snd];
935 // candidate at SECOND_PROBE, no linear steps needed
936 }
937 break;
938 case BUSY:
939 if (cmp(table[i_snd].key, key))
940 return {&table[i_snd], true}; // found existing
941 break;
942 }
943
944 // Determine if candidate is at i_fst or i_snd (for probe_type later)
945 const bool candidate_at_first = (candidate == &table[i_fst]);
946 const bool candidate_at_second = (candidate == &table[i_snd]);
947
948 size_t i = i_snd;
949 for (size_t c = 0; c < len; ++c)
950 {
951 index_forward(i);
952 // Prefetch next bucket for better cache performance
953 __builtin_prefetch(&table[(i + 1 < len) ? i + 1 : 0], 0, 1);
954 switch (table[i].status)
955 {
956 case BUSY:
957 if (cmp(table[i].key, key))
958 return {&table[i], true}; // found existing
959 break;
960 case DELETED:
961 if (candidate == nullptr)
962 {
963 candidate = &table[i];
964 candidate_linear_steps = c + 1; // Steps from i_snd
965 }
966 break;
967 case EMPTY:
968 {
969 // End of collision chain - insert at candidate or here
970 if (candidate)
971 {
972 if (candidate_at_first)
973 return {allocate_bucket(*candidate, FIRST_PROBE), false};
974
975 ++table[i_fst].probe_counter;
976
977 if (candidate_at_second)
978 return {allocate_bucket(*candidate, SECOND_PROBE), false};
979
980 // Candidate is in LINEAR_PROBE region
981 ++table[i_snd].probe_counter;
982 // Increment all buckets between i_snd and candidate
983 size_t j = i_snd;
984 for (size_t k = 0; k < candidate_linear_steps - 1; ++k)
985 {
986 index_forward(j);
987 ++table[j].probe_counter;
988 }
989 return {allocate_bucket(*candidate, LINEAR_PROBE), false};
990 }
991 // No candidate found, insert at this EMPTY slot
992 ++table[i_fst].probe_counter;
993 ++table[i_snd].probe_counter;
994 // Increment all buckets between i_snd and here
995 size_t j = i_snd;
996 for (size_t k = 0; k < c; ++k)
997 {
998 index_forward(j);
999 ++table[j].probe_counter;
1000 }
1001 return {allocate_bucket(table[i], LINEAR_PROBE), false};
1002 }
1003 default: AH_ERROR("ODhashTable: Invalid bucket status");
1004 break;
1005 }
1006 }
1007
1008 // All slots checked (full table), use candidate if found
1009 if (candidate)
1010 {
1011 if (candidate_at_first)
1012 return {allocate_bucket(*candidate, FIRST_PROBE), false};
1013
1014 ++table[i_fst].probe_counter;
1015
1016 if (candidate_at_second)
1017 return {allocate_bucket(*candidate, SECOND_PROBE), false};
1018
1019 // Candidate is in LINEAR_PROBE region
1020 ++table[i_snd].probe_counter;
1021 size_t j = i_snd;
1022 for (size_t k = 0; k < candidate_linear_steps - 1; ++k)
1023 {
1024 index_forward(j);
1025 ++table[j].probe_counter;
1026 }
1027 return {allocate_bucket(*candidate, LINEAR_PROBE), false};
1028 }
1029
1030 return {nullptr, false};
1031 }
1032
1038 void remove_bucket(Bucket *bucket)
1039 {
1040 ah_invalid_argument_if(not is_valid_bucket(bucket)) << "key pty does not belong to hash table";
1041 ah_domain_error_if(bucket->status != BUSY) << "Bucket containing key is not BUSY";
1042
1043 deallocate_bucket(bucket);
1044 }
1045
1046 private:
1047 // Removes key as remove() does, but without shrinking the table
1048 void remove_without_shrinking(const Key & key)
1049 {
1050 // Fast path: if key is a reference to a key inside the table
1051 if (is_key_in_table(key)) [[likely]]
1052 {
1053 Bucket *bucket = key_in_table_to_bucket(key);
1054 ah_domain_error_if(bucket->status != BUSY)
1055 << "Bucket containing key is not BUSY";
1056 deallocate_bucket(bucket);
1057 return;
1058 }
1059
1060 ah_domain_error_if(len == 0) << "Key not in hash table";
1061
1062 // External key: search for it (without modifying probe_counters)
1063 const size_t i_fst = hash_fct(key) % len;
1064
1065 // Check first probe position
1066 ah_domain_error_if(table[i_fst].status == EMPTY) << "Key not in hash table";
1067
1068 if (table[i_fst].status == BUSY and cmp(table[i_fst].key, key)) [[likely]]
1069 {
1070 deallocate_bucket(&table[i_fst]);
1071 return;
1072 }
1073
1074 // Early exit: if BUSY with different key and probe_counter == 1,
1075 // no other key with this first hash can exist in the table
1076 ah_domain_error_if(table[i_fst].status == BUSY and table[i_fst].probe_counter == 1)
1077 << "Key not in hash table";
1078
1079 const size_t i_snd = second_hash_fct(key) % len;
1080
1081 // If both hashes collide to same index, skip directly to linear probing
1082 if (i_fst == i_snd) [[unlikely]]
1083 goto linear_probe_remove;
1084
1085 // Check second probe position
1086 ah_domain_error_if(table[i_snd].status == EMPTY) << "Key not in hash table";
1087
1088 if (table[i_snd].status == BUSY and cmp(table[i_snd].key, key))
1089 {
1090 deallocate_bucket(&table[i_snd]);
1091 return;
1092 }
1093
1094 // Early exit: if BUSY with different key and probe_counter == 1,
1095 // no other key passed through this bucket
1096 ah_domain_error_if(table[i_snd].status == BUSY and table[i_snd].probe_counter == 1)
1097 << "Key not in hash table";
1098
1099 linear_probe_remove:
1100 // Linear probing (search only, no modifications until key found)
1101 size_t i = i_snd;
1102 for (size_t c = 0; c < len; ++c)
1103 {
1104 index_forward(i);
1105 // Prefetch next bucket for better cache performance
1106 __builtin_prefetch(&table[(i + 1 < len) ? i + 1 : 0], 0, 1);
1107
1108 switch (table[i].status)
1109 {
1110 case EMPTY:
1111 ah_domain_error() << "Key not in hash table";
1112 break; // unreachable, but silences -Wimplicit-fallthrough
1113
1114 case BUSY:
1115 if (cmp(table[i].key, key)) [[unlikely]]
1116 {
1118 return;
1119 }
1120 break;
1121
1122 case DELETED:
1123 break;
1124 }
1125 }
1126
1127 ah_domain_error() << "Key not in hash table";
1128 }
1129
1130 public:
1137 void remove(const Key & key)
1138 {
1140 this->shrink_after_removal();
1141 }
1142
1144
1145 [[nodiscard]] Stats stats() const
1146 {
1147 DynArray<size_t> lens;
1148 size_t num_busy = 0, num_deleted = 0, num_empty = 0;
1149 size_t max_len = std::numeric_limits<size_t>::min();
1150 for (size_t i = 0; i < len; ++i)
1151 switch (table[i].status)
1152 {
1153 case BUSY:
1154 {
1155 ++num_busy;
1156 const Key & key = table[i].key;
1157 size_t count = 1;
1158 const size_t i_fst = hash_fct(key) % len;
1159 if (cmp(table[i_fst].key, key))
1160 {
1161 assert(table[i_fst].probe_type == FIRST_PROBE);
1162 assert(table[i_fst].probe_counter > 0);;
1163 }
1164 else
1165 {
1166 ++count;
1167 size_t i_snd = second_hash_fct(key) % len;
1168 if (cmp(table[i_snd].key, key))
1169 {
1170 assert(table[i_snd].probe_type == SECOND_PROBE);
1171 assert(table[i_snd].probe_counter > 0);;
1172 }
1173 else
1174 {
1175 for (size_t i = index_forward(i_snd); true;
1176 index_forward(i))
1177 {
1178 if (table[i].status == BUSY and cmp(table[i].key, key))
1179 break;
1180 ++count;
1181 }
1182 }
1183 }
1184 max_len = std::max(max_len, count);
1185 update_stat_len(lens, count);
1186 break;
1187 }
1188 case EMPTY:
1189 ++num_empty;
1190 update_stat_len(lens, 0);
1191 break;
1192 case DELETED:
1193 ++num_deleted;
1194 break;
1195 }
1196 assert(num_deleted == deleted_buckets);
1197
1198 float avg = 0, sum = 0;
1199 for (size_t i = 0; i < lens.size(); ++i)
1200 {
1201 avg += lens(i) * i;
1202 sum += lens(i);
1203 }
1204
1205 // A table whose storage was taken by a move has no bucket to
1206 // average over: its average and its variance are zero.
1207 if (sum > 0)
1208 avg /= sum;
1209 float var = 0;
1210 for (size_t i = 0; i < lens.size(); ++i)
1211 {
1212 const float s = i - avg;
1213 var += lens(i) * s * s;
1214 }
1215 if (sum > 0)
1216 var /= sum;
1217
1218 Stats stats;
1219 stats.num_busy = num_busy;
1220 stats.num_deleted = num_deleted;
1221 stats.num_empty = num_empty;
1222 std::swap(lens, stats.lens);
1223 stats.avg = avg;
1224 stats.var = var;
1225 stats.max_len = max_len;
1226
1227 return stats;
1228 }
1229 };
1230
1231
1232 template <typename Key, class Cmp = Aleph::equal_to<Key>>
1234
1235
1236# ifdef NBACKUP
1237# define N NBACKUP
1238# undef NBACKUP
1239# endif
1240
1241# ifdef MBACKUP
1242# define M MBACKUP
1243# undef MBACKUP
1244# endif
1245
1246# undef EMPTY
1247# undef BUSY
1248# undef DELETED
1249# undef NO_PROBED
1250# undef FIRST_PROBE
1251# undef SECOND_PROBE
1252# undef LINEAR_PROBE
1253} // end namespace Aleph
1254
1255# endif // TPL_ODHASH_H
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error()
Throws std::domain_error unconditionally.
Definition ah-errors.H:702
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
#define AH_ERROR(...)
Print an error message (always enabled).
Definition ahDefs.H:270
DRY (Don't Repeat Yourself) utilities and macros.
#define Special_Ctors(Set_Type, Type)
Generates special constructors for containers.
Definition ahDry.H:123
Iterator wrapper for C++ raw arrays and circular buffers.
size_t size_t int32_t * out
Definition ca-c-api.h:120
size_t size() const noexcept
Return the current dimension of array.
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
Bucket * key_in_table_to_bucket(const Key &key) noexcept
Converts a key reference inside the table to its containing bucket.
Definition tpl_odhash.H:381
static Bucket * key_to_bucket(Key *rec) noexcept
Definition tpl_odhash.H:448
typename OhashCommon< ODhashTable< Key, Cmp >, Key >::Stats Stats
void release_bucket(Bucket *bucket, const Key &key, RecordBucket &&record_bucket) noexcept
Frees bucket, which was reached with the probe sequence of key, and walks that sequence back: every b...
Definition tpl_odhash.H:404
const Key * search(const Key &key) const noexcept
searches the table for the key.
Definition tpl_odhash.H:664
size_t bucket_to_index(Bucket *bucket) const noexcept
Definition tpl_odhash.H:357
void deallocate_bucket_with_record(Bucket *bucket, RecordBucket &&record_bucket) noexcept
Template version of deallocate_bucket that accepts a callback to record modified buckets before decre...
Definition tpl_odhash.H:390
void set_second_hash_fct(Hash_Fct fct)
Sets the hash function of the second probe.
Definition tpl_odhash.H:750
bool is_key_in_table(const Key &key) const noexcept
Returns true if the key reference points to a key inside the table.
Definition tpl_odhash.H:364
size_t(*)(const Key &) Hash_Fct_Ptr
Definition tpl_odhash.H:203
size_t index_backward(size_t &i) const noexcept
Definition tpl_odhash.H:332
Hash_Fct second_hash_fct
Definition tpl_odhash.H:268
void decrease_probe_counter(Bucket *bucket) noexcept
Definition tpl_odhash.H:296
constexpr Hash_Fct get_second_hash_fct() const noexcept
Definition tpl_odhash.H:737
void remove_without_shrinking(const Key &key)
~ODhashTable()
Free the whole hash table.
Definition tpl_odhash.H:569
std::function< size_t(const Key &)> Hash_Fct
Definition tpl_odhash.H:201
void swap(ODhashTable &other) noexcept
Swaps this table with other in constant time.
Definition tpl_odhash.H:470
ODhashTable(const size_t l, Hash_Fct fst_hash_fct, Hash_Fct snd_hash_fct, Cmp cpm_fct, const float lower, const float upper, const bool resize)
Definition tpl_odhash.H:485
void undo_allocate_bucket(Bucket *bucket, const Key &key) noexcept
Undoes what allocate_bucket() or hard_allocate_bucket() did when they reserved bucket for key,...
Definition tpl_odhash.H:319
constexpr Cmp & get_compare() noexcept
Definition tpl_odhash.H:457
ODhashTable(const ODhashTable &other)
Copy constructor.
Definition tpl_odhash.H:585
void remove_bucket(Bucket *bucket)
Delete the record from the table.
bool is_valid_bucket(Bucket *bucket) const noexcept
Definition tpl_odhash.H:340
ODhashTable(ODhashTable &&other) noexcept
Move constructor.
Definition tpl_odhash.H:609
void remove(const Key &key)
Remove a key from the hash table.
Bucket * allocate_bucket(const Key &key) noexcept
Definition tpl_odhash.H:775
ODhashTable(size_t len, H1 &&first_hash_fct, H2 &&second_hash_fct, Cmp cmp, float lower_alpha, float upper_alpha, bool with_resize)
Builds a table when a hash function is a lambda without captures.
Definition tpl_odhash.H:560
size_t index_forward(size_t &i) const noexcept
Definition tpl_odhash.H:324
static void update_stat_len(DynArray< size_t > &lens, size_t i)
Definition tpl_odhash.H:653
void deallocate_bucket(Bucket *bucket) noexcept
Definition tpl_odhash.H:310
constexpr const Cmp & get_compare() const noexcept
Definition tpl_odhash.H:455
ODhashTable(size_t len=Primes::DefaultPrime, Hash_Fct_Ptr first_hash_fct=Aleph::dft_hash_ptr_fct< Key >, Hash_Fct_Ptr second_hash_fct=Aleph::snd_hash_ptr_fct< Key >, Cmp cmp=Cmp(), float lower_alpha=hash_default_lower_alpha, float upper_alpha=hash_default_upper_alpha, bool with_resize=true)
Definition tpl_odhash.H:528
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
Bucket * allocate_bucket(Bucket &bucket, unsigned char probe_type) noexcept
Definition tpl_odhash.H:282
void set_second_hash_fct(Hash_Fct_Ptr fct)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition tpl_odhash.H:769
std::tuple< Bucket *, bool > hard_allocate_bucket(const Key &key) noexcept
Definition tpl_odhash.H:901
Stats stats() const
ODhashTable & operator=(const ODhashTable &other)
Copy assignment.
Definition tpl_odhash.H:636
Equality test for sets.
Definition ah-dry.H:3026
Common methods to the Aleph-w ( ) containers.
Definition ah-dry.H:1235
and
Insert a new element into the container by constructing it from the given args.
Definition ah-dry.H:1273
Common sequential searching methods on containers.
Definition ah-dry.H:555
CRTP mixin providing common operations for open addressing hash tables.
Definition hashDry.H:172
size_t resize(size_t new_size)
Resizes the hash table to a new capacity.
Definition hashDry.H:888
void copy_from_table(const HashTbl &other)
Copies all entries from another hash table.
Definition hashDry.H:413
constexpr bool contains(const Key &key) const noexcept
Alias for has().
Definition hashDry.H:769
void rehash()
Rebuilds the hash table with the same capacity.
Definition hashDry.H:915
void shrink_after_removal() noexcept
Shrinks a table that resizes itself, after a removal took its load factor under the lower threshold.
Definition hashDry.H:346
Mixin that adds STL begin()/end() and cbegin()/cend() to Aleph containers.
iterator end() noexcept
Return an STL-compatible end iterator.
iterator begin() noexcept
Return an STL-compatible iterator to the first element.
Equivalence relation constraint for equality comparators.
void swap_compare(Cmp &a, Cmp &b) noexcept
Swaps the comparators of two hash tables.
Definition hashDry.H:1357
Common hash table utilities and base classes.
#define OHASH_COMMON(class_name)
Definition hash-dry.H:50
Standard hash functions for Aleph types.
Common operations for open addressing hash tables (CRTP mixin).
const long double offset[]
Offset values indexed by symbol string length (bounded by MAX_OFFSET_INDEX)
Main namespace for Aleph-w library functions.
size_t snd_hash_fct(const Key &key) noexcept
Secondary default hash: different distribution from dft_hash_fct.
Definition hash-fct.H:1108
const float hash_default_upper_alpha
Definition hash-dry.C:40
const float hash_default_lower_alpha
Definition hash-dry.C:38
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
const unsigned long DefaultPrime
Default prime number used when no specific size is requested.
Definition primes.C:381
STL namespace.
Prime number utilities for hash tables and mathematical operations.
Bucket() noexcept(std::is_nothrow_default_constructible_v< Key >)
Definition tpl_odhash.H:216
constexpr bool valid() const noexcept
Definition tpl_odhash.H:228
friend std::ostream & operator<<(std::ostream &out, const Bucket &bucket)
Definition tpl_odhash.H:235
Generic traversal of the container through its iterator.
Definition ah-dry.H:363
static int * k
Lazy and scalable dynamic array implementation.
DynList< int > l