Skip to content

Instantly share code, notes, and snippets.

@alganet
Created August 19, 2022 10:24
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 alganet/d465197ed057f8b8ed5e908d5cb71b0e to your computer and use it in GitHub Desktop.
Save alganet/d465197ed057f8b8ed5e908d5cb71b0e to your computer and use it in GitHub Desktop.
djb2 hash implementation in portable shell
set -euf
IFS=''
LC_ALL=C
! command -v emulate >/dev/null 2>&1 || emulate ksh >/dev/null 2>&1
command -v local >/dev/null 2>&1 || alias local=typeset
_ordchr_='\015\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037\040\041\042\043\044\045\046\047\050\051\052\053\054\055\056\057\060\061\062\063\064\065\066\067\070\071\072\073\074\075\076\077\100\101\102\103\104\105\106\107\110\111\112\113\114\115\116\117\120\121\122\123\124\125\126\127\130\131\132\133\134\135\136\137\140\141\142\143\144\145\146\147\150\151\152\153\154\155\156\157\160\161\162\163\164\165\166\167\170\171\172\173\174\175\176\177\'
_ordchr_="$(printf "$_ordchr_")"
_subs () {
local str="$1" i=0 from=$(($2)) to=$(($3 + $2)) sub=
while test $i -lt $to
do
rest="${str#?}"
char="${str%"$rest"}"
str="${rest}"
test $from -gt $i || sub="$sub$char"
i=$((i + 1))
done
_r="$sub"
}
_ord () {
_r="${_ordchr_%$1*}"
_r=${#_r}
}
_chr () {
_subs "$_ordchr_" $1 1
}
_djb2_hash () {
local num="$1" hash=5381
while test ${#num} -gt 0
do
rest="${num#?}"
char="${num%"$rest"}"
num="${rest}"
_ord "$num"
hash=$(((hash + (hash << 5)) ^ _r))
done
echo $hash
}
_djb2_hash "the quick brown fox"
_djb2_hash "the quick brown fox2"
_djb2_hash 'b'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment