diff --git a/src/Utilities/CleverDicts.jl b/src/Utilities/CleverDicts.jl index 32f8a7412b..c1a4d16dc0 100644 --- a/src/Utilities/CleverDicts.jl +++ b/src/Utilities/CleverDicts.jl @@ -26,7 +26,7 @@ Provided no keys are deleted, the backing storage is a `Vector{V}`. Once a key has been deleted, the backing storage switches to an `OrderedDict{K, V}`. Use the `add_item` to enforce adding item in sequence. Once an object is added -out of order `add_item` does not work anymore and the storage is switched to +out of order `add_item` does not work anymore and the storage is switched to `OrderedDict{K, V}` if it is not one already. The i'th ordered element can be obtained with `c[LinearIndex(i)]`. @@ -149,6 +149,16 @@ function Base.haskey(c::CleverDict{K}, key::K) where K return Base.haskey(c.dict, key) end end +function Base.get(c::CleverDict, key, default) + if _is_dense(c) + if !haskey(c, key) + return default + end + return c.vector[c.hash(key)::Int64] + else + return get(c.dict, key, default) + end +end function Base.getindex(c::CleverDict, key) if _is_dense(c) if !haskey(c, key) diff --git a/test/Utilities/CleverDicts.jl b/test/Utilities/CleverDicts.jl index 80dedccbed..72f3119fc7 100644 --- a/test/Utilities/CleverDicts.jl +++ b/test/Utilities/CleverDicts.jl @@ -20,6 +20,10 @@ CleverDicts.index_to_key(::Type{MyKey}, index::Int) = MyKey{index}() d = CleverDicts.CleverDict{MathOptInterface.VariableIndex, String}() key = CleverDicts.add_item(d, "first") @test key == MathOptInterface.VariableIndex(1) + @test get(d, key, nothing) == "first" + @test get(d, MathOptInterface.VariableIndex(2), nothing) === nothing + @test Dict(key => "first") == d + @test Dict(key => "second") != d sizehint!(d, 1) @test d[key] == "first" @test haskey(d, key) == true @@ -35,6 +39,10 @@ CleverDicts.index_to_key(::Type{MyKey}, index::Int) = MyKey{index}() @test d[key2] == "second" d[key2] = "third" @test d[key2] == "third" + @test get(d, key, nothing) === nothing + @test get(d, key2, nothing) === "third" + @test Dict(key2 => "second") != d + @test Dict(key2 => "third") == d empty!(d)