From 9f985d550aa78beac49932267fd004b19fe7f270 Mon Sep 17 00:00:00 2001 From: smasher164 Date: Tue, 22 Sep 2020 23:53:13 -0400 Subject: [PATCH] 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. --- fmtsort/mapelem.go | 14 +++++++++----- fmtsort/mapelem_1.11.go | 6 +++--- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/fmtsort/mapelem.go b/fmtsort/mapelem.go index 07c4a471..af6124f1 100644 --- a/fmtsort/mapelem.go +++ b/fmtsort/mapelem.go @@ -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 } diff --git a/fmtsort/mapelem_1.11.go b/fmtsort/mapelem_1.11.go index 8c28451a..6c2b0222 100644 --- a/fmtsort/mapelem_1.11.go +++ b/fmtsort/mapelem_1.11.go @@ -8,8 +8,8 @@ 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 @@ -17,7 +17,7 @@ func mapElems(mapValue reflect.Value) ([]reflect.Value, []reflect.Value) { // 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 }