diff options
author | Ian Lance Taylor <iant@golang.org> | 2022-02-11 14:53:56 -0800 |
---|---|---|
committer | Ian Lance Taylor <iant@golang.org> | 2022-02-11 15:01:19 -0800 |
commit | 8dc2499aa62f768c6395c9754b8cabc1ce25c494 (patch) | |
tree | 43d7fd2bbfd7ad8c9625a718a5e8718889351994 /libgo/go/encoding | |
parent | 9a56779dbc4e2d9c15be8d31e36f2f59be7331a8 (diff) | |
download | gcc-8dc2499aa62f768c6395c9754b8cabc1ce25c494.tar.gz |
libgo: update to Go1.18beta2
gotools/
* Makefile.am (go_cmd_cgo_files): Add ast_go118.go
(check-go-tool): Copy golang.org/x/tools directories.
* Makefile.in: Regenerate.
Reviewed-on: https://go-review.googlesource.com/c/gofrontend/+/384695
Diffstat (limited to 'libgo/go/encoding')
49 files changed, 638 insertions, 434 deletions
diff --git a/libgo/go/encoding/ascii85/ascii85.go b/libgo/go/encoding/ascii85/ascii85.go index d42eb0ab00a..f1f7af863c3 100644 --- a/libgo/go/encoding/ascii85/ascii85.go +++ b/libgo/go/encoding/ascii85/ascii85.go @@ -142,9 +142,7 @@ func (e *encoder) Write(p []byte) (n int, err error) { } // Trailing fringe. - for i := 0; i < len(p); i++ { - e.buf[i] = p[i] - } + copy(e.buf[:], p) e.nbuf = len(p) n += len(p) return diff --git a/libgo/go/encoding/ascii85/ascii85_test.go b/libgo/go/encoding/ascii85/ascii85_test.go index c6371039426..9e6b34e9972 100644 --- a/libgo/go/encoding/ascii85/ascii85_test.go +++ b/libgo/go/encoding/ascii85/ascii85_test.go @@ -42,7 +42,7 @@ var pairs = []testpair{ }, } -func testEqual(t *testing.T, msg string, args ...interface{}) bool { +func testEqual(t *testing.T, msg string, args ...any) bool { t.Helper() if args[len(args)-2] != args[len(args)-1] { t.Errorf(msg, args...) diff --git a/libgo/go/encoding/asn1/asn1.go b/libgo/go/encoding/asn1/asn1.go index cffc06dc9c8..cad1d7b08f8 100644 --- a/libgo/go/encoding/asn1/asn1.go +++ b/libgo/go/encoding/asn1/asn1.go @@ -695,7 +695,7 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam err = SyntaxError{"data truncated"} return } - var result interface{} + var result any if !t.isCompound && t.class == ClassUniversal { innerBytes := bytes[offset : offset+t.length] switch t.tag { @@ -1086,7 +1086,7 @@ func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) { // // Other ASN.1 types are not supported; if it encounters them, // Unmarshal returns a parse error. -func Unmarshal(b []byte, val interface{}) (rest []byte, err error) { +func Unmarshal(b []byte, val any) (rest []byte, err error) { return UnmarshalWithParams(b, val, "") } @@ -1101,7 +1101,7 @@ func (e *invalidUnmarshalError) Error() string { return "asn1: Unmarshal recipient value is nil" } - if e.Type.Kind() != reflect.Ptr { + if e.Type.Kind() != reflect.Pointer { return "asn1: Unmarshal recipient value is non-pointer " + e.Type.String() } return "asn1: Unmarshal recipient value is nil " + e.Type.String() @@ -1109,9 +1109,9 @@ func (e *invalidUnmarshalError) Error() string { // UnmarshalWithParams allows field parameters to be specified for the // top-level element. The form of the params is the same as the field tags. -func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) { +func UnmarshalWithParams(b []byte, val any, params string) (rest []byte, err error) { v := reflect.ValueOf(val) - if v.Kind() != reflect.Ptr || v.IsNil() { + if v.Kind() != reflect.Pointer || v.IsNil() { return nil, &invalidUnmarshalError{reflect.TypeOf(val)} } offset, err := parseField(v.Elem(), b, 0, parseFieldParameters(params)) diff --git a/libgo/go/encoding/asn1/asn1_test.go b/libgo/go/encoding/asn1/asn1_test.go index 8985538468e..b1e05b96ae3 100644 --- a/libgo/go/encoding/asn1/asn1_test.go +++ b/libgo/go/encoding/asn1/asn1_test.go @@ -479,7 +479,7 @@ type TestSet struct { var unmarshalTestData = []struct { in []byte - out interface{} + out any }{ {[]byte{0x02, 0x01, 0x42}, newInt(0x42)}, {[]byte{0x05, 0x00}, &RawValue{0, 5, false, []byte{}, []byte{0x05, 0x00}}}, @@ -521,7 +521,7 @@ func TestUnmarshal(t *testing.T) { func TestUnmarshalWithNilOrNonPointer(t *testing.T) { tests := []struct { b []byte - v interface{} + v any want string }{ {b: []byte{0x05, 0x00}, v: nil, want: "asn1: Unmarshal recipient value is nil"}, @@ -567,7 +567,7 @@ type RelativeDistinguishedNameSET []AttributeTypeAndValue type AttributeTypeAndValue struct { Type ObjectIdentifier - Value interface{} + Value any } type Validity struct { @@ -998,9 +998,9 @@ func TestUnmarshalInvalidUTF8(t *testing.T) { } func TestMarshalNilValue(t *testing.T) { - nilValueTestData := []interface{}{ + nilValueTestData := []any{ nil, - struct{ V interface{} }{}, + struct{ V any }{}, } for i, test := range nilValueTestData { if _, err := Marshal(test); err == nil { diff --git a/libgo/go/encoding/asn1/common.go b/libgo/go/encoding/asn1/common.go index 1c712e1eff4..40115df8b4b 100644 --- a/libgo/go/encoding/asn1/common.go +++ b/libgo/go/encoding/asn1/common.go @@ -94,14 +94,7 @@ type fieldParameters struct { func parseFieldParameters(str string) (ret fieldParameters) { var part string for len(str) > 0 { - // This loop uses IndexByte and explicit slicing - // instead of strings.Split(str, ",") to reduce allocations. - i := strings.IndexByte(str, ',') - if i < 0 { - part, str = str, "" - } else { - part, str = str[:i], str[i+1:] - } + part, str, _ = strings.Cut(str, ",") switch { case part == "optional": ret.optional = true diff --git a/libgo/go/encoding/asn1/marshal.go b/libgo/go/encoding/asn1/marshal.go index 5b4d786d495..c2433491756 100644 --- a/libgo/go/encoding/asn1/marshal.go +++ b/libgo/go/encoding/asn1/marshal.go @@ -730,13 +730,13 @@ func makeField(v reflect.Value, params fieldParameters) (e encoder, err error) { // utf8: causes strings to be marshaled as ASN.1, UTF8String values // utc: causes time.Time to be marshaled as ASN.1, UTCTime values // generalized: causes time.Time to be marshaled as ASN.1, GeneralizedTime values -func Marshal(val interface{}) ([]byte, error) { +func Marshal(val any) ([]byte, error) { return MarshalWithParams(val, "") } // MarshalWithParams allows field parameters to be specified for the // top-level element. The form of the params is the same as the field tags. -func MarshalWithParams(val interface{}, params string) ([]byte, error) { +func MarshalWithParams(val any, params string) ([]byte, error) { e, err := makeField(reflect.ValueOf(val), parseFieldParameters(params)) if err != nil { return nil, err diff --git a/libgo/go/encoding/asn1/marshal_test.go b/libgo/go/encoding/asn1/marshal_test.go index f0217ba8a5e..d9c3cf48fa2 100644 --- a/libgo/go/encoding/asn1/marshal_test.go +++ b/libgo/go/encoding/asn1/marshal_test.go @@ -97,7 +97,7 @@ type testSET []int var PST = time.FixedZone("PST", -8*60*60) type marshalTest struct { - in interface{} + in any out string // hex encoded } @@ -196,7 +196,7 @@ func TestMarshal(t *testing.T) { } type marshalWithParamsTest struct { - in interface{} + in any params string out string // hex encoded } @@ -222,7 +222,7 @@ func TestMarshalWithParams(t *testing.T) { } type marshalErrTest struct { - in interface{} + in any err string } @@ -276,7 +276,7 @@ func TestMarshalOID(t *testing.T) { func TestIssue11130(t *testing.T) { data := []byte("\x06\x010") // == \x06\x01\x30 == OID = 0 (the figure) - var v interface{} + var v any // v has Zero value here and Elem() would panic _, err := Unmarshal(data, &v) if err != nil { @@ -299,7 +299,7 @@ func TestIssue11130(t *testing.T) { return } - var v1 interface{} + var v1 any _, err = Unmarshal(data1, &v1) if err != nil { t.Errorf("%v", err) @@ -382,7 +382,7 @@ func BenchmarkUnmarshal(b *testing.B) { type testCase struct { in []byte - out interface{} + out any } var testData []testCase for _, test := range unmarshalTestData { diff --git a/libgo/go/encoding/base32/base32.go b/libgo/go/encoding/base32/base32.go index 2f7d3637e5a..3feea9ba473 100644 --- a/libgo/go/encoding/base32/base32.go +++ b/libgo/go/encoding/base32/base32.go @@ -221,9 +221,7 @@ func (e *encoder) Write(p []byte) (n int, err error) { } // Trailing fringe. - for i := 0; i < len(p); i++ { - e.buf[i] = p[i] - } + copy(e.buf[:], p) e.nbuf = len(p) n += len(p) return diff --git a/libgo/go/encoding/base32/base32_test.go b/libgo/go/encoding/base32/base32_test.go index 8fb22b90781..dbd2b613b42 100644 --- a/libgo/go/encoding/base32/base32_test.go +++ b/libgo/go/encoding/base32/base32_test.go @@ -42,7 +42,7 @@ var bigtest = testpair{ "KR3WC4ZAMJZGS3DMNFTSYIDBNZSCA5DIMUQHG3DJORUHSIDUN53GK4Y=", } -func testEqual(t *testing.T, msg string, args ...interface{}) bool { +func testEqual(t *testing.T, msg string, args ...any) bool { t.Helper() if args[len(args)-2] != args[len(args)-1] { t.Errorf(msg, args...) diff --git a/libgo/go/encoding/base64/base64.go b/libgo/go/encoding/base64/base64.go index 0c33f8e5f84..4a3e590649e 100644 --- a/libgo/go/encoding/base64/base64.go +++ b/libgo/go/encoding/base64/base64.go @@ -229,9 +229,7 @@ func (e *encoder) Write(p []byte) (n int, err error) { } // Trailing fringe. - for i := 0; i < len(p); i++ { - e.buf[i] = p[i] - } + copy(e.buf[:], p) e.nbuf = len(p) n += len(p) return diff --git a/libgo/go/encoding/base64/base64_test.go b/libgo/go/encoding/base64/base64_test.go index 51047402bd4..57256a3846a 100644 --- a/libgo/go/encoding/base64/base64_test.go +++ b/libgo/go/encoding/base64/base64_test.go @@ -98,7 +98,7 @@ var bigtest = testpair{ "VHdhcyBicmlsbGlnLCBhbmQgdGhlIHNsaXRoeSB0b3Zlcw==", } -func testEqual(t *testing.T, msg string, args ...interface{}) bool { +func testEqual(t *testing.T, msg string, args ...any) bool { t.Helper() if args[len(args)-2] != args[len(args)-1] { t.Errorf(msg, args...) diff --git a/libgo/go/encoding/binary/binary.go b/libgo/go/encoding/binary/binary.go index a31149979da..ee933461ee1 100644 --- a/libgo/go/encoding/binary/binary.go +++ b/libgo/go/encoding/binary/binary.go @@ -159,7 +159,7 @@ func (bigEndian) GoString() string { return "binary.BigEndian" } // The error is EOF only if no bytes were read. // If an EOF happens after reading some but not all the bytes, // Read returns ErrUnexpectedEOF. -func Read(r io.Reader, order ByteOrder, data interface{}) error { +func Read(r io.Reader, order ByteOrder, data any) error { // Fast path for basic types and slices. if n := intDataSize(data); n != 0 { bs := make([]byte, n) @@ -243,7 +243,7 @@ func Read(r io.Reader, order ByteOrder, data interface{}) error { v := reflect.ValueOf(data) size := -1 switch v.Kind() { - case reflect.Ptr: + case reflect.Pointer: v = v.Elem() size = dataSize(v) case reflect.Slice: @@ -268,7 +268,7 @@ func Read(r io.Reader, order ByteOrder, data interface{}) error { // and read from successive fields of the data. // When writing structs, zero values are written for fields // with blank (_) field names. -func Write(w io.Writer, order ByteOrder, data interface{}) error { +func Write(w io.Writer, order ByteOrder, data any) error { // Fast path for basic types and slices. if n := intDataSize(data); n != 0 { bs := make([]byte, n) @@ -392,7 +392,7 @@ func Write(w io.Writer, order ByteOrder, data interface{}) error { // Size returns how many bytes Write would generate to encode the value v, which // must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. // If v is neither of these, Size returns -1. -func Size(v interface{}) int { +func Size(v any) int { return dataSize(reflect.Indirect(reflect.ValueOf(v))) } @@ -696,7 +696,7 @@ func (e *encoder) skip(v reflect.Value) { // intDataSize returns the size of the data required to represent the data when encoded. // It returns zero if the type cannot be implemented by the fast path in Read or Write. -func intDataSize(data interface{}) int { +func intDataSize(data any) int { switch data := data.(type) { case bool, int8, uint8, *bool, *int8, *uint8: return 1 diff --git a/libgo/go/encoding/binary/binary_test.go b/libgo/go/encoding/binary/binary_test.go index 83af89e8a7c..9e1b5f12db4 100644 --- a/libgo/go/encoding/binary/binary_test.go +++ b/libgo/go/encoding/binary/binary_test.go @@ -113,7 +113,7 @@ var src = []byte{1, 2, 3, 4, 5, 6, 7, 8} var res = []int32{0x01020304, 0x05060708} var putbuf = []byte{0, 0, 0, 0, 0, 0, 0, 0} -func checkResult(t *testing.T, dir string, order ByteOrder, err error, have, want interface{}) { +func checkResult(t *testing.T, dir string, order ByteOrder, err error, have, want any) { if err != nil { t.Errorf("%v %v: %v", dir, order, err) return @@ -123,13 +123,13 @@ func checkResult(t *testing.T, dir string, order ByteOrder, err error, have, wan } } -func testRead(t *testing.T, order ByteOrder, b []byte, s1 interface{}) { +func testRead(t *testing.T, order ByteOrder, b []byte, s1 any) { var s2 Struct err := Read(bytes.NewReader(b), order, &s2) checkResult(t, "Read", order, err, s2, s1) } -func testWrite(t *testing.T, order ByteOrder, b []byte, s1 interface{}) { +func testWrite(t *testing.T, order ByteOrder, b []byte, s1 any) { buf := new(bytes.Buffer) err := Write(buf, order, s1) checkResult(t, "Write", order, err, buf.Bytes(), b) @@ -175,7 +175,7 @@ func TestReadBoolSlice(t *testing.T) { } // Addresses of arrays are easier to manipulate with reflection than are slices. -var intArrays = []interface{}{ +var intArrays = []any{ &[100]int8{}, &[100]int16{}, &[100]int32{}, @@ -304,7 +304,7 @@ func TestSizeStructCache(t *testing.T) { count := func() int { var i int - structSize.Range(func(_, _ interface{}) bool { + structSize.Range(func(_, _ any) bool { i++ return true }) @@ -329,7 +329,7 @@ func TestSizeStructCache(t *testing.T) { } testcases := []struct { - val interface{} + val any want int }{ {new(foo), 1}, @@ -376,7 +376,7 @@ func TestUnexportedRead(t *testing.T) { func TestReadErrorMsg(t *testing.T) { var buf bytes.Buffer - read := func(data interface{}) { + read := func(data any) { err := Read(&buf, LittleEndian, data) want := "binary.Read: invalid type " + reflect.TypeOf(data).String() if err == nil { @@ -457,7 +457,7 @@ func TestReadInvalidDestination(t *testing.T) { } func testReadInvalidDestination(t *testing.T, order ByteOrder) { - destinations := []interface{}{ + destinations := []any{ int8(0), int16(0), int32(0), diff --git a/libgo/go/encoding/csv/fuzz.go b/libgo/go/encoding/csv/fuzz.go index a03fa83d8ce..5f5cdfcbf81 100644 --- a/libgo/go/encoding/csv/fuzz.go +++ b/libgo/go/encoding/csv/fuzz.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gofuzz -// +build gofuzz package csv diff --git a/libgo/go/encoding/gob/codec_test.go b/libgo/go/encoding/gob/codec_test.go index f38e88b638a..1ca9d878eec 100644 --- a/libgo/go/encoding/gob/codec_test.go +++ b/libgo/go/encoding/gob/codec_test.go @@ -1178,13 +1178,13 @@ func TestInterface(t *testing.T) { // A struct with all basic types, stored in interfaces. type BasicInterfaceItem struct { - Int, Int8, Int16, Int32, Int64 interface{} - Uint, Uint8, Uint16, Uint32, Uint64 interface{} - Float32, Float64 interface{} - Complex64, Complex128 interface{} - Bool interface{} - String interface{} - Bytes interface{} + Int, Int8, Int16, Int32, Int64 any + Uint, Uint8, Uint16, Uint32, Uint64 any + Float32, Float64 any + Complex64, Complex128 any + Bool any + String any + Bytes any } func TestInterfaceBasic(t *testing.T) { @@ -1223,8 +1223,8 @@ func TestInterfaceBasic(t *testing.T) { type String string type PtrInterfaceItem struct { - Str1 interface{} // basic - Str2 interface{} // derived + Str1 any // basic + Str2 any // derived } // We'll send pointers; should receive values. @@ -1318,7 +1318,7 @@ func TestUnexportedFields(t *testing.T) { } } -var singletons = []interface{}{ +var singletons = []any{ true, 7, uint(10), @@ -1354,9 +1354,9 @@ type DT struct { A int B string C float64 - I interface{} - J interface{} - I_nil interface{} + I any + J any + I_nil any M map[string]int T [3]int S []string @@ -1396,7 +1396,7 @@ func TestDebugStruct(t *testing.T) { debugFunc(debugBuffer) } -func encFuzzDec(rng *rand.Rand, in interface{}) error { +func encFuzzDec(rng *rand.Rand, in any) error { buf := new(bytes.Buffer) enc := NewEncoder(buf) if err := enc.Encode(&in); err != nil { @@ -1411,7 +1411,7 @@ func encFuzzDec(rng *rand.Rand, in interface{}) error { } dec := NewDecoder(buf) - var e interface{} + var e any if err := dec.Decode(&e); err != nil { return err } @@ -1425,7 +1425,7 @@ func TestFuzz(t *testing.T) { } // all possible inputs - input := []interface{}{ + input := []any{ new(int), new(float32), new(float64), @@ -1450,7 +1450,7 @@ func TestFuzzRegressions(t *testing.T) { testFuzz(t, 1330522872628565000, 100, new(int)) } -func testFuzz(t *testing.T, seed int64, n int, input ...interface{}) { +func testFuzz(t *testing.T, seed int64, n int, input ...any) { for _, e := range input { t.Logf("seed=%d n=%d e=%T", seed, n, e) rng := rand.New(rand.NewSource(seed)) diff --git a/libgo/go/encoding/gob/debug.go b/libgo/go/encoding/gob/debug.go index 5965fea921f..b6d5a3e95c4 100644 --- a/libgo/go/encoding/gob/debug.go +++ b/libgo/go/encoding/gob/debug.go @@ -4,7 +4,6 @@ // Delete the next line to include in the gob package. //go:build ignore -// +build ignore package gob @@ -119,7 +118,7 @@ type debugger struct { // dump prints the next nBytes of the input. // It arranges to print the output aligned from call to // call, to make it easy to see what has been consumed. -func (deb *debugger) dump(format string, args ...interface{}) { +func (deb *debugger) dump(format string, args ...any) { if !dumpBytes { return } diff --git a/libgo/go/encoding/gob/decgen.go b/libgo/go/encoding/gob/decgen.go index 994be877d93..e40816eb869 100644 --- a/libgo/go/encoding/gob/decgen.go +++ b/libgo/go/encoding/gob/decgen.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build ignore -// +build ignore // encgen writes the helper functions for encoding. Intended to be // used with go generate; see the invocation in encode.go. diff --git a/libgo/go/encoding/gob/decode.go b/libgo/go/encoding/gob/decode.go index d2f6c749b1b..34f302a5cf5 100644 --- a/libgo/go/encoding/gob/decode.go +++ b/libgo/go/encoding/gob/decode.go @@ -228,7 +228,7 @@ func ignoreTwoUints(i *decInstr, state *decoderState, v reflect.Value) { // The callers to the individual decoders are expected to have used decAlloc. // The individual decoders don't need to it. func decAlloc(v reflect.Value) reflect.Value { - for v.Kind() == reflect.Ptr { + for v.Kind() == reflect.Pointer { if v.IsNil() { v.Set(reflect.New(v.Type().Elem())) } @@ -376,7 +376,7 @@ func decUint8Slice(i *decInstr, state *decoderState, value reflect.Value) { if value.Cap() < n { value.Set(reflect.MakeSlice(value.Type(), n, n)) } else { - value.Set(value.Slice(0, n)) + value.SetLen(n) } if _, err := state.b.Read(value.Bytes()); err != nil { errorf("error decoding []byte: %s", err) @@ -464,7 +464,7 @@ func (dec *Decoder) decodeStruct(engine *decEngine, value reflect.Value) { if instr.index != nil { // Otherwise the field is unknown to us and instr.op is an ignore op. field = value.FieldByIndex(instr.index) - if field.Kind() == reflect.Ptr { + if field.Kind() == reflect.Pointer { field = decAlloc(field) } } @@ -518,7 +518,7 @@ func (dec *Decoder) decodeArrayHelper(state *decoderState, value reflect.Value, return } instr := &decInstr{elemOp, 0, nil, ovfl} - isPtr := value.Type().Elem().Kind() == reflect.Ptr + isPtr := value.Type().Elem().Kind() == reflect.Pointer for i := 0; i < length; i++ { if state.b.Len() == 0 { errorf("decoding array or slice: length exceeds input size (%d elements)", length) @@ -561,8 +561,8 @@ func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, value refl if value.IsNil() { value.Set(reflect.MakeMapWithSize(mtyp, n)) } - keyIsPtr := mtyp.Key().Kind() == reflect.Ptr - elemIsPtr := mtyp.Elem().Kind() == reflect.Ptr + keyIsPtr := mtyp.Key().Kind() == reflect.Pointer + elemIsPtr := mtyp.Elem().Kind() == reflect.Pointer keyInstr := &decInstr{keyOp, 0, nil, ovfl} elemInstr := &decInstr{elemOp, 0, nil, ovfl} keyP := reflect.New(mtyp.Key()) @@ -625,7 +625,7 @@ func (dec *Decoder) decodeSlice(state *decoderState, value reflect.Value, elemOp if value.Cap() < n { value.Set(reflect.MakeSlice(typ, n, n)) } else { - value.Set(value.Slice(0, n)) + value.SetLen(n) } dec.decodeArrayHelper(state, value, elemOp, n, ovfl, helper) } @@ -945,7 +945,7 @@ func (dec *Decoder) decIgnoreOpFor(wireId typeId, inProgress map[typeId]*decOp) func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) *decOp { rcvrType := ut.user if ut.decIndir == -1 { - rcvrType = reflect.PtrTo(rcvrType) + rcvrType = reflect.PointerTo(rcvrType) } else if ut.decIndir > 0 { for i := int8(0); i < ut.decIndir; i++ { rcvrType = rcvrType.Elem() @@ -954,7 +954,7 @@ func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) *decOp { var op decOp op = func(i *decInstr, state *decoderState, value reflect.Value) { // We now have the base type. We need its address if the receiver is a pointer. - if value.Kind() != reflect.Ptr && rcvrType.Kind() == reflect.Ptr { + if value.Kind() != reflect.Pointer && rcvrType.Kind() == reflect.Pointer { value = value.Addr() } state.dec.decodeGobDecoder(ut, state, value) diff --git a/libgo/go/encoding/gob/decoder.go b/libgo/go/encoding/gob/decoder.go index b476aaac93b..86f54b41932 100644 --- a/libgo/go/encoding/gob/decoder.go +++ b/libgo/go/encoding/gob/decoder.go @@ -138,9 +138,17 @@ func (dec *Decoder) nextUint() uint64 { // decoded. If this is an interface value, it can be ignored by // resetting that buffer. func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId { + firstMessage := true for dec.err == nil { if dec.buf.Len() == 0 { if !dec.recvMessage() { + // We can only return io.EOF if the input was empty. + // If we read one or more type spec messages, + // require a data item message to follow. + // If we hit an EOF before that, then give ErrUnexpectedEOF. + if !firstMessage && dec.err == io.EOF { + dec.err = io.ErrUnexpectedEOF + } break } } @@ -166,6 +174,7 @@ func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId { } dec.nextUint() } + firstMessage = false } return -1 } @@ -177,14 +186,14 @@ func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId { // correct type for the next data item received. // If the input is at EOF, Decode returns io.EOF and // does not modify e. -func (dec *Decoder) Decode(e interface{}) error { +func (dec *Decoder) Decode(e any) error { if e == nil { return dec.DecodeValue(reflect.Value{}) } value := reflect.ValueOf(e) // If e represents a value as opposed to a pointer, the answer won't // get back to the caller. Make sure it's a pointer. - if value.Type().Kind() != reflect.Ptr { + if value.Type().Kind() != reflect.Pointer { dec.err = errors.New("gob: attempt to decode into a non-pointer") return dec.err } @@ -199,7 +208,7 @@ func (dec *Decoder) Decode(e interface{}) error { // does not modify v. func (dec *Decoder) DecodeValue(v reflect.Value) error { if v.IsValid() { - if v.Kind() == reflect.Ptr && !v.IsNil() { + if v.Kind() == reflect.Pointer && !v.IsNil() { // That's okay, we'll store through the pointer. } else if !v.CanSet() { return errors.New("gob: DecodeValue of unassignable value") diff --git a/libgo/go/encoding/gob/dump.go b/libgo/go/encoding/gob/dump.go index 8c0bbc4ff2e..f4b1bebfba1 100644 --- a/libgo/go/encoding/gob/dump.go +++ b/libgo/go/encoding/gob/dump.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build ignore -// +build ignore package main diff --git a/libgo/go/encoding/gob/encgen.go b/libgo/go/encoding/gob/encgen.go index b562da177db..e5f68786a06 100644 --- a/libgo/go/encoding/gob/encgen.go +++ b/libgo/go/encoding/gob/encgen.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build ignore -// +build ignore // encgen writes the helper functions for encoding. Intended to be // used with go generate; see the invocation in encode.go. diff --git a/libgo/go/encoding/gob/encode.go b/libgo/go/encoding/gob/encode.go index 8f8f170c164..548d614f524 100644 --- a/libgo/go/encoding/gob/encode.go +++ b/libgo/go/encoding/gob/encode.go @@ -40,7 +40,7 @@ type encBuffer struct { } var encBufferPool = sync.Pool{ - New: func() interface{} { + New: func() any { e := new(encBuffer) e.data = e.scratch[0:0] return e @@ -279,7 +279,7 @@ func valid(v reflect.Value) bool { switch v.Kind() { case reflect.Invalid: return false - case reflect.Ptr: + case reflect.Pointer: return !v.IsNil() } return true @@ -368,11 +368,11 @@ func (enc *Encoder) encodeMap(b *encBuffer, mv reflect.Value, keyOp, elemOp encO state := enc.newEncoderState(b) state.fieldnum = -1 state.sendZero = true - keys := mv.MapKeys() - state.encodeUint(uint64(len(keys))) - for _, key := range keys { - encodeReflectValue(state, key, keyOp, keyIndir) - encodeReflectValue(state, mv.MapIndex(key), elemOp, elemIndir) + state.encodeUint(uint64(mv.Len())) + mi := mv.MapRange() + for mi.Next() { + encodeReflectValue(state, mi.Key(), keyOp, keyIndir) + encodeReflectValue(state, mi.Value(), elemOp, elemIndir) } enc.freeEncoderState(state) } @@ -386,7 +386,7 @@ func (enc *Encoder) encodeInterface(b *encBuffer, iv reflect.Value) { // Gobs can encode nil interface values but not typed interface // values holding nil pointers, since nil pointers point to no value. elem := iv.Elem() - if elem.Kind() == reflect.Ptr && elem.IsNil() { + if elem.Kind() == reflect.Pointer && elem.IsNil() { errorf("gob: cannot encode nil pointer of type %s inside interface", iv.Elem().Type()) } state := enc.newEncoderState(b) @@ -446,7 +446,7 @@ func isZero(val reflect.Value) bool { return !val.Bool() case reflect.Complex64, reflect.Complex128: return val.Complex() == 0 - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Ptr: + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Pointer: return val.IsNil() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return val.Int() == 0 @@ -600,7 +600,7 @@ func encOpFor(rt reflect.Type, inProgress map[reflect.Type]*encOp, building map[ func gobEncodeOpFor(ut *userTypeInfo) (*encOp, int) { rt := ut.user if ut.encIndir == -1 { - rt = reflect.PtrTo(rt) + rt = reflect.PointerTo(rt) } else if ut.encIndir > 0 { for i := int8(0); i < ut.encIndir; i++ { rt = rt.Elem() diff --git a/libgo/go/encoding/gob/encoder.go b/libgo/go/encoding/gob/encoder.go index 53e2cace166..5a80e6c3e82 100644 --- a/libgo/go/encoding/gob/encoder.go +++ b/libgo/go/encoding/gob/encoder.go @@ -172,7 +172,7 @@ func (enc *Encoder) sendType(w io.Writer, state *encoderState, origt reflect.Typ // Encode transmits the data item represented by the empty interface value, // guaranteeing that all necessary type information has been transmitted first. // Passing a nil pointer to Encoder will panic, as they cannot be transmitted by gob. -func (enc *Encoder) Encode(e interface{}) error { +func (enc *Encoder) Encode(e any) error { return enc.EncodeValue(reflect.ValueOf(e)) } @@ -219,7 +219,7 @@ func (enc *Encoder) EncodeValue(value reflect.Value) error { if value.Kind() == reflect.Invalid { return errors.New("gob: cannot encode nil value") } - if value.Kind() == reflect.Ptr && value.IsNil() { + if value.Kind() == reflect.Pointer && value.IsNil() { panic("gob: cannot encode nil pointer of type " + value.Type().String()) } diff --git a/libgo/go/encoding/gob/encoder_test.go b/libgo/go/encoding/gob/encoder_test.go index 6183646f60c..6934841b3af 100644 --- a/libgo/go/encoding/gob/encoder_test.go +++ b/libgo/go/encoding/gob/encoder_test.go @@ -9,14 +9,16 @@ import ( "encoding/hex" "fmt" "io" + "math" "reflect" + "sort" "strings" "testing" ) // Test basic operations in a safe manner. func TestBasicEncoderDecoder(t *testing.T) { - var values = []interface{}{ + var values = []any{ true, int(123), int8(123), @@ -226,7 +228,7 @@ func TestEncoderDecoder(t *testing.T) { // Run one value through the encoder/decoder, but use the wrong type. // Input is always an ET1; we compare it to whatever is under 'e'. -func badTypeCheck(e interface{}, shouldFail bool, msg string, t *testing.T) { +func badTypeCheck(e any, shouldFail bool, msg string, t *testing.T) { b := new(bytes.Buffer) enc := NewEncoder(b) et1 := new(ET1) @@ -254,7 +256,7 @@ func TestWrongTypeDecoder(t *testing.T) { } // Types not supported at top level by the Encoder. -var unsupportedValues = []interface{}{ +var unsupportedValues = []any{ make(chan int), func(a int) bool { return true }, } @@ -270,7 +272,7 @@ func TestUnsupported(t *testing.T) { } } -func encAndDec(in, out interface{}) error { +func encAndDec(in, out any) error { b := new(bytes.Buffer) enc := NewEncoder(b) err := enc.Encode(in) @@ -416,8 +418,8 @@ var testMap map[string]int var testArray [7]int type SingleTest struct { - in interface{} - out interface{} + in any + out any err string } @@ -534,7 +536,7 @@ func TestInterfaceIndirect(t *testing.T) { // encoder and decoder don't skew with respect to type definitions. type Struct0 struct { - I interface{} + I any } type NewType0 struct { @@ -542,7 +544,7 @@ type NewType0 struct { } type ignoreTest struct { - in, out interface{} + in, out any } var ignoreTests = []ignoreTest{ @@ -557,7 +559,7 @@ var ignoreTests = []ignoreTest{ // Decode struct containing an interface into a nil. {&Struct0{&NewType0{"value0"}}, nil}, // Decode singleton slice of interfaces into a nil. - {[]interface{}{"hi", &NewType0{"value1"}, 23}, nil}, + {[]any{"hi", &NewType0{"value1"}, 23}, nil}, } func TestDecodeIntoNothing(t *testing.T) { @@ -619,7 +621,7 @@ func TestIgnoreRecursiveType(t *testing.T) { // Another bug from golang-nuts, involving nested interfaces. type Bug0Outer struct { - Bug0Field interface{} + Bug0Field any } type Bug0Inner struct { @@ -633,7 +635,7 @@ func TestNestedInterfaces(t *testing.T) { Register(new(Bug0Outer)) Register(new(Bug0Inner)) f := &Bug0Outer{&Bug0Outer{&Bug0Inner{7}}} - var v interface{} = f + var v any = f err := e.Encode(&v) if err != nil { t.Fatal("Encode:", err) @@ -692,7 +694,7 @@ func TestMapBug1(t *testing.T) { } func TestGobMapInterfaceEncode(t *testing.T) { - m := map[string]interface{}{ + m := map[string]any{ "up": uintptr(0), "i0": []int{-1}, "i1": []int8{-1}, @@ -874,10 +876,10 @@ func TestGobPtrSlices(t *testing.T) { // getDecEnginePtr cached engine for ut.base instead of ut.user so we passed // a *map and then tried to reuse its engine to decode the inner map. func TestPtrToMapOfMap(t *testing.T) { - Register(make(map[string]interface{})) - subdata := make(map[string]interface{}) + Register(make(map[string]any)) + subdata := make(map[string]any) subdata["bar"] = "baz" - data := make(map[string]interface{}) + data := make(map[string]any) data["foo"] = subdata b := new(bytes.Buffer) @@ -885,7 +887,7 @@ func TestPtrToMapOfMap(t *testing.T) { if err != nil { t.Fatal("encode:", err) } - var newData map[string]interface{} + var newData map[string]any err = NewDecoder(b).Decode(&newData) if err != nil { t.Fatal("decode:", err) @@ -925,7 +927,7 @@ func TestTopLevelNilPointer(t *testing.T) { } } -func encodeAndRecover(value interface{}) (encodeErr, panicErr error) { +func encodeAndRecover(value any) (encodeErr, panicErr error) { defer func() { e := recover() if e != nil { @@ -957,7 +959,7 @@ func TestNilPointerPanics(t *testing.T) { ) testCases := []struct { - value interface{} + value any mustPanic bool }{ {nilStringPtr, true}, @@ -989,7 +991,7 @@ func TestNilPointerPanics(t *testing.T) { func TestNilPointerInsideInterface(t *testing.T) { var ip *int si := struct { - I interface{} + I any }{ I: ip, } @@ -1047,7 +1049,7 @@ type Z struct { func Test29ElementSlice(t *testing.T) { Register(Z{}) - src := make([]interface{}, 100) // Size needs to be bigger than size of type definition. + src := make([]any, 100) // Size needs to be bigger than size of type definition. for i := range src { src[i] = Z{} } @@ -1058,7 +1060,7 @@ func Test29ElementSlice(t *testing.T) { return } - var dst []interface{} + var dst []any err = NewDecoder(buf).Decode(&dst) if err != nil { t.Errorf("decode: %v", err) @@ -1089,9 +1091,9 @@ func TestErrorForHugeSlice(t *testing.T) { } type badDataTest struct { - input string // The input encoded as a hex string. - error string // A substring of the error that should result. - data interface{} // What to decode into. + input string // The input encoded as a hex string. + error string // A substring of the error that should result. + data any // What to decode into. } var badDataTests = []badDataTest{ @@ -1152,3 +1154,114 @@ func TestDecodeErrorMultipleTypes(t *testing.T) { t.Errorf("decode: expected duplicate type error, got %s", err.Error()) } } + +// Issue 24075 +func TestMarshalFloatMap(t *testing.T) { + nan1 := math.NaN() + nan2 := math.Float64frombits(math.Float64bits(nan1) ^ 1) // A different NaN in the same class. + + in := map[float64]string{ + nan1: "a", + nan1: "b", + nan2: "c", + } + + var b bytes.Buffer + enc := NewEncoder(&b) + if err := enc.Encode(in); err != nil { + t.Errorf("Encode : %v", err) + } + + out := map[float64]string{} + dec := NewDecoder(&b) + if err := dec.Decode(&out); err != nil { + t.Fatalf("Decode : %v", err) + } + + type mapEntry struct { + keyBits uint64 + value string + } + readMap := func(m map[float64]string) (entries []mapEntry) { + for k, v := range m { + entries = append(entries, mapEntry{math.Float64bits(k), v}) + } + sort.Slice(entries, func(i, j int) bool { + ei, ej := entries[i], entries[j] + if ei.keyBits != ej.keyBits { + return ei.keyBits < ej.keyBits + } + return ei.value < ej.value + }) + return entries + } + + got := readMap(out) + want := readMap(in) + if !reflect.DeepEqual(got, want) { + t.Fatalf("\nEncode: %v\nDecode: %v", want, got) + } +} + +func TestDecodePartial(t *testing.T) { + type T struct { + X []int + Y string + } + + var buf bytes.Buffer + t1 := T{X: []int{1, 2, 3}, Y: "foo"} + t2 := T{X: []int{4, 5, 6}, Y: "bar"} + enc := NewEncoder(&buf) + + t1start := 0 + if err := enc.Encode(&t1); err != nil { + t.Fatal(err) + } + + t2start := buf.Len() + if err := enc.Encode(&t2); err != nil { + t.Fatal(err) + } + + data := buf.Bytes() + for i := 0; i <= len(data); i++ { + bufr := bytes.NewReader(data[:i]) + + // Decode both values, stopping at the first error. + var t1b, t2b T + dec := NewDecoder(bufr) + var err error + err = dec.Decode(&t1b) + if err == nil { + err = dec.Decode(&t2b) + } + + switch i { + case t1start, t2start: + // Either the first or the second Decode calls had zero input. + if err != io.EOF { + t.Errorf("%d/%d: expected io.EOF: %v", i, len(data), err) + } + case len(data): + // We reached the end of the entire input. + if err != nil { + t.Errorf("%d/%d: unexpected error: %v", i, len(data), err) + } + if !reflect.DeepEqual(t1b, t1) { + t.Fatalf("t1 value mismatch: got %v, want %v", t1b, t1) + } + if !reflect.DeepEqual(t2b, t2) { + t.Fatalf("t2 value mismatch: got %v, want %v", t2b, t2) + } + default: + // In between, we must see io.ErrUnexpectedEOF. + // The decoder used to erroneously return io.EOF in some cases here, + // such as if the input was cut off right after some type specs, + // but before any value was actually transmitted. + if err != io.ErrUnexpectedEOF { + t.Errorf("%d/%d: expected io.ErrUnexpectedEOF: %v", i, len(data), err) + } + } + } +} diff --git a/libgo/go/encoding/gob/error.go b/libgo/go/encoding/gob/error.go index 949333bc037..3c9515b5ed6 100644 --- a/libgo/go/encoding/gob/error.go +++ b/libgo/go/encoding/gob/error.go @@ -20,7 +20,7 @@ type gobError struct { // errorf is like error_ but takes Printf-style arguments to construct an error. // It always prefixes the message with "gob: ". -func errorf(format string, args ...interface{}) { +func errorf(format string, args ...any) { error_(fmt.Errorf("gob: "+format, args...)) } diff --git a/libgo/go/encoding/gob/gobencdec_test.go b/libgo/go/encoding/gob/gobencdec_test.go index 6d2c8db42d0..1d5dde22a4e 100644 --- a/libgo/go/encoding/gob/gobencdec_test.go +++ b/libgo/go/encoding/gob/gobencdec_test.go @@ -734,7 +734,7 @@ func (a *isZeroBugArray) GobDecode(data []byte) error { } type isZeroBugInterface struct { - I interface{} + I any } func (i isZeroBugInterface) GobEncode() (b []byte, e error) { diff --git a/libgo/go/encoding/gob/timing_test.go b/libgo/go/encoding/gob/timing_test.go index 3478bd247ed..bdee39c447d 100644 --- a/libgo/go/encoding/gob/timing_test.go +++ b/libgo/go/encoding/gob/timing_test.go @@ -20,7 +20,7 @@ type Bench struct { D []byte } -func benchmarkEndToEnd(b *testing.B, ctor func() interface{}, pipe func() (r io.Reader, w io.Writer, err error)) { +func benchmarkEndToEnd(b *testing.B, ctor func() any, pipe func() (r io.Reader, w io.Writer, err error)) { b.RunParallel(func(pb *testing.PB) { r, w, err := pipe() if err != nil { @@ -41,7 +41,7 @@ func benchmarkEndToEnd(b *testing.B, ctor func() interface{}, pipe func() (r io. } func BenchmarkEndToEndPipe(b *testing.B) { - benchmarkEndToEnd(b, func() interface{} { + benchmarkEndToEnd(b, func() any { return &Bench{7, 3.2, "now is the time", bytes.Repeat([]byte("for all good men"), 100)} }, func() (r io.Reader, w io.Writer, err error) { r, w, err = os.Pipe() @@ -50,7 +50,7 @@ func BenchmarkEndToEndPipe(b *testing.B) { } func BenchmarkEndToEndByteBuffer(b *testing.B) { - benchmarkEndToEnd(b, func() interface{} { + benchmarkEndToEnd(b, func() any { return &Bench{7, 3.2, "now is the time", bytes.Repeat([]byte("for all good men"), 100)} }, func() (r io.Reader, w io.Writer, err error) { var buf bytes.Buffer @@ -59,10 +59,10 @@ func BenchmarkEndToEndByteBuffer(b *testing.B) { } func BenchmarkEndToEndSliceByteBuffer(b *testing.B) { - benchmarkEndToEnd(b, func() interface{} { + benchmarkEndToEnd(b, func() any { v := &Bench{7, 3.2, "now is the time", nil} Register(v) - arr := make([]interface{}, 100) + arr := make([]any, 100) for i := range arr { arr[i] = v } @@ -133,7 +133,7 @@ func TestCountDecodeMallocs(t *testing.T) { } } -func benchmarkEncodeSlice(b *testing.B, a interface{}) { +func benchmarkEncodeSlice(b *testing.B, a any) { b.ResetTimer() b.RunParallel(func(pb *testing.PB) { var buf bytes.Buffer @@ -182,7 +182,7 @@ func BenchmarkEncodeStringSlice(b *testing.B) { } func BenchmarkEncodeInterfaceSlice(b *testing.B) { - a := make([]interface{}, 1000) + a := make([]any, 1000) for i := range a { a[i] = "now is the time" } @@ -217,7 +217,7 @@ func (b *benchmarkBuf) reset() { b.offset = 0 } -func benchmarkDecodeSlice(b *testing.B, a interface{}) { +func benchmarkDecodeSlice(b *testing.B, a any) { var buf bytes.Buffer enc := NewEncoder(&buf) err := enc.Encode(a) @@ -279,9 +279,23 @@ func BenchmarkDecodeStringSlice(b *testing.B) { } benchmarkDecodeSlice(b, a) } +func BenchmarkDecodeStringsSlice(b *testing.B) { + a := make([][]string, 1000) + for i := range a { + a[i] = []string{"now is the time"} + } + benchmarkDecodeSlice(b, a) +} +func BenchmarkDecodeBytesSlice(b *testing.B) { + a := make([][]byte, 1000) + for i := range a { + a[i] = []byte("now is the time") + } + benchmarkDecodeSlice(b, a) +} func BenchmarkDecodeInterfaceSlice(b *testing.B) { - a := make([]interface{}, 1000) + a := make([]any, 1000) for i := range a { a[i] = "now is the time" } diff --git a/libgo/go/encoding/gob/type.go b/libgo/go/encoding/gob/type.go index 31c0ef7af15..6e2c7242324 100644 --- a/libgo/go/encoding/gob/type.go +++ b/libgo/go/encoding/gob/type.go @@ -61,7 +61,7 @@ func validUserType(rt reflect.Type) (*userTypeInfo, error) { slowpoke := ut.base // walks half as fast as ut.base for { pt := ut.base - if pt.Kind() != reflect.Ptr { + if pt.Kind() != reflect.Pointer { break } ut.base = pt.Elem() @@ -126,7 +126,7 @@ func implementsInterface(typ, gobEncDecType reflect.Type) (success bool, indir i if rt.Implements(gobEncDecType) { return true, indir } - if p := rt; p.Kind() == reflect.Ptr { + if p := rt; p.Kind() == reflect.Pointer { indir++ if indir > 100 { // insane number of indirections return false, 0 @@ -137,9 +137,9 @@ func implementsInterface(typ, gobEncDecType reflect.Type) (success bool, indir i break } // No luck yet, but if this is a base type (non-pointer), the pointer might satisfy. - if typ.Kind() != reflect.Ptr { + if typ.Kind() != reflect.Pointer { // Not a pointer, but does the pointer work? - if reflect.PtrTo(typ).Implements(gobEncDecType) { + if reflect.PointerTo(typ).Implements(gobEncDecType) { return true, -1 } } @@ -244,7 +244,7 @@ var ( tBytes = bootstrapType("bytes", (*[]byte)(nil), 5) tString = bootstrapType("string", (*string)(nil), 6) tComplex = bootstrapType("complex", (*complex128)(nil), 7) - tInterface = bootstrapType("interface", (*interface{})(nil), 8) + tInterface = bootstrapType("interface", (*any)(nil), 8) // Reserve some Ids for compatible expansion tReserved7 = bootstrapType("_reserved1", (*struct{ r7 int })(nil), 9) tReserved6 = bootstrapType("_reserved1", (*struct{ r6 int })(nil), 10) @@ -569,7 +569,7 @@ func isSent(field *reflect.StructField) bool { // If the field is a chan or func or pointer thereto, don't send it. // That is, treat it like an unexported field. typ := field.Type - for typ.Kind() == reflect.Ptr { + for typ.Kind() == reflect.Pointer { typ = typ.Elem() } if typ.Kind() == reflect.Chan || typ.Kind() == reflect.Func { @@ -611,7 +611,7 @@ func checkId(want, got typeId) { // used for building the basic types; called only from init(). the incoming // interface always refers to a pointer. -func bootstrapType(name string, e interface{}, expect typeId) typeId { +func bootstrapType(name string, e any, expect typeId) typeId { rt := reflect.TypeOf(e).Elem() _, present := types[rt] if present { @@ -804,7 +804,7 @@ var ( // RegisterName is like Register but uses the provided name rather than the // type's default. -func RegisterName(name string, value interface{}) { +func RegisterName(name string, value any) { if name == "" { // reserved for nil panic("attempt to register empty name") @@ -833,7 +833,7 @@ func RegisterName(name string, value interface{}) { // transferred as implementations of interface values need to be registered. // Expecting to be used only during initialization, it panics if the mapping // between types and names is not a bijection. -func Register(value interface{}) { +func Register(value any) { // Default to printed representation for unnamed types rt := reflect.TypeOf(value) name := rt.String() @@ -842,7 +842,7 @@ func Register(value interface{}) { // Dereference one pointer looking for a named type. star := "" if rt.Name() == "" { - if pt := rt; pt.Kind() == reflect.Ptr { + if pt := rt; pt.Kind() == reflect.Pointer { star = "*" // NOTE: The following line should be rt = pt.Elem() to implement // what the comment above claims, but fixing it would break compatibility diff --git a/libgo/go/encoding/gob/type_test.go b/libgo/go/encoding/gob/type_test.go index 934270eedd8..f5f8db8bcb4 100644 --- a/libgo/go/encoding/gob/type_test.go +++ b/libgo/go/encoding/gob/type_test.go @@ -168,7 +168,7 @@ type N2 struct{} // See comment in type.go/Register. func TestRegistrationNaming(t *testing.T) { testCases := []struct { - t interface{} + t any name string }{ {&N1{}, "*gob.N1"}, @@ -184,7 +184,7 @@ func TestRegistrationNaming(t *testing.T) { t.Errorf("nameToConcreteType[%q] = %v, want %v", tc.name, ct, tct) } // concreteTypeToName is keyed off the base type. - if tct.Kind() == reflect.Ptr { + if tct.Kind() == reflect.Pointer { tct = tct.Elem() } if n, _ := concreteTypeToName.Load(tct); n != tc.name { @@ -231,7 +231,7 @@ func TestTypeRace(t *testing.T) { var buf bytes.Buffer enc := NewEncoder(&buf) dec := NewDecoder(&buf) - var x interface{} + var x any switch i { case 0: x = &N1{} diff --git a/libgo/go/encoding/json/bench_test.go b/libgo/go/encoding/json/bench_test.go index 73c7b09fb6f..95609140b0d 100644 --- a/libgo/go/encoding/json/bench_test.go +++ b/libgo/go/encoding/json/bench_test.go @@ -192,7 +192,7 @@ func BenchmarkDecoderStream(b *testing.B) { var buf bytes.Buffer dec := NewDecoder(&buf) buf.WriteString(`"` + strings.Repeat("x", 1000000) + `"` + "\n\n\n") - var x interface{} + var x any if err := dec.Decode(&x); err != nil { b.Fatal("Decode:", err) } diff --git a/libgo/go/encoding/json/decode.go b/libgo/go/encoding/json/decode.go index a9917e72c76..555df0b7e87 100644 --- a/libgo/go/encoding/json/decode.go +++ b/libgo/go/encoding/json/decode.go @@ -93,7 +93,7 @@ import ( // Instead, they are replaced by the Unicode replacement // character U+FFFD. // -func Unmarshal(data []byte, v interface{}) error { +func Unmarshal(data []byte, v any) error { // Check for well-formedness. // Avoids filling out half a data structure // before discovering a JSON syntax error. @@ -161,15 +161,15 @@ func (e *InvalidUnmarshalError) Error() string { return "json: Unmarshal(nil)" } - if e.Type.Kind() != reflect.Ptr { + if e.Type.Kind() != reflect.Pointer { return "json: Unmarshal(non-pointer " + e.Type.String() + ")" } return "json: Unmarshal(nil " + e.Type.String() + ")" } -func (d *decodeState) unmarshal(v interface{}) error { +func (d *decodeState) unmarshal(v any) error { rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { + if rv.Kind() != reflect.Pointer || rv.IsNil() { return &InvalidUnmarshalError{reflect.TypeOf(v)} } @@ -398,7 +398,7 @@ type unquotedValue struct{} // quoted string literal or literal null into an interface value. // If it finds anything other than a quoted string literal or null, // valueQuoted returns unquotedValue{}. -func (d *decodeState) valueQuoted() interface{} { +func (d *decodeState) valueQuoted() any { switch d.opcode { default: panic(phasePanicMsg) @@ -440,7 +440,7 @@ func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnm // If v is a named type and is addressable, // start with its address, so that if the type has pointer methods, // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { + if v.Kind() != reflect.Pointer && v.Type().Name() != "" && v.CanAddr() { haveAddr = true v = v.Addr() } @@ -449,14 +449,14 @@ func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnm // usefully addressable. if v.Kind() == reflect.Interface && !v.IsNil() { e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { + if e.Kind() == reflect.Pointer && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Pointer) { haveAddr = false v = e continue } } - if v.Kind() != reflect.Ptr { + if v.Kind() != reflect.Pointer { break } @@ -641,7 +641,7 @@ func (d *decodeState) object(v reflect.Value) error { reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: default: - if !reflect.PtrTo(t.Key()).Implements(textUnmarshalerType) { + if !reflect.PointerTo(t.Key()).Implements(textUnmarshalerType) { d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)}) d.skip() return nil @@ -717,7 +717,7 @@ func (d *decodeState) object(v reflect.Value) error { subv = v destring = f.quoted for _, i := range f.index { - if subv.Kind() == reflect.Ptr { + if subv.Kind() == reflect.Pointer { if subv.IsNil() { // If a struct embeds a pointer to an unexported type, // it is not possible to set a newly allocated value @@ -782,7 +782,7 @@ func (d *decodeState) object(v reflect.Value) error { kt := t.Key() var kv reflect.Value switch { - case reflect.PtrTo(kt).Implements(textUnmarshalerType): + case reflect.PointerTo(kt).Implements(textUnmarshalerType): kv = reflect.New(kt) if err := d.literalStore(item, kv, true); err != nil { return err @@ -840,7 +840,7 @@ func (d *decodeState) object(v reflect.Value) error { // convertNumber converts the number literal s to a float64 or a Number // depending on the setting of d.useNumber. -func (d *decodeState) convertNumber(s string) (interface{}, error) { +func (d *decodeState) convertNumber(s string) (any, error) { if d.useNumber { return Number(s), nil } @@ -907,7 +907,7 @@ func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool break } switch v.Kind() { - case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: + case reflect.Interface, reflect.Pointer, reflect.Map, reflect.Slice: v.Set(reflect.Zero(v.Type())) // otherwise, ignore null for primitives/string } @@ -1037,7 +1037,7 @@ func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool // but they avoid the weight of reflection in this common case. // valueInterface is like value but returns interface{} -func (d *decodeState) valueInterface() (val interface{}) { +func (d *decodeState) valueInterface() (val any) { switch d.opcode { default: panic(phasePanicMsg) @@ -1054,8 +1054,8 @@ func (d *decodeState) valueInterface() (val interface{}) { } // arrayInterface is like array but returns []interface{}. -func (d *decodeState) arrayInterface() []interface{} { - var v = make([]interface{}, 0) +func (d *decodeState) arrayInterface() []any { + var v = make([]any, 0) for { // Look ahead for ] - can only happen on first iteration. d.scanWhile(scanSkipSpace) @@ -1080,8 +1080,8 @@ func (d *decodeState) arrayInterface() []interface{} { } // objectInterface is like object but returns map[string]interface{}. -func (d *decodeState) objectInterface() map[string]interface{} { - m := make(map[string]interface{}) +func (d *decodeState) objectInterface() map[string]any { + m := make(map[string]any) for { // Read opening " of string key or closing }. d.scanWhile(scanSkipSpace) @@ -1131,7 +1131,7 @@ func (d *decodeState) objectInterface() map[string]interface{} { // literalInterface consumes and returns a literal from d.data[d.off-1:] and // it reads the following byte ahead. The first byte of the literal has been // read already (that's how the caller knows it's a literal). -func (d *decodeState) literalInterface() interface{} { +func (d *decodeState) literalInterface() any { // All bytes inside literal return scanContinue op code. start := d.readIndex() d.rescanLiteral() diff --git a/libgo/go/encoding/json/decode_test.go b/libgo/go/encoding/json/decode_test.go index 219e845c7b0..c2c036b6091 100644 --- a/libgo/go/encoding/json/decode_test.go +++ b/libgo/go/encoding/json/decode_test.go @@ -31,7 +31,7 @@ type U struct { } type V struct { - F1 interface{} + F1 any F2 int32 F3 Number F4 *VOuter @@ -62,18 +62,18 @@ func (*SS) UnmarshalJSON(data []byte) error { // ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and // without UseNumber -var ifaceNumAsFloat64 = map[string]interface{}{ +var ifaceNumAsFloat64 = map[string]any{ "k1": float64(1), "k2": "s", - "k3": []interface{}{float64(1), float64(2.0), float64(3e-3)}, - "k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)}, + "k3": []any{float64(1), float64(2.0), float64(3e-3)}, + "k4": map[string]any{"kk1": "s", "kk2": float64(2)}, } -var ifaceNumAsNumber = map[string]interface{}{ +var ifaceNumAsNumber = map[string]any{ "k1": Number("1"), "k2": "s", - "k3": []interface{}{Number("1"), Number("2.0"), Number("3e-3")}, - "k4": map[string]interface{}{"kk1": "s", "kk2": Number("2")}, + "k3": []any{Number("1"), Number("2.0"), Number("3e-3")}, + "k4": map[string]any{"kk1": "s", "kk2": Number("2")}, } type tx struct { @@ -262,9 +262,9 @@ type Ambig struct { } type XYZ struct { - X interface{} - Y interface{} - Z interface{} + X any + Y any + Z any } type unexportedWithMethods struct{} @@ -389,8 +389,8 @@ type mapStringToStringData struct { type unmarshalTest struct { in string - ptr interface{} // new(type) - out interface{} + ptr any // new(type) + out any err error useNumber bool golden bool @@ -414,13 +414,13 @@ var unmarshalTests = []unmarshalTest{ {in: `-5`, ptr: new(int16), out: int16(-5)}, {in: `2`, ptr: new(Number), out: Number("2"), useNumber: true}, {in: `2`, ptr: new(Number), out: Number("2")}, - {in: `2`, ptr: new(interface{}), out: float64(2.0)}, - {in: `2`, ptr: new(interface{}), out: Number("2"), useNumber: true}, + {in: `2`, ptr: new(any), out: float64(2.0)}, + {in: `2`, ptr: new(any), out: Number("2"), useNumber: true}, {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"}, {in: `"http:\/\/"`, ptr: new(string), out: "http://"}, {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"}, {in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"}, - {in: "null", ptr: new(interface{}), out: nil}, + {in: "null", ptr: new(any), out: nil}, {in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeOf(""), 7, "T", "X"}}, {in: `{"X": 23}`, ptr: new(T), out: T{}, err: &UnmarshalTypeError{"number", reflect.TypeOf(""), 8, "T", "X"}}, {in: `{"x": 1}`, ptr: new(tx), out: tx{}}, {in: `{"x": 1}`, ptr: new(tx), out: tx{}}, @@ -428,8 +428,8 @@ var unmarshalTests = []unmarshalTest{ {in: `{"S": 23}`, ptr: new(W), out: W{}, err: &UnmarshalTypeError{"number", reflect.TypeOf(SS("")), 0, "W", "S"}}, {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}}, {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true}, - {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64}, - {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsNumber, useNumber: true}, + {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(any), out: ifaceNumAsFloat64}, + {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(any), out: ifaceNumAsNumber, useNumber: true}, // raw values with whitespace {in: "\n true ", ptr: new(bool), out: true}, @@ -472,10 +472,10 @@ var unmarshalTests = []unmarshalTest{ {in: `[1, 2, 3]`, ptr: new(MustNotUnmarshalJSON), err: errors.New("MustNotUnmarshalJSON was used")}, // empty array to interface test - {in: `[]`, ptr: new([]interface{}), out: []interface{}{}}, - {in: `null`, ptr: new([]interface{}), out: []interface{}(nil)}, - {in: `{"T":[]}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": []interface{}{}}}, - {in: `{"T":null}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": interface{}(nil)}}, + {in: `[]`, ptr: new([]any), out: []any{}}, + {in: `null`, ptr: new([]any), out: []any(nil)}, + {in: `{"T":[]}`, ptr: new(map[string]any), out: map[string]any{"T": []any{}}}, + {in: `{"T":null}`, ptr: new(map[string]any), out: map[string]any{"T": any(nil)}}, // composite tests {in: allValueIndent, ptr: new(All), out: allValue}, @@ -1103,7 +1103,7 @@ func TestUnmarshal(t *testing.T) { } typ := reflect.TypeOf(tt.ptr) - if typ.Kind() != reflect.Ptr { + if typ.Kind() != reflect.Pointer { t.Errorf("#%d: unmarshalTest.ptr %T is not a pointer type", i, tt.ptr) continue } @@ -1176,7 +1176,7 @@ func TestUnmarshal(t *testing.T) { func TestUnmarshalMarshal(t *testing.T) { initBig() - var v interface{} + var v any if err := Unmarshal(jsonBig, &v); err != nil { t.Fatalf("Unmarshal: %v", err) } @@ -1248,7 +1248,7 @@ type Xint struct { func TestUnmarshalInterface(t *testing.T) { var xint Xint - var i interface{} = &xint + var i any = &xint if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil { t.Fatalf("Unmarshal: %v", err) } @@ -1382,8 +1382,8 @@ type All struct { PSmall *Small PPSmall **Small - Interface interface{} - PInterface *interface{} + Interface any + PInterface *any unexported int } @@ -1717,9 +1717,9 @@ func intpp(x *int) **int { } var interfaceSetTests = []struct { - pre interface{} + pre any json string - post interface{} + post any }{ {"foo", `"bar"`, "bar"}, {"foo", `2`, 2.0}, @@ -1738,7 +1738,7 @@ var interfaceSetTests = []struct { func TestInterfaceSet(t *testing.T) { for _, tt := range interfaceSetTests { - b := struct{ X interface{} }{tt.pre} + b := struct{ X any }{tt.pre} blob := `{"X":` + tt.json + `}` if err := Unmarshal([]byte(blob), &b); err != nil { t.Errorf("Unmarshal %#q: %v", blob, err) @@ -1768,7 +1768,7 @@ type NullTest struct { PBool *bool Map map[string]string Slice []string - Interface interface{} + Interface any PRaw *RawMessage PTime *time.Time @@ -1989,7 +1989,7 @@ func TestSliceOfCustomByte(t *testing.T) { } var decodeTypeErrorTests = []struct { - dest interface{} + dest any src string }{ {new(string), `{"user": "name"}`}, // issue 4628. @@ -2022,7 +2022,7 @@ var unmarshalSyntaxTests = []string{ } func TestUnmarshalSyntax(t *testing.T) { - var x interface{} + var x any for _, src := range unmarshalSyntaxTests { err := Unmarshal([]byte(src), &x) if _, ok := err.(*SyntaxError); !ok { @@ -2035,8 +2035,8 @@ func TestUnmarshalSyntax(t *testing.T) { // Issue 4660 type unexportedFields struct { Name string - m map[string]interface{} `json:"-"` - m2 map[string]interface{} `json:"abcd"` + m map[string]any `json:"-"` + m2 map[string]any `json:"abcd"` s []int `json:"-"` } @@ -2087,7 +2087,7 @@ func TestUnmarshalJSONLiteralError(t *testing.T) { // Issue 3717 func TestSkipArrayObjects(t *testing.T) { json := `[{}]` - var dest [0]interface{} + var dest [0]any err := Unmarshal([]byte(json), &dest) if err != nil { @@ -2102,8 +2102,8 @@ func TestPrefilled(t *testing.T) { // Values here change, cannot reuse table across runs. var prefillTests = []struct { in string - ptr interface{} - out interface{} + ptr any + out any }{ { in: `{"X": 1, "Y": 2}`, @@ -2112,8 +2112,8 @@ func TestPrefilled(t *testing.T) { }, { in: `{"X": 1, "Y": 2}`, - ptr: &map[string]interface{}{"X": float32(3), "Y": int16(4), "Z": 1.5}, - out: &map[string]interface{}{"X": float64(1), "Y": float64(2), "Z": 1.5}, + ptr: &map[string]any{"X": float32(3), "Y": int16(4), "Z": 1.5}, + out: &map[string]any{"X": float64(1), "Y": float64(2), "Z": 1.5}, }, { in: `[2]`, @@ -2150,7 +2150,7 @@ func TestPrefilled(t *testing.T) { } var invalidUnmarshalTests = []struct { - v interface{} + v any want string }{ {nil, "json: Unmarshal(nil)"}, @@ -2173,7 +2173,7 @@ func TestInvalidUnmarshal(t *testing.T) { } var invalidUnmarshalTextTests = []struct { - v interface{} + v any want string }{ {nil, "json: Unmarshal(nil)"}, @@ -2205,7 +2205,7 @@ func TestInvalidStringOption(t *testing.T) { M map[string]string `json:",string"` S []string `json:",string"` A [1]string `json:",string"` - I interface{} `json:",string"` + I any `json:",string"` P *int `json:",string"` }{M: make(map[string]string), S: make([]string, 0), I: num, P: &num} @@ -2276,8 +2276,8 @@ func TestUnmarshalEmbeddedUnexported(t *testing.T) { tests := []struct { in string - ptr interface{} - out interface{} + ptr any + out any err error }{{ // Error since we cannot set S1.embed1, but still able to set S1.R. @@ -2375,7 +2375,7 @@ func TestUnmarshalErrorAfterMultipleJSON(t *testing.T) { dec := NewDecoder(strings.NewReader(tt.in)) var err error for { - var v interface{} + var v any if err = dec.Decode(&v); err != nil { break } @@ -2403,7 +2403,7 @@ func TestUnmarshalPanic(t *testing.T) { // The decoder used to hang if decoding into an interface pointing to its own address. // See golang.org/issues/31740. func TestUnmarshalRecursivePointer(t *testing.T) { - var v interface{} + var v any v = &v data := []byte(`{"a": "b"}`) @@ -2517,36 +2517,36 @@ func TestUnmarshalMaxDepth(t *testing.T) { targets := []struct { name string - newValue func() interface{} + newValue func() any }{ { name: "unstructured", - newValue: func() interface{} { - var v interface{} + newValue: func() any { + var v any return &v }, }, { name: "typed named field", - newValue: func() interface{} { + newValue: func() any { v := struct { - A interface{} `json:"a"` + A any `json:"a"` }{} return &v }, }, { name: "typed missing field", - newValue: func() interface{} { + newValue: func() any { v := struct { - B interface{} `json:"b"` + B any `json:"b"` }{} return &v }, }, { name: "custom unmarshaler", - newValue: func() interface{} { + newValue: func() any { v := unmarshaler{} return &v }, diff --git a/libgo/go/encoding/json/encode.go b/libgo/go/encoding/json/encode.go index e473e615a9e..1f5e3e446a9 100644 --- a/libgo/go/encoding/json/encode.go +++ b/libgo/go/encoding/json/encode.go @@ -155,7 +155,7 @@ import ( // handle them. Passing cyclic structures to Marshal will result in // an error. // -func Marshal(v interface{}) ([]byte, error) { +func Marshal(v any) ([]byte, error) { e := newEncodeState() err := e.marshal(v, encOpts{escapeHTML: true}) @@ -172,7 +172,7 @@ func Marshal(v interface{}) ([]byte, error) { // MarshalIndent is like Marshal but applies Indent to format the output. // Each JSON element in the output will begin on a new line beginning with prefix // followed by one or more copies of indent according to the indentation nesting. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { +func MarshalIndent(v any, prefix, indent string) ([]byte, error) { b, err := Marshal(v) if err != nil { return nil, err @@ -294,7 +294,7 @@ type encodeState struct { // startDetectingCyclesAfter, so that we skip the work if we're within a // reasonable amount of nested pointers deep. ptrLevel uint - ptrSeen map[interface{}]struct{} + ptrSeen map[any]struct{} } const startDetectingCyclesAfter = 1000 @@ -311,7 +311,7 @@ func newEncodeState() *encodeState { e.ptrLevel = 0 return e } - return &encodeState{ptrSeen: make(map[interface{}]struct{})} + return &encodeState{ptrSeen: make(map[any]struct{})} } // jsonError is an error wrapper type for internal use only. @@ -319,7 +319,7 @@ func newEncodeState() *encodeState { // can distinguish intentional panics from this package. type jsonError struct{ error } -func (e *encodeState) marshal(v interface{}, opts encOpts) (err error) { +func (e *encodeState) marshal(v any, opts encOpts) (err error) { defer func() { if r := recover(); r != nil { if je, ok := r.(jsonError); ok { @@ -350,7 +350,7 @@ func isEmptyValue(v reflect.Value) bool { return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 - case reflect.Interface, reflect.Ptr: + case reflect.Interface, reflect.Pointer: return v.IsNil() } return false @@ -419,13 +419,13 @@ func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc { // Marshaler with a value receiver, then we're better off taking // the address of the value - otherwise we end up with an // allocation as we cast the value to an interface. - if t.Kind() != reflect.Ptr && allowAddr && reflect.PtrTo(t).Implements(marshalerType) { + if t.Kind() != reflect.Pointer && allowAddr && reflect.PointerTo(t).Implements(marshalerType) { return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false)) } if t.Implements(marshalerType) { return marshalerEncoder } - if t.Kind() != reflect.Ptr && allowAddr && reflect.PtrTo(t).Implements(textMarshalerType) { + if t.Kind() != reflect.Pointer && allowAddr && reflect.PointerTo(t).Implements(textMarshalerType) { return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false)) } if t.Implements(textMarshalerType) { @@ -455,7 +455,7 @@ func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc { return newSliceEncoder(t) case reflect.Array: return newArrayEncoder(t) - case reflect.Ptr: + case reflect.Pointer: return newPtrEncoder(t) default: return unsupportedTypeEncoder @@ -467,7 +467,7 @@ func invalidValueEncoder(e *encodeState, v reflect.Value, _ encOpts) { } func marshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { - if v.Kind() == reflect.Ptr && v.IsNil() { + if v.Kind() == reflect.Pointer && v.IsNil() { e.WriteString("null") return } @@ -504,7 +504,7 @@ func addrMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { } func textMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { - if v.Kind() == reflect.Ptr && v.IsNil() { + if v.Kind() == reflect.Pointer && v.IsNil() { e.WriteString("null") return } @@ -738,7 +738,7 @@ FieldLoop: // Find the nested struct field by following f.index. fv := v for _, i := range f.index { - if fv.Kind() == reflect.Ptr { + if fv.Kind() == reflect.Pointer { if fv.IsNil() { continue FieldLoop } @@ -893,7 +893,7 @@ func (se sliceEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { func newSliceEncoder(t reflect.Type) encoderFunc { // Byte slices get special treatment; arrays don't. if t.Elem().Kind() == reflect.Uint8 { - p := reflect.PtrTo(t.Elem()) + p := reflect.PointerTo(t.Elem()) if !p.Implements(marshalerType) && !p.Implements(textMarshalerType) { return encodeByteSlice } @@ -989,7 +989,7 @@ func isValidTag(s string) bool { func typeByIndex(t reflect.Type, index []int) reflect.Type { for _, i := range index { - if t.Kind() == reflect.Ptr { + if t.Kind() == reflect.Pointer { t = t.Elem() } t = t.Field(i).Type @@ -1009,7 +1009,7 @@ func (w *reflectWithString) resolve() error { return nil } if tm, ok := w.k.Interface().(encoding.TextMarshaler); ok { - if w.k.Kind() == reflect.Ptr && w.k.IsNil() { + if w.k.Kind() == reflect.Pointer && w.k.IsNil() { return nil } buf, err := tm.MarshalText() @@ -1243,7 +1243,7 @@ func typeFields(t reflect.Type) structFields { sf := f.typ.Field(i) if sf.Anonymous { t := sf.Type - if t.Kind() == reflect.Ptr { + if t.Kind() == reflect.Pointer { t = t.Elem() } if !sf.IsExported() && t.Kind() != reflect.Struct { @@ -1269,7 +1269,7 @@ func typeFields(t reflect.Type) structFields { index[len(f.index)] = i ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { + if ft.Name() == "" && ft.Kind() == reflect.Pointer { // Follow pointer. ft = ft.Elem() } diff --git a/libgo/go/encoding/json/encode_test.go b/libgo/go/encoding/json/encode_test.go index 0dad9510952..0b021f00749 100644 --- a/libgo/go/encoding/json/encode_test.go +++ b/libgo/go/encoding/json/encode_test.go @@ -28,8 +28,8 @@ type Optionals struct { Slr []string `json:"slr,random"` Slo []string `json:"slo,omitempty"` - Mr map[string]interface{} `json:"mr"` - Mo map[string]interface{} `json:",omitempty"` + Mr map[string]any `json:"mr"` + Mo map[string]any `json:",omitempty"` Fr float64 `json:"fr"` Fo float64 `json:"fo,omitempty"` @@ -59,8 +59,8 @@ var optionalsExpected = `{ func TestOmitEmpty(t *testing.T) { var o Optionals o.Sw = "something" - o.Mr = map[string]interface{}{} - o.Mo = map[string]interface{}{} + o.Mr = map[string]any{} + o.Mo = map[string]any{} got, err := MarshalIndent(&o, "", " ") if err != nil { @@ -180,16 +180,16 @@ type PointerCycle struct { var pointerCycle = &PointerCycle{} type PointerCycleIndirect struct { - Ptrs []interface{} + Ptrs []any } type RecursiveSlice []RecursiveSlice var ( pointerCycleIndirect = &PointerCycleIndirect{} - mapCycle = make(map[string]interface{}) - sliceCycle = []interface{}{nil} - sliceNoCycle = []interface{}{nil, nil} + mapCycle = make(map[string]any) + sliceCycle = []any{nil} + sliceNoCycle = []any{nil, nil} recursiveSliceCycle = []RecursiveSlice{nil} ) @@ -199,13 +199,13 @@ func init() { samePointerNoCycle.Ptr2 = ptr pointerCycle.Ptr = pointerCycle - pointerCycleIndirect.Ptrs = []interface{}{pointerCycleIndirect} + pointerCycleIndirect.Ptrs = []any{pointerCycleIndirect} mapCycle["x"] = mapCycle sliceCycle[0] = sliceCycle sliceNoCycle[1] = sliceNoCycle[:1] for i := startDetectingCyclesAfter; i > 0; i-- { - sliceNoCycle = []interface{}{sliceNoCycle} + sliceNoCycle = []any{sliceNoCycle} } recursiveSliceCycle[0] = recursiveSliceCycle } @@ -222,7 +222,7 @@ func TestSliceNoCycle(t *testing.T) { } } -var unsupportedValues = []interface{}{ +var unsupportedValues = []any{ math.NaN(), math.Inf(-1), math.Inf(1), @@ -367,15 +367,15 @@ func TestMarshalerEscaping(t *testing.T) { func TestAnonymousFields(t *testing.T) { tests := []struct { - label string // Test name - makeInput func() interface{} // Function to create input value - want string // Expected JSON output + label string // Test name + makeInput func() any // Function to create input value + want string // Expected JSON output }{{ // Both S1 and S2 have a field named X. From the perspective of S, // it is ambiguous which one X refers to. // This should not serialize either field. label: "AmbiguousField", - makeInput: func() interface{} { + makeInput: func() any { type ( S1 struct{ x, X int } S2 struct{ x, X int } @@ -391,7 +391,7 @@ func TestAnonymousFields(t *testing.T) { label: "DominantField", // Both S1 and S2 have a field named X, but since S has an X field as // well, it takes precedence over S1.X and S2.X. - makeInput: func() interface{} { + makeInput: func() any { type ( S1 struct{ x, X int } S2 struct{ x, X int } @@ -407,7 +407,7 @@ func TestAnonymousFields(t *testing.T) { }, { // Unexported embedded field of non-struct type should not be serialized. label: "UnexportedEmbeddedInt", - makeInput: func() interface{} { + makeInput: func() any { type ( myInt int S struct{ myInt } @@ -418,7 +418,7 @@ func TestAnonymousFields(t *testing.T) { }, { // Exported embedded field of non-struct type should be serialized. label: "ExportedEmbeddedInt", - makeInput: func() interface{} { + makeInput: func() any { type ( MyInt int S struct{ MyInt } @@ -430,7 +430,7 @@ func TestAnonymousFields(t *testing.T) { // Unexported embedded field of pointer to non-struct type // should not be serialized. label: "UnexportedEmbeddedIntPointer", - makeInput: func() interface{} { + makeInput: func() any { type ( myInt int S struct{ *myInt } @@ -444,7 +444,7 @@ func TestAnonymousFields(t *testing.T) { // Exported embedded field of pointer to non-struct type // should be serialized. label: "ExportedEmbeddedIntPointer", - makeInput: func() interface{} { + makeInput: func() any { type ( MyInt int S struct{ *MyInt } @@ -459,7 +459,7 @@ func TestAnonymousFields(t *testing.T) { // exported fields be serialized regardless of whether the struct types // themselves are exported. label: "EmbeddedStruct", - makeInput: func() interface{} { + makeInput: func() any { type ( s1 struct{ x, X int } S2 struct{ y, Y int } @@ -476,7 +476,7 @@ func TestAnonymousFields(t *testing.T) { // exported fields be serialized regardless of whether the struct types // themselves are exported. label: "EmbeddedStructPointer", - makeInput: func() interface{} { + makeInput: func() any { type ( s1 struct{ x, X int } S2 struct{ y, Y int } @@ -492,7 +492,7 @@ func TestAnonymousFields(t *testing.T) { // Exported fields on embedded unexported structs at multiple levels // of nesting should still be serialized. label: "NestedStructAndInts", - makeInput: func() interface{} { + makeInput: func() any { type ( MyInt1 int MyInt2 int @@ -519,7 +519,7 @@ func TestAnonymousFields(t *testing.T) { // the embedded fields behind it. Not properly doing so may // result in the wrong output or reflect panics. label: "EmbeddedFieldBehindNilPointer", - makeInput: func() interface{} { + makeInput: func() any { type ( S2 struct{ Field string } S struct{ *S2 } @@ -589,22 +589,22 @@ func (nm *nilTextMarshaler) MarshalText() ([]byte, error) { // See golang.org/issue/16042 and golang.org/issue/34235. func TestNilMarshal(t *testing.T) { testCases := []struct { - v interface{} + v any want string }{ {v: nil, want: `null`}, {v: new(float64), want: `0`}, - {v: []interface{}(nil), want: `null`}, + {v: []any(nil), want: `null`}, {v: []string(nil), want: `null`}, {v: map[string]string(nil), want: `null`}, {v: []byte(nil), want: `null`}, {v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`}, {v: struct{ M Marshaler }{}, want: `{"M":null}`}, {v: struct{ M Marshaler }{(*nilJSONMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, - {v: struct{ M interface{} }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`}, + {v: struct{ M any }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`}, {v: struct{ M encoding.TextMarshaler }{}, want: `{"M":null}`}, {v: struct{ M encoding.TextMarshaler }{(*nilTextMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, - {v: struct{ M interface{} }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`}, + {v: struct{ M any }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`}, } for _, tt := range testCases { @@ -864,7 +864,7 @@ type textint int func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) } -func tenc(format string, a ...interface{}) ([]byte, error) { +func tenc(format string, a ...any) ([]byte, error) { var buf bytes.Buffer fmt.Fprintf(&buf, format, a...) return buf.Bytes(), nil @@ -877,7 +877,7 @@ func (f textfloat) MarshalText() ([]byte, error) { return tenc(`TF:%0.2f`, f) } // Issue 13783 func TestEncodeBytekind(t *testing.T) { testdata := []struct { - data interface{} + data any want string }{ {byte(7), "7"}, @@ -966,7 +966,7 @@ func TestMarshalFloat(t *testing.T) { t.Parallel() nfail := 0 test := func(f float64, bits int) { - vf := interface{}(f) + vf := any(f) if bits == 32 { f = float64(float32(f)) // round vf = float32(f) @@ -1062,25 +1062,25 @@ func TestMarshalRawMessageValue(t *testing.T) { ) tests := []struct { - in interface{} + in any want string ok bool }{ // Test with nil RawMessage. {rawNil, "null", true}, {&rawNil, "null", true}, - {[]interface{}{rawNil}, "[null]", true}, - {&[]interface{}{rawNil}, "[null]", true}, - {[]interface{}{&rawNil}, "[null]", true}, - {&[]interface{}{&rawNil}, "[null]", true}, + {[]any{rawNil}, "[null]", true}, + {&[]any{rawNil}, "[null]", true}, + {[]any{&rawNil}, "[null]", true}, + {&[]any{&rawNil}, "[null]", true}, {struct{ M RawMessage }{rawNil}, `{"M":null}`, true}, {&struct{ M RawMessage }{rawNil}, `{"M":null}`, true}, {struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true}, {&struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true}, - {map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, - {&map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, - {map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, - {&map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, + {map[string]any{"M": rawNil}, `{"M":null}`, true}, + {&map[string]any{"M": rawNil}, `{"M":null}`, true}, + {map[string]any{"M": &rawNil}, `{"M":null}`, true}, + {&map[string]any{"M": &rawNil}, `{"M":null}`, true}, {T1{rawNil}, "{}", true}, {T2{&rawNil}, `{"M":null}`, true}, {&T1{rawNil}, "{}", true}, @@ -1089,18 +1089,18 @@ func TestMarshalRawMessageValue(t *testing.T) { // Test with empty, but non-nil, RawMessage. {rawEmpty, "", false}, {&rawEmpty, "", false}, - {[]interface{}{rawEmpty}, "", false}, - {&[]interface{}{rawEmpty}, "", false}, - {[]interface{}{&rawEmpty}, "", false}, - {&[]interface{}{&rawEmpty}, "", false}, + {[]any{rawEmpty}, "", false}, + {&[]any{rawEmpty}, "", false}, + {[]any{&rawEmpty}, "", false}, + {&[]any{&rawEmpty}, "", false}, {struct{ X RawMessage }{rawEmpty}, "", false}, {&struct{ X RawMessage }{rawEmpty}, "", false}, {struct{ X *RawMessage }{&rawEmpty}, "", false}, {&struct{ X *RawMessage }{&rawEmpty}, "", false}, - {map[string]interface{}{"nil": rawEmpty}, "", false}, - {&map[string]interface{}{"nil": rawEmpty}, "", false}, - {map[string]interface{}{"nil": &rawEmpty}, "", false}, - {&map[string]interface{}{"nil": &rawEmpty}, "", false}, + {map[string]any{"nil": rawEmpty}, "", false}, + {&map[string]any{"nil": rawEmpty}, "", false}, + {map[string]any{"nil": &rawEmpty}, "", false}, + {&map[string]any{"nil": &rawEmpty}, "", false}, {T1{rawEmpty}, "{}", true}, {T2{&rawEmpty}, "", false}, {&T1{rawEmpty}, "{}", true}, @@ -1113,18 +1113,18 @@ func TestMarshalRawMessageValue(t *testing.T) { // See https://golang.org/issues/14493#issuecomment-255857318 {rawText, `"foo"`, true}, // Issue6458 {&rawText, `"foo"`, true}, - {[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 - {&[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 - {[]interface{}{&rawText}, `["foo"]`, true}, - {&[]interface{}{&rawText}, `["foo"]`, true}, + {[]any{rawText}, `["foo"]`, true}, // Issue6458 + {&[]any{rawText}, `["foo"]`, true}, // Issue6458 + {[]any{&rawText}, `["foo"]`, true}, + {&[]any{&rawText}, `["foo"]`, true}, {struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458 {&struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, {struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true}, {&struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true}, - {map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 - {&map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 - {map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, - {&map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, + {map[string]any{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 + {&map[string]any{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 + {map[string]any{"M": &rawText}, `{"M":"foo"}`, true}, + {&map[string]any{"M": &rawText}, `{"M":"foo"}`, true}, {T1{rawText}, `{"M":"foo"}`, true}, // Issue6458 {T2{&rawText}, `{"M":"foo"}`, true}, {&T1{rawText}, `{"M":"foo"}`, true}, diff --git a/libgo/go/encoding/json/fuzz.go b/libgo/go/encoding/json/fuzz.go index d3fa2d11138..b8f4ff2c1d6 100644 --- a/libgo/go/encoding/json/fuzz.go +++ b/libgo/go/encoding/json/fuzz.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gofuzz -// +build gofuzz package json @@ -12,10 +11,10 @@ import ( ) func Fuzz(data []byte) (score int) { - for _, ctor := range []func() interface{}{ - func() interface{} { return new(interface{}) }, - func() interface{} { return new(map[string]interface{}) }, - func() interface{} { return new([]interface{}) }, + for _, ctor := range []func() any{ + func() any { return new(any) }, + func() any { return new(map[string]any) }, + func() any { return new([]any) }, } { v := ctor() err := Unmarshal(data, v) diff --git a/libgo/go/encoding/json/fuzz_test.go b/libgo/go/encoding/json/fuzz_test.go new file mode 100644 index 00000000000..778664c3e57 --- /dev/null +++ b/libgo/go/encoding/json/fuzz_test.go @@ -0,0 +1,83 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "bytes" + "io" + "testing" +) + +func FuzzUnmarshalJSON(f *testing.F) { + f.Add([]byte(`{ +"object": { + "slice": [ + 1, + 2.0, + "3", + [4], + {5: {}} + ] +}, +"slice": [[]], +"string": ":)", +"int": 1e5, +"float": 3e-9" +}`)) + + f.Fuzz(func(t *testing.T, b []byte) { + for _, typ := range []func() interface{}{ + func() interface{} { return new(interface{}) }, + func() interface{} { return new(map[string]interface{}) }, + func() interface{} { return new([]interface{}) }, + } { + i := typ() + if err := Unmarshal(b, i); err != nil { + return + } + + encoded, err := Marshal(i) + if err != nil { + t.Fatalf("failed to marshal: %s", err) + } + + if err := Unmarshal(encoded, i); err != nil { + t.Fatalf("failed to roundtrip: %s", err) + } + } + }) +} + +func FuzzDecoderToken(f *testing.F) { + f.Add([]byte(`{ +"object": { + "slice": [ + 1, + 2.0, + "3", + [4], + {5: {}} + ] +}, +"slice": [[]], +"string": ":)", +"int": 1e5, +"float": 3e-9" +}`)) + + f.Fuzz(func(t *testing.T, b []byte) { + r := bytes.NewReader(b) + d := NewDecoder(r) + for { + _, err := d.Token() + if err != nil { + if err == io.EOF { + break + } + return + } + } + }) +} diff --git a/libgo/go/encoding/json/scanner.go b/libgo/go/encoding/json/scanner.go index 9dc1903e2db..dbaa821becc 100644 --- a/libgo/go/encoding/json/scanner.go +++ b/libgo/go/encoding/json/scanner.go @@ -83,7 +83,7 @@ type scanner struct { } var scannerPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &scanner{} }, } diff --git a/libgo/go/encoding/json/scanner_test.go b/libgo/go/encoding/json/scanner_test.go index 3737516a450..3474b3e4810 100644 --- a/libgo/go/encoding/json/scanner_test.go +++ b/libgo/go/encoding/json/scanner_test.go @@ -237,7 +237,7 @@ func initBig() { jsonBig = b } -func genValue(n int) interface{} { +func genValue(n int) any { if n > 1 { switch rand.Intn(2) { case 0: @@ -270,7 +270,7 @@ func genString(stddev float64) string { return string(c) } -func genArray(n int) []interface{} { +func genArray(n int) []any { f := int(math.Abs(rand.NormFloat64()) * math.Min(10, float64(n/2))) if f > n { f = n @@ -278,14 +278,14 @@ func genArray(n int) []interface{} { if f < 1 { f = 1 } - x := make([]interface{}, f) + x := make([]any, f) for i := range x { x[i] = genValue(((i+1)*n)/f - (i*n)/f) } return x } -func genMap(n int) map[string]interface{} { +func genMap(n int) map[string]any { f := int(math.Abs(rand.NormFloat64()) * math.Min(10, float64(n/2))) if f > n { f = n @@ -293,7 +293,7 @@ func genMap(n int) map[string]interface{} { if n > 0 && f == 0 { f = 1 } - x := make(map[string]interface{}) + x := make(map[string]any) for i := 0; i < f; i++ { x[genString(10)] = genValue(((i+1)*n)/f - (i*n)/f) } diff --git a/libgo/go/encoding/json/stream.go b/libgo/go/encoding/json/stream.go index 81f404f4267..6362170d5df 100644 --- a/libgo/go/encoding/json/stream.go +++ b/libgo/go/encoding/json/stream.go @@ -46,7 +46,7 @@ func (dec *Decoder) DisallowUnknownFields() { dec.d.disallowUnknownFields = true // // See the documentation for Unmarshal for details about // the conversion of JSON into a Go value. -func (dec *Decoder) Decode(v interface{}) error { +func (dec *Decoder) Decode(v any) error { if dec.err != nil { return dec.err } @@ -198,7 +198,7 @@ func NewEncoder(w io.Writer) *Encoder { // // See the documentation for Marshal for details about the // conversion of Go values to JSON. -func (enc *Encoder) Encode(v interface{}) error { +func (enc *Encoder) Encode(v any) error { if enc.err != nil { return enc.err } @@ -288,7 +288,7 @@ var _ Unmarshaler = (*RawMessage)(nil) // string, for JSON string literals // nil, for JSON null // -type Token interface{} +type Token any const ( tokenTopValue = iota @@ -452,7 +452,7 @@ func (dec *Decoder) Token() (Token, error) { if !dec.tokenValueAllowed() { return dec.tokenError(c) } - var x interface{} + var x any if err := dec.Decode(&x); err != nil { return nil, err } diff --git a/libgo/go/encoding/json/stream_test.go b/libgo/go/encoding/json/stream_test.go index c284f2d9650..0e156d98e94 100644 --- a/libgo/go/encoding/json/stream_test.go +++ b/libgo/go/encoding/json/stream_test.go @@ -18,14 +18,14 @@ import ( // Test values for the stream test. // One of each JSON kind. -var streamTest = []interface{}{ +var streamTest = []any{ 0.1, "hello", nil, true, false, - []interface{}{"a", "b", "c"}, - map[string]interface{}{"K": "Kelvin", "ß": "long s"}, + []any{"a", "b", "c"}, + map[string]any{"K": "Kelvin", "ß": "long s"}, 3.14, // another value to make sure something can follow map } @@ -124,7 +124,7 @@ func TestEncoderSetEscapeHTML(t *testing.T) { for _, tt := range []struct { name string - v interface{} + v any wantEscape string want string }{ @@ -182,7 +182,7 @@ func TestDecoder(t *testing.T) { buf.WriteRune(c) } } - out := make([]interface{}, i) + out := make([]any, i) dec := NewDecoder(&buf) for j := range out { if err := dec.Decode(&out[j]); err != nil { @@ -297,7 +297,7 @@ func TestBlocking(t *testing.T) { for _, enc := range blockingTests { r, w := net.Pipe() go w.Write([]byte(enc)) - var val interface{} + var val any // If Decode reads beyond what w.Write writes above, // it will block, and the test will deadlock. @@ -326,80 +326,80 @@ func BenchmarkEncoderEncode(b *testing.B) { type tokenStreamCase struct { json string - expTokens []interface{} + expTokens []any } type decodeThis struct { - v interface{} + v any } var tokenStreamCases = []tokenStreamCase{ // streaming token cases - {json: `10`, expTokens: []interface{}{float64(10)}}, - {json: ` [10] `, expTokens: []interface{}{ + {json: `10`, expTokens: []any{float64(10)}}, + {json: ` [10] `, expTokens: []any{ Delim('['), float64(10), Delim(']')}}, - {json: ` [false,10,"b"] `, expTokens: []interface{}{ + {json: ` [false,10,"b"] `, expTokens: []any{ Delim('['), false, float64(10), "b", Delim(']')}}, - {json: `{ "a": 1 }`, expTokens: []interface{}{ + {json: `{ "a": 1 }`, expTokens: []any{ Delim('{'), "a", float64(1), Delim('}')}}, - {json: `{"a": 1, "b":"3"}`, expTokens: []interface{}{ + {json: `{"a": 1, "b":"3"}`, expTokens: []any{ Delim('{'), "a", float64(1), "b", "3", Delim('}')}}, - {json: ` [{"a": 1},{"a": 2}] `, expTokens: []interface{}{ + {json: ` [{"a": 1},{"a": 2}] `, expTokens: []any{ Delim('['), Delim('{'), "a", float64(1), Delim('}'), Delim('{'), "a", float64(2), Delim('}'), Delim(']')}}, - {json: `{"obj": {"a": 1}}`, expTokens: []interface{}{ + {json: `{"obj": {"a": 1}}`, expTokens: []any{ Delim('{'), "obj", Delim('{'), "a", float64(1), Delim('}'), Delim('}')}}, - {json: `{"obj": [{"a": 1}]}`, expTokens: []interface{}{ + {json: `{"obj": [{"a": 1}]}`, expTokens: []any{ Delim('{'), "obj", Delim('['), Delim('{'), "a", float64(1), Delim('}'), Delim(']'), Delim('}')}}, // streaming tokens with intermittent Decode() - {json: `{ "a": 1 }`, expTokens: []interface{}{ + {json: `{ "a": 1 }`, expTokens: []any{ Delim('{'), "a", decodeThis{float64(1)}, Delim('}')}}, - {json: ` [ { "a" : 1 } ] `, expTokens: []interface{}{ + {json: ` [ { "a" : 1 } ] `, expTokens: []any{ Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, + decodeThis{map[string]any{"a": float64(1)}}, Delim(']')}}, - {json: ` [{"a": 1},{"a": 2}] `, expTokens: []interface{}{ + {json: ` [{"a": 1},{"a": 2}] `, expTokens: []any{ Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, - decodeThis{map[string]interface{}{"a": float64(2)}}, + decodeThis{map[string]any{"a": float64(1)}}, + decodeThis{map[string]any{"a": float64(2)}}, Delim(']')}}, - {json: `{ "obj" : [ { "a" : 1 } ] }`, expTokens: []interface{}{ + {json: `{ "obj" : [ { "a" : 1 } ] }`, expTokens: []any{ Delim('{'), "obj", Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, + decodeThis{map[string]any{"a": float64(1)}}, Delim(']'), Delim('}')}}, - {json: `{"obj": {"a": 1}}`, expTokens: []interface{}{ + {json: `{"obj": {"a": 1}}`, expTokens: []any{ Delim('{'), "obj", - decodeThis{map[string]interface{}{"a": float64(1)}}, + decodeThis{map[string]any{"a": float64(1)}}, Delim('}')}}, - {json: `{"obj": [{"a": 1}]}`, expTokens: []interface{}{ + {json: `{"obj": [{"a": 1}]}`, expTokens: []any{ Delim('{'), "obj", - decodeThis{[]interface{}{ - map[string]interface{}{"a": float64(1)}, + decodeThis{[]any{ + map[string]any{"a": float64(1)}, }}, Delim('}')}}, - {json: ` [{"a": 1} {"a": 2}] `, expTokens: []interface{}{ + {json: ` [{"a": 1} {"a": 2}] `, expTokens: []any{ Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, + decodeThis{map[string]any{"a": float64(1)}}, decodeThis{&SyntaxError{"expected comma after array element", 11}}, }}, - {json: `{ "` + strings.Repeat("a", 513) + `" 1 }`, expTokens: []interface{}{ + {json: `{ "` + strings.Repeat("a", 513) + `" 1 }`, expTokens: []any{ Delim('{'), strings.Repeat("a", 513), decodeThis{&SyntaxError{"expected colon after object key", 518}}, }}, - {json: `{ "\a" }`, expTokens: []interface{}{ + {json: `{ "\a" }`, expTokens: []any{ Delim('{'), &SyntaxError{"invalid character 'a' in string escape code", 3}, }}, - {json: ` \a`, expTokens: []interface{}{ + {json: ` \a`, expTokens: []any{ &SyntaxError{"invalid character '\\\\' looking for beginning of value", 1}, }}, } @@ -410,7 +410,7 @@ func TestDecodeInStream(t *testing.T) { dec := NewDecoder(strings.NewReader(tcase.json)) for i, etk := range tcase.expTokens { - var tk interface{} + var tk any var err error if dt, ok := etk.(decodeThis); ok { diff --git a/libgo/go/encoding/json/tagkey_test.go b/libgo/go/encoding/json/tagkey_test.go index bbb4e6a28d2..6330efd3c21 100644 --- a/libgo/go/encoding/json/tagkey_test.go +++ b/libgo/go/encoding/json/tagkey_test.go @@ -73,7 +73,7 @@ type unicodeTag struct { } var structTagObjectKeyTests = []struct { - raw interface{} + raw any value string key string }{ @@ -101,12 +101,12 @@ func TestStructTagObjectKey(t *testing.T) { if err != nil { t.Fatalf("Marshal(%#q) failed: %v", tt.raw, err) } - var f interface{} + var f any err = Unmarshal(b, &f) if err != nil { t.Fatalf("Unmarshal(%#q) failed: %v", b, err) } - for i, v := range f.(map[string]interface{}) { + for i, v := range f.(map[string]any) { switch i { case tt.key: if s, ok := v.(string); !ok || s != tt.value { diff --git a/libgo/go/encoding/json/tags.go b/libgo/go/encoding/json/tags.go index c38fd5102f6..b490328f4c4 100644 --- a/libgo/go/encoding/json/tags.go +++ b/libgo/go/encoding/json/tags.go @@ -15,10 +15,8 @@ type tagOptions string // parseTag splits a struct field's json tag into its name and // comma-separated options. func parseTag(tag string) (string, tagOptions) { - if idx := strings.Index(tag, ","); idx != -1 { - return tag[:idx], tagOptions(tag[idx+1:]) - } - return tag, tagOptions("") + tag, opt, _ := strings.Cut(tag, ",") + return tag, tagOptions(opt) } // Contains reports whether a comma-separated list of options @@ -30,15 +28,11 @@ func (o tagOptions) Contains(optionName string) bool { } s := string(o) for s != "" { - var next string - i := strings.Index(s, ",") - if i >= 0 { - s, next = s[:i], s[i+1:] - } - if s == optionName { + var name string + name, s, _ = strings.Cut(s, ",") + if name == optionName { return true } - s = next } return false } diff --git a/libgo/go/encoding/pem/pem.go b/libgo/go/encoding/pem/pem.go index a7272da5ad3..e7adf883823 100644 --- a/libgo/go/encoding/pem/pem.go +++ b/libgo/go/encoding/pem/pem.go @@ -78,6 +78,7 @@ func removeSpacesAndTabs(data []byte) []byte { var pemStart = []byte("\n-----BEGIN ") var pemEnd = []byte("\n-----END ") var pemEndOfLine = []byte("-----") +var colon = []byte(":") // Decode will find the next PEM formatted block (certificate, private key // etc) in the input. It returns that block and the remainder of the input. If @@ -89,8 +90,8 @@ func Decode(data []byte) (p *Block, rest []byte) { rest = data if bytes.HasPrefix(data, pemStart[1:]) { rest = rest[len(pemStart)-1 : len(data)] - } else if i := bytes.Index(data, pemStart); i >= 0 { - rest = rest[i+len(pemStart) : len(data)] + } else if _, after, ok := bytes.Cut(data, pemStart); ok { + rest = after } else { return nil, data } @@ -114,13 +115,12 @@ func Decode(data []byte) (p *Block, rest []byte) { } line, next := getLine(rest) - i := bytes.IndexByte(line, ':') - if i == -1 { + key, val, ok := bytes.Cut(line, colon) + if !ok { break } // TODO(agl): need to cope with values that spread across lines. - key, val := line[:i], line[i+1:] key = bytes.TrimSpace(key) val = bytes.TrimSpace(val) p.Headers[string(key)] = string(val) diff --git a/libgo/go/encoding/xml/marshal.go b/libgo/go/encoding/xml/marshal.go index d8a04a95a25..6859be04a22 100644 --- a/libgo/go/encoding/xml/marshal.go +++ b/libgo/go/encoding/xml/marshal.go @@ -76,7 +76,7 @@ const ( // See MarshalIndent for an example. // // Marshal will return an error if asked to marshal a channel, function, or map. -func Marshal(v interface{}) ([]byte, error) { +func Marshal(v any) ([]byte, error) { var b bytes.Buffer if err := NewEncoder(&b).Encode(v); err != nil { return nil, err @@ -122,7 +122,7 @@ type MarshalerAttr interface { // MarshalIndent works like Marshal, but each XML element begins on a new // indented line that starts with prefix and is followed by one or more // copies of indent according to the nesting depth. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { +func MarshalIndent(v any, prefix, indent string) ([]byte, error) { var b bytes.Buffer enc := NewEncoder(&b) enc.Indent(prefix, indent) @@ -158,7 +158,7 @@ func (enc *Encoder) Indent(prefix, indent string) { // of Go values to XML. // // Encode calls Flush before returning. -func (enc *Encoder) Encode(v interface{}) error { +func (enc *Encoder) Encode(v any) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil) if err != nil { return err @@ -173,7 +173,7 @@ func (enc *Encoder) Encode(v interface{}) error { // of Go values to XML. // // EncodeElement calls Flush before returning. -func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error { +func (enc *Encoder) EncodeElement(v any, start StartElement) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start) if err != nil { return err @@ -420,7 +420,7 @@ func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplat // Drill into interfaces and pointers. // This can turn into an infinite loop given a cyclic chain, // but it matches the Go 1 behavior. - for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { + for val.Kind() == reflect.Interface || val.Kind() == reflect.Pointer { if val.IsNil() { return nil } @@ -494,6 +494,10 @@ func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplat } if start.Name.Local == "" { name := typ.Name() + if i := strings.IndexByte(name, '['); i >= 0 { + // Truncate generic instantiation name. See issue 48318. + name = name[:i] + } if name == "" { return &UnsupportedTypeError{typ} } @@ -599,7 +603,7 @@ func (p *printer) marshalAttr(start *StartElement, name Name, val reflect.Value) // Dereference or skip nil pointer, interface values. switch val.Kind() { - case reflect.Ptr, reflect.Interface: + case reflect.Pointer, reflect.Interface: if val.IsNil() { return nil } @@ -793,7 +797,7 @@ var ddBytes = []byte("--") // This can turn into an infinite loop given a cyclic chain, // but it matches the Go 1 behavior. func indirect(vf reflect.Value) reflect.Value { - for vf.Kind() == reflect.Interface || vf.Kind() == reflect.Ptr { + for vf.Kind() == reflect.Interface || vf.Kind() == reflect.Pointer { if vf.IsNil() { return vf } @@ -942,7 +946,7 @@ func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error { return err } if len(finfo.parents) > len(s.stack) { - if vf.Kind() != reflect.Ptr && vf.Kind() != reflect.Interface || !vf.IsNil() { + if vf.Kind() != reflect.Pointer && vf.Kind() != reflect.Interface || !vf.IsNil() { if err := s.push(finfo.parents[len(s.stack):]); err != nil { return err } @@ -1051,7 +1055,7 @@ func isEmptyValue(v reflect.Value) bool { return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 - case reflect.Interface, reflect.Ptr: + case reflect.Interface, reflect.Pointer: return v.IsNil() } return false diff --git a/libgo/go/encoding/xml/marshal_test.go b/libgo/go/encoding/xml/marshal_test.go index d2e5137afd7..115a93f152b 100644 --- a/libgo/go/encoding/xml/marshal_test.go +++ b/libgo/go/encoding/xml/marshal_test.go @@ -120,17 +120,17 @@ type MixedNested struct { } type NilTest struct { - A interface{} `xml:"parent1>parent2>a"` - B interface{} `xml:"parent1>b"` - C interface{} `xml:"parent1>parent2>c"` + A any `xml:"parent1>parent2>a"` + B any `xml:"parent1>b"` + C any `xml:"parent1>parent2>c"` } type Service struct { XMLName struct{} `xml:"service"` Domain *Domain `xml:"host>domain"` Port *Port `xml:"host>port"` - Extra1 interface{} - Extra2 interface{} `xml:"host>extra2"` + Extra1 any + Extra2 any `xml:"host>extra2"` } var nilStruct *Ship @@ -283,7 +283,7 @@ type Data struct { } type Plain struct { - V interface{} + V any } type MyInt int @@ -387,7 +387,7 @@ type NestedAndCData struct { CDATA string `xml:",cdata"` } -func ifaceptr(x interface{}) interface{} { +func ifaceptr(x any) any { return &x } @@ -412,7 +412,7 @@ type DirectComment struct { type IfaceComment struct { T1 T1 - Comment interface{} `xml:",comment"` + Comment any `xml:",comment"` T2 T2 } @@ -430,7 +430,7 @@ type DirectChardata struct { type IfaceChardata struct { T1 T1 - Chardata interface{} `xml:",chardata"` + Chardata any `xml:",chardata"` T2 T2 } @@ -448,7 +448,7 @@ type DirectCDATA struct { type IfaceCDATA struct { T1 T1 - CDATA interface{} `xml:",cdata"` + CDATA any `xml:",cdata"` T2 T2 } @@ -466,7 +466,7 @@ type DirectInnerXML struct { type IfaceInnerXML struct { T1 T1 - InnerXML interface{} `xml:",innerxml"` + InnerXML any `xml:",innerxml"` T2 T2 } @@ -484,7 +484,7 @@ type DirectElement struct { type IfaceElement struct { T1 T1 - Element interface{} + Element any T2 T2 } @@ -502,7 +502,7 @@ type DirectOmitEmpty struct { type IfaceOmitEmpty struct { T1 T1 - OmitEmpty interface{} `xml:",omitempty"` + OmitEmpty any `xml:",omitempty"` T2 T2 } @@ -520,10 +520,18 @@ type DirectAny struct { type IfaceAny struct { T1 T1 - Any interface{} `xml:",any"` + Any any `xml:",any"` T2 T2 } +/* FIXME: Commented out for gofrontend. + +type Generic[T any] struct { + X T +} + +*/ + var ( nameAttr = "Sarah" ageAttr = uint(12) @@ -536,7 +544,7 @@ var ( // please try to make them two-way as well to ensure that // marshaling and unmarshaling are as symmetrical as feasible. var marshalTests = []struct { - Value interface{} + Value any ExpectXML string MarshalOnly bool MarshalError string @@ -641,6 +649,7 @@ var marshalTests = []struct { {Value: &Particle{HasMass: true}, ExpectXML: `<particle>true</particle>`}, {Value: &Departure{When: ParseTime("2013-01-09T00:15:00-09:00")}, ExpectXML: `<departure>2013-01-09T00:15:00-09:00</departure>`}, {Value: atomValue, ExpectXML: atomXML}, + // {Value: &Generic[int]{1}, ExpectXML: `<Generic><X>1</X></Generic>`}, { Value: &Ship{ Name: "Heart of Gold", @@ -1695,7 +1704,7 @@ type BadAttr struct { } var marshalErrorTests = []struct { - Value interface{} + Value any Err string Kind reflect.Kind }{ @@ -1733,7 +1742,7 @@ var marshalErrorTests = []struct { } var marshalIndentTests = []struct { - Value interface{} + Value any Prefix string Indent string ExpectXML string @@ -1928,7 +1937,7 @@ func BenchmarkUnmarshal(b *testing.B) { func TestStructPointerMarshal(t *testing.T) { type A struct { XMLName string `xml:"a"` - B []interface{} + B []any } type C struct { XMLName Name @@ -2322,7 +2331,7 @@ loop: continue loop } } - errorf := func(f string, a ...interface{}) { + errorf := func(f string, a ...any) { t.Errorf("#%d %s token #%d:%s", i, tt.desc, len(tt.toks)-1, fmt.Sprintf(f, a...)) } switch { diff --git a/libgo/go/encoding/xml/read.go b/libgo/go/encoding/xml/read.go index ef5df3f7f6a..0701e186259 100644 --- a/libgo/go/encoding/xml/read.go +++ b/libgo/go/encoding/xml/read.go @@ -129,13 +129,13 @@ import ( // A missing element or empty attribute value will be unmarshaled as a zero value. // If the field is a slice, a zero value will be appended to the field. Otherwise, the // field will be set to its zero value. -func Unmarshal(data []byte, v interface{}) error { +func Unmarshal(data []byte, v any) error { return NewDecoder(bytes.NewReader(data)).Decode(v) } // Decode works like Unmarshal, except it reads the decoder // stream to find the start element. -func (d *Decoder) Decode(v interface{}) error { +func (d *Decoder) Decode(v any) error { return d.DecodeElement(v, nil) } @@ -143,9 +143,9 @@ func (d *Decoder) Decode(v interface{}) error { // a pointer to the start XML element to decode into v. // It is useful when a client reads some raw XML tokens itself // but also wants to defer to Unmarshal for some elements. -func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error { +func (d *Decoder) DecodeElement(v any, start *StartElement) error { val := reflect.ValueOf(v) - if val.Kind() != reflect.Ptr { + if val.Kind() != reflect.Pointer { return errors.New("non-pointer passed to Unmarshal") } return d.unmarshal(val.Elem(), start) @@ -188,7 +188,7 @@ type UnmarshalerAttr interface { } // receiverType returns the receiver type to use in an expression like "%s.MethodName". -func receiverType(val interface{}) string { +func receiverType(val any) string { t := reflect.TypeOf(val) if t.Name() != "" { return t.String() @@ -244,7 +244,7 @@ func (d *Decoder) unmarshalTextInterface(val encoding.TextUnmarshaler) error { // unmarshalAttr unmarshals a single XML attribute into val. func (d *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error { - if val.Kind() == reflect.Ptr { + if val.Kind() == reflect.Pointer { if val.IsNil() { val.Set(reflect.New(val.Type().Elem())) } @@ -324,12 +324,12 @@ func (d *Decoder) unmarshal(val reflect.Value, start *StartElement) error { // usefully addressable. if val.Kind() == reflect.Interface && !val.IsNil() { e := val.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() { + if e.Kind() == reflect.Pointer && !e.IsNil() { val = e } } - if val.Kind() == reflect.Ptr { + if val.Kind() == reflect.Pointer { if val.IsNil() { val.Set(reflect.New(val.Type().Elem())) } @@ -602,7 +602,7 @@ Loop: func copyValue(dst reflect.Value, src []byte) (err error) { dst0 := dst - if dst.Kind() == reflect.Ptr { + if dst.Kind() == reflect.Pointer { if dst.IsNil() { dst.Set(reflect.New(dst.Type().Elem())) } diff --git a/libgo/go/encoding/xml/read_test.go b/libgo/go/encoding/xml/read_test.go index 8c2e70fa22e..391fe731a80 100644 --- a/libgo/go/encoding/xml/read_test.go +++ b/libgo/go/encoding/xml/read_test.go @@ -270,7 +270,7 @@ type PathTestE struct { Before, After string } -var pathTests = []interface{}{ +var pathTests = []any{ &PathTestA{Items: []PathTestItem{{"A"}, {"D"}}, Before: "1", After: "2"}, &PathTestB{Other: []PathTestItem{{"A"}, {"D"}}, Before: "1", After: "2"}, &PathTestC{Values1: []string{"A", "C", "D"}, Values2: []string{"B"}, Before: "1", After: "2"}, @@ -321,7 +321,7 @@ type BadPathEmbeddedB struct { } var badPathTests = []struct { - v, e interface{} + v, e any }{ {&BadPathTestA{}, &TagPathError{reflect.TypeOf(BadPathTestA{}), "First", "items>item1", "Second", "items"}}, {&BadPathTestB{}, &TagPathError{reflect.TypeOf(BadPathTestB{}), "First", "items>item1", "Second", "items>item1>value"}}, @@ -691,7 +691,7 @@ type Pea struct { } type Pod struct { - Pea interface{} `xml:"Pea"` + Pea any `xml:"Pea"` } // https://golang.org/issue/6836 diff --git a/libgo/go/encoding/xml/typeinfo.go b/libgo/go/encoding/xml/typeinfo.go index 162724ef1a5..6b399b9a0e6 100644 --- a/libgo/go/encoding/xml/typeinfo.go +++ b/libgo/go/encoding/xml/typeinfo.go @@ -67,7 +67,7 @@ func getTypeInfo(typ reflect.Type) (*typeInfo, error) { // For embedded structs, embed its fields. if f.Anonymous { t := f.Type - if t.Kind() == reflect.Ptr { + if t.Kind() == reflect.Pointer { t = t.Elem() } if t.Kind() == reflect.Struct { @@ -115,8 +115,8 @@ func structFieldInfo(typ reflect.Type, f *reflect.StructField) (*fieldInfo, erro // Split the tag from the xml namespace if necessary. tag := f.Tag.Get("xml") - if i := strings.Index(tag, " "); i >= 0 { - finfo.xmlns, tag = tag[:i], tag[i+1:] + if ns, t, ok := strings.Cut(tag, " "); ok { + finfo.xmlns, tag = ns, t } // Parse flags. @@ -229,7 +229,7 @@ func structFieldInfo(typ reflect.Type, f *reflect.StructField) (*fieldInfo, erro // in case it exists and has a valid xml field tag, otherwise // it returns nil. func lookupXMLName(typ reflect.Type) (xmlname *fieldInfo) { - for typ.Kind() == reflect.Ptr { + for typ.Kind() == reflect.Pointer { typ = typ.Elem() } if typ.Kind() != reflect.Struct { @@ -358,7 +358,7 @@ func (finfo *fieldInfo) value(v reflect.Value, shouldInitNilPointers bool) refle for i, x := range finfo.idx { if i > 0 { t := v.Type() - if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct { + if t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.Struct { if v.IsNil() { if !shouldInitNilPointers { return reflect.Value{} diff --git a/libgo/go/encoding/xml/xml.go b/libgo/go/encoding/xml/xml.go index c14954df155..8a0a9c253ad 100644 --- a/libgo/go/encoding/xml/xml.go +++ b/libgo/go/encoding/xml/xml.go @@ -52,7 +52,7 @@ type Attr struct { // A Token is an interface holding one of the token types: // StartElement, EndElement, CharData, Comment, ProcInst, or Directive. -type Token interface{} +type Token any // A StartElement represents an XML start element. type StartElement struct { @@ -1164,11 +1164,11 @@ func (d *Decoder) nsname() (name Name, ok bool) { } if strings.Count(s, ":") > 1 { name.Local = s - } else if i := strings.Index(s, ":"); i < 1 || i > len(s)-2 { + } else if space, local, ok := strings.Cut(s, ":"); !ok || space == "" || local == "" { name.Local = s } else { - name.Space = s[0:i] - name.Local = s[i+1:] + name.Space = space + name.Local = local } return name, true } @@ -2012,25 +2012,26 @@ func emitCDATA(w io.Writer, s []byte) error { if _, err := w.Write(cdataStart); err != nil { return err } + for { - i := bytes.Index(s, cdataEnd) - if i >= 0 && i+len(cdataEnd) <= len(s) { - // Found a nested CDATA directive end. - if _, err := w.Write(s[:i]); err != nil { - return err - } - if _, err := w.Write(cdataEscape); err != nil { - return err - } - i += len(cdataEnd) - } else { - if _, err := w.Write(s); err != nil { - return err - } + before, after, ok := bytes.Cut(s, cdataEnd) + if !ok { break } - s = s[i:] + // Found a nested CDATA directive end. + if _, err := w.Write(before); err != nil { + return err + } + if _, err := w.Write(cdataEscape); err != nil { + return err + } + s = after + } + + if _, err := w.Write(s); err != nil { + return err } + _, err := w.Write(cdataEnd) return err } @@ -2041,20 +2042,16 @@ func procInst(param, s string) string { // TODO: this parsing is somewhat lame and not exact. // It works for all actual cases, though. param = param + "=" - idx := strings.Index(s, param) - if idx == -1 { - return "" - } - v := s[idx+len(param):] + _, v, _ := strings.Cut(s, param) if v == "" { return "" } if v[0] != '\'' && v[0] != '"' { return "" } - idx = strings.IndexRune(v[1:], rune(v[0])) - if idx == -1 { + unquote, _, ok := strings.Cut(v[1:], v[:1]) + if !ok { return "" } - return v[1 : idx+1] + return unquote } |