aboutsummaryrefslogtreecommitdiff
path: root/src/strings/strings.go
diff options
context:
space:
mode:
authorJes Cok <xigua67damn@gmail.com>2024-08-01 16:18:06 +0000
committerGopher Robot <gobot@golang.org>2024-08-01 21:32:50 +0000
commit67c3f012cf5bfd69841c74666243281f0698e09f (patch)
treeee612f3b0c4d16414946cd84919fb152d42aed7f /src/strings/strings.go
parente50913cefcdb590cdf7d9432455de2847ef93851 (diff)
downloadgo-67c3f012cf5bfd69841c74666243281f0698e09f.tar.xz
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 <iant@google.com> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Ian Lance Taylor <iant@google.com> Reviewed-by: Michael Knyszek <mknyszek@google.com>
Diffstat (limited to 'src/strings/strings.go')
-rw-r--r--src/strings/strings.go14
1 files changed, 5 insertions, 9 deletions
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()