Skip to content

Instantly share code, notes, and snippets.

@ismasan
Last active October 16, 2023 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ismasan/b8b3c395d43984b1a25e8e5c6b6f0cee to your computer and use it in GitHub Desktop.
Save ismasan/b8b3c395d43984b1a25e8e5c6b6f0cee to your computer and use it in GitHub Desktop.
hash64.rb
module Hash64
# Turn a string into a well distributed 64 bit integer
# This matches the hash_64() PGSQL function used to partition streams.
#
# @param value [String] the string to hash
# @return [Integer] a 64 bit integer
def self.call(value)
binary_string = ('0' + Digest::MD5.hexdigest(value)[0...16]).hex.to_s(2)
# Convert the binary string to a signed BigInt
bigint_value = binary_string.to_i(2)
# Check if the most significant bit is set (indicating a negative value in 2's complement)
if binary_string[0] == '1'
# Handle negative value by applying 2's complement
bigint_value -= 2**64
end
bigint_value.abs
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment