Skip to content

Commit a6187ea

Browse files
authored
Fallback implementation of sizehint! for AbstractDict (#44687)
Fixes #44686 + additional haslength check + docs that sizehint! returns the collection.
1 parent 7f29b70 commit a6187ea

File tree

5 files changed

+20
-3
lines changed

5 files changed

+20
-3
lines changed

base/abstractdict.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,9 @@ Dict{Int64, Int64} with 3 entries:
217217
"""
218218
function merge!(d::AbstractDict, others::AbstractDict...)
219219
for other in others
220-
haslength(other) && sizehint!(d, length(d) + length(other))
220+
if haslength(d) && haslength(other)
221+
sizehint!(d, length(d) + length(other))
222+
end
221223
for (k,v) in other
222224
d[k] = v
223225
end
@@ -522,6 +524,9 @@ function ==(l::AbstractDict, r::AbstractDict)
522524
return anymissing ? missing : true
523525
end
524526

527+
# Fallback implementation
528+
sizehint!(d::AbstractDict, n) = d
529+
525530
const hasha_seed = UInt === UInt64 ? 0x6d35bb51952d5539 : 0x952d5539
526531
function hash(a::AbstractDict, h::UInt)
527532
hv = hasha_seed

base/abstractset.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# This file is a part of Julia. License is MIT: https://julialang.org/license
22

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

66
function copy!(dst::AbstractSet, src::AbstractSet)
77
dst === src && return dst

base/array.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1244,7 +1244,7 @@ function resize!(a::Vector, nl::Integer)
12441244
end
12451245

12461246
"""
1247-
sizehint!(s, n)
1247+
sizehint!(s, n) -> s
12481248
12491249
Suggest that collection `s` reserve capacity for at least `n` elements. This can improve performance.
12501250

test/dict.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1199,6 +1199,7 @@ end
11991199
map!(v->v-1, values(testdict))
12001200
@test testdict[:a] == 0
12011201
@test testdict[:b] == 1
1202+
@test sizehint!(testdict, 1) === testdict
12021203
end
12031204
@testset "Dict" begin
12041205
testdict = Dict(:a=>1, :b=>2)

test/sets.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -853,3 +853,14 @@ end
853853
@test !((1, 2) (1, 2, 2))
854854
@test !((1, 2, 2) (1, 2))
855855
end
856+
857+
@testset "AbstractSet & Fallback" begin
858+
mutable struct TestSet{T} <: AbstractSet{T}
859+
set::Set{T}
860+
function TestSet{T}() where T
861+
new{T}(Set{T}())
862+
end
863+
end
864+
set = TestSet{Any}()
865+
@test sizehint!(set, 1) === set
866+
end

0 commit comments

Comments
 (0)