replaceMembers

Inspects a passed struct or class for members whose values match that of the passed token. Matches members are set to a replacement value, which is an optional parameter that defaults to the .init value of the token's type.

@safe pure nothrow @nogc
void
replaceMembers
(
Flag!"recurse" recurse = No.recurse
Thing
Token
)
(
ref Thing thing
,
Token token
,
Token replacement = Token.init
)
if (
isAggregateType!Thing &&
isMutable!Thing
&&
isEqualityComparable!Token
)

Parameters

recurse

Whether or not to recurse into aggregate members.

thing Thing

Reference to a struct or class whose members to iterate over.

token Token

What value to look for in members, be it a string or an integer or whatever; anything that can be compared to.

replacement Token

What to assign matched values. Defaults to the .init of the matched type.

Examples

1 import std.conv : to;
2 
3 struct Bar
4 {
5     string s = "content";
6 }
7 
8 struct Foo
9 {
10     Bar b;
11     string s = "more content";
12 }
13 
14 {
15     Foo foo1;
16     Foo foo2;
17 
18     foo1.replaceMembers("-");
19     assert(foo1 == foo2);
20 
21     foo2.s = "-";
22     foo2.replaceMembers("-");
23     assert(!foo2.s.length);
24 
25     foo2.b.s = "-";
26     foo2.replaceMembers!(Yes.recurse)("-", "herblp");
27     assert((foo2.b.s == "herblp"), foo2.b.s);
28 }
29 {
30     Foo foo;
31     foo.s = "---";
32     foo.b.s = "---";
33 
34     foo.replaceMembers!(No.recurse)("---");
35     assert(!foo.s.length);
36     assert((foo.b.s == "---"), foo.b.s);
37 
38     foo.replaceMembers!(Yes.recurse)("---");
39     assert(!foo.b.s.length);
40 }
41 {
42     class Baz
43     {
44         string barS = "init";
45         string barT = "*";
46         Foo f;
47     }
48 
49     Baz b1 = new Baz;
50     Baz b2 = new Baz;
51 
52     b1.replaceMembers("-");
53     assert((b1.barS == b2.barS), b1.barS);
54     assert((b1.barT == b2.barT), b1.barT);
55 
56     b1.replaceMembers("*");
57     assert(b1.barS.length, b1.barS);
58     assert(!b1.barT.length, b1.barT);
59     assert(b1.f.s.length, b1.f.s);
60 
61     b1.replaceMembers!(Yes.recurse)("more content");
62     assert(!b1.f.s.length, b1.f.s);
63 }
64 {
65     struct Qux
66     {
67         int i = 42;
68     }
69 
70     Qux q;
71 
72     q.replaceMembers("*");
73     assert(q.i == 42);
74 
75     q.replaceMembers(43);
76     assert(q.i == 42);
77 
78     q.replaceMembers(42, 99);
79     assert((q.i == 99), q.i.to!string);
80 }
81 {
82     struct Flerp
83     {
84         string[] arr;
85     }
86 
87     Flerp flerp;
88 
89     flerp.arr = [ "-" ];
90     assert(flerp.arr.length == 1);
91 
92     flerp.replaceMembers("-");
93     assert(!flerp.arr.length);
94 }