1
0
mirror of https://github.com/golang/go synced 2024-11-24 10:30:10 -07:00

strings: limit allocation in SplitN

This commit is contained in:
Philippe Antoine 2022-03-17 14:13:47 +01:00
parent 7ca6902c17
commit d1f45b44a8
2 changed files with 5 additions and 0 deletions

View File

@ -244,6 +244,9 @@ func genSplit(s, sep string, sepSave, n int) []string {
n = Count(s, sep) + 1 n = Count(s, sep) + 1
} }
if n > len(s)+1 {
n = len(s) + 1
}
a := make([]string, n) a := make([]string, n)
n-- n--
i := 0 i := 0

View File

@ -8,6 +8,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"math"
"math/rand" "math/rand"
"reflect" "reflect"
"strconv" "strconv"
@ -404,6 +405,7 @@ var splittests = []SplitTest{
{faces, "~", -1, []string{faces}}, {faces, "~", -1, []string{faces}},
{"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}}, {"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}},
{"1 2", " ", 3, []string{"1", "2"}}, {"1 2", " ", 3, []string{"1", "2"}},
{"", "T", math.MaxInt / 4, []string{""}},
} }
func TestSplit(t *testing.T) { func TestSplit(t *testing.T) {