From a04e825e776ebb5684a94a310b1dc2c54e515d0c Mon Sep 17 00:00:00 2001
From: "Anton A. Melnikov" <a.melnikov@postgrespro.ru>
Date: Wed, 12 Feb 2025 20:22:45 +0300
Subject: [PATCH] Use valgrind-safe code to find a number of rightmost zero 
 bytes.

---
 src/include/common/hashfn_unstable.h | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/src/include/common/hashfn_unstable.h b/src/include/common/hashfn_unstable.h
index e07c0226c1f..82158f0d9c3 100644
--- a/src/include/common/hashfn_unstable.h
+++ b/src/include/common/hashfn_unstable.h
@@ -255,7 +255,7 @@ static inline size_t
 fasthash_accum_cstring_aligned(fasthash_state *hs, const char *str)
 {
 	const char *const start = str;
-	size_t		remainder;
+	size_t		remainder = 0;
 	uint64		zero_byte_low;
 
 	Assert(PointerIsAligned(start, uint64));
@@ -291,11 +291,18 @@ fasthash_accum_cstring_aligned(fasthash_state *hs, const char *str)
 	}
 
 	/*
-	 * The byte corresponding to the NUL will be 0x80, so the rightmost bit
-	 * position will be in the range 7, 15, ..., 63. Turn this into byte
-	 * position by dividing by 8.
+	 * The byte corresponding to the NUL terminator will be the rightmost 0x80.
+	 * pAll zero bytes to the right of it correspond to the tail of the string.
+	 * It remains to count them.
 	 */
-	remainder = pg_rightmost_one_pos64(zero_byte_low) / BITS_PER_BYTE;
+	while ((zero_byte_low & 0xFF) == 0)
+	{
+		zero_byte_low >>= 8;
+		++remainder;
+	}
+
+	Assert(remainder != 0);
+
 	fasthash_accum(hs, str, remainder);
 	str += remainder;
 
-- 
2.48.1

