Skip to content

Commit

Permalink
add merge function to RobinDict, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
eulerkochy committed May 24, 2020
1 parent 0d9cb40 commit ea48409
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/robin_dict.jl
@@ -1,5 +1,5 @@
import Base: setindex!, sizehint!, empty!, isempty, length, copy, empty,
getindex, getkey, haskey, iterate, @propagate_inbounds,
getindex, getkey, haskey, iterate, @propagate_inbounds, merge,
pop!, delete!, get, get!, isbitstype, in, hashindex, isbitsunion,
isiterable, dict_with_eltype, KeySet, Callable, _tablesz, filter!

Expand Down Expand Up @@ -610,3 +610,22 @@ end
@propagate_inbounds iterate(t::RobinDict, i) = _iterate(t, get_next_filled(t, i))

filter!(f, d::RobinDict) = Base.filter_in_one_pass!(f, d)

function _merge_kvtypes(d, others...)
K, V = keytype(d), valtype(d)
for other in others
K = promote_type(K, keytype(other))
V = promote_type(V, valtype(other))
end
return (K, V)
end

function merge(d::RobinDict, others::AbstractDict...)
K, V = _merge_kvtypes(d, others...)
merge!(RobinDict{K,V}(), d, others...)
end

function merge(combine::Function, d::RobinDict, others::AbstractDict...)
K, V = _merge_kvtypes(d, others...)
merge!(combine, RobinDict{K,V}(), d, others...)
end
22 changes: 22 additions & 0 deletions test/test_robin_dict.jl
Expand Up @@ -359,6 +359,28 @@ end
@test h.idxfloor == get_idxfloor(h) == 0
end

@testset "merge" begin
h1 = RobinDict("a" => 1, "b" => 2)
h2 = RobinDict("c" => 3, "d" => 4)
d = merge(h1, h2)
@test isa(d, RobinDict{String, Int})
@test length(d) == 4
@test d["a"] == 1
@test d["b"] == 2
@test d["c"] == 3
@test d["d"] == 4
end

@testset "merge with combine function" begin
h1 = RobinDict("a" => 1, "b" => 2)
h2 = RobinDict("b" => 3, "c" => 4)
d = merge(+, h1, h2)
@test isa(d, RobinDict{String, Int})
@test d["b"] == 5
@test d["a"] == 1
@test d["c"] == 4
end

@testset "invariants" begin
h1 = RobinDict{Int, Int}()
for i in 1:300
Expand Down

0 comments on commit ea48409

Please sign in to comment.