1
0
mirror of https://github.com/6543/go-hexcolor synced 2024-12-18 15:54:17 +00:00

no regex - it's faster

This commit is contained in:
6543 2020-09-10 22:18:29 +02:00
parent d25019851f
commit c32969ffb1
Signed by: 6543
GPG Key ID: A1CA74D27FD13271

View File

@ -3,7 +3,6 @@ package go_hexcolor
import ( import (
"fmt" "fmt"
"image/color" "image/color"
"regexp"
"strconv" "strconv"
"strings" "strings"
) )
@ -14,35 +13,20 @@ type HexColor struct {
hex string hex string
} }


// The compiled regular expression used to test the validity of a color statement
var (
hexDefault *regexp.Regexp
hexShort *regexp.Regexp
)

// The raw regular expression string used for testing the validity
const (
hexDefaultRaw string = `[0-9a-f]{6}`
hexShortRaw string = `[0-9a-f]{3}`
)

func init() {
hexDefault = regexp.MustCompile("^" + hexDefaultRaw + "$")
hexShort = regexp.MustCompile("^" + hexShortRaw + "$")
}

// NewHexColor convert string into a HexColor // NewHexColor convert string into a HexColor
func NewHexColor(hc string) (*HexColor, error) { func NewHexColor(hc string) (*HexColor, error) {
c := &HexColor{original: hc} c := &HexColor{original: hc}
hc = strings.TrimLeft(strings.ToLower(hc), "#") hc = strings.TrimLeft(strings.ToLower(hc), "#")


if hexDefault.MatchString(hc) { if _, err := strconv.ParseUint(hc, 16, 24); err == nil {
c.hex = hc if len(hc) == 6 {
return c, nil c.hex = hc
} return c, nil
if hexShort.MatchString(hc) { }
c.hex = hc[:1] + hc[:1] + hc[1:][:1] + hc[1:][:1] + hc[2:] + hc[2:] if len(hc) == 3 {
return c, nil c.hex = hc[:1] + hc[:1] + hc[1:][:1] + hc[1:][:1] + hc[2:] + hc[2:]
return c, nil
}
} }


// handle named colors // handle named colors
@ -63,22 +47,14 @@ func (c *HexColor) ToRGBA() (*color.RGBA, error) {
if c == nil { if c == nil {
return nil, nil return nil, nil
} }
rr, err := strconv.ParseUint(c.hex[:2], 16, 8) var r, g, b uint8
if err != nil { if _, err := fmt.Sscanf(c.hex, "%2x%2x%2x", &r, &g, &b); err != nil {
return nil, err
}
gg, err := strconv.ParseUint(c.hex[2:][:2], 16, 8)
if err != nil {
return nil, err
}
bb, err := strconv.ParseUint(c.hex[4:], 16, 8)
if err != nil {
return nil, err return nil, err
} }
return &color.RGBA{ return &color.RGBA{
R: uint8(rr), R: r,
G: uint8(gg), G: g,
B: uint8(bb), B: b,
A: 0xff, A: 0xff,
}, nil }, nil
} }