diff --git a/src/chainedvector.jl b/src/chainedvector.jl index c068b97..63b1461 100644 --- a/src/chainedvector.jl +++ b/src/chainedvector.jl @@ -416,6 +416,8 @@ function Base.copyto!(dest::ChainedVector{T}, doffs::Union{Signed, Unsigned}, (doffs > 0 && (doffs + n - 1) <= length(dest) && soffs > 0 && (soffs + n - 1) <= length(src)) || throw(ArgumentError("out of range arguments to copyto! on ChainedVector")) n == 0 && return dest + # copying chunk by chunk would overwrite an overlapping source before reading it + src = Base.unalias(dest, src) N = length(dest.inds) # find first chunk where we'll start copying to aidx, _ = index(dest, doffs) @@ -452,6 +454,7 @@ function Base.copyto!(dest::AbstractVector{T}, doffs::Union{Signed, Unsigned}, (doffs > 0 && (doffs + n - 1) <= length(dest) && soffs > 0 && (soffs + n - 1) <= length(src)) || throw(ArgumentError("out of range arguments to copyto! on ChainedVector")) n == 0 && return dest + src = Base.unalias(dest, src) N = length(src.inds) # find first chunk where we'll start copying from aidx, i = index(src, soffs) @@ -482,6 +485,7 @@ function Base.copyto!(dest::ChainedVector{T}, doffs::Union{Signed, Unsigned}, (doffs > 0 && (doffs + n - 1) <= length(dest) && soffs > 0 && (soffs + n - 1) <= length(src)) || throw(ArgumentError("out of range arguments to copyto! on ChainedVector")) n == 0 && return dest + src = Base.unalias(dest, src) cleanup!(src) # find first chunk where we'll start copying to dN = length(dest.inds) diff --git a/test/chainedvector.jl b/test/chainedvector.jl index d835451..1ab79ac 100644 --- a/test/chainedvector.jl +++ b/test/chainedvector.jl @@ -836,6 +836,20 @@ end @test sum(unique!(ChainedVector([[1],[2],[3]]))) == 6 end +@testset "copyto! within one ChainedVector handles overlap" begin + for (d, s, n) in ((2, 1, 2), (1, 2, 2), (2, 1, 4), (3, 1, 3)) + # the source range is read before any write, so a copy of it gives the expected result + expected = copyto!([1, 2, 3, 4, 5], d, [1, 2, 3, 4, 5][s:s+n-1]) + x = ChainedVector([[1, 2], [3], [4, 5]]) + @test copyto!(x, d, x, s, n) == expected + x = ChainedVector([[1, 2], [3], [4, 5]]) + @test copyto!(x, d, view(x, s:s+n-1)) == expected + x = ChainedVector([[1, 2], [3], [4, 5]]) + copyto!(view(x, d:d+n-1), 1, x, s, n) + @test x == expected + end +end + @testset "no-op resizing ChainedVector" begin emptied = empty!(ChainedVector([[1, 2], [3]])) popped = ChainedVector([[1]])