diff options
| author | Jes Cok <xigua67damn@gmail.com> | 2024-08-01 16:18:06 +0000 |
|---|---|---|
| committer | Gopher Robot <gobot@golang.org> | 2024-08-01 21:32:50 +0000 |
| commit | 67c3f012cf5bfd69841c74666243281f0698e09f (patch) | |
| tree | ee612f3b0c4d16414946cd84919fb152d42aed7f /src/bytes | |
| parent | e50913cefcdb590cdf7d9432455de2847ef93851 (diff) | |
| download | go-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/bytes')
| -rw-r--r-- | src/bytes/bytes.go | 11 |
1 files changed, 5 insertions, 6 deletions
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 |
