4 * When included this file generates a "templated" (by way of macros)
5 * open-addressing hash table implementation specialized to user-defined
8 * It's probably not worthwhile to generate such a specialized implementation
9 * for hash tables that aren't performance or space sensitive.
11 * Compared to dynahash, simplehash has the following benefits:
13 * - Due to the "templated" code generation has known structure sizes and no
14 * indirect function calls (which show up substantially in dynahash
15 * profiles). These features considerably increase speed for small
17 * - Open addressing has better CPU cache behavior than dynahash's chained
19 * - The generated interface is type-safe and easier to use than dynahash,
20 * though at the cost of more complex setup.
21 * - Allocates memory in a MemoryContext or another allocator with a
22 * malloc/free style interface (which isn't easily usable in a shared
24 * - Does not require the overhead of a separate memory context.
28 * To generate a hash-table and associated functions for a use case several
29 * macros have to be #define'ed before this file is included. Including
30 * the file #undef's all those, so a new hash table can be generated
32 * The relevant parameters are:
33 * - SH_PREFIX - prefix for all symbol names generated. A prefix of 'foo'
34 * will result in hash table type 'foo_hash' and functions like
35 * 'foo_insert'/'foo_lookup' and so forth.
36 * - SH_ELEMENT_TYPE - type of the contained elements
37 * - SH_KEY_TYPE - type of the hashtable's key
38 * - SH_DECLARE - if defined function prototypes and type declarations are
40 * - SH_DEFINE - if defined function definitions are generated
41 * - SH_SCOPE - in which scope (e.g. extern, static inline) do function
43 * - SH_RAW_ALLOCATOR - if defined, memory contexts are not used; instead,
44 * use this to allocate bytes. The allocator must zero the returned space.
45 * - SH_USE_NONDEFAULT_ALLOCATOR - if defined no element allocator functions
46 * are defined, so you can supply your own
47 * The following parameters are only relevant when SH_DEFINE is defined:
48 * - SH_KEY - name of the element in SH_ELEMENT_TYPE containing the hash key
49 * - SH_EQUAL(table, a, b) - compare two table keys
50 * - SH_HASH_KEY(table, key) - generate hash for the key
51 * - SH_STORE_HASH - if defined the hash is stored in the elements
52 * - SH_GET_HASH(tb, a) - return the field to store the hash in
54 * The element type is required to contain a "status" member that can store
55 * the range of values defined in the SH_STATUS enum.
57 * While SH_STORE_HASH (and subsequently SH_GET_HASH) are optional, because
58 * the hash table implementation needs to compare hashes to move elements
59 * (particularly when growing the hash), it's preferable, if possible, to
60 * store the element's hash in the element's data type. If the hash is so
61 * stored, the hash table will also compare hashes before calling SH_EQUAL
62 * when comparing two keys.
64 * For convenience the hash table create functions accept a void pointer
65 * that will be stored in the hash table type's member private_data. This
66 * allows callbacks to reference caller provided data.
68 * For examples of usage look at tidbitmap.c (file local definition) and
69 * execnodes.h/execGrouping.c (exposed declaration, file local
74 * The hash table design chosen is a variant of linear open-addressing. The
75 * reason for doing so is that linear addressing is CPU cache & pipeline
76 * friendly. The biggest disadvantage of simple linear addressing schemes
77 * are highly variable lookup times due to clustering, and deletions
78 * leaving a lot of tombstones around. To address these issues a variant
79 * of "robin hood" hashing is employed. Robin hood hashing optimizes
80 * chaining lengths by moving elements close to their optimal bucket
81 * ("rich" elements), out of the way if a to-be-inserted element is further
82 * away from its optimal position (i.e. it's "poor"). While that can make
83 * insertions slower, the average lookup performance is a lot better, and
84 * higher fill factors can be used in a still performant manner. To avoid
85 * tombstones - which normally solve the issue that a deleted node's
86 * presence is relevant to determine whether a lookup needs to continue
87 * looking or is done - buckets following a deleted element are shifted
88 * backwards, unless they're empty or already at their optimal position.
90 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
91 * Portions Copyright (c) 1994, Regents of the University of California
93 * src/include/lib/simplehash.h
99 #define SH_MAKE_PREFIX(a) CppConcat(a,_)
100 #define SH_MAKE_NAME(name) SH_MAKE_NAME_(SH_MAKE_PREFIX(SH_PREFIX),name)
101 #define SH_MAKE_NAME_(a,b) CppConcat(a,b)
103/* name macros for: */
105/* type declarations */
106 #define SH_TYPE SH_MAKE_NAME(hash)
107 #define SH_STATUS SH_MAKE_NAME(status)
108 #define SH_STATUS_EMPTY SH_MAKE_NAME(SH_EMPTY)
109 #define SH_STATUS_IN_USE SH_MAKE_NAME(SH_IN_USE)
110 #define SH_ITERATOR SH_MAKE_NAME(iterator)
112/* function declarations */
113 #define SH_CREATE SH_MAKE_NAME(create)
114 #define SH_DESTROY SH_MAKE_NAME(destroy)
115 #define SH_RESET SH_MAKE_NAME(reset)
116 #define SH_INSERT SH_MAKE_NAME(insert)
117 #define SH_INSERT_HASH SH_MAKE_NAME(insert_hash)
118 #define SH_DELETE_ITEM SH_MAKE_NAME(delete_item)
119 #define SH_DELETE SH_MAKE_NAME(delete)
120 #define SH_LOOKUP SH_MAKE_NAME(lookup)
121 #define SH_LOOKUP_HASH SH_MAKE_NAME(lookup_hash)
122 #define SH_GROW SH_MAKE_NAME(grow)
123 #define SH_START_ITERATE SH_MAKE_NAME(start_iterate)
124 #define SH_START_ITERATE_AT SH_MAKE_NAME(start_iterate_at)
125 #define SH_ITERATE SH_MAKE_NAME(iterate)
126 #define SH_ALLOCATE SH_MAKE_NAME(allocate)
127 #define SH_FREE SH_MAKE_NAME(free)
128 #define SH_STAT SH_MAKE_NAME(stat)
130/* internal helper functions (no externally visible prototypes) */
131 #define SH_COMPUTE_SIZE SH_MAKE_NAME(compute_size)
132 #define SH_UPDATE_PARAMETERS SH_MAKE_NAME(update_parameters)
133 #define SH_NEXT SH_MAKE_NAME(next)
134 #define SH_PREV SH_MAKE_NAME(prev)
135 #define SH_DISTANCE_FROM_OPTIMAL SH_MAKE_NAME(distance)
136 #define SH_INITIAL_BUCKET SH_MAKE_NAME(initial_bucket)
137 #define SH_ENTRY_HASH SH_MAKE_NAME(entry_hash)
138 #define SH_INSERT_HASH_INTERNAL SH_MAKE_NAME(insert_hash_internal)
139 #define SH_LOOKUP_HASH_INTERNAL SH_MAKE_NAME(lookup_hash_internal)
141/* generate forward declarations necessary to use the hash table */
144/* type definitions */
148 * Size of data / bucket array, 64 bits to handle UINT32_MAX sized hash
149 * tables. Note that the maximum number of elements is lower
150 * (SH_MAX_FILLFACTOR)
154 /* how many elements have valid contents */
157 /* mask for bucket and size calculations, based on size */
160 /* boundary after which to grow hashtable */
166#ifndef SH_RAW_ALLOCATOR
167 /* memory context to use for allocations */
171 /* user defined data, useful for callbacks */
185 bool done;
/* iterator exhausted? */
188/* externally visible function prototypes */
189#ifdef SH_RAW_ALLOCATOR
190/* <prefix>_hash <prefix>_create(uint32 nelements, void *private_data) */
194 * <prefix>_hash <prefix>_create(MemoryContext ctx, uint32 nelements,
195 * void *private_data)
201/* void <prefix>_destroy(<prefix>_hash *tb) */
204/* void <prefix>_reset(<prefix>_hash *tb) */
207/* void <prefix>_grow(<prefix>_hash *tb, uint64 newsize) */
210/* <element> *<prefix>_insert(<prefix>_hash *tb, <key> key, bool *found) */
214 * <element> *<prefix>_insert_hash(<prefix>_hash *tb, <key> key, uint32 hash,
220/* <element> *<prefix>_lookup(<prefix>_hash *tb, <key> key) */
223/* <element> *<prefix>_lookup_hash(<prefix>_hash *tb, <key> key, uint32 hash) */
227/* void <prefix>_delete_item(<prefix>_hash *tb, <element> *entry) */
230/* bool <prefix>_delete(<prefix>_hash *tb, <key> key) */
233/* void <prefix>_start_iterate(<prefix>_hash *tb, <prefix>_iterator *iter) */
237 * void <prefix>_start_iterate_at(<prefix>_hash *tb, <prefix>_iterator *iter,
242/* <element> *<prefix>_iterate(<prefix>_hash *tb, <prefix>_iterator *iter) */
245/* void <prefix>_stat(<prefix>_hash *tb */
248#endif /* SH_DECLARE */
251/* generate implementation of the hash table */
254#ifndef SH_RAW_ALLOCATOR
258/* max data array size,we allow up to PG_UINT32_MAX buckets, including 0 */
259#define SH_MAX_SIZE (((uint64) PG_UINT32_MAX) + 1)
261/* normal fillfactor, unless already close to maximum */
263#define SH_FILLFACTOR (0.9)
265/* increase fillfactor if we otherwise would error out */
266#define SH_MAX_FILLFACTOR (0.98)
267/* grow if actual and optimal location bigger than */
268#ifndef SH_GROW_MAX_DIB
269#define SH_GROW_MAX_DIB 25
271/* grow if more than elements to move when inserting */
272#ifndef SH_GROW_MAX_MOVE
273#define SH_GROW_MAX_MOVE 150
275#ifndef SH_GROW_MIN_FILLFACTOR
276/* but do not grow due to SH_GROW_MAX_* if below */
277#define SH_GROW_MIN_FILLFACTOR 0.1
281#define SH_COMPARE_KEYS(tb, ahash, akey, b) (ahash == SH_GET_HASH(tb, b) && SH_EQUAL(tb, b->SH_KEY, akey))
283#define SH_COMPARE_KEYS(tb, ahash, akey, b) (SH_EQUAL(tb, b->SH_KEY, akey))
287 * Wrap the following definitions in include guards, to avoid multiple
288 * definition errors if this header is included more than once. The rest of
289 * the file deliberately has no include guards, because it can be included
290 * with different parameters to define functions and types with non-colliding
297#define sh_error(...) pg_fatal(__VA_ARGS__)
298#define sh_log(...) pg_log_info(__VA_ARGS__)
300#define sh_error(...) elog(ERROR, __VA_ARGS__)
301#define sh_log(...) elog(LOG, __VA_ARGS__)
307 * Compute allocation size for hashtable. Result can be passed to
308 * SH_UPDATE_PARAMETERS.
315 /* supporting zero sized hashes would complicate matters */
316 size =
Max(newsize, 2);
318 /* round up size to the next power of 2, that's how bucketing works */
320 Assert(size <= SH_MAX_SIZE);
323 * Verify that allocation of ->data is possible on this platform, without
327 sh_error(
"hash table too large");
333 * Update sizing parameters for hashtable. Called when creating and growing
346 * Compute the next threshold at which we need to grow the hash table
349 if (tb->
size == SH_MAX_SIZE)
355/* return the optimal bucket for the hash */
362/* return next bucket after the current, handling wraparound */
366 curelem = (curelem + 1) & tb->
sizemask;
368 Assert(curelem != startelem);
373/* return bucket before the current, handling wraparound */
377 curelem = (curelem - 1) & tb->
sizemask;
379 Assert(curelem != startelem);
384/* return distance between bucket and its optimal position */
388 if (optimal <= bucket)
389 return bucket - optimal;
391 return (tb->
size + bucket) - optimal;
404/* default memory allocator function */
408#ifndef SH_USE_NONDEFAULT_ALLOCATOR
410/* default memory allocator function */
414#ifdef SH_RAW_ALLOCATOR
422/* default memory free function */
432 * Create a hash table with enough space for `nelements` distinct members.
433 * Memory for the hash table is allocated from the passed-in context. If
434 * desired, the array of elements can be allocated using a passed-in allocator;
435 * this could be useful in order to place the array of elements in a shared
436 * memory, or in a context that will outlive the rest of the hash table.
437 * Memory other than for the array of elements will still be allocated from
438 * the passed-in context.
440#ifdef SH_RAW_ALLOCATOR
451#ifdef SH_RAW_ALLOCATOR
459 /* increase nelements by fillfactor, want to store nelements elements */
460 size =
Min((
double) SH_MAX_SIZE, ((
double) nelements) / SH_FILLFACTOR);
470/* destroy a previously created hash table */
478/* reset the contents of a previously created hash table */
487 * Grow a hash table to at least `newsize` buckets.
489 * Usually this will automatically be called by insertions/deletions, when
490 * necessary. But resizing to the exact input size can be advantageous
491 * performance-wise, when known at some point.
504 Assert(oldsize != SH_MAX_SIZE);
505 Assert(oldsize < newsize);
512 * Update parameters for new table after allocation succeeds to avoid
513 * inconsistent state on OOM.
520 * Copy entries from the old data to newdata. We theoretically could use
521 * SH_INSERT here, to avoid code duplication, but that's more general than
522 * we need. We neither want tb->members increased, nor do we need to do
523 * deal with deleted elements, nor do we need to compare keys. So a
524 * special-cased implementation is lot faster. As resizing can be time
525 * consuming and frequent, that's worthwhile to optimize.
527 * To be able to simply move entries over, we have to start not at the
528 * first bucket (i.e olddata[0]), but find the first bucket that's either
529 * empty, or is occupied by an entry at its optimal position. Such a
530 * bucket has to exist in any table with a load factor under 1, as not all
531 * buckets are occupied, i.e. there always has to be an empty bucket. By
532 * starting at such a bucket we can move the entries to the larger table,
533 * without having to deal with conflicts.
536 /* search for the first element in the hash that's not wrapped around */
537 for (
i = 0;
i < oldsize;
i++)
559 /* and copy all elements in the old table */
560 copyelem = startelem;
561 for (
i = 0;
i < oldsize;
i++)
574 curelem = startelem2;
576 /* find empty element to put data into */
579 newentry = &newdata[curelem];
586 curelem =
SH_NEXT(tb, curelem, startelem2);
589 /* copy entry to new slot */
593 /* can't use SH_NEXT here, would use new size */
595 if (copyelem >= oldsize)
605 * This is a separate static inline function, so it can be reliably be inlined
606 * into its wrapper functions even if SH_SCOPE is extern.
620 * We do the grow check even if the key is actually present, to avoid
621 * doing the check inside the loop. This also lets us avoid having to
622 * re-find our position in the hashtable after resizing.
624 * Note that this also reached when resizing the table due to
625 * SH_GROW_MAX_DIB / SH_GROW_MAX_MOVE.
630 sh_error(
"hash table size exceeded");
633 * When optimizing, it can be very useful to print these out.
640 /* perform insert, start bucket search at optimal location */
651 /* any empty bucket can directly be used */
665 * If the bucket is not empty, we either found a match (in which case
666 * we're done), or we have to decide whether to skip over or move the
667 * colliding entry. When the colliding element's distance to its
668 * optimal position is smaller than the to-be-inserted entry's, we
669 * shift the colliding entry (and its followers) forward by one.
672 if (SH_COMPARE_KEYS(tb,
hash,
key, entry))
683 if (insertdist > curdist)
686 uint32 emptyelem = curelem;
690 /* find next empty bucket */
695 emptyelem =
SH_NEXT(tb, emptyelem, startelem);
696 emptyentry = &
data[emptyelem];
700 lastentry = emptyentry;
705 * To avoid negative consequences from overly imbalanced
706 * hashtables, grow the hashtable if collisions would require
707 * us to move a lot of entries. The most likely cause of such
708 * imbalance is filling a (currently) small table, from a
709 * currently big one, in hash-table order. Don't grow if the
710 * hashtable would be too empty, to prevent quick space
711 * explosion for some weird edge cases.
713 if (
unlikely(++emptydist > SH_GROW_MAX_MOVE) &&
714 ((
double) tb->
members / tb->
size) >= SH_GROW_MIN_FILLFACTOR)
721 /* shift forward, starting at last occupied element */
724 * TODO: This could be optimized to be one memcpy in many cases,
725 * excepting wrapping around at the end of ->data. Hasn't shown up
726 * in profiles so far though.
728 moveelem = emptyelem;
729 while (moveelem != curelem)
733 moveelem =
SH_PREV(tb, moveelem, startelem);
734 moveentry = &
data[moveelem];
737 lastentry = moveentry;
740 /* and fill the now empty spot */
752 curelem =
SH_NEXT(tb, curelem, startelem);
756 * To avoid negative consequences from overly imbalanced hashtables,
757 * grow the hashtable if collisions lead to large runs. The most
758 * likely cause of such imbalance is filling a (currently) small
759 * table, from a currently big one, in hash-table order. Don't grow
760 * if the hashtable would be too empty, to prevent quick space
761 * explosion for some weird edge cases.
763 if (
unlikely(insertdist > SH_GROW_MAX_DIB) &&
764 ((
double) tb->
members / tb->
size) >= SH_GROW_MIN_FILLFACTOR)
773 * Insert the key into the hash-table, set *found to true if the key already
774 * exists, false otherwise. Returns the hash-table entry in either case.
785 * Insert the key into the hash-table using an already-calculated hash. Set
786 * *found to true if the key already exists, false otherwise. Returns the
787 * hash-table entry in either case.
796 * This is a separate static inline function, so it can be reliably be inlined
797 * into its wrapper functions even if SH_SCOPE is extern.
803 uint32 curelem = startelem;
816 if (SH_COMPARE_KEYS(tb,
hash,
key, entry))
820 * TODO: we could stop search based on distance. If the current
821 * buckets's distance-from-optimal is smaller than what we've skipped
822 * already, the entry doesn't exist. Probably only do so if
823 * SH_STORE_HASH is defined, to avoid re-computing hashes?
826 curelem =
SH_NEXT(tb, curelem, startelem);
831 * Lookup entry in hash table. Returns NULL if key not present.
842 * Lookup entry in hash table using an already-calculated hash.
844 * Returns NULL if key not present.
853 * Delete entry from hash table by key. Returns whether to-be-deleted key was
861 uint32 curelem = startelem;
871 SH_COMPARE_KEYS(tb,
hash,
key, entry))
878 * Backward shift following elements till either an empty element
879 * or an element at its optimal position is encountered.
881 * While that sounds expensive, the average chain length is short,
882 * and deletions would otherwise require tombstones.
890 curelem =
SH_NEXT(tb, curelem, startelem);
891 curentry = &tb->
data[curelem];
902 /* current is at optimal position, done */
903 if (curoptimal == curelem)
912 lastentry = curentry;
918 /* TODO: return false; if distance too big */
920 curelem =
SH_NEXT(tb, curelem, startelem);
925 * Delete entry from hash table by entry pointer
935 /* Calculate the index of 'entry' */
936 curelem = entry - &tb->
data[0];
941 * Backward shift following elements till either an empty element or an
942 * element at its optimal position is encountered.
944 * While that sounds expensive, the average chain length is short, and
945 * deletions would otherwise require tombstones.
953 curelem =
SH_NEXT(tb, curelem, startelem);
954 curentry = &tb->
data[curelem];
965 /* current is at optimal position, done */
966 if (curoptimal == curelem)
975 lastentry = curentry;
980 * Initialize iterator.
988 * Search for the first empty element. As deletions during iterations are
989 * supported, we want to start/end at an element that cannot be affected
990 * by elements being shifted.
1003 /* we should have found an empty element */
1004 Assert(startelem < SH_MAX_SIZE);
1007 * Iterate backwards, that allows the current element to be deleted, even
1008 * if there are backward shifts
1010 iter->
cur = startelem;
1016 * Initialize iterator to a specific bucket. That's really only useful for
1017 * cases where callers are partially iterating over the hashspace, and that
1018 * iteration deletes and inserts elements based on visited entries. Doing that
1019 * repeatedly could lead to an unbalanced keyspace when always starting at the
1026 * Iterate backwards, that allows the current element to be deleted, even
1027 * if there are backward shifts.
1029 iter->
cur = at & tb->
sizemask;
/* ensure at is within a valid range */
1035 * Iterate over all entries in the hash-table. Return the next occupied entry,
1038 * During iteration the current entry in the hash table may be deleted,
1039 * without leading to elements being skipped or returned twice. Additionally
1040 * the rest of the table may be modified (i.e. there can be insertions or
1041 * deletions), but if so, there's neither a guarantee that all nodes are
1042 * visited at least once, nor a guarantee that a node is visited at most once.
1053 /* next element in backward direction */
1068 * Report some statistics about the state of the hashtable. For
1069 * debugging/profiling purposes only.
1074 uint32 max_chain_length = 0;
1075 uint32 total_chain_length = 0;
1076 double avg_chain_length;
1081 uint32 total_collisions = 0;
1082 uint32 max_collisions = 0;
1083 double avg_collisions;
1085 for (
i = 0;
i < tb->
size;
i++)
1092 elem = &tb->
data[
i];
1101 if (dist > max_chain_length)
1102 max_chain_length = dist;
1103 total_chain_length += dist;
1105 collisions[optimal]++;
1108 for (
i = 0;
i < tb->
size;
i++)
1110 uint32 curcoll = collisions[
i];
1115 /* single contained element is not a collision */
1117 total_collisions += curcoll;
1118 if (curcoll > max_collisions)
1119 max_collisions = curcoll;
1122 /* large enough to be worth freeing, even if just used for debugging */
1128 avg_chain_length = ((double) total_chain_length) / tb->
members;
1129 avg_collisions = ((double) total_collisions) / tb->
members;
1134 avg_chain_length = 0;
1138 sh_log(
"size: " UINT64_FORMAT ", members: %u, filled: %f, total chain: %u, max chain: %u, avg chain: %f, total_collisions: %u, max_collisions: %u, avg_collisions: %f",
1140 total_collisions, max_collisions, avg_collisions);
1143#endif /* SH_DEFINE */
1146/* undefine external parameters, so next hash table can be defined */
1150#undef SH_ELEMENT_TYPE
1157#undef SH_USE_NONDEFAULT_ALLOCATOR
1160/* undefine locally declared macros */
1161#undef SH_MAKE_PREFIX
1165#undef SH_MAX_FILLFACTOR
1166#undef SH_GROW_MAX_DIB
1167#undef SH_GROW_MAX_MOVE
1168#undef SH_GROW_MIN_FILLFACTOR
1174#undef SH_STATUS_EMPTY
1175#undef SH_STATUS_IN_USE
1178/* external function names */
1183#undef SH_INSERT_HASH
1184#undef SH_DELETE_ITEM
1187#undef SH_LOOKUP_HASH
1189#undef SH_START_ITERATE
1190#undef SH_START_ITERATE_AT
1196/* internal function names */
1197#undef SH_COMPUTE_SIZE
1198#undef SH_UPDATE_PARAMETERS
1199#undef SH_COMPARE_KEYS
1200#undef SH_INITIAL_BUCKET
1203#undef SH_DISTANCE_FROM_OPTIMAL
1205#undef SH_INSERT_HASH_INTERNAL
1206#undef SH_LOOKUP_HASH_INTERNAL
#define SH_HASH_KEY(tb, key)
#define SH_GET_HASH(tb, a)
Assert(PointerIsAligned(start, uint64))
if(TABLE==NULL||TABLE_index==NULL)
void * MemoryContextAllocZero(MemoryContext context, Size size)
void pfree(void *pointer)
void * palloc0(Size size)
void * MemoryContextAllocExtended(MemoryContext context, Size size, int flags)
static uint64 pg_nextpower2_64(uint64 num)
static unsigned hash(unsigned *uv, int n)
#define SH_INITIAL_BUCKET
#define SH_UPDATE_PARAMETERS
#define SH_DISTANCE_FROM_OPTIMAL
#define SH_LOOKUP_HASH_INTERNAL
#define SH_INSERT_HASH_INTERNAL
#define SH_START_ITERATE_AT