Created
March 4, 2012 04:10
-
-
Save jasonjohnson/1970629 to your computer and use it in GitHub Desktop.
PHP Hash Implementation using DJB
This file contains hidden or 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
<?php | |
class Hash { | |
var $buckets = array(); | |
function put($key, $value) { | |
$this->buckets[$this->generate_hash($key)] = $value; | |
} | |
function get($key) { | |
return $this->buckets[$this->generate_hash($key)]; | |
} | |
function generate_hash($str) { | |
$hash = 5381; | |
for($i = 0; $i < strlen($str); $i++) { | |
$hash = (($hash << 5) + $hash) + ord($str[$i]); | |
} | |
return $hash; | |
} | |
} | |
$h = new Hash(); | |
$h->put("key1", "Hello World!"); | |
$h->put("key2", "Goodbye World!"); | |
echo $h->get("key1") . PHP_EOL; | |
echo $h->get("key2") . PHP_EOL; |
The djb hash algorithm depends on integer overflows and php has unpredictable behaviour about this (different version, architectures, etc.). This can lead to different results which of course is not something we want. :) You can read about it here: http://stackoverflow.com/questions/300840/force-php-integer-overflow
I've made some changes in this gist: https://gist.github.com/aralbald/5772554
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pretty helpful!~