Skip to content

Commit bc0e777

Browse files
authored
Fix CleverDict with negative indices (#1168)
1 parent 5b94495 commit bc0e777

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

src/Utilities/CleverDicts.jl

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,8 +167,12 @@ end
167167

168168
function Base.setindex!(c::CleverDict{K, V}, value::V, key::K)::V where {K, V}
169169
h = c.hash(key)::Int64
170-
if h > c.last_index
171-
c.last_index = ifelse(h == c.last_index + 1, h, -1)
170+
if c.last_index != -1
171+
if h == c.last_index + 1
172+
c.last_index = h
173+
elseif h <= 0 || h > c.last_index
174+
c.last_index = -1
175+
end
172176
end
173177
if 1 <= h <= length(c.vector) && _is_dense(c)
174178
c.vector[h] = value

test/Utilities/CleverDicts.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,4 +238,15 @@ CleverDicts.index_to_key(::Type{MyKey}, index::Int64) = MyKey(index)
238238
@test d[4] == 0.25
239239
@test d[6] == 0.75
240240
end
241+
242+
@testset "Negative index" begin
243+
d = CleverDicts.CleverDict{MathOptInterface.VariableIndex, String}()
244+
d[MathOptInterface.VariableIndex(-3)] = "a"
245+
@test d[MathOptInterface.VariableIndex(-3)] == "a"
246+
@test_throws ErrorException CleverDicts.add_item(d, "b")
247+
d[MathOptInterface.VariableIndex(0)] = "b"
248+
@test d[MathOptInterface.VariableIndex(-3)] == "a"
249+
@test d[MathOptInterface.VariableIndex(0)] == "b"
250+
@test_throws ErrorException CleverDicts.add_item(d, "c")
251+
end
241252
end

0 commit comments

Comments
 (0)