color-hash.ksh: small improvements

Don't set color and return the index instead. This allows also using it
for background. Sprinkle a couple of '-nr --' for 'print' calls. Add the
fnv1 variant.
This commit is contained in:
Lucas 2023-10-24 19:51:20 +00:00
parent 0d7fd8f76a
commit 19049d2472
3 changed files with 69 additions and 37 deletions

View file

@ -6,9 +6,25 @@ function _color_hash_djb2
while (( ${#s} > 0 )); do
c=0x${s%${s#??}}
s=${s#??}
h=$(( ((($h << 5) + $h) + $c) & 0xffff ))
h=$(( ((($h << 5) + $h) ^ $c) & 0xffff ))
done
print $h
print -nr -- $h
}
function _color_hash_fnv1
{
local c h s
s=$1
h=${2:-2166136261}
while (( ${#s} > 0 )); do
c=0x${s%${s#??}}
s=${s#??}
h=$(( (($h << 24) + ($h << 8) +
($h << 7) + ($h << 4) + ($h << 1) + $h) & 0xffffffff ))
h=$(( $h ^ $c ))
done
# xor-fold to 16 bits
print -nr -- $(( ($h >> 16) ^ ($h & 0xffff) ))
}
function _color_hash_fnv1a
@ -24,7 +40,7 @@ function _color_hash_fnv1a
($h << 7) + ($h << 4) + ($h << 1) + $h) & 0xffffffff ))
done
# xor-fold to 16 bits
print $(( ($h >> 16) ^ ($h & 0xffff) ))
print -nr -- $(( ($h >> 16) ^ ($h & 0xffff) ))
}
function color_hash
@ -36,7 +52,7 @@ function color_hash
while getopts bi: flag; do
case $flag in
b) bright=true ;;
i) if [[ $OPTARG != @(djb2|fnv1a) ]]; then
i) if [[ $OPTARG != @(djb2|fnv1|fnv1a) ]]; then
return 1
fi
impl=_color_hash_$OPTARG
@ -47,7 +63,7 @@ function color_hash
shift $(($OPTIND - 1))
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
h=$($impl "$s" $h)
# Avoid modulo bias.
@ -63,5 +79,5 @@ function color_hash
n=$(( $h + ($h < 6 ? 1 : 3) ))
fi
tput setaf $n 0 0 2>/dev/null
print -nr -- "$n"
}