Created
December 6, 2012 10:28
-
-
Save dpk/4223533 to your computer and use it in GitHub Desktop.
Apple's CFHash algorithm for strings in Ruby
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
# Why? Why not! | |
def cfhash string | |
result = string.length | |
max = 2 ** 32 | |
string.each_codepoint do |cp| | |
result = ((result * 257) % max) + cp | |
end | |
return (result + (result << (string.length & 31))) % max | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This still isn't quite right. For some strings it's correct, for others it's wrong.
(Notably, it will be wrong for strings longer than 96 characters, because that's special-cased in the original algorithm. But I don't need to cover that case for what I'm using this for.)