You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
package models
import ( "fmt" "regexp" "strconv" )
type ColorValue struct { Hue int `json:"h,omitempty"` Saturation int `json:"s,omitempty"` Kelvin int `json:"kelvin,omitempty"` }
func (c *ColorValue) IsHueSat() bool { return !c.IsKelvin() }
func (c *ColorValue) IsKelvin() bool { return c.Kelvin > 0 }
func (c *ColorValue) String() string { if c.Kelvin > 0 { return fmt.Sprintf("kelvin:%d", c.Kelvin) }
return fmt.Sprintf("hsv:%d,%d", c.Hue, c.Saturation) }
var kelvinRegex = regexp.MustCompile("kelvin:([0-9]+)") var hsRegex = regexp.MustCompile("hs:([0-9]+),([0-9]+)")
func ParseColorValue(raw string) (ColorValue, error) { if kelvinRegex.MatchString(raw) { part := kelvinRegex.FindString(raw) parsedPart, err := strconv.Atoi(part) if err != nil { return ColorValue{}, ErrBadInput }
return ColorValue{Kelvin: parsedPart}, nil }
if hsRegex.MatchString(raw) { parts := kelvinRegex.FindAllString(raw, 2) if len(parts) < 2 { return ColorValue{}, ErrUnknownColorFormat }
part1, err1 := strconv.Atoi(parts[0]) part2, err2 := strconv.Atoi(parts[1]) if err1 != nil || err2 != nil { return ColorValue{}, ErrBadInput }
return ColorValue{Hue: part1, Saturation: part2}, nil }
return ColorValue{}, ErrUnknownColorFormat }
|