1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
package format
import (
"strings"
"github.com/nicholas-fedor/shoutrrr/pkg/types"
)
// EnumInvalid is the constant value that an enum gets assigned when it could not be parsed.
const EnumInvalid = -1
// EnumFormatter is the helper methods for enum-like types.
type EnumFormatter struct {
names []string
firstOffset int
aliases map[string]int
}
// Names is the list of the valid Enum string values.
func (ef EnumFormatter) Names() []string {
return ef.names[ef.firstOffset:]
}
// Print takes a enum mapped int and returns it's string representation or "Invalid".
func (ef EnumFormatter) Print(e int) string {
if e >= len(ef.names) || e < 0 {
return "Invalid"
}
return ef.names[e]
}
// Parse takes an enum mapped string and returns it's int representation or EnumInvalid (-1).
func (ef EnumFormatter) Parse(mappedString string) int {
target := strings.ToLower(mappedString)
for index, name := range ef.names {
if target == strings.ToLower(name) {
return index
}
}
if index, found := ef.aliases[mappedString]; found {
return index
}
return EnumInvalid
}
// CreateEnumFormatter creates a EnumFormatter struct.
func CreateEnumFormatter(names []string, optAliases ...map[string]int) types.EnumFormatter {
aliases := map[string]int{}
if len(optAliases) > 0 {
aliases = optAliases[0]
}
firstOffset := 0
for i, name := range names {
if name != "" {
firstOffset = i
break
}
}
return &EnumFormatter{
names,
firstOffset,
aliases,
}
}
|