]> Cypherpunks repositories - gostls13.git/commitdiff
encoding/xml: truncate generic type names
authorKeith Randall <khr@golang.org>
Sat, 11 Sep 2021 13:50:06 +0000 (06:50 -0700)
committerKeith Randall <khr@golang.org>
Tue, 21 Sep 2021 17:25:35 +0000 (17:25 +0000)
xml names can't have any of '[],' in them, which might appear in
generic type names. Truncate at the first '[' so the names are still valid.

Fixes #48318

Change-Id: I110ff4269f763089467e7cf84b0f0c5075fb44b7
Reviewed-on: https://go-review.googlesource.com/c/go/+/349349
Trust: Keith Randall <khr@golang.org>
Run-TryBot: Keith Randall <khr@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
src/encoding/xml/marshal.go
test/typeparam/issue48318.go [new file with mode: 0644]

index d8a04a95a2520fa39b8028dd97f43bef70804aba..a8c8f659caca59ff9367c588ef81730daa395e95 100644 (file)
@@ -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}
                }
diff --git a/test/typeparam/issue48318.go b/test/typeparam/issue48318.go
new file mode 100644 (file)
index 0000000..ae53a28
--- /dev/null
@@ -0,0 +1,33 @@
+// run -gcflags=-G=3
+
+// 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 main
+
+import (
+       "encoding/xml"
+       "fmt"
+)
+
+type A[T, U any] struct {
+       Name T `xml:"name"`
+       Data U `xml:"data"`
+}
+
+func main() {
+       src := &A[string, int]{Name: "name", Data: 1}
+       data, err := xml.Marshal(src)
+       if err != nil {
+               panic(err)
+       }
+       dst := &A[string, int]{}
+       err = xml.Unmarshal(data, dst)
+       if err != nil {
+               panic(err)
+       }
+       if *src != *dst {
+               panic(fmt.Sprintf("wanted %#v got %#v", src, dst))
+       }
+}