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