Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_linHash.H
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
50# ifndef TPL_LINHASH_H
51# define TPL_LINHASH_H
52
53# include <iostream>
54# include <new>
55# include <primes.H>
56# include <dlink.H>
57# include <tpl_dynArray.H>
58# include <tpl_dnode.H>
59# include <htlist.H>
60# include <hashDry.H>
61# include <hash-fct.H>
62# include <hash-dry.H>
63# include <ah-errors.H>
64# include <ah-concepts.H>
65
66# ifdef N
67# define NBACKUP N
68# undef N
69# endif
70
71# ifdef M
72# define MBACKUP M
73# undef M
74# endif
75
76
77using namespace Aleph;
78
79namespace Aleph {
80
81# define LINBUCKET_BODY(BUCKETNAME) \
82 \
83 Dlink link; \
84 \
85public: \
86 \
87 BUCKETNAME(const BUCKETNAME & bucket) \
88 : Dnode<Key>(bucket) {} \
89 \
90 BUCKETNAME() {} \
91 \
92 BUCKETNAME(const Key & key) \
93 : Dnode<Key>(key) {} \
94 \
95 Key & get_key() noexcept { return this->get_data(); } \
96 \
97 Dlink * get_link() noexcept { return &link; } \
98 \
99 DLINK_TO_BASE(BUCKETNAME, link);
100
101
109 template <typename Key>
110class LinHashBucket : public Dnode<Key>
111{
113};
114
122 template <typename Key>
123class LinHashBucketVtl : public Dnode<Key>
124{
126
128 virtual ~LinHashBucketVtl() {}
129};
130
131
156 template <typename Key, template <class> class BucketType,
158 requires EqualityComparator<Cmp, Key>
160 : public HashStats<GenLinearHashTable<Key, BucketType, Cmp>>
161{
162 friend class HashStats<GenLinearHashTable<Key, BucketType, Cmp>>;
163
164public:
165
168 using Hash_Fct = std::function<size_t(const Key &)>;
169 using Hash_Fct_Ptr = size_t (*) (const Key &);
170
172 using Bucket = BucketType<Key>;
173
174 using Key_Type = Key;
175
176 using Item_Type = Key;
177
178private:
179
180 // The header of a list holds no key: only the buckets do. So the array
181 // of the table builds, copies and swaps no key, and the table allocates
182 // nothing for a list until a bucket goes into it
184
186
187 static size_t multiply_by_two(size_t n) noexcept { return n << 1; }
188
189 static size_t divide_by_two(size_t n) noexcept { return n >> 1; }
190
193
194protected:
195
198
199private:
200
201 size_t M; // Table size
202 size_t N; // Number of elements in the table
203 size_t busy_slots_counter; // Number of occupied entries
204 bool remove_all_buckets; // Indicates if destructor should free
205 // the buckets
206 bool with_resize; // whether the table expands and contracts
207
208protected:
209
210 float upper_alpha; // upper load factor
211 float lower_alpha; // lower load factor
212
213private:
214
215 size_t p; // index of the list being partitioned (or expanded)
216 size_t l; // number of times the table has been doubled
217 size_t MP; // stores the value p + M
218 size_t MM; // product 2*M
219
220protected:
221
222 mutable size_t len;
223
224private:
225
226 // The index of the list of the keys whose hash is hash
227 size_t list_index(const size_t hash) const noexcept
228 {
229 const auto i = hash % M;
230 return i < p ? hash % MM : i;
231 }
232
233 size_t call_hash_fct(const Key & key) const
234 {
235 return list_index(hash_fct(key));
236 }
237
238 void expand()
239 { // expand the table until load is below upper_alpha
240 for (float alpha = 1.0*N/MP; alpha >= upper_alpha; alpha = 1.0*N/MP)
241 {
242 BucketList * src_list_ptr = table.test(p);
243 if (src_list_ptr != nullptr) // is table[p] written?
244 if (not src_list_ptr->is_empty()) // is table[p] not empty?
245 {
246 BucketList * tgt_list_ptr = nullptr;
247
248 // traverse collision list and move buckets to table[p+M]
249 for (BucketItor it(*src_list_ptr); it.has_curr(); /* nothing */)
250 {
251 Bucket * bucket = static_cast<Bucket*>(it.get_curr());
252
253 it.next_ne(); // advance to the next element in the list
254
255 const Key & key = bucket->get_key();
256 const size_t i = hash_fct(key) % MM;
257 if (i == p) // does this key belong to table[p]?
258 continue; // yes ==> key stays in table[p] ==> next
259
260 if (tgt_list_ptr == nullptr)
261 tgt_list_ptr = &table.touch(MP);
262
263 // bucket does not belong to table[p] but to table[p+m] ==>
264 // remove bucket from table[i] and insert it in table[p+m]
265 bucket->del();
266 tgt_list_ptr->append(bucket);
267 }
268
269 if (src_list_ptr->is_empty()) // did table[p] become empty?
270 --busy_slots_counter; // yes ==> one empty slot
271
272 if (tgt_list_ptr != nullptr) // did some key go to table[p+M]?
273 ++busy_slots_counter; // yes ==> one new busy slot
274 }
275 ++p;
276 ++MP;
277 if (p == M) // (p == 2*M) should the table size be doubled?
278 { // yes ==> change table size to 2*M
279 ++l; // Number of times the table has been doubled
280 p = 0;
281 MP = M = MM; // assign 2*M to them
283 }
284 }
285 }
286
287 // Contracts the table while its load is at or under lower_alpha. Merging
288 // the last list into its buddy may allocate the buddy, which may throw
289 // std::bad_alloc; that is done before the step changes anything, so the
290 // table is then as the last complete step left it. Cutting the array at
291 // the end of a step copies no key: the header of a list holds none.
292 void contract()
293 { // contract the table until load is below lower_alpha
294 for (float alpha = (1.0*N)/MP; alpha <= lower_alpha and MP > len;
295 alpha = (1.0*N)/MP)
296 {
297 // the last list, table[MP - 1], goes into table[new_p]
298 const size_t new_p = p == 0 ? divide_by_two(M) - 1 : p - 1;
299 BucketList * src_list_ptr =
300 MP - 1 < table.size() ? table.test(MP - 1) : nullptr;
301 BucketList * tgt_list_ptr = nullptr;
302 if (src_list_ptr != nullptr and not src_list_ptr->is_empty())
303 tgt_list_ptr = &table.touch(new_p); // allocate table[new_p]
304
305 if (p == 0) // should the table size be halved?
306 { // yes ==> update table size to M/2
307 --l; // Number of times the table has been doubled decreases
308 MM = M; // divide by two
309 M = divide_by_two(M);
310 p = M - 1;
311 }
312 else
313 --p; // no ==> just reduce index p
314
315 --MP;
316 assert(p == new_p);
317 if (src_list_ptr != nullptr) // does entry for table[p+M] exist?
318 {
319 if (tgt_list_ptr != nullptr) // is table[p+M] not empty?
320 { // yes ==> merge the lists
321 const bool tgt_was_busy = not tgt_list_ptr->is_empty();
322 tgt_list_ptr->concat_list(src_list_ptr);
323 if (tgt_was_busy) // otherwise table[p] takes its place
324 --busy_slots_counter; // table[p+M] became empty
325 }
326 table.cut_ne(MP); // eventually free memory of table[p+M]
327 }
328 }
329 }
330
331public:
332
342 {
344 << "LinearHashTable::set_hash_fct(): the table is not empty";
345 hash_fct = std::move(fct);
346 }
347
350 {
352 << "LinearHashTable::set_hash_fct(): the table is not empty";
353 hash_fct = Hash_Fct(fct);
354 }
355
356 Hash_Fct get_hash_fct() const noexcept { return hash_fct; }
357
358 Cmp & get_compare() noexcept { return cmp; }
359
360 const Cmp & get_compare() const noexcept { return cmp; }
361
363 float current_alpha() const noexcept { return 1.0*N/MP; }
364
365 protected:
366
367 GenLinearHashTable(size_t __len, Hash_Fct __hash_fct, Cmp __cmp,
368 float __lower_alpha, float __upper_alpha,
369 bool __remove_all_buckets, bool __with_resize)
370 : table(__len), hash_fct(__hash_fct), cmp(__cmp), M(__len), N(0),
371 busy_slots_counter(0), remove_all_buckets(__remove_all_buckets),
372 with_resize(__with_resize),
373 upper_alpha(__upper_alpha), lower_alpha(__lower_alpha),
374 p(0), l(0), MP(M), MM(multiply_by_two(M)), len(__len)
375 {
376 ah_length_error_if(M == 0) << "table's length is zero";
377
378 ah_length_error_if(MM > table.max_size()) << "table's length too big";
379
381 << "upper alpha must be greater than lower alpha";
382 }
383
384 public:
385
420
432 void swap(GenLinearHashTable & other) noexcept
433 {
434 // Not std::swap(), which goes through a third array
435 table.swap(other.table);
436 entries_list.swap(other.entries_list);
437 std::swap(hash_fct, other.hash_fct);
439 std::swap(M, other.M);
440 std::swap(N, other.N);
441 std::swap(busy_slots_counter, other.busy_slots_counter);
442 std::swap(remove_all_buckets, other.remove_all_buckets);
443 std::swap(with_resize, other.with_resize);
444 std::swap(upper_alpha, other.upper_alpha);
445 std::swap(lower_alpha, other.lower_alpha);
446 std::swap(p, other.p);
447 std::swap(l, other.l);
448 std::swap(MP, other.MP);
449 std::swap(MM, other.MM);
450 std::swap(len, other.len);
451 }
452
453
462 void empty() noexcept
463 {
464 while (not entries_list.is_empty())
465 {
466 Bucket * bucket = Bucket::dlink_to_base(entries_list.remove_first_ne());
467 bucket->del(); // remove from the list in the array
468 bucket->get_link()->del(); // remove from entries list
469 delete bucket;
470 }
471
472 M = MP = len;
474 N = p = l = 0;
476 try
477 {
478 table.cut_ne(len);
479 }
480 catch (...)
481 {
482 // cut_ne() is not declared noexcept; with lists without a key it
483 // has nothing that throws
484 }
485 }
486
492 void clear() noexcept { empty(); }
493
500 bool contains(const Key & key) const noexcept { return search(key) != nullptr; }
501
503 {
505 empty();
506 }
507
517
520
521private:
522
523 // The bucket of list whose key is equivalent to key, which may be of
524 // another type that the comparator compares with a Key
525 template <typename SearchKey>
526 Bucket *
527 search_in_bucket_list(BucketList * list, const SearchKey & key) const
528 {
529 for (BucketItor it(*list); it.has_curr(); it.next_ne())
530 {
531 Bucket * bucket = static_cast<Bucket*>(it.get_curr());
532 if (cmp (key, bucket->get_key()))
533 return bucket;
534 }
535
536 return nullptr;
537 }
538
539public:
540
544 Bucket * search(const Key & key) const noexcept
545 {
546 auto i = call_hash_fct(key);
547 BucketList * list = table.test(i);
548 if (list == nullptr) // Has table[i] ever been written?
549 return nullptr; // No ==> element is not in the table
550
551 if (list->is_empty())
552 return nullptr;
553
554 return search_in_bucket_list(list, key);
555 }
556
557protected:
558
576 template <typename HashFunc, typename SearchKey>
577 Bucket * search_with_custom_hash(const HashFunc & hash_func,
578 const SearchKey & search_key) const noexcept
579 {
580 BucketList * list = table.test(list_index(hash_func(search_key)));
581 if (list == nullptr or list->is_empty())
582 return nullptr;
583
584 return search_in_bucket_list(list, search_key);
585 }
586
587public:
588
590 const size_t & size() const noexcept { return N; }
591
593 bool is_empty() const noexcept { return N == 0; }
594
596 const size_t & capacity() const noexcept { return MP; }
597
599 const size_t & busy_slots() const noexcept { return busy_slots_counter; }
600
602 const size_t & expansions() const noexcept { return l; }
603
606 Bucket * insert(Bucket * bucket)
607 {
608 const size_t i = call_hash_fct(bucket->get_key());
609 BucketList & list = table.touch(i); // allocates memory for table[i]
610 if (list.is_empty())
612
613 if (search_in_bucket_list(&list, bucket->get_key()) != nullptr)
614 return nullptr; // duplicated key
615
616 list.append(bucket);
617 entries_list.append(bucket->get_link());
618 ++N;
619 if (with_resize)
620 expand();
621
622 return bucket;
623 }
624
626 {
627 const size_t i = call_hash_fct(bucket->get_key());
628 BucketList & list = table.touch(i); // allocates memory for table[i]
629 if (list.is_empty())
631
632 Bucket * p = search_in_bucket_list(&list, bucket->get_key());
633 if (p != nullptr)
634 return p; // duplicated key
635
636 list.append(bucket);
637 entries_list.append(bucket->get_link());
638 ++N;
639 if (with_resize)
640 expand();
641
642 return bucket;
643 }
644
646 size_t resize(size_t) noexcept { return MP; }
647
648private:
649
650 // This routine deletes bucket from hash table EXCEPT from
651 // entries_list. The end of this routine is to dry the deletion and to
652 // allow remove from other places; ofor instance, from the del()
653 // method of Iterator class
654 Bucket * remove_bucket(Bucket * bucket) noexcept
655 {
656 assert(bucket != nullptr);
657 assert(search(bucket->get_key()) == bucket);
658
659 Bucket * next = static_cast<Bucket*>(bucket->get_next());
660
661 bucket->del(); // remove from collision list
662
663 if (next->is_empty()) // collision list empty?
664 --busy_slots_counter; // yes ==> one empty slot
665
666 --N;
667 if (with_resize)
668 try
669 {
670 contract();
671 }
672 catch (...) // std::bad_alloc (see contract())
673 {
674 // the table keeps the capacity of the last complete step
675 }
676
677 return bucket;
678 }
679
680public:
681
692 Bucket * remove(Bucket * bucket) noexcept
693 {
694 bucket->get_link()->del(); // remove from entries_list
695 return remove_bucket(bucket);
696 }
697
698 void print()
699 {
700 for (size_t i = 0; i < MP; ++i)
701 {
702 std::cout << "table[" << i << "] = [ ";
703
704 if (table.exist(i))
705 {
706 BucketList & list = table.access(i);
707
708 if (not list.is_empty())
709 for (BucketItor it(list); it.has_curr(); it.next_ne())
710 {
711 Bucket * bucket = static_cast<Bucket*>(it.get_curr());
712 const Key & key = bucket->get_key();
713 std::cout << key << ",";
714 }
715 }
716 std::cout << "]" << '\n';
717 }
718 }
719
721 {
722 private:
723
725 long pos = 0;
726
727 public:
728
731
733 using Item_Type = Bucket *;
734
737 : Dlink::Iterator(const_cast<Dlink &>(table.entries_list)),
738 hash_table(& const_cast<GenLinearHashTable &>(table))
739 {
740 // Empty
741 }
742
744 Iterator() noexcept { /* Empty */ }
745
746 Bucket * get_curr_ne() noexcept
747 {
748 return Bucket::dlink_to_base(this->Dlink::Iterator::get_curr_ne());
749 }
750
753 {
754 return Bucket::dlink_to_base(this->Dlink::Iterator::get_curr());
755 }
756
758 {
759 Bucket * bucket = Bucket::dlink_to_base(this->Dlink::Iterator::del());
760 return (Bucket *) hash_table->remove_bucket(bucket);
761 }
762
763 void next_ne() noexcept
764 {
766 pos++;
767 }
768
769 void next()
770 {
771 this->Dlink::Iterator::next();
772 pos++;
773 }
774
775 void prev()
776 {
777 this->Dlink::Iterator::prev();
778 pos--;
779 }
780
781 long get_pos() const noexcept { return pos; }
782 };
783};
784
785
804template <typename Key, class Cmp = Aleph::equal_to<Key>>
806
807
826 template <typename Key, class Cmp = Aleph::equal_to<Key>>
828
829
830} // end namespace Aleph
831
832# ifdef NBACKUP
833# define N NBACKUP
834# undef NBACKUP
835# endif
836
837# ifdef MBACKUP
838# define M MBACKUP
839# undef MBACKUP
840# endif
841
842# endif // TPL_LINHASH_H
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#define ah_length_error_if(C)
Throws std::length_error if condition holds.
Definition ah-errors.H:846
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
Iterator on a list of Dnode objects.
Definition tpl_dnode.H:294
Node belonging to a double circular linked list with header node.
Definition tpl_dnode.H:106
Iterator() noexcept
Instantiate an empty iterator.
Bucket * get_curr()
Return the current bucket.
Bucket * Item_Type
The element type returned by get_curr().
Iterator(const GenLinearHashTable &table) noexcept
Instantiate an iterator over the hash table.
Generic linear hash table.
Bucket * search_with_custom_hash(const HashFunc &hash_func, const SearchKey &search_key) const noexcept
Searches for a key of another type, without building a Key.
const size_t & capacity() const noexcept
Returns the table capacity.
void swap(GenLinearHashTable &other) noexcept
Swaps this table with other in constant time.
std::function< size_t(const Key &)> Hash_Fct
The hash function type.
DynArray< BucketList > table
void set_hash_fct(Hash_Fct_Ptr fct)
This is an overloaded member function, provided for convenience. It differs from the above function o...
void clear() noexcept
Empties the container.
static size_t divide_by_two(size_t n) noexcept
Bucket * remove_bucket(Bucket *bucket) noexcept
Cmp & get_compare() noexcept
const size_t & size() const noexcept
Returns the number of elements in the table.
bool is_empty() const noexcept
return true is table is empty
GenLinearHashTable(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=hash_default_upper_alpha, bool remove_all_buckets=true, bool with_resize=true)
Instantiate a generic linear hash table.
Bucket * search_in_bucket_list(BucketList *list, const SearchKey &key) const
void empty() noexcept
Empties the table: frees every bucket and gives the table its initial size.
typename Dnode< Key >::Iterator BucketItor
static size_t multiply_by_two(size_t n) noexcept
const size_t & expansions() const noexcept
Returns the expansion level performed on the table.
size_t list_index(const size_t hash) const noexcept
size_t call_hash_fct(const Key &key) const
float current_alpha() const noexcept
return the current table load
Bucket * remove(Bucket *bucket) noexcept
Removes bucket from the table, without freeing it.
BucketType< Key > Bucket
The bucket type.
GenLinearHashTable(const GenLinearHashTable &)=delete
Not copyable: the copy that the compiler would write copies the links of the lists,...
const size_t & busy_slots() const noexcept
Returns the number of busy slots in the table.
bool contains(const Key &key) const noexcept
Checks if a key exists in the table.
Bucket * insert(Bucket *bucket)
Insert bucket in the table.
Hash_Fct get_hash_fct() const noexcept
size_t(*)(const Key &) Hash_Fct_Ptr
Bucket * search_or_insert(Bucket *bucket)
GenLinearHashTable & operator=(const GenLinearHashTable &)=delete
Not copyable, for the same reason as the copy constructor.
GenLinearHashTable(size_t __len, Hash_Fct __hash_fct, Cmp __cmp, float __lower_alpha, float __upper_alpha, bool __remove_all_buckets, bool __with_resize)
const Cmp & get_compare() const noexcept
void set_hash_fct(Hash_Fct fct)
Sets the hash function of an empty table.
Bucket * search(const Key &key) const noexcept
Search for key in the linear hash table.
size_t resize(size_t) noexcept
Provided for generic programming compatibility.
Bucket with virtual destructor for a hash table with collision resolution by separate chaining.
virtual ~LinHashBucketVtl()
virtual destructor.
Bucket without virtual destructor for a hash table with collision resolution by separate chaining.
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
CRTP mixin providing statistics and configuration for chained hash tables.
Definition hashDry.H:1392
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.
Standard hash functions for Aleph types.
Common operations for open addressing hash tables (CRTP mixin).
Singly linked list implementations with head-tail access.
Main namespace for Aleph-w library functions.
const float hash_default_upper_alpha
Definition hash-dry.C:40
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
const float hash_default_lower_alpha
Definition hash-dry.C:38
const unsigned long DefaultPrime
Default prime number used when no specific size is requested.
Definition primes.C:381
Prime number utilities for hash tables and mathematical operations.
Doubly linked list node with typed data.
Lazy and scalable dynamic array implementation.
#define LINBUCKET_BODY(BUCKETNAME)
Definition tpl_linHash.H:81