diff --git a/src/Utilities/CleverDicts.jl b/src/Utilities/CleverDicts.jl index 02ad069719..6fad3c9130 100644 --- a/src/Utilities/CleverDicts.jl +++ b/src/Utilities/CleverDicts.jl @@ -167,8 +167,12 @@ end function Base.setindex!(c::CleverDict{K, V}, value::V, key::K)::V where {K, V} h = c.hash(key)::Int64 - if h > c.last_index - c.last_index = ifelse(h == c.last_index + 1, h, -1) + if c.last_index != -1 + if h == c.last_index + 1 + c.last_index = h + elseif h <= 0 || h > c.last_index + c.last_index = -1 + end end if 1 <= h <= length(c.vector) && _is_dense(c) c.vector[h] = value diff --git a/test/Utilities/CleverDicts.jl b/test/Utilities/CleverDicts.jl index 91f9b4b426..0fa0d55193 100644 --- a/test/Utilities/CleverDicts.jl +++ b/test/Utilities/CleverDicts.jl @@ -238,4 +238,15 @@ CleverDicts.index_to_key(::Type{MyKey}, index::Int64) = MyKey(index) @test d[4] == 0.25 @test d[6] == 0.75 end + + @testset "Negative index" begin + d = CleverDicts.CleverDict{MathOptInterface.VariableIndex, String}() + d[MathOptInterface.VariableIndex(-3)] = "a" + @test d[MathOptInterface.VariableIndex(-3)] == "a" + @test_throws ErrorException CleverDicts.add_item(d, "b") + d[MathOptInterface.VariableIndex(0)] = "b" + @test d[MathOptInterface.VariableIndex(-3)] == "a" + @test d[MathOptInterface.VariableIndex(0)] == "b" + @test_throws ErrorException CleverDicts.add_item(d, "c") + end end