Tue, 07 Dec 2021 11:41:07 +0200
New logger and iteration interface
0 | 1 | ################################# |
2 | # Tools for working with structs | |
3 | ################################# | |
4 | ||
4
59fd17a3cea0
Add __precompile__() for what it is worth
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
5 | __precompile__() |
59fd17a3cea0
Add __precompile__() for what it is worth
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
6 | |
0 | 7 | module StructTools |
8 | ||
9 | ############## | |
10 | # Our exports | |
11 | ############## | |
12 | ||
13 | export replace, | |
14 | IterableStruct | |
15 | ||
16 | ###################################################### | |
17 | # Replace entries by those given as keyword arguments | |
18 | ###################################################### | |
19 | ||
20 | function replace(base::T; kw...) where T | |
21 | k = keys(kw) | |
22 | T([n ∈ k ? kw[n] : getfield(base, n) for n ∈ fieldnames(T)]...) | |
23 | end | |
24 | ||
25 | ######################################################### | |
26 | # Iteration of structs. | |
27 | # One only needs to make them instance of IterableStruct | |
28 | ######################################################### | |
29 | ||
30 | abstract type IterableStruct end | |
31 | ||
32 | function Base.iterate(s::T) where T <: IterableStruct | |
33 | return Base.iterate(s, (0, fieldnames(T))) | |
34 | end | |
35 | ||
36 | function Base.iterate( | |
37 | s::T, st::Tuple{Integer,NTuple{N,Symbol}} | |
38 | ) where T <: IterableStruct where N | |
39 | (i, k)=st | |
40 | return (i<N ? (getfield(s, i+1), (i+1, k)) : nothing) | |
41 | end | |
42 | ||
43 | end |