Skip to content

Instantly share code, notes, and snippets.

@dpk
Created December 6, 2012 10:28
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 dpk/4223533 to your computer and use it in GitHub Desktop.
Save dpk/4223533 to your computer and use it in GitHub Desktop.
Apple's CFHash algorithm for strings in Ruby
# 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
@dpk
Copy link
Author

dpk commented Dec 6, 2012

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.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment