58# include <type_traits>
81 template <
class Bucket>
85 <<
"hash table: the bytes of " << len <<
" buckets do not fit in a size_t";
101 template <
class Bucket>
170template <
class HashTbl,
typename Key>
176 HashTbl *
me() {
return static_cast<HashTbl*
>(
this); }
181 const HashTbl *
const_me()
const {
return static_cast<const HashTbl*
>(
this); }
187 noexcept(std::swap(std::declval<Key &>(), std::declval<Key &>()));
202 template <
class Bucket>
205 if constexpr (std::is_nothrow_copy_assignable_v<Key>)
214 me()->undo_allocate_bucket(bucket, key);
232 template <
class Bucket>
236 std::swap(bucket->key, key);
258 new typename HashTbl::Bucket[hash_dry_detail::checked_table_len<typename HashTbl::Bucket>(new_len)];
259 typename HashTbl::Bucket * old_table =
me()->table;
260 const size_t old_len =
me()->len;
261 const size_t old_N =
me()->N;
262 const size_t old_deleted =
me()->deleted_buckets;
264 me()->table = new_table;
267 me()->deleted_buckets = 0;
271 for (
size_t i = 0, c = 0; i < old_len
and c < old_N; ++i)
272 if (old_table[i].status == HashTbl::BUSY)
274 Key & key = old_table[i].key;
275 auto bucket =
me()->allocate_bucket(key);
277 std::swap(bucket->key, key);
285 me()->table = old_table;
288 me()->deleted_buckets = old_deleted;
293 assert(old_N ==
me()->
N);
312 if (2.0f*t->N/t->len >= t->upper_alpha)
330 if (not t->with_resize
331 or 1.0f*(t->N + t->deleted_buckets)/t->len < t->upper_alpha)
357 if (
me()->
N < new_len
and 1.0f*
me()->
N/new_len <
me()->upper_alpha)
415 assert(
me()->
N == 0
and me()->len >= other.N);
416 for (
long i = 0, c = 0; c < other.N; ++i)
418 auto & bucket = other.table[i];
419 if (bucket.status != HashTbl::BUSY)
422 (void)
me()->insert(bucket.key);
425 assert(
me()->
N == other.N);
438 for (
long i = 0; i <
me()->len; ++i)
439 me()->table[i].reset();
441 me()->deleted_buckets = 0;
468 if (
me()->len == 0) [[unlikely]]
475 if (
me()->
N +
me()->deleted_buckets <
me()->len - 1) [[likely]]
478 if (not
me()->with_resize)
479 return me()->N <
me()->len - 1;
481 if (
me()->
N <
me()->len - 1)
507 [[nodiscard]] Key *
insert(
const Key & key)
512 auto bucket =
me()->allocate_bucket(key);
513 if (bucket ==
nullptr)
518 return me()->test_resize(bucket, key);
546 auto bucket =
me()->allocate_bucket(key);
547 if (bucket ==
nullptr)
552 return me()->test_resize(bucket, bucket->key);
578 return me()->search(key);
580 auto r =
me()->hard_allocate_bucket(key);
581 auto bucket = get<0>(
r);
582 if (bucket ==
nullptr)
589 return me()->test_resize(bucket, bucket->key);
617 return me()->search(key);
619 auto r =
me()->hard_allocate_bucket(key);
620 auto bucket = get<0>(
r);
621 if (bucket ==
nullptr)
628 return me()->test_resize(bucket, bucket->key);
665 Key * key_ptr =
me()->search(key);
666 return { key_ptr, key_ptr !=
nullptr };
669 auto r =
me()->hard_allocate_bucket(key);
670 auto bucket = get<0>(
r);
671 if (bucket ==
nullptr)
672 return {
nullptr,
false };
674 return { &bucket->key,
true };
677 auto key_ptr =
me()->test_resize(bucket, bucket->key);
679 return { key_ptr,
false };
708 Key * key_ptr =
me()->search(key);
709 return { key_ptr, key_ptr !=
nullptr };
712 auto r =
me()->hard_allocate_bucket(key);
713 auto bucket = get<0>(
r);
714 if (bucket ==
nullptr)
715 return {
nullptr,
false };
717 return { &bucket->key,
true };
720 auto key_ptr =
me()->test_resize(bucket, bucket->key);
722 return { key_ptr,
false };
733 [[nodiscard]] Key *
append(
const Key & key)
748 return this->
insert(std::move(key));
758 [[nodiscard]]
constexpr bool has(
const Key & key)
const noexcept
760 return const_me()->search(key) !=
nullptr;
769 [[nodiscard]]
constexpr bool contains(
const Key & key)
const noexcept {
return has(key); }
782 [[nodiscard]] Key &
find(
const Key & key)
784 auto key_ptr =
me()->search(key);
786 <<
"Key not found in hash";
800 [[nodiscard]]
const Key &
find(
const Key & key)
const
834 <<
"Hash table is full and does not resize itself";
862 auto bucket = HashTbl::key_to_bucket(key);
864 <<
"remove_ptr(): key does not point into the table";
866 <<
"remove_ptr(): the key of the bucket was removed";
867 me()->deallocate_bucket(bucket);
890 if (new_size == 0 or new_size ==
me()->len)
895 <<
"New size is not enough for current number of entries";
936 delete []
me()->table;
937 me()->table = new_table;
939 me()->deleted_buckets = 0;
954 [[nodiscard]]
constexpr size_t size() const noexcept {
return const_me()->N; }
997 [[nodiscard]]
bool check() const noexcept
1034 <<
"Iterator next() overflow";
1044 <<
"Iterator next() underflow";
1138 <<
"O hash::Iterator next() overflow";
1141 <<
"O hash::Iterator next() underflow";
1224 <<
"Overflow in del() of iterator";
1249 return const_me()->template maps<Key> ([] (
const Key & key) {
return key; });
1290 std::cout <<
"M = " << this->
capacity() <<
'\n'
1291 <<
"N = " << this->
size() <<
'\n'
1292 <<
"busy slots = " << stats.
num_busy <<
'\n'
1293 <<
"deleted slots = " << stats.
num_deleted <<
'\n'
1294 <<
"empty slots = " << stats.
num_empty <<
'\n'
1295 <<
"alpha = " <<
const_me()->current_alpha() <<
'\n'
1296 <<
"max length = " << stats.
max_len <<
'\n';
1297 for (
size_t i = 0; i < stats.
lens.
size(); ++i)
1298 std::cout <<
" " << i <<
" = " << stats.
lens(i) <<
'\n';
1312 if (
const_me()->len == 0) [[unlikely]]
1335 template <
class Bucket>
1356 template <
class Cmp>
1359 if constexpr (std::is_move_constructible_v<Cmp>
1360 and std::is_move_assignable_v<Cmp>)
1390template <
class HashTbl>
1396 HashTbl *
me() {
return static_cast<HashTbl*
>(
this); }
1401 const HashTbl *
const_me()
const {
return static_cast<const HashTbl*
>(
this); }
1440 const auto & table =
const_me()->table;
1442 if constexpr (
requires { table.test(i); })
1444 list = table.test(i);
1445 if (list ==
nullptr)
1452 for (
typename HashTbl::BucketItor it(*list); it.has_curr(); it.next())
1473 for (
size_t i = 0; i <
const_me()->capacity(); ++i)
1477 float avg = 0,
sum = 0;
1478 for (
size_t i = 0; i < lens.
size(); ++i)
1487 for (
size_t i = 0; i < lens.
size(); ++i)
1513 std::cout <<
"M = " <<
const_me()->capacity() <<
'\n'
1514 <<
"N = " <<
const_me()->size() <<
'\n'
1515 <<
"busy slots = " <<
const_me()->busy_slots_counter <<
'\n'
1516 <<
"Average = " <<
stats.
avg <<
'\n'
1518 <<
"alpha = " <<
const_me()->current_alpha()
1521 std::cout <<
" " << i <<
" = " <<
stats.
lens(i) <<
'\n';
1535 <<
"upper_alpha lower than lower_alpha";
1537 me()->upper_alpha = _upper_alpha;
1551 <<
"lower_alpha greater than upper_alpha";
1553 me()->lower_alpha = _lower_alpha;
Exception handling system with formatted messages for Aleph-w.
#define ah_underflow_error_if(C)
Throws std::underflow_error if condition holds.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
STL-compatible iterator adapters for Aleph containers.
Core header for the Aleph-w library.
void put_itor_at_the_end(Itor &it) noexcept
Read-only view of an Aleph iterator: the iterator of a constant container.
Doubly linked circular list node.
T & touch(const size_t i)
Touch the entry i.
size_t size() const noexcept
Return the current dimension of array.
void reserve(const size_t l, const size_t r)
Allocate a range of entries.
Doubly-linked list (defined in tpl_dynList.H).
Number Theoretic Transform over Z / MOD Z.
CRTP mixin providing statistics and configuration for chained hash tables.
size_t bucket_length(const size_t i) const
Returns the length of the collision chain of bucket i.
constexpr float get_upper_alpha() const noexcept
Returns the upper load factor threshold.
void set_upper_alpha(float _upper_alpha)
Sets the upper load factor threshold.
HashTbl * me()
Returns a pointer to the derived class (CRTP pattern).
void set_with_resize(const bool with_resize) noexcept
Turns the automatic resizing on or off.
void set_lower_alpha(float _lower_alpha)
Sets the lower load factor threshold.
Stats stats() const
Computes statistics about chain length distribution.
constexpr bool get_with_resize() const noexcept
Returns whether the table resizes itself.
static void update_stat_len(DynArray< size_t > &lens, size_t i)
Updates chain length histogram.
void print_stats(const Stats &stats) const
Prints statistics to standard output.
const HashTbl * const_me() const
Returns a const pointer to the derived class (CRTP pattern).
constexpr float get_lower_alpha() const noexcept
Returns the lower load factor threshold.
Bidirectional iterator for traversing hash table entries.
Key & get_curr()
Returns a reference to the current entry with bounds checking.
Iterator() noexcept=default
Default constructor creates an "end" iterator.
bool check() const noexcept
Validates iterator state (debug only).
bool has_curr() const noexcept
Checks if the iterator is at a valid position.
constexpr long get_pos() const noexcept
Returns the current logical position.
const Key & get_curr() const
Returns a const reference to the current entry with bounds checking.
Iterator(const HashTbl &)=delete
A constant table is iterated through Const_Iterator.
void del()
Deletes the current entry and advances to the next.
void end() noexcept
Positions the iterator at the end (past-the-last element).
HashTbl * table_ptr
Pointer to the hash table being iterated.
void prev()
Moves to the previous entry with bounds checking.
void next()
Advances to the next entry with bounds checking.
long curr_idx
Current bucket index.
const Key & get_curr_ne() const noexcept
Returns a const reference to the current entry without checking.
void locate_next_available_entry()
Advances to next entry with bounds checking.
void prev_ne()
Moves to the previous entry without bounds checking.
void locate_prev_available_entry_ne()
Moves to previous entry without bounds checking.
Key & get_curr_ne() noexcept
Returns a reference to the current entry without checking.
void reset_first() noexcept
Positions the iterator at the first entry.
void reset_last() noexcept
Positions the iterator at the last entry.
void locate_prev_available_entry()
Moves to previous entry with bounds checking.
long ordinal
Logical position (0-based count of visited entries).
void next_ne() noexcept
Advances to the next entry without bounds checking.
void locate_next_available_entry_ne() noexcept
Advances to next entry without bounds checking.
constexpr bool is_last() const noexcept
Checks if the iterator is at the last entry.
CRTP mixin providing common operations for open addressing hash tables.
HashTbl * me()
Returns a pointer to the derived class (CRTP pattern).
size_t capacity_after_insertion() const
Capacity that an insertion leaves the table with, or 0 if it keeps it.
Key * append(const Key &key)
Alias for insert() (copy version).
void rebuild(const size_t new_len)
Places the keys of the table in new_len new buckets.
std::pair< Key *, bool > contains_or_insert(const Key &key)
Searches for a key, inserting if not found, with existence flag (copy version).
constexpr size_t size() const noexcept
Returns the number of entries in the table.
std::pair< Key *, bool > contains_or_insert(Key &&key)
Searches for a key, inserting if not found, with existence flag (move version).
Key * search_or_insert(const Key &key)
Searches for a key, inserting it if not found (copy version).
constexpr size_t capacity() const noexcept
Returns the current capacity of the table.
Key * search_or_insert(Key &&key)
Searches for a key, inserting it if not found (move version).
void clear()
Empties the container.
size_t resize(size_t new_size)
Resizes the hash table to a new capacity.
void store_copy(Bucket *bucket, const Key &key)
Stores a copy of a key in the bucket reserved for it.
static constexpr bool nothrow_key_swap
Whether two keys can be swapped without throwing.
void store_move(Bucket *bucket, Key &key)
Moves a key into the bucket reserved for it.
void clean_table()
Removes all entries from the table without deallocating storage.
constexpr float get_upper_alpha() const noexcept
Returns the upper load factor threshold for automatic growing.
const Key & find(const Key &key) const
Finds a key and returns a const reference to it.
void set_with_resize(const bool with_resize) noexcept
Turns the automatic resizing on or off.
void empty()
Clears all entries and resets to default capacity.
constexpr bool is_empty() const noexcept
Checks if the table is empty.
void copy_from_table(const HashTbl &other)
Copies all entries from another hash table.
void print_stats(const Stats &stats) const
Prints statistics to standard output.
void remove_ptr(Key *key)
Removes an entry by pointer.
size_t rebuild_capacity() const
Capacity to rebuild a table that resizes itself with, when its buckets in use are too many.
DynList< Key > keys() const
Returns a list containing all keys in the table.
Key * insert(Key &&key)
Inserts a key into the hash table (move version).
const Key & operator[](const Key &key) const
Subscript operator for const access.
constexpr float get_lower_alpha() const noexcept
Returns the lower load factor threshold for automatic shrinking.
Key * insert(const Key &key)
Inserts a key into the hash table (copy version).
constexpr bool has(const Key &key) const noexcept
Checks if a key exists in the table.
constexpr bool contains(const Key &key) const noexcept
Alias for has().
Key & find(const Key &key)
Finds a key and returns a reference to it.
void rehash()
Rebuilds the hash table with the same capacity.
bool check_resize_before_insert()
Makes room for one more key, if the table can take it.
void shrink_after_removal() noexcept
Shrinks a table that resizes itself, after a removal took its load factor under the lower threshold.
Key * append(Key &&key)
Alias for insert() (move version).
constexpr bool get_with_resize() const noexcept
Returns whether the table resizes itself.
auto items() const
Alias for keys().
constexpr float current_alpha() const noexcept
Returns the current load factor (alpha).
const HashTbl * const_me() const
Returns a const pointer to the derived class (CRTP pattern).
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_sqrt_function > > sqrt(const __gmp_expr< T, U > &expr)
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
void free_bucket_not_taken(Bucket *bucket) noexcept
Frees a bucket that a hash table of lists was given and did not take.
void swap_compare(Cmp &a, Cmp &b) noexcept
Swaps the comparators of two hash tables.
and
Check uniqueness with explicit hash + equality functors.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
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.
unsigned long next_prime(unsigned long n)
Find a prime >= n in the database, for hash table sizing.
size_t prime_table_len(const size_t len)
The length of a table for a request of len buckets: the next prime.
size_t checked_table_len(const size_t len)
Checks that the bytes of a table of buckets fit in a size_t.
Prime number utilities for hash tables and mathematical operations.
Statistics about chain length distribution.
DynArray< size_t > lens
Distribution: lens[i] = number of chains with length i.
float avg
Average chain length.
float var
Variance of chain lengths.
Statistics about hash table performance.
size_t num_deleted
Number of buckets marked as deleted.
size_t num_empty
Number of empty buckets.
DynArray< size_t > lens
Distribution of probe sequence lengths.
float avg
Average probe sequence length.
Stats()
Default constructor initializing max_len to minimum.
size_t num_busy
Number of occupied buckets.
float var
Variance of probe sequence lengths.
size_t max_len
Maximum probe sequence length.
Lazy and scalable dynamic array implementation.