From 5bb2628c6f143be065776727cef03276c0e516f7 Mon Sep 17 00:00:00 2001 From: Philippe Antoine Date: Tue, 5 Apr 2022 20:28:16 +0000 Subject: [PATCH] bytes: limit allocation in SplitN So that bytes.SplitN("", "T", int(144115188075855872)) does not panic. Change-Id: I7c068852bd708416164fc2ed8b84cf6b2d593666 GitHub-Last-Rev: f8df09d65e2bc889fbd0c736bfb5e9a9078dfced GitHub-Pull-Request: golang/go#52147 Reviewed-on: https://go-review.googlesource.com/c/go/+/398076 Run-TryBot: Ian Lance Taylor TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Reviewed-by: mzh --- src/bytes/bytes.go | 3 +++ src/bytes/bytes_test.go | 2 ++ 2 files changed, 5 insertions(+) diff --git a/src/bytes/bytes.go b/src/bytes/bytes.go index e3dab4d035..d9d502927e 100644 --- a/src/bytes/bytes.go +++ b/src/bytes/bytes.go @@ -348,6 +348,9 @@ func genSplit(s, sep []byte, sepSave, n int) [][]byte { if n < 0 { n = Count(s, sep) + 1 } + if n > len(s)+1 { + n = len(s) + 1 + } a := make([][]byte, n) n-- diff --git a/src/bytes/bytes_test.go b/src/bytes/bytes_test.go index 2e6ab31540..b702efb239 100644 --- a/src/bytes/bytes_test.go +++ b/src/bytes/bytes_test.go @@ -8,6 +8,7 @@ import ( . "bytes" "fmt" "internal/testenv" + "math" "math/rand" "reflect" "strings" @@ -723,6 +724,7 @@ var splittests = []SplitTest{ {"1 2", " ", 3, []string{"1", "2"}}, {"123", "", 2, []string{"1", "23"}}, {"123", "", 17, []string{"1", "2", "3"}}, + {"bT", "T", math.MaxInt / 4, []string{"b", ""}}, } func TestSplit(t *testing.T) { -- 2.50.0