Skip to content

Commit aff4e0f

Browse files
authored
Implement get for CleverDict (#1153)
* Implement get for CleverDict * Add tests when `is_dense` is `true`
1 parent a3d28af commit aff4e0f

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

src/Utilities/CleverDicts.jl

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ Provided no keys are deleted, the backing storage is a `Vector{V}`. Once a key
2626
has been deleted, the backing storage switches to an `OrderedDict{K, V}`.
2727
2828
Use the `add_item` to enforce adding item in sequence. Once an object is added
29-
out of order `add_item` does not work anymore and the storage is switched to
29+
out of order `add_item` does not work anymore and the storage is switched to
3030
`OrderedDict{K, V}` if it is not one already.
3131
3232
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
149149
return Base.haskey(c.dict, key)
150150
end
151151
end
152+
function Base.get(c::CleverDict, key, default)
153+
if _is_dense(c)
154+
if !haskey(c, key)
155+
return default
156+
end
157+
return c.vector[c.hash(key)::Int64]
158+
else
159+
return get(c.dict, key, default)
160+
end
161+
end
152162
function Base.getindex(c::CleverDict, key)
153163
if _is_dense(c)
154164
if !haskey(c, key)

test/Utilities/CleverDicts.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ CleverDicts.index_to_key(::Type{MyKey}, index::Int) = MyKey{index}()
2020
d = CleverDicts.CleverDict{MathOptInterface.VariableIndex, String}()
2121
key = CleverDicts.add_item(d, "first")
2222
@test key == MathOptInterface.VariableIndex(1)
23+
@test get(d, key, nothing) == "first"
24+
@test get(d, MathOptInterface.VariableIndex(2), nothing) === nothing
25+
@test Dict(key => "first") == d
26+
@test Dict(key => "second") != d
2327
sizehint!(d, 1)
2428
@test d[key] == "first"
2529
@test haskey(d, key) == true
@@ -35,6 +39,10 @@ CleverDicts.index_to_key(::Type{MyKey}, index::Int) = MyKey{index}()
3539
@test d[key2] == "second"
3640
d[key2] = "third"
3741
@test d[key2] == "third"
42+
@test get(d, key, nothing) === nothing
43+
@test get(d, key2, nothing) === "third"
44+
@test Dict(key2 => "second") != d
45+
@test Dict(key2 => "third") == d
3846

3947
empty!(d)
4048

0 commit comments

Comments
 (0)