From 4f427bc298b0cfc45bd25381cd04df86868c0843 Mon Sep 17 00:00:00 2001
From: antirez <antirez@gmail.com>
Date: Thu, 5 Feb 2015 12:15:58 +0100
Subject: [PATCH] dict.c: don't try buckets that are empty for sure in
 dictGetRandomKey().

This is very similar to the optimization applied to dictGetRandomKeys,
but applied to the single key variant.

Related to issue #2306.
---
 src/dict.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/dict.c b/src/dict.c
index e197266e..9ba0d7d7 100644
--- a/src/dict.c
+++ b/src/dict.c
@@ -631,7 +631,11 @@ dictEntry *dictGetRandomKey(dict *d)
     if (dictIsRehashing(d)) _dictRehashStep(d);
     if (dictIsRehashing(d)) {
         do {
-            h = random() % (d->ht[0].size+d->ht[1].size);
+            /* We are sure there are no elements in indexes from 0
+             * to rehashidx-1 */
+            h = d->rehashidx + (random() % (d->ht[0].size +
+                                            d->ht[1].size -
+                                            d->rehashidx));
             he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] :
                                       d->ht[0].table[h];
         } while(he == NULL);