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

View File

@ -11,14 +11,36 @@ function _color_hash_djb2
print $h 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 function color_hash
{ {
local bright flag h n s local bright impl flag h n s
bright=false bright=false
while getopts b flag; do impl=_color_hash_fnv1a
while getopts bi: flag; do
case $flag in case $flag in
b) bright=true ;; b) bright=true ;;
i) if [[ $OPTARG != @(djb2|fnv1a) ]]; then
return 1
fi
impl=_color_hash_$OPTARG
;;
*) return 1 ;; *) return 1 ;;
esac esac
done done
@ -27,7 +49,7 @@ function color_hash
h= h=
s=$(print -nr "$1" | od -A n -t x1 | tr -d '[:space:]*') s=$(print -nr "$1" | od -A n -t x1 | tr -d '[:space:]*')
while :; do while :; do
h=$(_color_hash_djb2 "$s" $h) h=$($impl "$s" $h)
# Avoid modulo bias. # Avoid modulo bias.
(( $h >= 4 )) && break (( $h >= 4 )) && break
done done