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.

61 lines
1.3 KiB

4 years ago
  1. package models
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strconv"
  6. )
  7. type ColorValue struct {
  8. Hue int `json:"h,omitempty"`
  9. Saturation int `json:"s,omitempty"`
  10. Kelvin int `json:"kelvin,omitempty"`
  11. }
  12. func (c *ColorValue) IsHueSat() bool {
  13. return !c.IsKelvin()
  14. }
  15. func (c *ColorValue) IsKelvin() bool {
  16. return c.Kelvin > 0
  17. }
  18. func (c *ColorValue) String() string {
  19. if c.Kelvin > 0 {
  20. return fmt.Sprintf("kelvin:%d", c.Kelvin)
  21. }
  22. return fmt.Sprintf("hsv:%d,%d", c.Hue, c.Saturation)
  23. }
  24. var kelvinRegex = regexp.MustCompile("kelvin:([0-9]+)")
  25. var hsRegex = regexp.MustCompile("hs:([0-9]+),([0-9]+)")
  26. func ParseColorValue(raw string) (ColorValue, error) {
  27. if kelvinRegex.MatchString(raw) {
  28. part := kelvinRegex.FindString(raw)
  29. parsedPart, err := strconv.Atoi(part)
  30. if err != nil {
  31. return ColorValue{}, ErrBadInput
  32. }
  33. return ColorValue{Kelvin: parsedPart}, nil
  34. }
  35. if hsRegex.MatchString(raw) {
  36. parts := kelvinRegex.FindAllString(raw, 2)
  37. if len(parts) < 2 {
  38. return ColorValue{}, ErrUnknownColorFormat
  39. }
  40. part1, err1 := strconv.Atoi(parts[0])
  41. part2, err2 := strconv.Atoi(parts[1])
  42. if err1 != nil || err2 != nil {
  43. return ColorValue{}, ErrBadInput
  44. }
  45. return ColorValue{Hue: part1, Saturation: part2}, nil
  46. }
  47. return ColorValue{}, ErrUnknownColorFormat
  48. }