docs/Writerside/topics/hash_map.h.md

Wed, 31 Dec 2025 16:32:36 +0100

author
Mike Becker <universe@uap-core.de>
date
Wed, 31 Dec 2025 16:32:36 +0100
changeset 1697
ca825e816a50
parent 1694
a2757c6427cc
permissions
-rw-r--r--

Added tag v4.0 for changeset 976e629ce990

# Hash Map

UCX provides a basic hash map implementation with a configurable number of buckets.
If you do not specify the number of buckets, a default of 16 buckets will be used.

You can always rehash the map with `cxMapRehash()` to change the number of buckets to something more efficient,
but you need to be careful, because when you use this function you are effectively locking into using this
specific hash map implementation, and you would need to remove all calls to this function when you want to
exchange the concrete map implementation with something different.

```C
#include <cx/hash_map.h>

CxMap *cxHashMapCreate(const CxAllocator *allocator,
        size_t itemsize, size_t buckets);

int cxMapRehash(CxMap *map);
```

The function `cxHashMapCreate()` creates a new [map](map.h.md) where both the map structure
and the contained buckets are allocated by the specified `allocator`.

The map will store items of size `itemsize`.
You can use the `CX_STORE_POINTERS` macro for `itemsize` to indicate that the map shall store
pointers instead of actual items.

If you pass zero for the number of `buckets`,
the map is initialized with a default of 16 buckets; otherwise the specified number of buckets is allocated.

The `cxMapRehash()` function creates a new bucket array and reassigns all elements when the element count surpasses three-quarters of the bucket count.
If this condition isn't met, the function returns 0 without making any changes.
Post-rehashing, the bucket count will be at least two and a half times the element count.

> Advice if you want to create your own hash map structures:
> Calling `cxMapRehash()` on a map is only defined when the map is based on the
> `struct cx_hash_map_s` structure.

<seealso>
<category ref="apidoc">
<a href="https://ucx.sourceforge.io/api/hash__map_8h.html">hash_map.h</a>
</category>
</seealso>

mercurial