Skip to content

Commit 75c7c60

Browse files
ararslanKristofferC
authored andcommitted
Add a fast path for returning "" from repeat(str, 0) (#35579)
Currently the case where `r == 0` falls through the same logic as every other non-negative value of `r` (aside from 1). This works for signed integers. However, this does not work for unsigned integers: in the loop where we unsafely fill in the output string, we're looping from 0 to `r - 1`, which for unsigned integers wraps around and causes us to request the address of the output string at a location that is well beyond what was allocated. Fixes #35578. (cherry picked from commit 1dcb42f)
1 parent 3be9f10 commit 75c7c60

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed

base/strings/substring.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ end
198198

199199
function repeat(s::Union{String, SubString{String}}, r::Integer)
200200
r < 0 && throw(ArgumentError("can't repeat a string $r times"))
201+
r == 0 && return ""
201202
r == 1 && return String(s)
202203
n = sizeof(s)
203204
out = _string_n(n*r)

test/strings/basic.jl

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -620,15 +620,17 @@ end
620620
@test_throws ArgumentError repeat(c, -1)
621621
@test_throws ArgumentError repeat(s, -1)
622622
@test_throws ArgumentError repeat(S, -1)
623-
@test repeat(c, 0) === ""
624-
@test repeat(s, 0) === ""
625-
@test repeat(S, 0) === ""
626-
@test repeat(c, 1) === s
627-
@test repeat(s, 1) === s
628-
@test repeat(S, 1) === S
629-
@test repeat(c, 3) === S
630-
@test repeat(s, 3) === S
631-
@test repeat(S, 3) === S*S*S
623+
for T in (Int, UInt)
624+
@test repeat(c, T(0)) === ""
625+
@test repeat(s, T(0)) === ""
626+
@test repeat(S, T(0)) === ""
627+
@test repeat(c, T(1)) === s
628+
@test repeat(s, T(1)) === s
629+
@test repeat(S, T(1)) === S
630+
@test repeat(c, T(3)) === S
631+
@test repeat(s, T(3)) === S
632+
@test repeat(S, T(3)) === S*S*S
633+
end
632634
end
633635
# Issue #32160 (string allocation unsigned overflow)
634636
@test_throws OutOfMemoryError repeat('x', typemax(Csize_t))

0 commit comments

Comments
 (0)