1
0
mirror of https://github.com/golang/go synced 2024-11-26 03:07:57 -07:00

encoding/json: use slices to simplify the code

Use "slices.Equal" instead of "reflect.DeepEqual".

Replace unnecessary helper type "byIndex" with "slices.SortFunc".

No effect on benchmarks.
This commit is contained in:
apocelipes 2024-04-02 21:19:18 +08:00
parent 3b29222ffd
commit 8429bc1452
2 changed files with 7 additions and 23 deletions

View File

@ -14,6 +14,7 @@ import (
"math/big"
"net"
"reflect"
"slices"
"strconv"
"strings"
"testing"
@ -1998,7 +1999,7 @@ func TestByteKind(t *testing.T) {
if err != nil {
t.Fatalf("Unmarshal error: %v", err)
}
if !reflect.DeepEqual(got, want) {
if !slices.Equal(got, want) {
t.Fatalf("Marshal/Unmarshal mismatch:\n\tgot: %v\n\twant: %v", got, want)
}
}
@ -2017,7 +2018,7 @@ func TestSliceOfCustomByte(t *testing.T) {
if err != nil {
t.Fatalf("Unmarshal error: %v", err)
}
if !reflect.DeepEqual(got, want) {
if !slices.Equal(got, want) {
t.Fatalf("Marshal/Unmarshal mismatch:\n\tgot: %v\n\twant: %v", got, want)
}
}

View File

@ -1042,25 +1042,6 @@ type field struct {
encoder encoderFunc
}
// byIndex sorts field by index sequence.
type byIndex []field
func (x byIndex) Len() int { return len(x) }
func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (x byIndex) Less(i, j int) bool {
for k, xik := range x[i].index {
if k >= len(x[j].index) {
return false
}
if xik != x[j].index[k] {
return xik < x[j].index[k]
}
}
return len(x[i].index) < len(x[j].index)
}
// typeFields returns a list of fields that JSON should recognize for the given type.
// The algorithm is breadth-first search over the set of structs to include - the top struct
// and then any reachable anonymous structs.
@ -1195,7 +1176,7 @@ func typeFields(t reflect.Type) structFields {
if x[i].tag != x[j].tag {
return x[i].tag
}
return byIndex(x).Less(i, j)
return slices.Compare(x[i].index, x[j].index) == -1
})
// Delete all fields that are hidden by the Go rules for embedded fields,
@ -1227,7 +1208,9 @@ func typeFields(t reflect.Type) structFields {
}
fields = out
sort.Sort(byIndex(fields))
slices.SortFunc(fields, func(i, j field) int {
return slices.Compare(i.index, j.index)
})
for i := range fields {
f := &fields[i]