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/bytes/bytes.go | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) (limited to 'src/bytes/bytes.go') diff --git a/src/bytes/bytes.go b/src/bytes/bytes.go index 45d8d07475..5c03e54d78 100644 --- a/src/bytes/bytes.go +++ b/src/bytes/bytes.go @@ -8,6 +8,7 @@ package bytes import ( "internal/bytealg" + "math/bits" "unicode" "unicode/utf8" _ "unsafe" // for linkname @@ -594,10 +595,11 @@ func Repeat(b []byte, count int) []byte { if count < 0 { panic("bytes: negative Repeat count") } - if len(b) > maxInt/count { + hi, lo := bits.Mul(uint(len(b)), uint(count)) + if hi > 0 || lo > uint(maxInt) { panic("bytes: Repeat output length overflow") } - n := len(b) * count + n := int(lo) // lo = len(b) * count if len(b) == 0 { return []byte{} @@ -624,10 +626,7 @@ func Repeat(b []byte, count int) []byte { nb := bytealg.MakeNoZero(n)[:n:n] bp := copy(nb, b) for bp < n { - chunk := bp - if chunk > chunkMax { - chunk = chunkMax - } + chunk := min(bp, chunkMax) bp += copy(nb[bp:], nb[:chunk]) } return nb -- cgit v1.3