Skip to content

Commit

Permalink
Implement get! and get for IdDict with a callable default (JuliaLang#…
Browse files Browse the repository at this point in the history
  • Loading branch information
fingolfin authored and JeffBezanson committed Nov 30, 2018
1 parent e4f408e commit 7ba6c82
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
17 changes: 17 additions & 0 deletions base/abstractdict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,23 @@ copy(d::IdDict) = typeof(d)(d)

get!(d::IdDict{K,V}, @nospecialize(key), @nospecialize(default)) where {K, V} = (d[key] = get(d, key, default))::V

function get(default::Callable, d::IdDict{K,V}, @nospecialize(key)) where {K, V}
val = get(d, key, secret_table_token)
if val === secret_table_token
val = default()
end
return val
end

function get!(default::Callable, d::IdDict{K,V}, @nospecialize(key)) where {K, V}
val = get(d, key, secret_table_token)
if val === secret_table_token
val = default()
setindex!(d, val, key)
end
return val
end

in(@nospecialize(k), v::KeySet{<:Any,<:IdDict}) = get(v.dict, k, secret_table_token) !== secret_table_token

# For some AbstractDict types, it is safe to implement filter!
Expand Down
21 changes: 21 additions & 0 deletions test/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,27 @@ end
@test_throws DomainError IdDict((sqrt(p[1]), sqrt(p[2])) for p in zip(-1:2, -1:2))
end

@testset "issue 30165, get! for IdDict" begin
f(x) = x^2
d = IdDict(8=>19)
@test get!(d, 8, 5) == 19
@test get!(d, 19, 2) == 2

@test get!(d, 42) do # d is updated with f(2)
f(2)
end == 4

@test get!(d, 42) do # d is not updated
f(200)
end == 4

@test get(d, 13) do # d is not updated
f(4)
end == 16

@test d == IdDict(8=>19, 19=>2, 42=>4)
end

@testset "issue #26833, deletion from IdDict" begin
d = IdDict()
i = 1
Expand Down

0 comments on commit 7ba6c82

Please sign in to comment.