Skip to content

Commit

Permalink
Parametrize safe/unsafe inserts (#42)
Browse files Browse the repository at this point in the history
* Parametrize safe/unsafe inserts

* Fix formatting

---------

Co-authored-by: Lars Hellemo <[email protected]>
  • Loading branch information
hellemo and hellemo authored Jun 5, 2023
1 parent df6c78c commit a8afb3e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
1 change: 1 addition & 0 deletions src/SparseVariables.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export SparseArray
export IndexedVarArray
export insertvar!
export unsafe_insertvar!
export SafeInsert, UnsafeInsert

@setup_workload begin
# Putting some things in `setup` can reduce the size of the
Expand Down
22 changes: 19 additions & 3 deletions src/indexedarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ struct IndexedVarArray{V<:AbstractVariableRef,N,T} <: AbstractSparseArray{V,N}
index_cache::Vector{Dictionary}
end

struct SafeInsert end
struct UnsafeInsert end

_data(sa::IndexedVarArray) = sa.data

already_defined(var, index) = haskey(_data(var), index)
Expand Down Expand Up @@ -37,23 +40,36 @@ end
Insert a new variable with the given index only after checking if keys are valid and not already defined.
"""
function insertvar!(var::IndexedVarArray{V,N,T}, index...) where {V,N,T}
return insertvar!(var, SafeInsert(), index...)
end
function insertvar!(
var::IndexedVarArray{V,N,T},
::SafeInsert = SafeInsert(),
index...,
) where {V,N,T}
!valid_index(var, index) && throw(BoundsError(var, index))# "Not a valid index for $(var.name): $index"g
already_defined(var, index) && error("$index already defined for array")

var[index] = var.f(index...)

clear_cache!(var)
return var[index]
end

function insertvar!(
var::IndexedVarArray{V,N,T},
::UnsafeInsert,
index...,
) where {V,N,T}
return var[index] = var.f(index...)
end

"""
unsafe_insertvar!(var::indexedVarArray{V,N,T}, index...)
Insert a new variable with the given index withouth checking if the index is valid or
already assigned.
"""
function unsafe_insertvar!(var::IndexedVarArray{V,N,T}, index...) where {V,N,T}
return var[index] = var.f(index...)
return insertvar!(var, UnsafeInsert(), index...)
end

joinex(ex1, ex2) = :($ex1..., $ex2...)
Expand Down
3 changes: 3 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,9 @@ end
unsafe_insertvar!(x, 2, 102)
@test length(x) == 2

insertvar!(x, UnsafeInsert(), 2, 103)
@test length(x) == 3

# When no names are provided
@variable(m, y[1:3, 100:102] >= 0, container = IndexedVarArray)
@test length(y) == 0
Expand Down

0 comments on commit a8afb3e

Please sign in to comment.