Skip to content

Commit 1ac30c3

Browse files
authored
Merge pull request #19245 from pabloferz/pz/dict
Improve type stability of Dict(g::Generator) (fixes #19243)
2 parents ca509cd + a448b0d commit 1ac30c3

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

base/dict.jl

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,11 +152,20 @@ function Dict(kv)
152152
end
153153
end
154154

155-
dict_with_eltype{K,V}(kv, ::Type{Tuple{K,V}}) = Dict{K,V}(kv)
156-
dict_with_eltype{K,V}(kv, ::Type{Pair{K,V}}) = Dict{K,V}(kv)
155+
typealias TP{K,V} Union{Type{Tuple{K,V}},Type{Pair{K,V}}}
156+
157+
dict_with_eltype{K,V}(kv, ::TP{K,V}) = Dict{K,V}(kv)
158+
dict_with_eltype{K,V}(kv::Generator, ::TP{K,V}) = Dict{K,V}(kv)
157159
dict_with_eltype{K,V}(::Type{Pair{K,V}}) = Dict{K,V}()
158160
dict_with_eltype(::Type) = Dict()
159161
dict_with_eltype(kv, t) = grow_to!(dict_with_eltype(_default_eltype(typeof(kv))), kv)
162+
function dict_with_eltype(kv::Generator, t)
163+
T = _default_eltype(typeof(kv))
164+
if T <: Union{Pair,NTuple{2}} && isleaftype(T)
165+
return dict_with_eltype(kv, T)
166+
end
167+
return grow_to!(dict_with_eltype(T), kv)
168+
end
160169

161170
# this is a special case due to (1) allowing both Pairs and Tuples as elements,
162171
# and (2) Pair being invariant. a bit annoying.

test/dict.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ end
138138
@test first(Dict(:f=>2)) == (:f=>2)
139139

140140
# constructing Dicts from iterators
141-
let d = Dict(i=>i for i=1:3)
141+
let d = @inferred Dict(i=>i for i=1:3)
142142
@test isa(d, Dict{Int,Int})
143143
@test d == Dict(1=>1, 2=>2, 3=>3)
144144
end

0 commit comments

Comments
 (0)