Skip to content

Commit

Permalink
new method Name()
Browse files Browse the repository at this point in the history
  • Loading branch information
mazznoer committed Jul 29, 2022
1 parent 0b6f745 commit 2c4150a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
12 changes: 12 additions & 0 deletions colorparser.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@ func (c Color) RGBString() string {
return fmt.Sprintf("rgb(%d,%d,%d)", r, g, b)
}

// Name returns name of this color if its available.
func (c Color) Name() (string, bool) {
r, g, b, _ := c.RGBA255()
rgb := [3]uint8{r, g, b}
for k, v := range namedColors {
if v == rgb {
return k, true
}
}
return "", false
}

// Implement the Go TextUnmarshaler interface
func (c *Color) UnmarshalText(text []byte) error {
col, err := Parse(string(text))
Expand Down
20 changes: 20 additions & 0 deletions colorparser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package csscolorparser

import (
"image/color"
"strings"
"testing"
)

Expand Down Expand Up @@ -70,6 +71,25 @@ func TestParseColor(t *testing.T) {
}

func TestNamedColors(t *testing.T) {
for name, rgb := range namedColors {
c, _ := Parse(name)
r, g, b, _ := c.RGBA255()
rgb_ := [3]uint8{r, g, b}
if rgb_ != rgb {
t.Errorf("%s != %s", rgb_, rgb)
}
if name == "aqua" || name == "cyan" || name == "fuchsia" || name == "magenta" {
continue
}
if strings.Contains(name, "gray") || strings.Contains(name, "grey") {
continue
}
name_, _ := c.Name()
if name_ != name {
t.Errorf("%s != %s", name_, name)
}
}

data := [][2]string{
{"aliceblue", "#f0f8ff"},
{"bisque", "#ffe4c4"},
Expand Down

0 comments on commit 2c4150a

Please sign in to comment.