comparison src/StaticDicts/StaticDicts.jl @ 719:2f8c67c5979e feature/static_dict

Start adding a StaticDict type
author Jonatan Werpers <jonatan@werpers.com>
date Tue, 16 Mar 2021 17:28:40 +0100
parents
children 172c55c4cf2e
comparison
equal deleted inserted replaced
718:05d8ea88c690 719:2f8c67c5979e
1 module StaticDicts
2
3 export StaticDict
4
5 # Vidar 2021-02-27
6 #NOTE: This type was added since ==-comparison of structs containing
7 # Dict (even Base.ImmutableDict) fails even though the fields satisfy
8 # ==-comparison. This is due to the fact that === is called for Dict-fields.
9 # See https://github.com/JuliaLang/julia/issues/4648. If the PR gets resolved
10 # we should consider removing StaticDict.
11 """
12 StaticDict{K,V,N}(NTuple{N,Pair{K,V}})
13
14 A simple static dictonary. Performs lookup using linear search with ==-comparison
15 of keys. No hashing is used.
16 """
17 struct StaticDict{K,V,N} <: AbstractDict{K,V}
18 pairs::NTuple{N,Pair{K,V}}
19 end
20
21 function StaticDict(pairs::Vararg{Pair})
22 K = typejoin(firsttype.(pairs)...)
23 V = typejoin(secondtype.(pairs)...)
24 N = length(pairs)
25 return StaticDict{K,V,N}(pairs)
26 end
27
28 function Base.get(d::StaticDict, key, default)
29 for p ∈ d.pairs # TBD: Is this the best? Should we use the iterator on `d`?
30 if key == p.first
31 return p.second
32 end
33 end
34
35 return default
36 end
37
38 firsttype(::Pair{T1,T2}) where {T1,T2} = T1
39 secondtype(::Pair{T1,T2}) where {T1,T2} = T2
40
41 Base.iterate(d::StaticDict) = iterate(d.pairs)
42 Base.iterate(d::StaticDict, state) = iterate(d.pairs,state)
43
44 Base.length(d::StaticDict) = length(d.pairs)
45
46
47 # TODO documentation: duplicate keys not allowed atm. will error
48 function Base.merge(d1::StaticDict, d2::StaticDict)
49 return StaticDict(d1.pairs..., d2.pairs...)
50 end
51
52 end # module