Skip to content

Commit

Permalink
fmtsort: sort interfaces deterministically
Browse files Browse the repository at this point in the history
Previously, the result of sorting a map[interface{}] containing
multiple concrete types was non-deterministic. To ensure consistent
results, sort first by type name, then by concrete value.

Fixes golang#30398
  • Loading branch information
lukechampine committed Feb 26, 2019
1 parent b5a68a9 commit f0f560b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/internal/fmtsort/sort.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,9 @@ func compare(aVal, bVal reflect.Value) int {
if c, ok := nilCompare(aVal, bVal); ok {
return c
}
c := compare(reflect.ValueOf(aType), reflect.ValueOf(bType))
aTypeName := aVal.Elem().Type().String()
bTypeName := bVal.Elem().Type().String()
c := compare(reflect.ValueOf(aTypeName), reflect.ValueOf(bTypeName))
if c != 0 {
return c
}
Expand Down
24 changes: 24 additions & 0 deletions src/internal/fmtsort/sort_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,30 @@ var sortTests = []sortTest{
map[interface{}]string{7: "7", 4: "4", 3: "3", nil: "nil"},
"<nil>:nil 3:3 4:4 7:7",
},
{
map[interface{}]string{
(*int)(nil): "nil",
[2]int{1, 0}: "[2]int",
[2]int{0, 1}: "[2]int",
true: "bool",
false: "bool",
2 + 1i: "complex128",
1 + 2i: "complex128",
3.1: "float64",
2.1: "float64",
1.1: "float64",
math.NaN(): "float64",
3: "int",
2: "int",
1: "int",
"c": "string",
"b": "string",
"a": "string",
struct{ x, y int }{1, 0}: "struct{ x int; y int }",
struct{ x, y int }{0, 1}: "struct{ x int; y int }",
},
"<nil>:nil [0 1]:[2]int [1 0]:[2]int false:bool true:bool (1+2i):complex128 (2+1i):complex128 NaN:float64 1.1:float64 2.1:float64 3.1:float64 1:int 2:int 3:int a:string b:string c:string {0 1}:struct{ x int; y int } {1 0}:struct{ x int; y int }",
},
}

func sprint(data interface{}) string {
Expand Down

0 comments on commit f0f560b

Please sign in to comment.