From 75c7c600ced9cc7006b74eb3c55e1881d1bc2328 Mon Sep 17 00:00:00 2001 From: Alex Arslan Date: Thu, 23 Apr 2020 23:19:18 -0700 Subject: [PATCH] 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 1dcb42f29caffc98ad0722577844ce5c54c5ba0c) --- base/strings/substring.jl | 1 + test/strings/basic.jl | 20 +++++++++++--------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/base/strings/substring.jl b/base/strings/substring.jl index cfebe9991eb7f..d98dab5ae790b 100644 --- a/base/strings/substring.jl +++ b/base/strings/substring.jl @@ -198,6 +198,7 @@ end function repeat(s::Union{String, SubString{String}}, r::Integer) r < 0 && throw(ArgumentError("can't repeat a string $r times")) + r == 0 && return "" r == 1 && return String(s) n = sizeof(s) out = _string_n(n*r) diff --git a/test/strings/basic.jl b/test/strings/basic.jl index d2be061b52d70..192592c215e91 100644 --- a/test/strings/basic.jl +++ b/test/strings/basic.jl @@ -620,15 +620,17 @@ end @test_throws ArgumentError repeat(c, -1) @test_throws ArgumentError repeat(s, -1) @test_throws ArgumentError repeat(S, -1) - @test repeat(c, 0) === "" - @test repeat(s, 0) === "" - @test repeat(S, 0) === "" - @test repeat(c, 1) === s - @test repeat(s, 1) === s - @test repeat(S, 1) === S - @test repeat(c, 3) === S - @test repeat(s, 3) === S - @test repeat(S, 3) === S*S*S + for T in (Int, UInt) + @test repeat(c, T(0)) === "" + @test repeat(s, T(0)) === "" + @test repeat(S, T(0)) === "" + @test repeat(c, T(1)) === s + @test repeat(s, T(1)) === s + @test repeat(S, T(1)) === S + @test repeat(c, T(3)) === S + @test repeat(s, T(3)) === S + @test repeat(S, T(3)) === S*S*S + end end # Issue #32160 (string allocation unsigned overflow) @test_throws OutOfMemoryError repeat('x', typemax(Csize_t))