Skip to content

Commit

Permalink
Fallback implementation of sizehint! for AbstractDict (#44687)
Browse files Browse the repository at this point in the history
Fixes #44686 + additional haslength check + docs that sizehint! returns the collection.
  • Loading branch information
petvana committed Mar 21, 2022
1 parent 7f29b70 commit a6187ea
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 3 deletions.
7 changes: 6 additions & 1 deletion base/abstractdict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,9 @@ Dict{Int64, Int64} with 3 entries:
"""
function merge!(d::AbstractDict, others::AbstractDict...)
for other in others
haslength(other) && sizehint!(d, length(d) + length(other))
if haslength(d) && haslength(other)
sizehint!(d, length(d) + length(other))
end
for (k,v) in other
d[k] = v
end
Expand Down Expand Up @@ -522,6 +524,9 @@ function ==(l::AbstractDict, r::AbstractDict)
return anymissing ? missing : true
end

# Fallback implementation
sizehint!(d::AbstractDict, n) = d

const hasha_seed = UInt === UInt64 ? 0x6d35bb51952d5539 : 0x952d5539
function hash(a::AbstractDict, h::UInt)
hv = hasha_seed
Expand Down
2 changes: 1 addition & 1 deletion base/abstractset.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# This file is a part of Julia. License is MIT: https://julialang.org/license

eltype(::Type{<:AbstractSet{T}}) where {T} = @isdefined(T) ? T : Any
sizehint!(s::AbstractSet, n) = nothing
sizehint!(s::AbstractSet, n) = s

function copy!(dst::AbstractSet, src::AbstractSet)
dst === src && return dst
Expand Down
2 changes: 1 addition & 1 deletion base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1244,7 +1244,7 @@ function resize!(a::Vector, nl::Integer)
end

"""
sizehint!(s, n)
sizehint!(s, n) -> s
Suggest that collection `s` reserve capacity for at least `n` elements. This can improve performance.
Expand Down
1 change: 1 addition & 0 deletions test/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1199,6 +1199,7 @@ end
map!(v->v-1, values(testdict))
@test testdict[:a] == 0
@test testdict[:b] == 1
@test sizehint!(testdict, 1) === testdict
end
@testset "Dict" begin
testdict = Dict(:a=>1, :b=>2)
Expand Down
11 changes: 11 additions & 0 deletions test/sets.jl
Original file line number Diff line number Diff line change
Expand Up @@ -853,3 +853,14 @@ end
@test !((1, 2) (1, 2, 2))
@test !((1, 2, 2) (1, 2))
end

@testset "AbstractSet & Fallback" begin
mutable struct TestSet{T} <: AbstractSet{T}
set::Set{T}
function TestSet{T}() where T
new{T}(Set{T}())
end
end
set = TestSet{Any}()
@test sizehint!(set, 1) === set
end

0 comments on commit a6187ea

Please sign in to comment.