Skip to content

Commit

Permalink
Fix JuliaLang#14489 (Throw ArgumentError for invalid indices on creat…
Browse files Browse the repository at this point in the history
…ing SparseVector)

For indices that are non positive or exceed the size of the vector, we should throw an error.
  • Loading branch information
lvnguyen committed Feb 12, 2016
1 parent 3256421 commit d6332a0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
8 changes: 8 additions & 0 deletions base/sparse/sparsevector.jl
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ immutable SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}
n >= 0 || throw(ArgumentError("The number of elements must be non-negative."))
length(nzind) == length(nzval) ||
throw(ArgumentError("index and value vectors must be the same length"))
for i=1:length(nzind)
if nzind[i] <= 0
throw(ArgumentError("indices must be positive"))
end
if nzind[i] > n
throw(ArgumentError("indices exceeds size of vector"))
end
end
new(convert(Int, n), nzind, nzval)
end
end
Expand Down
3 changes: 3 additions & 0 deletions test/sparsedir/sparsevector.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ spv_x1 = SparseVector(8, [2, 5, 6], [1.25, -0.75, 3.5])
x1_full = zeros(length(spv_x1))
x1_full[SparseArrays.nonzeroinds(spv_x1)] = nonzeros(spv_x1)

@test_throws ArgumentError SparseVector(2, [1, 2, 3], [1, 1, 2])
@test_throws ArgumentError SparseVector(4, [1, 0], [0, 1])

### Basic Properties

let x = spv_x1
Expand Down

0 comments on commit d6332a0

Please sign in to comment.