color.go 798 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package color
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "regexp"
  6. )
  7. var hexColorRegex = regexp.MustCompile("^([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
  8. const (
  9. hexColorLongFormat = "%02x%02x%02x"
  10. hexColorShortFormat = "%1x%1x%1x"
  11. )
  12. type RGB struct{ R, G, B uint8 }
  13. func RGBFromHex(hexcolor string) (RGB, error) {
  14. c := RGB{}
  15. if !hexColorRegex.MatchString(hexcolor) {
  16. return c, newColorError("Invalid hex color: %s", hexcolor)
  17. }
  18. if len(hexcolor) == 3 {
  19. fmt.Sscanf(hexcolor, hexColorShortFormat, &c.R, &c.G, &c.B)
  20. c.R *= 17
  21. c.G *= 17
  22. c.B *= 17
  23. } else {
  24. fmt.Sscanf(hexcolor, hexColorLongFormat, &c.R, &c.G, &c.B)
  25. }
  26. return c, nil
  27. }
  28. func (c RGB) String() string {
  29. return fmt.Sprintf("#%02x%02x%02x", c.R, c.G, c.B)
  30. }
  31. func (c RGB) LogValue() slog.Value {
  32. return slog.StringValue(c.String())
  33. }