comparison src/StaticDicts/StaticDicts.jl @ 769:0158c3fd521c operator_storage_array_of_table

Merge in default
author Jonatan Werpers <jonatan@werpers.com>
date Thu, 15 Jul 2021 00:06:16 +0200
parents ffb71bdb4486
children 76e5682d0e52
comparison
equal deleted inserted replaced
768:7c87a33963c5 769:0158c3fd521c
1 module StaticDicts
2
3 export StaticDict
4
5 """
6 StaticDict{K,V,N} <: AbstractDict{K,V}
7
8 A static dictionary implementing the interface for an `AbstractDict`. A
9 `StaticDict` is fully immutable and after creation no changes can be made.
10
11 The immutable nature means that `StaticDict` can be compared with `===`, in
12 constrast to regular `Dict` or `ImmutableDict` which can not. (See
13 https://github.com/JuliaLang/julia/issues/4648 for details) One important
14 aspect of this is that `StaticDict` can be used in a struct while still
15 allowing the struct to be comared using the default implementation of `==` for
16 structs.
17
18 Lookups are done by linear search.
19
20 Duplicate keys are not allowed and an error will be thrown if they are passed
21 to the constructor.
22 """
23 struct StaticDict{K,V,N} <: AbstractDict{K,V}
24 pairs::NTuple{N,Pair{K,V}}
25
26 function StaticDict{K,V}(pairs::Vararg{Pair,N}) where {K,V,N}
27 if !allunique(first.(pairs))
28 throw(DomainError(pairs, "keys must be unique"))
29 end
30 return new{K,V,N}(pairs)
31 end
32 end
33
34 function StaticDict(pairs::Vararg{Pair})
35 K = typejoin(firsttype.(pairs)...)
36 V = typejoin(secondtype.(pairs)...)
37 return StaticDict{K,V}(pairs...)
38 end
39
40 StaticDict(pairs::NTuple{N,Pair} where N) = StaticDict(pairs...)
41
42 function Base.get(d::StaticDict, key, default)
43 for p ∈ d.pairs
44 if key == p.first
45 return p.second
46 end
47 end
48
49 return default
50 end
51
52 Base.iterate(d::StaticDict) = iterate(d.pairs)
53 Base.iterate(d::StaticDict, state) = iterate(d.pairs,state)
54 Base.length(d::StaticDict) = length(d.pairs)
55
56
57 """
58 merge(d1::StaticDict, d2::StaticDict)
59
60 Merge two `StaticDict`. Repeating keys is considered and error. This may
61 change in a future version.
62 """
63 function Base.merge(d1::StaticDict, d2::StaticDict)
64 return StaticDict(d1.pairs..., d2.pairs...)
65 end
66
67
68 """
69 firsttype(::Pair{T1,T2})
70
71 The type of the first element in the pair.
72 """
73 firsttype(::Pair{T1,T2}) where {T1,T2} = T1
74
75 """
76 secondtype(::Pair{T1,T2})
77
78 The type of the secondtype element in the pair.
79 """
80 secondtype(::Pair{T1,T2}) where {T1,T2} = T2
81
82 end # module