46 lines
747 B
Bash
46 lines
747 B
Bash
|
function _color_hash_djb2
|
||
|
{
|
||
|
local c h s
|
||
|
s=$1
|
||
|
h=${2:-5381}
|
||
|
while (( ${#s} > 0 )); do
|
||
|
c=0x${s%${s#??}}
|
||
|
s=${s#??}
|
||
|
h=$(( ((($h << 5) + $h) + $c) & 0xffff ))
|
||
|
done
|
||
|
print $h
|
||
|
}
|
||
|
|
||
|
function color_hash
|
||
|
{
|
||
|
local bright flag h n s
|
||
|
|
||
|
bright=false
|
||
|
while getopts b flag; do
|
||
|
case $flag in
|
||
|
b) bright=true ;;
|
||
|
*) return 1 ;;
|
||
|
esac
|
||
|
done
|
||
|
shift $(($OPTIND - 1))
|
||
|
|
||
|
h=
|
||
|
s=$(print -nr "$1" | od -A n -t x1 | tr -d '[:space:]*')
|
||
|
while :; do
|
||
|
h=$(_color_hash_djb2 "$s" $h)
|
||
|
# Avoid modulo bias.
|
||
|
(( $h >= 4 )) && break
|
||
|
done
|
||
|
h=$(( $h % 12 ))
|
||
|
|
||
|
if $bright; then
|
||
|
# $h < 6 ? 8 + 1 + $h : 8 + 1 + $h - 6
|
||
|
n=$(( $h + ($h < 6 ? 9 : 3) ))
|
||
|
else
|
||
|
# $h < 6 ? 1 + $h : 8 + 1 + $h - 6
|
||
|
n=$(( $h + ($h < 6 ? 1 : 3) ))
|
||
|
fi
|
||
|
|
||
|
tput setaf $n 0 0 2>/dev/null
|
||
|
}
|