Skip to content

Commit

Permalink
make constructors throw when given negative dimension size (#28)
Browse files Browse the repository at this point in the history
Pointed out by vtjnash.
  • Loading branch information
nsajko authored Apr 23, 2024
1 parent 958ab85 commit 9a28eb6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/FixedSizeArrays.jl
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ Base.isassigned(a::FixedSizeArray, i::Int) = isassigned(a.mem, i)
checked_dims_impl(a::Int, ::Tuple{}) = a
function checked_dims_impl(a::Int, t::Tuple{Int,Vararg{Int,N}}) where {N}
b = first(t)
if (a < 0) || (b < 0)
throw(ArgumentError("array dimension size can't be negative"))
end
(m, o) = Base.Checked.mul_with_overflow(a, b)
o && throw(ArgumentError("array dimensions too great, can't represent length"))
r = Base.tail(t)::NTuple{N,Int}
Expand Down
21 changes: 20 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,29 @@ end
@testset "Constructors" begin
@test FixedSizeArray{Float64,0}(undef) isa FixedSizeArray{Float64,0}
@test FixedSizeArray{Float64,0}(undef, ()) isa FixedSizeArray{Float64,0}
@test_throws ArgumentError FixedSizeArray{Float64,1}(undef, typemin(Int))
@test_throws ArgumentError FixedSizeArray{Float64,1}(undef, -1)
@test_throws ArgumentError FixedSizeArray{Float64,1}(undef, (-1,))
@test_throws ArgumentError FixedSizeArray{Float64,2}(undef, -1, -1)
@test_throws ArgumentError FixedSizeArray{Float64,2}(undef, typemax(Int), typemax(Int))
@test_throws ArgumentError FixedSizeArray{Float64,3}(undef, typemax(Int), typemax(Int), 2)
@test_throws ArgumentError FixedSizeArray{Float64,4}(undef, typemax(Int), typemax(Int), 2, 4)
@testset "negative dimension size" begin
for n 2:4
funs = (
Returns(-1),
(i -> (i == 1) ? 1 : -1),
(i -> (i == 1) ? -1 : 1),
(i -> (i == n) ? 1 : -1),
(i -> (i == n) ? -1 : 1),
)
fun = f -> ntuple(f, n)
sizes = map(fun, funs)
for siz sizes
@test_throws ArgumentError FixedSizeArray{Float64,n}(undef, siz)
@test_throws ArgumentError FixedSizeArray{Float64,n}(undef, siz...)
end
end
end
end

@testset "safe computation of length from dimensions size" begin
Expand Down

0 comments on commit 9a28eb6

Please sign in to comment.