Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_olhash.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
97# ifndef TPL_OLHASH_H
98# define TPL_OLHASH_H
99
100# include <iostream>
101# include <cstddef>
102# include <cstdint>
103# include <primes.H>
104# include <dlink.H>
105# include <ahDry.H>
106# include <utility>
107# include <hash-dry.H>
108# include <hashDry.H>
109# include <hash-fct.H>
110# include <ah-errors.H>
111# include <ah-concepts.H>
112
113using namespace Primes;
114
115using namespace Aleph;
116
117# ifdef N
118# define NBACKUP N
119# undef N
120# endif
121
122# ifdef M
123# define MBACKUP M
124# undef M
125# endif
126
127namespace Aleph
128{
129
166 template <typename Key, class Cmp = Aleph::equal_to<Key>>
169 : public OhashCommon<OLhashTable<Key, Cmp>, Key>,
170 public GenericTraverse<OLhashTable<Key, Cmp>>,
171 public LocateFunctions<OLhashTable<Key, Cmp>, Key>,
172 public FunctionalMethods<OLhashTable<Key, Cmp>, Key>,
173 public EqualToMethod<OLhashTable<Key, Cmp>>,
174 public StlAlephIterator<OLhashTable<Key, Cmp>>
175 {
176 friend class OhashCommon<OLhashTable<Key, Cmp>, Key>;
177
178 public:
179
180 using Key_Type = Key;
181
182 using Item_Type = Key;
183
184 using Hash_Fct = std::function<size_t(const Key &)>;
185
186 using Hash_Fct_Ptr = size_t (*)(const Key &);
187
192
193 struct Bucket
194 {
195 Key key;
196 char status = EMPTY;
197
198 Bucket() noexcept(std::is_nothrow_default_constructible_v<Key>) : status(EMPTY) {}
199 void reset() noexcept { status = EMPTY; }
200 };
201
202 [[nodiscard]] static Bucket *key_to_bucket(Key *rec) noexcept
203 {
204 // Note: cannot be constexpr due to reinterpret_cast
205 const auto base = reinterpret_cast<std::uintptr_t>(rec);
206 const auto offset = offsetof(Bucket, key);
207 return reinterpret_cast<Bucket *>(base - offset);
208 }
209
210 Bucket *table = nullptr;
211 size_t N = 0;
212
213 protected:
214
215 size_t len;
219
220 private:
221
224 size_t deleted_buckets = 0; // buckets marked as the ones of removed keys
225
226 [[nodiscard]] bool is_valid_bucket(Bucket *bucket) const noexcept
227 {
228 if (table == nullptr)
229 return false;
230
231 const auto begin = reinterpret_cast<std::uintptr_t>(&table[0]);
232 const auto end = reinterpret_cast<std::uintptr_t>(&table[len]);
233 const auto addr = reinterpret_cast<std::uintptr_t>(bucket);
234
235 if (addr < begin or addr >= end)
236 return false;
237
238 const auto offset_with_base =
239 static_cast<std::ptrdiff_t>(addr - begin);
240
241 return offset_with_base % sizeof(*bucket) == 0;
242 }
243
244 public:
245
246 [[nodiscard]] constexpr const Cmp &get_compare() const noexcept { return cmp; }
247
248 [[nodiscard]] constexpr Cmp &get_compare() noexcept { return cmp; }
249
250 public:
251
255 OLhashTable(const size_t l, Hash_Fct hash_f, Cmp cmp_f,
256 const float l_alpha, const float u_alpha, const bool resize)
257 : table(nullptr), N(0), len(hash_dry_detail::prime_table_len<Bucket>(l)),
258 lower_alpha(l_alpha), upper_alpha(u_alpha), cmp(cmp_f),
259 hash_fct(hash_f), with_resize(resize)
260 {
261 table = new Bucket[len];
262 }
263
267
269
270 using Base::contains;
271
273 Hash_Fct_Ptr hash_fct = Aleph::dft_hash_ptr_fct<Key>,
274 Cmp cmp = Cmp(),
276 float upper_alpha = 0.70f,
277 bool with_resize = true)
280
285
293
310 template <typename H>
316
332 template <typename H1, typename H2>
333 requires (std::is_constructible_v<Hash_Fct, H1>
334 and std::is_constructible_v<Hash_Fct, H2>
337 OLhashTable(size_t len, H1 && hash_fct, H2 &&, Cmp cmp,
338 float lower_alpha, float upper_alpha, bool with_resize)
339 : OLhashTable(len, Hash_Fct(std::forward<H1>(hash_fct)), cmp,
341
343
346 {
347 if (table != nullptr)
348 delete[] table;
349 }
350
362 void swap(OLhashTable &other) noexcept
363 {
364 std::swap(table, other.table);
365 std::swap(N, other.N);
366 std::swap(len, other.len);
368 std::swap(hash_fct, other.hash_fct);
369 std::swap(lower_alpha, other.lower_alpha);
370 std::swap(upper_alpha, other.upper_alpha);
371 std::swap(with_resize, other.with_resize);
372 std::swap(deleted_buckets, other.deleted_buckets);
373 }
374
386 : OLhashTable(other.len == 0 ? Primes::DefaultPrime : other.len,
387 other.hash_fct, other.cmp,
388 other.lower_alpha, other.upper_alpha, other.with_resize)
389 {
390 this->copy_from_table(other);
391 }
392
408 OLhashTable(OLhashTable &&other) noexcept
409 : table(other.table), N(other.N), len(other.len),
410 lower_alpha(other.lower_alpha), upper_alpha(other.upper_alpha),
411 cmp(other.cmp), hash_fct(other.hash_fct),
412 with_resize(other.with_resize), deleted_buckets(other.deleted_buckets)
413 {
414 other.table = nullptr;
415 other.N = 0;
416 other.len = 0;
417 other.deleted_buckets = 0;
418 }
419
431 {
432 if (this == &other)
433 return *this;
434
435 OLhashTable tmp(other);
436 swap(tmp);
437
438 return *this;
439 }
440
442 {
443 swap(other);
444 return *this;
445 }
446
449 [[nodiscard]] Key * search(const Key & key) noexcept
450 {
451 return const_cast<Key *>(std::as_const(*this).search(key));
452 }
453
456 [[nodiscard]] const Key *search(const Key &key) const noexcept
457 {
458 if (len == 0) [[unlikely]]
459 return nullptr; // the storage was taken by a move
460
461 size_t i = hash_fct(key) % len;
462 for (size_t c = 0; c < len; ++c)
463 {
464 // Prefetch next bucket for better cache performance
465 __builtin_prefetch(&table[(i + 1 < len) ? i + 1 : 0], 0, 1);
466
467 if (table[i].status == EMPTY) [[unlikely]]
468 return nullptr;
469
470 if (table[i].status == BUSY and cmp(table[i].key, key)) [[likely]]
471 return &table[i].key;
472
473 if (++i == len)
474 i = 0;
475 }
476
477 return nullptr; // Key not found
478 }
479
480 protected:
481
483 Bucket *occupy(Bucket *bucket) noexcept
484 {
485 if (bucket->status == DELETED)
487 bucket->status = BUSY;
488 ++N;
489 return bucket;
490 }
491
492 Bucket *allocate_bucket(const Key &key) noexcept
493 {
494 Bucket * first_deleted = nullptr;
495 size_t i = hash_fct(key) % len;
496
497 for (size_t c = 0; c < len; ++c)
498 {
499 // Prefetch next bucket for better cache performance
500 __builtin_prefetch(&table[(i + 1 < len) ? i + 1 : 0], 0, 1);
501
502 auto & b = table[i];
503 if (b.status == EMPTY) [[likely]]
504 return occupy(first_deleted != nullptr ? first_deleted : &b);
505 if (b.status == BUSY)
506 {
507 if (cmp(key, b.key)) [[unlikely]]
508 return nullptr; // Duplicate
509 }
510 else // DELETED
511 {
512 if (first_deleted == nullptr)
513 first_deleted = &b;
514 }
515
516 if (++i == len)
517 i = 0;
518 }
519
520 if (first_deleted != nullptr) [[unlikely]]
521 return occupy(first_deleted);
522
523 return nullptr;
524 }
525
526 // Allocate a new bucket for storing key. It always returns a
527 // pointer to the bucket entry into the table. If the key is
528 // already inserted in the table, then second value is true,
529 // otherwise, not allocation is done, and false is returned as second
530 std::tuple<Bucket *, bool> hard_allocate_bucket(const Key &key) noexcept
531 {
532 Bucket * first_deleted = nullptr;
533 size_t i = hash_fct(key) % len;
534
535 for (size_t c = 0; c < len; ++c)
536 {
537 // Prefetch next bucket for better cache performance
538 __builtin_prefetch(&table[(i + 1 < len) ? i + 1 : 0], 0, 1);
539
540 auto & b = table[i];
541 if (b.status == EMPTY) [[likely]]
542 return {occupy(first_deleted != nullptr ? first_deleted : &b), false};
543 else if (b.status == BUSY)
544 {
545 if (cmp(key, b.key))
546 return {&b, true}; // Found existing
547 }
548 else // DELETED
549 {
550 if (first_deleted == nullptr)
551 first_deleted = &b;
552 }
553
554 if (++i == len)
555 i = 0;
556 }
557
558 if (first_deleted != nullptr) [[unlikely]]
559 return {occupy(first_deleted), false};
560
561 return {nullptr, false};
562 }
563
565 [[nodiscard]] size_t prev_index(const size_t i) const noexcept
566 {
567 return (i == 0) ? len - 1 : i - 1;
568 }
569
571 [[nodiscard]] size_t next_index(const size_t i) const noexcept
572 {
573 return (i + 1 == len) ? 0 : i + 1;
574 }
575
581 void cleanup_deleted_chain(size_t idx) noexcept
582 {
583 // If next bucket is not EMPTY, we must keep this as DELETED
584 if (table[next_index(idx)].status != EMPTY)
585 return;
586
587 // Next is EMPTY, so we can mark this as EMPTY
588 table[idx].status = EMPTY;
590
591 // Propagate backwards: any DELETED bucket whose next is now EMPTY
592 // can also become EMPTY
593 size_t prev = prev_index(idx);
594 size_t count = 0;
595 while (table[prev].status == DELETED and count < len)
596 {
597 table[prev].status = EMPTY;
599 prev = prev_index(prev);
600 ++count;
601 }
602 }
603
607 void deallocate_bucket(Bucket *bucket) noexcept
608 {
609 assert(is_valid_bucket(bucket) and bucket->status == BUSY);
610
611 --N;
612 const auto idx = static_cast<size_t>(bucket - &table[0]);
613 table[idx].status = DELETED;
616 }
617
627 void undo_allocate_bucket(Bucket *bucket, const Key &) noexcept
628 {
629 assert(is_valid_bucket(bucket) and bucket->status == BUSY);
630
631 --N;
632 const auto idx = static_cast<size_t>(bucket - &table[0]);
633 size_t i = idx;
634 for (size_t steps = 1; steps < len; ++steps)
635 {
636 i = next_index(i);
637 const Bucket & b = table[i];
638 if (b.status == EMPTY)
639 break;
640 if (b.status != BUSY)
641 continue; // a removed key's bucket: the run goes on
642
643 // The probe sequence of b's key started `displacement` buckets
644 // before i, so it went through `bucket` if that is `steps` or more
645 const size_t displacement = (i + len - hash_fct(b.key) % len) % len;
646 if (displacement >= steps)
647 {
648 bucket->status = DELETED;
650 return;
651 }
652 }
653
654 bucket->status = EMPTY;
655 size_t prev = prev_index(idx);
656 for (size_t count = 0; table[prev].status == DELETED and count < len;
657 ++count)
658 {
659 table[prev].status = EMPTY;
661 prev = prev_index(prev);
662 }
663 }
664
665 public:
666
672 void remove(const Key &key)
673 {
674 ah_domain_error_if(len == 0) << "Key not in hash table";
675
676 size_t i = hash_fct(key) % len;
677 for (size_t c = 0; c < len; ++c)
678 {
679 // Prefetch next bucket for better cache performance
680 __builtin_prefetch(&table[(i + 1 < len) ? i + 1 : 0], 0, 1);
681
682 if (table[i].status == EMPTY) [[unlikely]]
683 ah_domain_error() << "Key not in hash table";
684
685 if (table[i].status == BUSY and cmp(table[i].key, key)) [[likely]]
686 {
687 table[i].status = DELETED;
689 --N;
691 this->shrink_after_removal();
692 return;
693 }
694
695 if (++i == len)
696 i = 0;
697 }
698
699 ah_domain_error() << "Key not in hash table";
700 }
701
703
705
706 [[nodiscard]] Stats stats() const
707 {
708 DynArray<size_t> lens;
709 size_t num_busy = 0;
710 size_t num_deleted = 0;
711 size_t num_empty = 0;
712 size_t max_len = std::numeric_limits<size_t>::min();
713 for (size_t i = 0; i < len; ++i)
714 switch (table[i].status)
715 {
716 case BUSY:
717 {
718 ++num_busy;
719 const Key &key = table[i].key;
720 size_t i = hash_fct(key) % len;
721 size_t count = 1;
722
723 while (true)
724 {
725 if (table[i].status == BUSY and cmp(table[i].key, key))
726 break;
727 ++count;
728 if (++i == len)
729 i = 0;
730 }
731
732 max_len = std::max(max_len, count);
733 update_stat_len(lens, count);
734 break;
735 }
736 case EMPTY:
737 ++num_empty;
738 update_stat_len(lens, 0);
739 break;
740 case DELETED:
741 ++num_deleted;
742 break;
743 }
744 assert(num_deleted == deleted_buckets);
745
746 float avg = 0;
747 float sum = 0;
748 for (size_t i = 0; i < lens.size(); ++i)
749 {
750 avg += lens(i) * i;
751 sum += lens(i);
752 }
753
754 // A table whose storage was taken by a move has no bucket to
755 // average over: its average and its variance are zero.
756 if (sum > 0)
757 avg /= sum;
758 float var = 0;
759 for (size_t i = 0; i < lens.size(); ++i)
760 {
761 const float s = i - avg;
762 var += lens(i) * s * s;
763 }
764 if (sum > 0)
765 var /= sum;
766
767 Stats stats;
768 stats.num_busy = num_busy;
769 stats.num_deleted = num_deleted;
770 stats.num_empty = num_empty;
771 std::swap(lens, stats.lens);
772 stats.avg = avg;
773 stats.var = var;
774 stats.max_len = max_len;
775
776 return stats;
777 }
778 };
779
780 template <typename Key, class Cmp = Aleph::equal_to<Key>>
782
783}
784# endif // TPL_OLHASH_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
DRY (Don't Repeat Yourself) utilities and macros.
#define Special_Ctors(Set_Type, Type)
Generates special constructors for containers.
Definition ahDry.H:123
size_t steps
Definition ca-c-api.h:126
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 linear probing collision resolution.
Definition tpl_olhash.H:175
OLhashTable(size_t len, Hash_Fct hash_fct, Hash_Fct, Cmp cmp, float lower_alpha, float upper_alpha, bool with_resize)
Definition tpl_olhash.H:264
~OLhashTable()
Release all occupied memory.
Definition tpl_olhash.H:345
OLhashTable(size_t len, Hash_Fct_Ptr hash_fct, Hash_Fct_Ptr, Cmp cmp, float lower_alpha, float upper_alpha, bool with_resize)
Definition tpl_olhash.H:281
Bucket * occupy(Bucket *bucket) noexcept
Gives bucket, empty or the one of a removed key, to a new key.
Definition tpl_olhash.H:483
std::tuple< Bucket *, bool > hard_allocate_bucket(const Key &key) noexcept
Definition tpl_olhash.H:530
size_t next_index(const size_t i) const noexcept
Index of next bucket (handles wrap-around)
Definition tpl_olhash.H:571
std::function< size_t(const Key &)> Hash_Fct
Definition tpl_olhash.H:184
OLhashTable(OLhashTable &&other) noexcept
Move constructor.
Definition tpl_olhash.H:408
OLhashTable(size_t len, Hash_Fct hash_fct, Hash_Fct_Ptr, Cmp cmp, float lower_alpha, float upper_alpha, bool with_resize)
Constructor with two hash functions for metaprogramming compatibility with ODhashTable type.
Definition tpl_olhash.H:289
void cleanup_deleted_chain(size_t idx) noexcept
Cleanup DELETED entries that are at the end of collision chains.
Definition tpl_olhash.H:581
static void update_stat_len(DynArray< size_t > &lens, size_t i)
Definition tpl_olhash.H:702
OLhashTable(const OLhashTable &other)
Copy constructor.
Definition tpl_olhash.H:385
bool is_valid_bucket(Bucket *bucket) const noexcept
Definition tpl_olhash.H:226
OLhashTable(size_t len=Primes::DefaultPrime, Hash_Fct_Ptr hash_fct=Aleph::dft_hash_ptr_fct< Key >, Cmp cmp=Cmp(), float lower_alpha=hash_default_lower_alpha, float upper_alpha=0.70f, bool with_resize=true)
Definition tpl_olhash.H:272
size_t(*)(const Key &) Hash_Fct_Ptr
Definition tpl_olhash.H:186
constexpr const Cmp & get_compare() const noexcept
Definition tpl_olhash.H:246
OLhashTable(size_t len, H1 &&hash_fct, H2 &&, Cmp cmp, float lower_alpha, float upper_alpha, bool with_resize)
Builds a table from two hash functions when one of them is a lambda without captures.
Definition tpl_olhash.H:337
Bucket * allocate_bucket(const Key &key) noexcept
Definition tpl_olhash.H:492
void undo_allocate_bucket(Bucket *bucket, const Key &) noexcept
Undoes what allocate_bucket() or hard_allocate_bucket() did when they reserved bucket for a key that ...
Definition tpl_olhash.H:627
void deallocate_bucket(Bucket *bucket) noexcept
Removes the key of bucket, a busy bucket of the table.
Definition tpl_olhash.H:607
constexpr Cmp & get_compare() noexcept
Definition tpl_olhash.H:248
OLhashTable(size_t len, H &&hash_fct, Cmp cmp, float lower_alpha, float upper_alpha, bool with_resize)
Builds a table whose hash function is a lambda without captures.
Definition tpl_olhash.H:312
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
OLhashTable(const size_t l, Hash_Fct hash_f, Cmp cmp_f, const float l_alpha, const float u_alpha, const bool resize)
Instantiate a hash table with hash function __hash_fct and dimension len.
Definition tpl_olhash.H:255
OLhashTable & operator=(OLhashTable &&other) noexcept
Definition tpl_olhash.H:441
const Key * search(const Key &key) const noexcept
Finds the key and returns the associated record if key is find inside the table; otherwise,...
Definition tpl_olhash.H:456
size_t prev_index(const size_t i) const noexcept
Index of previous bucket (handles wrap-around)
Definition tpl_olhash.H:565
static Bucket * key_to_bucket(Key *rec) noexcept
Definition tpl_olhash.H:202
OLhashTable & operator=(const OLhashTable &other)
Copy assignment.
Definition tpl_olhash.H:430
typename OhashCommon< OLhashTable< Key, Cmp >, Key >::Stats Stats
Definition tpl_olhash.H:704
Stats stats() const
Definition tpl_olhash.H:706
void remove(const Key &key)
Remove the key referenced by key.
Definition tpl_olhash.H:672
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 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.
A class type that converts to the function pointer type Ptr.
Definition hash-dry.H:153
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.
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_olhash.H:198
Generic traversal of the container through its iterator.
Definition ah-dry.H:363
DynList< int > l