Skip to content

Instantly share code, notes, and snippets.

@BYK
Forked from anonymous/djb2.sql
Last active December 26, 2015 03:49
Show Gist options
  • Save BYK/7088984 to your computer and use it in GitHub Desktop.
Save BYK/7088984 to your computer and use it in GitHub Desktop.
Compatible DJB2 Hash implementation in JS and SQL
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);
}
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