Last active
October 16, 2023 20:20
-
-
Save ismasan/b8b3c395d43984b1a25e8e5c6b6f0cee to your computer and use it in GitHub Desktop.
hash64.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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