From d1f45b44a8011ddb27c71e1bc9983b62b5d3d771 Mon Sep 17 00:00:00 2001 From: Philippe Antoine Date: Thu, 17 Mar 2022 14:13:47 +0100 Subject: [PATCH] strings: limit allocation in SplitN --- src/strings/strings.go | 3 +++ src/strings/strings_test.go | 2 ++ 2 files changed, 5 insertions(+) diff --git a/src/strings/strings.go b/src/strings/strings.go index 5793d9e26f4..ed3184b59c8 100644 --- a/src/strings/strings.go +++ b/src/strings/strings.go @@ -244,6 +244,9 @@ func genSplit(s, sep string, sepSave, n int) []string { n = Count(s, sep) + 1 } + if n > len(s)+1 { + n = len(s) + 1 + } a := make([]string, n) n-- i := 0 diff --git a/src/strings/strings_test.go b/src/strings/strings_test.go index 0f30ca738e6..9e7fb85ddf0 100644 --- a/src/strings/strings_test.go +++ b/src/strings/strings_test.go @@ -8,6 +8,7 @@ import ( "bytes" "fmt" "io" + "math" "math/rand" "reflect" "strconv" @@ -404,6 +405,7 @@ var splittests = []SplitTest{ {faces, "~", -1, []string{faces}}, {"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}}, {"1 2", " ", 3, []string{"1", "2"}}, + {"", "T", math.MaxInt / 4, []string{""}}, } func TestSplit(t *testing.T) {