Skip to content

Commit 9a28eb6

Browse files
authored
make constructors throw when given negative dimension size (#28)
Pointed out by vtjnash.
1 parent 958ab85 commit 9a28eb6

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/FixedSizeArrays.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ Base.isassigned(a::FixedSizeArray, i::Int) = isassigned(a.mem, i)
4343
checked_dims_impl(a::Int, ::Tuple{}) = a
4444
function checked_dims_impl(a::Int, t::Tuple{Int,Vararg{Int,N}}) where {N}
4545
b = first(t)
46+
if (a < 0) || (b < 0)
47+
throw(ArgumentError("array dimension size can't be negative"))
48+
end
4649
(m, o) = Base.Checked.mul_with_overflow(a, b)
4750
o && throw(ArgumentError("array dimensions too great, can't represent length"))
4851
r = Base.tail(t)::NTuple{N,Int}

test/runtests.jl

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,29 @@ end
1616
@testset "Constructors" begin
1717
@test FixedSizeArray{Float64,0}(undef) isa FixedSizeArray{Float64,0}
1818
@test FixedSizeArray{Float64,0}(undef, ()) isa FixedSizeArray{Float64,0}
19-
@test_throws ArgumentError FixedSizeArray{Float64,1}(undef, typemin(Int))
19+
@test_throws ArgumentError FixedSizeArray{Float64,1}(undef, -1)
20+
@test_throws ArgumentError FixedSizeArray{Float64,1}(undef, (-1,))
21+
@test_throws ArgumentError FixedSizeArray{Float64,2}(undef, -1, -1)
2022
@test_throws ArgumentError FixedSizeArray{Float64,2}(undef, typemax(Int), typemax(Int))
2123
@test_throws ArgumentError FixedSizeArray{Float64,3}(undef, typemax(Int), typemax(Int), 2)
2224
@test_throws ArgumentError FixedSizeArray{Float64,4}(undef, typemax(Int), typemax(Int), 2, 4)
25+
@testset "negative dimension size" begin
26+
for n 2:4
27+
funs = (
28+
Returns(-1),
29+
(i -> (i == 1) ? 1 : -1),
30+
(i -> (i == 1) ? -1 : 1),
31+
(i -> (i == n) ? 1 : -1),
32+
(i -> (i == n) ? -1 : 1),
33+
)
34+
fun = f -> ntuple(f, n)
35+
sizes = map(fun, funs)
36+
for siz sizes
37+
@test_throws ArgumentError FixedSizeArray{Float64,n}(undef, siz)
38+
@test_throws ArgumentError FixedSizeArray{Float64,n}(undef, siz...)
39+
end
40+
end
41+
end
2342
end
2443

2544
@testset "safe computation of length from dimensions size" begin

0 commit comments

Comments
 (0)