Skip to content

Commit 52c55d7

Browse files
authored
Check axes in Array(::AbstractArray) (fixes #36220) (#36397)
1 parent 3604a25 commit 52c55d7

File tree

4 files changed

+14
-5
lines changed

4 files changed

+14
-5
lines changed

base/abstractarray.jl

+6
Original file line numberDiff line numberDiff line change
@@ -940,6 +940,12 @@ function copyto!(B::AbstractVecOrMat{R}, ir_dest::AbstractRange{Int}, jr_dest::A
940940
return B
941941
end
942942

943+
function copyto_axcheck!(dest, src)
944+
@noinline checkaxs(axd, axs) = axd == axs || throw(DimensionMismatch("axes must agree, got $axd and $axs"))
945+
946+
checkaxs(axes(dest), axes(src))
947+
copyto!(dest, src)
948+
end
943949

944950
"""
945951
copymutable(a)

base/array.jl

+2-2
Original file line numberDiff line numberDiff line change
@@ -561,8 +561,8 @@ promote_rule(a::Type{Array{T,n}}, b::Type{Array{S,n}}) where {T,n,S} = el_same(p
561561

562562
if nameof(@__MODULE__) === :Base # avoid method overwrite
563563
# constructors should make copies
564-
Array{T,N}(x::AbstractArray{S,N}) where {T,N,S} = copyto!(Array{T,N}(undef, size(x)), x)
565-
AbstractArray{T,N}(A::AbstractArray{S,N}) where {T,N,S} = copyto!(similar(A,T), A)
564+
Array{T,N}(x::AbstractArray{S,N}) where {T,N,S} = copyto_axcheck!(Array{T,N}(undef, size(x)), x)
565+
AbstractArray{T,N}(A::AbstractArray{S,N}) where {T,N,S} = copyto_axcheck!(similar(A,T), A)
566566
end
567567

568568
## copying iterators to containers

test/hashing.jl

+5-3
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,12 @@ end
111111

112112
for a in vals
113113
a isa AbstractArray || continue
114-
if keys(a) == keys(Array(a))
115-
@test hash(a) == hash(Array(a)) == hash(Array{Any}(a))
114+
aa = copyto!(Array{eltype(a)}(undef, size(a)), a)
115+
aaa = copyto!(Array{Any}(undef, size(a)), a)
116+
if keys(a) == keys(aa)
117+
@test hash(a) == hash(aa) == hash(aaa)
116118
else
117-
@test hash(a) == hash(OffsetArray(Array(a), (first.(axes(a)).-1)...)) == hash(OffsetArray(Array{Any}(a), (first.(axes(a)).-1)...))
119+
@test hash(a) == hash(OffsetArray(aa, (first.(axes(a)).-1)...)) == hash(OffsetArray(aaa, (first.(axes(a)).-1)...))
118120
end
119121
end
120122

test/offsetarray.jl

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ h = OffsetArray([-1,1,-2,2,0], (-3,))
2121
@test axes(v) == (-2:1,)
2222
@test size(v) == (4,)
2323
@test size(v, 1) == 4
24+
@test_throws DimensionMismatch Array(v)
2425

2526
A0 = [1 3; 2 4]
2627
A = OffsetArray(A0, (-1,2)) # IndexLinear

0 commit comments

Comments
 (0)