Skip to content

Commit be73573

Browse files
BioTurboNickKristofferC
authored andcommitted
Add offset in hvncat dimension calculation to fix issue with 0-length elements in first dimension (#58881)
(cherry picked from commit ed1fd39)
1 parent 9517f81 commit be73573

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

base/abstractarray.jl

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2553,16 +2553,23 @@ function _typed_hvncat_dims(::Type{T}, dims::NTuple{N, Int}, row_first::Bool, as
25532553
end
25542554

25552555
# discover number of rows or columns
2556+
# d1 dimension is increased by 1 to appropriately handle 0-length arrays
25562557
for i 1:dims[d1]
25572558
outdims[d1] += cat_size(as[i], d1)
25582559
end
25592560

2561+
# adjustment to handle 0-length arrays
2562+
first_dim_zero = outdims[d1] == 0
2563+
if first_dim_zero
2564+
outdims[d1] = dims[d1]
2565+
end
2566+
25602567
currentdims = zeros(Int, N)
25612568
blockcount = 0
25622569
elementcount = 0
25632570
for i eachindex(as)
25642571
elementcount += cat_length(as[i])
2565-
currentdims[d1] += cat_size(as[i], d1)
2572+
currentdims[d1] += first_dim_zero ? 1 : cat_size(as[i], d1)
25662573
if currentdims[d1] == outdims[d1]
25672574
currentdims[d1] = 0
25682575
for d (d2, 3:N...)
@@ -2590,6 +2597,10 @@ function _typed_hvncat_dims(::Type{T}, dims::NTuple{N, Int}, row_first::Bool, as
25902597
throw(DimensionMismatch("argument $i has too many elements along axis $d1"))
25912598
end
25922599
end
2600+
# restore 0-length adjustment
2601+
if first_dim_zero
2602+
outdims[d1] = 0
2603+
end
25932604

25942605
outlen = prod(outdims)
25952606
elementcount == outlen ||

test/abstractarray.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -831,6 +831,9 @@ function test_cat(::Type{TestAbstractArray})
831831
r = rand(Float32, 56, 56, 64, 1);
832832
f(r) = cat(r, r, dims=(3,))
833833
@inferred f(r);
834+
835+
#58866 - ensure proper dimension calculation for 0-dimension elements
836+
@test [zeros(1, 0) zeros(1,0); zeros(0,0) zeros(0, 0)] == Matrix{Float64}(undef, 1, 0)
834837
end
835838

836839
function test_ind2sub(::Type{TestAbstractArray})
@@ -1743,6 +1746,9 @@ using Base: typed_hvncat
17431746
@test ["A";;"B";;"C";;"D"] == ["A" "B" "C" "D"]
17441747
@test ["A";"B";;"C";"D"] == ["A" "C"; "B" "D"]
17451748
@test [["A";"B"];;"C";"D"] == ["A" "C"; "B" "D"]
1749+
1750+
#58866 - ensure proper dimension calculation for 0-dimension elements
1751+
@test [zeros(1, 0) zeros(1,0);;; zeros(0,0) zeros(0, 0)] == Array{Float64, 3}(undef, 1, 0, 0)
17461752
end
17471753

17481754
@testset "stack" begin

0 commit comments

Comments
 (0)