Skip to content

Commit

Permalink
Add GetColorByName()/GetColorNames() for preset colors, adjust errors…
Browse files Browse the repository at this point in the history
… for Open*
  • Loading branch information
hyorigo committed Oct 17, 2023
1 parent 6c28ea1 commit b7a9ddd
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
3 changes: 2 additions & 1 deletion find.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package blink1

import (
"fmt"
"sort"
"sync"

Expand Down Expand Up @@ -28,7 +29,7 @@ func FindDeviceInfoBySerialNumber(sn string) (*hid.DeviceInfo, error) {
})
// not found
if dev == nil {
return nil, errDeviceNotFound
return nil, fmt.Errorf("%w for %q", errDeviceNotFound, sn)
}
return dev, nil
}
Expand Down
27 changes: 27 additions & 0 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"image/color"
"regexp"
"sort"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -55,6 +56,9 @@ var (
fadeMsecRegexPats = make(map[int]*regexp.Regexp)
ledIdxRegexPats = make(map[int]*regexp.Regexp)

nameOnce sync.Once
colorNames []string

errNoRepeatMatch = errors.New("b1: no repeat times match")
errNoColorMatch = errors.New("b1: no color match")
errNoFadeMatch = errors.New("b1: no fade time match")
Expand Down Expand Up @@ -93,6 +97,29 @@ func initRegex() {
ledIdxRegexPats[12] = regexp.MustCompile(`\b(led|light)[:#=\s]*([012]|top|bottom|btm|all|both|zero|one|two)\b`)
}

func initNames() {
colorNames = make([]string, 0, len(colorMap))
for k := range colorMap {
colorNames = append(colorNames, k)
}
sort.Strings(colorNames)
}

// GetColorByName returns the color corresponding to the given name from the preset color map.
// If the color is found, it returns the color and true, otherwise it returns nil and false.
func GetColorByName(name string) (cl color.Color, found bool) {
cl, found = colorMap[name]
return
}

// GetColorNames returns the color names from the preset color map.
func GetColorNames() []string {
nameOnce.Do(initNames)
cls := make([]string, len(colorNames))
copy(cls, colorNames)
return cls
}

// ParseRepeatTimes parses the case-insensitive unstructured description of repeat times and returns the number of times to repeat.
func ParseRepeatTimes(query string) (uint, error) {
// init regex
Expand Down

0 comments on commit b7a9ddd

Please sign in to comment.