From 67c3f012cf5bfd69841c74666243281f0698e09f Mon Sep 17 00:00:00 2001 From: Jes Cok Date: Thu, 1 Aug 2024 16:18:06 +0000 Subject: bytes,slices,strings: optimize Repeat a bit Like slices.Repeat, use math/bits.Mul to detect overflow in order to avoid a divide which is slow. While here, also use builtin min/max to simplify code. Change-Id: I4a6d8cd5df97fa75f4e324d4be1405ce53c03d31 GitHub-Last-Rev: 54ba5c7126b1d4a301e95d664b5f6deee6d579d9 GitHub-Pull-Request: golang/go#68704 Reviewed-on: https://go-review.googlesource.com/c/go/+/602475 Auto-Submit: Ian Lance Taylor LUCI-TryBot-Result: Go LUCI Reviewed-by: Ian Lance Taylor Reviewed-by: Michael Knyszek --- src/strings/strings.go | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) (limited to 'src/strings') diff --git a/src/strings/strings.go b/src/strings/strings.go index 0bd3c1c233..0729c4ad42 100644 --- a/src/strings/strings.go +++ b/src/strings/strings.go @@ -10,6 +10,7 @@ package strings import ( "internal/bytealg" "internal/stringslite" + "math/bits" "unicode" "unicode/utf8" ) @@ -568,10 +569,11 @@ func Repeat(s string, count int) string { if count < 0 { panic("strings: negative Repeat count") } - if len(s) > maxInt/count { + hi, lo := bits.Mul(uint(len(s)), uint(count)) + if hi > 0 || lo > uint(maxInt) { panic("strings: Repeat output length overflow") } - n := len(s) * count + n := int(lo) // lo = len(s) * count if len(s) == 0 { return "" @@ -617,13 +619,7 @@ func Repeat(s string, count int) string { b.Grow(n) b.WriteString(s) for b.Len() < n { - chunk := n - b.Len() - if chunk > b.Len() { - chunk = b.Len() - } - if chunk > chunkMax { - chunk = chunkMax - } + chunk := min(n-b.Len(), b.Len(), chunkMax) b.WriteString(b.String()[:chunk]) } return b.String() -- cgit v1.3-5-g9baa