Skip to content

Commit 9f985d5

Browse files
smasher164mvdan
authored andcommitted
fmtsort: don't out-of-bounds panic if there's a race condition
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.
1 parent c5fd45a commit 9f985d5

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

fmtsort/mapelem.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,16 @@ import "reflect"
77
const brokenNaNs = false
88

99
func mapElems(mapValue reflect.Value) ([]reflect.Value, []reflect.Value) {
10-
key := make([]reflect.Value, mapValue.Len())
11-
value := make([]reflect.Value, len(key))
10+
// Note: this code is arranged to not panic even in the presence
11+
// of a concurrent map update. The runtime is responsible for
12+
// yelling loudly if that happens. See issue 33275.
13+
n := mapValue.Len()
14+
key := make([]reflect.Value, 0, n)
15+
value := make([]reflect.Value, 0, n)
1216
iter := mapValue.MapRange()
13-
for i := 0; iter.Next(); i++ {
14-
key[i] = iter.Key()
15-
value[i] = iter.Value()
17+
for iter.Next() {
18+
key = append(key, iter.Key())
19+
value = append(value, iter.Value())
1620
}
1721
return key, value
1822
}

fmtsort/mapelem_1.11.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,16 @@ const brokenNaNs = true
88

99
func mapElems(mapValue reflect.Value) ([]reflect.Value, []reflect.Value) {
1010
key := mapValue.MapKeys()
11-
value := make([]reflect.Value, len(key))
12-
for i, k := range key {
11+
value := make([]reflect.Value, 0, len(key))
12+
for _, k := range key {
1313
v := mapValue.MapIndex(k)
1414
if !v.IsValid() {
1515
// Note: we can't retrieve the value, probably because
1616
// the key is NaN, so just do the best we can and
1717
// add a zero value of the correct type in that case.
1818
v = reflect.Zero(mapValue.Type().Elem())
1919
}
20-
value[i] = v
20+
value = append(value, v)
2121
}
2222
return key, value
2323
}

0 commit comments

Comments
 (0)