color-hash.ksh: provide a fnv1a implementation and switch to it

This commit is contained in:
Lucas 2023-02-11 18:42:20 +00:00
parent f7077ac5c5
commit 9f004d4faf
1 changed files with 25 additions and 3 deletions

View File

@ -11,14 +11,36 @@ function _color_hash_djb2
print $h
}
function _color_hash_fnv1a
{
local c h s
s=$1
h=${2:-2166136261}
while (( ${#s} > 0 )); do
c=0x${s%${s#??}}
s=${s#??}
h=$(( $h ^ $c ))
h=$(( (($h << 24) + ($h << 8) +
($h << 7) + ($h << 4) + ($h << 1) + $h) & 0xffffffff ))
done
# xor-fold to 16 bits
print $(( ($h >> 16) ^ ($h & 0xffff) ))
}
function color_hash
{
local bright flag h n s
local bright impl flag h n s
bright=false
while getopts b flag; do
impl=_color_hash_fnv1a
while getopts bi: flag; do
case $flag in
b) bright=true ;;
i) if [[ $OPTARG != @(djb2|fnv1a) ]]; then
return 1
fi
impl=_color_hash_$OPTARG
;;
*) return 1 ;;
esac
done
@ -27,7 +49,7 @@ function color_hash
h=
s=$(print -nr "$1" | od -A n -t x1 | tr -d '[:space:]*')
while :; do
h=$(_color_hash_djb2 "$s" $h)
h=$($impl "$s" $h)
# Avoid modulo bias.
(( $h >= 4 )) && break
done