Skip to content

Commit bf946e8

Browse files
authored
Implement get for DoubleDict (#1154)
1 parent aff4e0f commit bf946e8

2 files changed

Lines changed: 26 additions & 4 deletions

File tree

src/Utilities/DoubleDicts.jl

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,15 +100,22 @@ function Base.length(d::AbstractDoubleDict)
100100
end
101101

102102
function Base.haskey(dict::AbstractDoubleDict, key::CI{F,S}) where {F,S}
103-
inner = get(dict.dict, (F,S), nothing)
103+
inner = get(dict.dict, (F, S), nothing)
104104
if inner !== nothing
105-
inner = dict.dict[(F,S)]
106105
return haskey(inner, key.value)
107106
else
108107
return false
109108
end
110109
end
111110

111+
function Base.get(dict::AbstractDoubleDict, key::CI{F,S}, default) where {F,S}
112+
inner = get(dict.dict, (F, S), nothing)
113+
if inner !== nothing && haskey(inner, key.value)
114+
return typed_value(dict, inner[key.value], F, S)
115+
end
116+
return default
117+
end
118+
112119
function Base.getindex(dict::AbstractDoubleDict, key::CI{F,S}) where {F,S}
113120
inner = dict.dict[(F,S)]
114121
k_value = key.value::Int64

test/Utilities/DoubleDicts.jl

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ function test_iterator(dict)
2020
@test isempty(setdiff(kk, keys(dict)))
2121
@test length(vv) == length(values(dict))
2222
@test isempty(setdiff(vv, values(dict)))
23+
@test dict == Dict(kk .=> vv)
2324
end
2425

2526
function basic_functionality(dict, k_values, v_values)
@@ -44,11 +45,25 @@ function basic_functionality(dict, k_values, v_values)
4445
@test values(dict) == [v_values[1]]
4546
@test keys(dict) == [k_values[1]]
4647
@test dict[k_values[1]] == v_values[1]
48+
@test get(dict, k_values[1], nothing) == v_values[1]
49+
@test get(dict, k_values[1], v_values[2]) == v_values[1]
50+
for i in eachindex(k_values)
51+
if i != 1
52+
@test get(dict, k_values[i], nothing) === nothing
53+
# Test that the implementation does not only work with `nothing`
54+
@test get(dict, k_values[i], v_values[i]) == v_values[i]
55+
end
56+
end
4757

4858
test_iterator(dict)
4959

5060
delete!(dict, k_values[1])
5161
@test !haskey(dict, k_values[1])
62+
for i in eachindex(k_values)
63+
@test get(dict, k_values[i], nothing) === nothing
64+
# Test that the implementation does not only work with `nothing`
65+
@test get(dict, k_values[i], v_values[i]) == v_values[i]
66+
end
5267
@test isempty(dict)
5368

5469
dict[k_values[1]] = v_values[1]
@@ -142,7 +157,7 @@ end
142157
dict[k] = v
143158
end
144159
dest = DoubleDicts.IndexDoubleDict()
145-
MOIU._reverse_dict(dest, src)
160+
MOI.Utilities._reverse_dict(dest, src)
146161
for (k, v) in src
147162
@test dest[v] == k
148163
end
@@ -161,4 +176,4 @@ end
161176
(MOI.SingleVariable(MOI.VariableIndex(1)), MOI.ZeroOne()),
162177
]
163178
basic_functionality(dict, keys, vals)
164-
end
179+
end

0 commit comments

Comments
 (0)