From 442f7aa1f58efeac72983496ce75f07550b97abc Mon Sep 17 00:00:00 2001 From: N5N3 <2642243996@qq.com> Date: Mon, 16 May 2022 20:07:03 +0800 Subject: [PATCH] Use `CartesianIndices(Rsrc)` as the shared iterator. (#45289) There's no performance change, if the `indices`s of `Rdest` and `Rsrc` are all `NTuple{N,<:AbstractUnitRange}`. (cherry picked from commit a91be39b671638b8c48215931eb4ccd948ce33a3) --- base/multidimensional.jl | 12 +++++++----- test/copy.jl | 13 ++++++++----- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/base/multidimensional.jl b/base/multidimensional.jl index b5e401a7834e7..4be18766a30e6 100644 --- a/base/multidimensional.jl +++ b/base/multidimensional.jl @@ -1113,16 +1113,18 @@ function copyto!(dest::AbstractArray{T1,N}, Rdest::CartesianIndices{N}, checkbounds(src, first(Rsrc)) checkbounds(src, last(Rsrc)) src′ = unalias(dest, src) - ΔI = first(Rdest) - first(Rsrc) + CRdest = CartesianIndices(Rdest) + CRsrc = CartesianIndices(Rsrc) + ΔI = first(CRdest) - first(CRsrc) if @generated quote - @nloops $N i (n->Rsrc.indices[n]) begin - @inbounds @nref($N,dest,n->i_n+ΔI[n]) = @nref($N,src′,i) + @nloops $N i (n->CRsrc.indices[n]) begin + @inbounds @nref($N,dest,n->Rdest.indices[n][i_n+ΔI[n]]) = @nref($N,src,n->Rsrc.indices[n][i_n]) end end else - for I in Rsrc - @inbounds dest[I + ΔI] = src′[I] + for I in CRsrc + @inbounds dest[Rdest[I + ΔI]] = src′[Rsrc[I]] end end dest diff --git a/test/copy.jl b/test/copy.jl index 28d34e4756a6b..654e95dec67d5 100644 --- a/test/copy.jl +++ b/test/copy.jl @@ -58,11 +58,14 @@ end @test B == A end let A = reshape(1:6, 3, 2), B = zeros(8,8) - RA = CartesianIndices(axes(A)) - copyto!(B, CartesianIndices((5:7,2:3)), A, RA) - @test B[5:7,2:3] == A - B[5:7,2:3] .= 0 - @test all(x->x==0, B) + RBs = Any[(5:7,2:3), (3:2:7,1:2:3), (6:-1:4,2:-1:1)] + RAs = Any[axes(A), reverse.(axes(A))] + for RB in RBs, RA in RAs + copyto!(B, CartesianIndices(RB), A, CartesianIndices(RA)) + @test B[RB...] == A[RA...] + B[RB...] .= 0 + @test all(iszero, B) + end end end