util.go

  1package ansi
  2
  3import (
  4	"fmt"
  5	"image/color"
  6	"strconv"
  7	"strings"
  8
  9	"github.com/lucasb-eyer/go-colorful"
 10)
 11
 12// colorToHexString returns a hex string representation of a color.
 13func colorToHexString(c color.Color) string { //nolint:unused
 14	if c == nil {
 15		return ""
 16	}
 17	shift := func(v uint32) uint32 {
 18		if v > 0xff {
 19			return v >> 8
 20		}
 21		return v
 22	}
 23	r, g, b, _ := c.RGBA()
 24	r, g, b = shift(r), shift(g), shift(b)
 25	return fmt.Sprintf("#%02x%02x%02x", r, g, b)
 26}
 27
 28// rgbToHex converts red, green, and blue values to a hexadecimal value.
 29//
 30//	hex := rgbToHex(0, 0, 255) // 0x0000FF
 31func rgbToHex(r, g, b uint32) uint32 { //nolint:unused
 32	return r<<16 + g<<8 + b
 33}
 34
 35type shiftable interface {
 36	~uint | ~uint16 | ~uint32 | ~uint64
 37}
 38
 39func shift[T shiftable](x T) T {
 40	if x > 0xff {
 41		x >>= 8
 42	}
 43	return x
 44}
 45
 46// XParseColor is a helper function that parses a string into a color.Color. It
 47// provides a similar interface to the XParseColor function in Xlib. It
 48// supports the following formats:
 49//
 50//   - #RGB
 51//   - #RRGGBB
 52//   - rgb:RRRR/GGGG/BBBB
 53//   - rgba:RRRR/GGGG/BBBB/AAAA
 54//
 55// If the string is not a valid color, nil is returned.
 56//
 57// See: https://linux.die.net/man/3/xparsecolor
 58func XParseColor(s string) color.Color {
 59	switch {
 60	case strings.HasPrefix(s, "#"):
 61		c, err := colorful.Hex(s)
 62		if err != nil {
 63			return nil
 64		}
 65
 66		return c
 67	case strings.HasPrefix(s, "rgb:"):
 68		parts := strings.Split(s[4:], "/")
 69		if len(parts) != 3 {
 70			return nil
 71		}
 72
 73		r, _ := strconv.ParseUint(parts[0], 16, 32)
 74		g, _ := strconv.ParseUint(parts[1], 16, 32)
 75		b, _ := strconv.ParseUint(parts[2], 16, 32)
 76
 77		return color.RGBA{uint8(shift(r)), uint8(shift(g)), uint8(shift(b)), 255} //nolint:gosec
 78	case strings.HasPrefix(s, "rgba:"):
 79		parts := strings.Split(s[5:], "/")
 80		if len(parts) != 4 {
 81			return nil
 82		}
 83
 84		r, _ := strconv.ParseUint(parts[0], 16, 32)
 85		g, _ := strconv.ParseUint(parts[1], 16, 32)
 86		b, _ := strconv.ParseUint(parts[2], 16, 32)
 87		a, _ := strconv.ParseUint(parts[3], 16, 32)
 88
 89		return color.RGBA{uint8(shift(r)), uint8(shift(g)), uint8(shift(b)), uint8(shift(a))} //nolint:gosec
 90	}
 91	return nil
 92}
 93
 94type ordered interface {
 95	~int | ~int8 | ~int16 | ~int32 | ~int64 |
 96		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
 97		~float32 | ~float64 |
 98		~string
 99}
100
101func max[T ordered](a, b T) T { //nolint:predeclared
102	if a > b {
103		return a
104	}
105	return b
106}