Repository navigation
fix: compare enum entries by JSON value #656
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
Open
CaliLuke
wants to merge
1
commit into
pb33f:main
Choose a base branch
from
CaliLuke:codex/enum-value-equality
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+218
−15
Open
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| package utils | ||
|
|
||
| import ( | ||
| "math/big" | ||
| "sort" | ||
| "strconv" | ||
| "strings" | ||
|
|
||
| "github.com/pb33f/go-yaml" | ||
| ) | ||
|
|
||
| type enumValueIndex struct { | ||
| values map[string]int | ||
| nodes map[*yaml.Node]int | ||
| active map[*yaml.Node]bool | ||
| } | ||
|
|
||
| // CheckEnumForDuplicates returns each occurrence after the first of an equal | ||
| // JSON value, preserving input order and node identity. Numbers compare by value, | ||
| // arrays by ordered elements, and objects by members irrespective of key order. | ||
| // YAML aliases are followed; cyclic or non-JSON values are ignored. | ||
| func CheckEnumForDuplicates(seq []*yaml.Node) []*yaml.Node { | ||
| var duplicates []*yaml.Node | ||
| seen := make(map[int]bool) | ||
| index := enumValueIndex{ | ||
| values: make(map[string]int), | ||
| nodes: make(map[*yaml.Node]int), | ||
| active: make(map[*yaml.Node]bool), | ||
| } | ||
| for _, node := range seq { | ||
| id := index.valueID(node) | ||
| if id == 0 { | ||
| continue | ||
| } | ||
| if seen[id] { | ||
| duplicates = append(duplicates, node) | ||
| } | ||
| seen[id] = true | ||
| } | ||
| return duplicates | ||
| } | ||
|
|
||
| // valueID interns each value using its children's IDs, keeping repeated aliases | ||
| // compact. Zero denotes a value outside the JSON data model. | ||
| func (index *enumValueIndex) valueID(node *yaml.Node) int { | ||
| if node == nil || index.active[node] { | ||
| return 0 | ||
| } | ||
| if id, ok := index.nodes[node]; ok { | ||
| return id | ||
| } | ||
| index.active[node] = true | ||
| defer delete(index.active, node) | ||
| var id int | ||
| if node.Kind == yaml.AliasNode { | ||
| id = index.valueID(node.Alias) | ||
| } else if key, ok := index.valueKey(node); ok { | ||
| id = index.values[key] | ||
| if id == 0 { | ||
| id = len(index.values) + 1 | ||
| index.values[key] = id | ||
| } | ||
| } | ||
| index.nodes[node] = id | ||
| return id | ||
| } | ||
|
|
||
| func (index *enumValueIndex) valueKey(node *yaml.Node) (string, bool) { | ||
| switch node.Kind { | ||
| case yaml.ScalarNode: | ||
| switch node.ShortTag() { | ||
| case "!!str": | ||
| return "s" + strconv.Quote(node.Value), true | ||
| case "!!null": | ||
| return "null", true | ||
| case "!!bool": | ||
| var value bool | ||
| if err := node.Decode(&value); err != nil { | ||
| return "", false | ||
| } | ||
| return strconv.FormatBool(value), true | ||
| case "!!int": | ||
| // YAML accepts base-prefixed integers and legacy octal (012 == 10). | ||
| value, ok := new(big.Int).SetString(node.Value, 0) | ||
| if !ok { | ||
| return "", false | ||
| } | ||
| return "n" + value.String(), true | ||
| case "!!float": | ||
| value, ok := new(big.Rat).SetString(node.Value) | ||
| if !ok { | ||
| return "", false | ||
| } | ||
| return "n" + value.RatString(), true | ||
| } | ||
| case yaml.SequenceNode: | ||
| if node.ShortTag() != "!!seq" { | ||
| return "", false | ||
| } | ||
| parts := make([]string, 0, len(node.Content)) | ||
| for _, child := range node.Content { | ||
| id := index.valueID(child) | ||
| if id == 0 { | ||
| return "", false | ||
| } | ||
| parts = append(parts, strconv.Itoa(id)) | ||
| } | ||
| return "[" + strings.Join(parts, ",") + "]", true | ||
| case yaml.MappingNode: | ||
| if node.ShortTag() != "!!map" || len(node.Content)%2 != 0 { | ||
| return "", false | ||
| } | ||
| parts := make([]string, 0, len(node.Content)/2) | ||
| keys := make(map[string]bool) | ||
| for i := 0; i < len(node.Content); i += 2 { | ||
| name := node.Content[i] | ||
| if name == nil || name.Kind != yaml.ScalarNode || name.ShortTag() != "!!str" || keys[name.Value] { | ||
| return "", false | ||
| } | ||
| keys[name.Value] = true | ||
| id := index.valueID(node.Content[i+1]) | ||
| if id == 0 { | ||
| return "", false | ||
| } | ||
| parts = append(parts, strconv.Quote(name.Value)+":"+strconv.Itoa(id)) | ||
| } | ||
| sort.Strings(parts) | ||
| return "{" + strings.Join(parts, ",") + "}", true | ||
| } | ||
| return "", false | ||
| } | ||
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,87 @@ | ||
| package utils | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/pb33f/go-yaml" | ||
| "github.com/pb33f/testify/require" | ||
| ) | ||
|
|
||
| func TestCheckEnumForDuplicates_Values(t *testing.T) { | ||
| for _, tc := range []struct { | ||
| name string | ||
| yaml string | ||
| duplicates []int | ||
| }{ | ||
| {"distinct arrays", `[[a], [b], [a, b], [b, a], []]`, nil}, | ||
| {"duplicate arrays", `[[a], [b], [a], [a]]`, []int{2, 3}}, | ||
| {"distinct objects", `[{a: 1}, {a: 2}, {b: 1}, {}]`, nil}, | ||
| {"object order", `[{a: 1, b: [2, 3]}, {b: [2.0, 3], a: 1.0}]`, []int{1}}, | ||
| {"nested types", `[{a: [1]}, {a: ["1"]}]`, nil}, | ||
| {"scalar types", `[1, "1", true, "true", null, "null", "", [], {}]`, nil}, | ||
| {"octal integers", `[012, 10, 12, -012, -10, 0o12, 10.0]`, []int{1, 4, 5, 6}}, | ||
| {"numbers", `[1, 1.0, 1e0, -0, 0.0, 0, 0.1, 1e-1]`, []int{1, 2, 4, 5, 7}}, | ||
| {"precision", `[9007199254740992, 9007199254740993, 9007199254740993.0]`, []int{2}}, | ||
| {"yaml scalars", `[true, TRUE, null, ~, 0x10, 16]`, []int{1, 3, 5}}, | ||
| {"aliases", `[&a {x: [1]}, *a, {x: [1.0]}]`, []int{1, 2}}, | ||
| {"repeated aliases", `[&a [1], [*a, *a], [[1], [1]]]`, []int{2}}, | ||
| {"delimiters", `[["a,b", c], [a, "b,c"], {"a:b": c}, {a: "b:c"}]`, nil}, | ||
| } { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| var root yaml.Node | ||
| require.NoError(t, yaml.Unmarshal([]byte(tc.yaml), &root)) | ||
| values := root.Content[0].Content | ||
| duplicates := CheckEnumForDuplicates(values) | ||
| require.Len(t, duplicates, len(tc.duplicates)) | ||
| for i, index := range tc.duplicates { | ||
| require.Same(t, values[index], duplicates[i]) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestCheckEnumForDuplicates_NonJSONValues(t *testing.T) { | ||
| for _, source := range []string{ | ||
| `[&a [*a], &b [*b]]`, | ||
| `[{1: a}, {1: a}]`, | ||
| `[{a: 1, a: 2}, {a: 1, a: 2}]`, | ||
| `[.inf, .inf, .nan, .nan]`, | ||
| `[!custom a, !custom a]`, | ||
| `[!custom [], []]`, | ||
| `[!custom {}, {}]`, | ||
| `[{x: !custom a}, {x: !custom a}]`, | ||
| } { | ||
| t.Run(source, func(t *testing.T) { | ||
| var root yaml.Node | ||
| require.NoError(t, yaml.Unmarshal([]byte(source), &root)) | ||
| require.Empty(t, CheckEnumForDuplicates(root.Content[0].Content)) | ||
| }) | ||
| } | ||
| for _, node := range []*yaml.Node{ | ||
| nil, | ||
| {Kind: yaml.AliasNode}, | ||
| {Kind: yaml.MappingNode, Content: []*yaml.Node{nil}}, | ||
| {Kind: yaml.MappingNode, Content: []*yaml.Node{nil, nil}}, | ||
| {Kind: yaml.SequenceNode, Content: []*yaml.Node{nil}}, | ||
| {Kind: yaml.ScalarNode, Tag: "!!bool", Value: "invalid"}, | ||
| {Kind: yaml.ScalarNode, Tag: "!!int", Value: "invalid"}, | ||
| {Kind: yaml.DocumentNode}, | ||
| } { | ||
| require.Empty(t, CheckEnumForDuplicates([]*yaml.Node{node, node})) | ||
| } | ||
| } | ||
|
|
||
| func TestCheckEnumForDuplicates_SharedAliases(t *testing.T) { | ||
| value := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: "1"} | ||
| // The graph is linear in size; expanding its aliases would create 2^128 leaves. | ||
| for range 128 { | ||
| value = &yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{ | ||
| {Kind: yaml.AliasNode, Alias: value}, | ||
| {Kind: yaml.AliasNode, Alias: value}, | ||
| }} | ||
| } | ||
| alias := &yaml.Node{Kind: yaml.AliasNode, Alias: value} | ||
| duplicates := CheckEnumForDuplicates([]*yaml.Node{value, alias}) | ||
| require.Len(t, duplicates, 1) | ||
| require.Same(t, alias, duplicates[0]) | ||
| } |
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
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.
big.Ratexpands the exponent in full.1e999999costs ~50ms and builds a 1MB key per value, and the key stays in the map. vacuum runs this on specs we don't control, so a few thousand of those in an enum pins a CPU and eats GBs.Cap it before parsing. Anything outside float64 range (exponent beyond ±400 or so) can return
"", falseor fall back to the raw text. Same treatment for absurdly long!!intliterals.