from .charts_color_types import Rgb
_HEX = "0123456789abcdef"
def _nibble(ch: str, hex: str) -> int:
n = _HEX.find(ch.lower())
if n < 0:
raise ValueError('"%s" is not a hex colour (#rgb or #rrggbb)' % (hex,))
return n
def parse_hex(hex: str) -> Rgb: # noqa: A002 - the manifest names it hex
""""#rrggbb" or the short "#rgb" (digits doubled, as CSS does), either case."""
if not isinstance(hex, str) or not hex.startswith("#") or len(hex) not in (4, 7):
raise ValueError('"%s" is not a hex colour (#rgb or #rrggbb)' % (hex,))
if len(hex) == 4:
return Rgb(r=_nibble(hex[1], hex) * 17, g=_nibble(hex[2], hex) * 17, b=_nibble(hex[3], hex) * 17)
return Rgb(
r=_nibble(hex[1], hex) * 16 + _nibble(hex[2], hex),
g=_nibble(hex[3], hex) * 16 + _nibble(hex[4], hex),
b=_nibble(hex[5], hex) * 16 + _nibble(hex[6], hex),
)