Skip to content

Commit cb1f7e8

Browse files
committed
reflect: Fix slice length check in Value.CanConvert.
Upstream uses a conversion to unsafeheader.Slice, which isn't supported by GopherJS. Using Value.Len() is preferrable, since we already override it to provide compatibility. If/when golang/go#48346 gets into the stable release, this patch will no longer be necessary.
1 parent d35909a commit cb1f7e8

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

compiler/natives/src/reflect/reflect.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1270,6 +1270,28 @@ func getJsTag(tag string) string {
12701270
return ""
12711271
}
12721272

1273+
// CanConvert reports whether the value v can be converted to type t. If
1274+
// v.CanConvert(t) returns true then v.Convert(t) will not panic.
1275+
//
1276+
// TODO(nevkontakte): this overlay can be removed after
1277+
// https://github.com/golang/go/pull/48346 is in the lastest stable Go release.
1278+
func (v Value) CanConvert(t Type) bool {
1279+
vt := v.Type()
1280+
if !vt.ConvertibleTo(t) {
1281+
return false
1282+
}
1283+
// Currently the only conversion that is OK in terms of type
1284+
// but that can panic depending on the value is converting
1285+
// from slice to pointer-to-array.
1286+
if vt.Kind() == Slice && t.Kind() == Ptr && t.Elem().Kind() == Array {
1287+
n := t.Elem().Len()
1288+
if n > v.Len() { // Avoiding use of unsafeheader.Slice here.
1289+
return false
1290+
}
1291+
}
1292+
return true
1293+
}
1294+
12731295
func (v Value) Index(i int) Value {
12741296
switch k := v.kind(); k {
12751297
case Array:

0 commit comments

Comments
 (0)