Skip to content

Commit

Permalink
fmtsort: don't out-of-bounds panic if there's a race condition
Browse files Browse the repository at this point in the history
Applied upstream CL 191197 to mapelem.go. Cannot fully port to 1.11,
since MapRange started to be supported in 1.12, but we can still avoid
an index out-of-bounds panic.

Fixes #108.
  • Loading branch information
smasher164 authored and mvdan committed Oct 11, 2020
1 parent c5fd45a commit 9f985d5
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
14 changes: 9 additions & 5 deletions fmtsort/mapelem.go
Expand Up @@ -7,12 +7,16 @@ import "reflect"
const brokenNaNs = false

func mapElems(mapValue reflect.Value) ([]reflect.Value, []reflect.Value) {
key := make([]reflect.Value, mapValue.Len())
value := make([]reflect.Value, len(key))
// Note: this code is arranged to not panic even in the presence
// of a concurrent map update. The runtime is responsible for
// yelling loudly if that happens. See issue 33275.
n := mapValue.Len()
key := make([]reflect.Value, 0, n)
value := make([]reflect.Value, 0, n)
iter := mapValue.MapRange()
for i := 0; iter.Next(); i++ {
key[i] = iter.Key()
value[i] = iter.Value()
for iter.Next() {
key = append(key, iter.Key())
value = append(value, iter.Value())
}
return key, value
}
6 changes: 3 additions & 3 deletions fmtsort/mapelem_1.11.go
Expand Up @@ -8,16 +8,16 @@ const brokenNaNs = true

func mapElems(mapValue reflect.Value) ([]reflect.Value, []reflect.Value) {
key := mapValue.MapKeys()
value := make([]reflect.Value, len(key))
for i, k := range key {
value := make([]reflect.Value, 0, len(key))
for _, k := range key {
v := mapValue.MapIndex(k)
if !v.IsValid() {
// Note: we can't retrieve the value, probably because
// the key is NaN, so just do the best we can and
// add a zero value of the correct type in that case.
v = reflect.Zero(mapValue.Type().Elem())
}
value[i] = v
value = append(value, v)
}
return key, value
}

0 comments on commit 9f985d5

Please sign in to comment.