-
-
Save BYK/7088984 to your computer and use it in GitHub Desktop.
Compatible DJB2 Hash implementation in JS and SQL
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
function djb2Hash(str, seed) { | |
for (var counter = 0, len = str.length; counter < len; counter++) { | |
seed ^= (seed << 5); | |
seed ^= str.charCodeAt(counter); | |
} | |
// We discard the sign-bit for compatibility with the DB implementation | |
// and "always positive integers" | |
return seed & ~(1 << 31); | |
} |
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
CREATE OR REPLACE FUNCTION djb2_hash(string text) | |
RETURNS bigint | |
LANGUAGE sql | |
AS $$ | |
WITH RECURSIVE t(seed, string) AS ( | |
VALUES ( | |
87049::bigint, | |
$1 | |
) | |
UNION ALL | |
SELECT | |
( | |
( | |
(t.seed << 5) # | |
t.seed # | |
ascii ( | |
substr ( | |
t.string, | |
1, | |
1 | |
) | |
) | |
) | |
), | |
substr ( | |
t.string, | |
2 | |
) | |
FROM t | |
) | |
SELECT seed & ~(1 << 31)::bigint | |
FROM t | |
WHERE string = '' | |
$$; | |
WITH v(s) AS ( | |
VALUES | |
('foo'), | |
('bar'), | |
('disqus'), | |
('bazinga') | |
) | |
SELECT s, djb2_hash(s) | |
FROM v; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment