From e491edc66906158d92c25802bf9622374c5bb1b5 Mon Sep 17 00:00:00 2001 From: Milan Bouchet-Valat Date: Fri, 16 Feb 2018 23:36:39 +0100 Subject: [PATCH] Make resize! a no-op when size does not change Else we set the last element to zero for one-byte element types like UInt8, which means that resizing a vector allocated with StringVector corrupts it. Also add redundant checks in Julia code to avoid a function call. --- base/array.jl | 2 +- src/array.c | 4 ++++ test/strings/basic.jl | 10 ++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/base/array.jl b/base/array.jl index 458dab4ef13560..353c4029dd7780 100644 --- a/base/array.jl +++ b/base/array.jl @@ -936,7 +936,7 @@ function resize!(a::Vector, nl::Integer) l = length(a) if nl > l ccall(:jl_array_grow_end, Cvoid, (Any, UInt), a, nl-l) - else + elseif nl != l if nl < 0 throw(ArgumentError("new length must be ≥ 0")) end diff --git a/src/array.c b/src/array.c index 5c36497ad7b294..4b91b6314413d3 100644 --- a/src/array.c +++ b/src/array.c @@ -999,6 +999,8 @@ JL_DLLEXPORT void jl_array_del_beg(jl_array_t *a, size_t dec) jl_bounds_error_int((jl_value_t*)a, dec); if (__unlikely(a->flags.isshared)) array_try_unshare(a); + if (dec == 0) + return; jl_array_del_at_beg(a, 0, dec, n); } @@ -1009,6 +1011,8 @@ JL_DLLEXPORT void jl_array_del_end(jl_array_t *a, size_t dec) jl_bounds_error_int((jl_value_t*)a, 0); if (__unlikely(a->flags.isshared)) array_try_unshare(a); + if (dec == 0) + return; jl_array_del_at_end(a, n - dec, dec, n); } diff --git a/test/strings/basic.jl b/test/strings/basic.jl index 5b7e2b8b24c059..e86a4925ec0f84 100644 --- a/test/strings/basic.jl +++ b/test/strings/basic.jl @@ -8,6 +8,16 @@ using Random @test String("abc!") == "abc!" @test String(0x61:0x63) == "abc" + # Check that resizing empty source vector does not corrupt string + b = IOBuffer() + write(b, "ab") + x = take!(b) + s = String(x) + resize!(x, 0) + @test s == "ab" + resize!(x, 1) + @test s == "ab" + @test isempty(string()) @test eltype(GenericString) == Char @test firstindex("abc") == 1