From fa999daec1325e614d3effe6c8624b891d33f80d Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@2ndquadrant.com>
Date: Sun, 10 Dec 2017 20:04:45 +0100
Subject: [PATCH 2/3] universal hashing to compute initial bucket

---
 src/include/lib/simplehash.h | 25 ++++++++++++++++++++++++-
 1 file changed, 24 insertions(+), 1 deletion(-)

diff --git a/src/include/lib/simplehash.h b/src/include/lib/simplehash.h
index c5af5b9..4f687a8 100644
--- a/src/include/lib/simplehash.h
+++ b/src/include/lib/simplehash.h
@@ -113,6 +113,11 @@ typedef struct SH_TYPE
 	/* boundary after which to grow hashtable */
 	uint32		grow_threshold;
 
+	/* random values used for universal hashing */
+	uint64		a;
+	uint64		b;
+	uint64		p;
+
 	/* hash buckets */
 	SH_ELEMENT_TYPE *data;
 
@@ -210,6 +215,10 @@ static inline void
 SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32 newsize)
 {
 	uint64		size;
+	static uint64 primes[] = {32416190071, 32416174391, 31448680931,
+							  30241080791, 29035441483, 27831898657,
+							  26630552983, 25431443617, 24234583979,
+							  23040315733, 21848589131, 20659651601};
 
 	/* supporting zero sized hashes would complicate matters */
 	size = Max(newsize, 2);
@@ -241,13 +250,27 @@ SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint32 newsize)
 		tb->grow_threshold = ((double) tb->size) * SH_MAX_FILLFACTOR;
 	else
 		tb->grow_threshold = ((double) tb->size) * SH_FILLFACTOR;
+
+	/*
+	 * Pick random value for universal hashing. Make sure it's odd and
+	 * fits into 32 bits.
+	 *
+	 * XXX There are additional requirements on good values ...
+	 */
+	tb->a = 1 + random() % 1000000000;
+	tb->a += (tb->a % 2 == 0) ? 1 : 0;
+
+	tb->b = 1 + random() % 1000000000;
+	tb->b += (tb->b % 2 == 0) ? 1 : 0;
+
+	tb->p = primes[random() % 12];
 }
 
 /* return the optimal bucket for the hash */
 static inline uint32
 SH_INITIAL_BUCKET(SH_TYPE * tb, uint32 hash)
 {
-	return hash & tb->sizemask;
+	return ((hash * tb->a + tb->b) % tb->p) & tb->sizemask;
 }
 
 /* return next bucket after the current, handling wraparound */
-- 
2.9.5

