-
Notifications
You must be signed in to change notification settings - Fork 0
[FEAT] Parse Generic #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+421
−0
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,16 @@ | ||
| package enumify | ||
|
|
||
| import ( | ||
| "database/sql" | ||
| "database/sql/driver" | ||
| "encoding/json" | ||
| "fmt" | ||
| ) | ||
|
|
||
| type Enum interface { | ||
| fmt.Stringer | ||
| json.Marshaler | ||
| json.Unmarshaler | ||
| sql.Scanner | ||
| driver.Valuer | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| package enumify_test | ||
|
|
||
| //============================================================================ | ||
| // Test Enum Type | ||
| //============================================================================ | ||
|
|
||
| type Status uint8 | ||
|
|
||
| const ( | ||
| StatusUnknown Status = iota | ||
| StatusDraft | ||
| StatusReview | ||
| StatusPublished | ||
| StatusArchived | ||
| ) | ||
|
|
||
| var StatusNames = []string{ | ||
| "unknown", | ||
| "draft", | ||
| "review", | ||
| "published", | ||
| "archived", | ||
| } | ||
|
|
||
| var StatusNames2D = [][]string{ | ||
| {"unknown", "draft", "review", "published", "archived"}, | ||
| {"Unknown", "Draft", "Needs Review", "Published", "Archived"}, | ||
| {"Unbekannt", "Entwurf", "Überprüfung", "Veröffentlicht", "Archiviert"}, | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,11 @@ | ||
| module go.rtnl.ai/enumify | ||
|
|
||
| go 1.26.1 | ||
|
|
||
| require github.com/stretchr/testify v1.11.1 | ||
|
|
||
| require ( | ||
| github.com/davecgh/go-spew v1.1.1 // indirect | ||
| github.com/pmezard/go-difflib v1.0.0 // indirect | ||
| gopkg.in/yaml.v3 v3.0.1 // indirect | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= | ||
| github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||
| github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= | ||
| github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | ||
| github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= | ||
| github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= | ||
| gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= | ||
| gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= | ||
| gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= | ||
| gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| package enumify | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "strings" | ||
| ) | ||
|
|
||
| // Generic parser function that can be used to parse a specific enum type. | ||
| type Parser[T ~uint8] func(any) (T, error) | ||
|
|
||
| // ParseFactory creates a parser function for a specific enum type. The parser can parse | ||
| // the enum from a string or a numeric type that can be converted into a uint8. In order | ||
| // to support string parsing, a names array is required. It can either be a single | ||
| // array where the index of the name is the value of the enum, or a 2D array where the | ||
| // first column contains the names indexed according to the enum value. | ||
| // | ||
| // NOTE: string parsing is case-insensitive and leading and trailing whitespace is | ||
| // ignored. Names should be slug values to ensure consistent parsing. | ||
| func ParseFactory[T ~uint8, Names []string | [][]string](names Names) Parser[T] { | ||
| var normalizedNames []string | ||
| switch col := any(names).(type) { | ||
| case []string: | ||
| if len(col) < 1 { | ||
| panic(fmt.Errorf("names array must contain at least one name")) | ||
| } | ||
|
|
||
| normalizedNames = make([]string, len(col)) | ||
| for i, name := range col { | ||
| normalizedNames[i] = normalize(name) | ||
| } | ||
| case [][]string: | ||
| if len(col) < 1 { | ||
| panic(fmt.Errorf("names array must contain at least one column")) | ||
| } | ||
|
|
||
| if len(col[0]) < 1 { | ||
| panic(fmt.Errorf("names array must contain at least one name")) | ||
| } | ||
|
|
||
| normalizedNames = make([]string, len(col[0])) | ||
| for i, name := range col[0] { | ||
| normalizedNames[i] = normalize(name) | ||
| } | ||
| } | ||
|
|
||
| // The "unknown" value is the zero-valued T. | ||
| unknown := T(0) | ||
|
|
||
| return func(val any) (T, error) { | ||
| switch v := val.(type) { | ||
| case string: | ||
| v = normalize(v) | ||
|
|
||
| // For an empty string, return the "unknown" or zero-valued T. | ||
| if v == "" { | ||
| return unknown, nil | ||
| } | ||
|
|
||
| // Iterate over the normalized names and return the value of the first match. | ||
| for i, name := range normalizedNames { | ||
| if name == v { | ||
| return T(i), nil | ||
| } | ||
| } | ||
|
|
||
| // If no match is found, return an error. | ||
| return unknown, fmt.Errorf("invalid %T value: %q", unknown, v) | ||
| case T: | ||
| if v >= T(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return v, nil | ||
| case uint: | ||
| if v >= uint(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case uint8: | ||
| if v >= uint8(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case uint16: | ||
| if v >= uint16(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case uint32: | ||
| if v >= uint32(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case uint64: | ||
| if v >= uint64(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case int: | ||
| if v < 0 || v >= len(normalizedNames) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case int8: | ||
| if v < 0 || v >= int8(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case int16: | ||
| if v < 0 || v >= int16(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case int32: | ||
| if v < 0 || v >= int32(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case int64: | ||
| if v < 0 || v >= int64(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %d", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case float32: | ||
| if v < 0 || v >= float32(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %f", unknown, v) | ||
| } | ||
| return T(v), nil | ||
| case float64: | ||
| if v < 0 || v >= float64(len(normalizedNames)) { | ||
| return unknown, fmt.Errorf("invalid %T value: %f", unknown, v) | ||
| } | ||
| return T(v), nil | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Float values silently truncated to enum integersLow Severity Non-integer float values (e.g., |
||
| default: | ||
| return unknown, fmt.Errorf("cannot parse %T into %T", v, unknown) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func normalize(s string) string { | ||
| return strings.ToLower(strings.TrimSpace(s)) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.


There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Integer overflow in
int8bounds checkMedium Severity
The cast
int8(len(normalizedNames))silently overflows when the names slice has 128 or more entries. SinceTis~uint8and can represent up to 256 enum values, this is a reachable scenario. When overflowed (e.g., 130 names →int8(130)= −126), the comparisonv >= -126becomes true for all non-negativeint8values, incorrectly rejecting every valid input.