Skip to content

Commit

Permalink
fixes to colonful reshape
Browse files Browse the repository at this point in the history
In several different situations `reshape` had thrown `DivideError`
instead of returning a correct result or throwing.

Fixes JuliaLang#54245
  • Loading branch information
nsajko committed Apr 29, 2024
1 parent 3265387 commit 77a2463
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
12 changes: 11 additions & 1 deletion base/reshapedarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,17 @@ reshape(parent::AbstractArray, dims::Tuple{Vararg{Union{Int,Colon}}}) = reshape(
pre = _before_colon(dims...)
post = _after_colon(dims...)
_any_colon(post...) && throw1(dims)
sz, remainder = divrem(length(A), prod(pre)*prod(post))
len = length(A)
sz, remainder = if iszero(len)
(0, 0)
else
let pr = Core.checked_dims(pre..., post...) # safe product
if iszero(pr)
throw2(A, dims)
end
divrem(len, pr)
end
end::NTuple{2,Int}
remainder == 0 || throw2(A, dims)
(pre..., Int(sz), post...)
end
Expand Down
10 changes: 10 additions & 0 deletions test/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1852,6 +1852,16 @@ function check_pointer_strides(A::AbstractArray)
return true
end

@testset "colonful `reshape`, #54245" begin
@test reshape([], (0, :)) isa Matrix
@test_throws DimensionMismatch reshape([7], (0, :))
let b = prevpow(2, typemax(Int))
@test iszero(b*b)
@test_throws ArgumentError reshape([7], (b, :, b))
@test reshape([], (b, :, b)) isa Array{<:Any, 3}
end
end

@testset "strides for ReshapedArray" begin
# Type-based contiguous Check
a = vec(reinterpret(reshape, Int16, reshape(view(reinterpret(Int32, randn(10)), 2:11), 5, :)))
Expand Down

0 comments on commit 77a2463

Please sign in to comment.