SafeAccess

Allows to build access chains of class members as done with the ?. operator in other languages. In the chain, any null member that is a class instance or that returns one, has for effect to shortcut the complete evaluation.

struct SafeAccess (
M
) if (
is(M == class)
) {
M m;
}

Disabled Default Constructor

A disabled default is present on this object. To use it, use one of the other constructors or a factory function.

Constructors

this
this(M m)

Instantiate.

Alias This

m

Members

Aliases

unwrap
alias unwrap = m

Unprotect the class instance.

Functions

opDispatch
auto ref opDispatch(auto ref A a)

Handles safe access.

Bugs

Assigning a member only works with unwrap.

Examples

General usage

1 import std.exception;
2 
3 class LongLineOfIdent3{int foo; void setFoo(int v) @safe{foo = v;}}
4 class LongLineOfIdent2{LongLineOfIdent3 longLineOfIdent3;}
5 class LongLineOfIdent1{LongLineOfIdent2 longLineOfIdent2;}
6 class Root {LongLineOfIdent1 longLineOfIdent1;}
7 
8 SafeAccess!Root sar = SafeAccess!Root(new Root);
9 // without the SafeAccess we would receive a SIGSEGV here
10 sar.longLineOfIdent1.longLineOfIdent2.longLineOfIdent3.setFoo(0xDEADBEEF);
11 
12 bool notAccessed = true;
13 // the same with `&&` whould be much longer
14 if (LongLineOfIdent3 a = sar.longLineOfIdent1.longLineOfIdent2.longLineOfIdent3)
15 {
16     notAccessed = false;
17 }
18 assert(notAccessed);
19 
20 // checks that forwarding actually works
21 sar.m.longLineOfIdent1 = new LongLineOfIdent1;
22 sar.m.longLineOfIdent1.longLineOfIdent2 = new LongLineOfIdent2;
23 sar.m.longLineOfIdent1.longLineOfIdent2.longLineOfIdent3 = new LongLineOfIdent3;
24 
25 sar.longLineOfIdent1.longLineOfIdent2.longLineOfIdent3.setFoo(42);
26 assert(sar.longLineOfIdent1.longLineOfIdent2.longLineOfIdent3.unwrap.foo == 42);

Getters are also supported

1 class Second {}
2 class First
3 {
4     Second _second;
5     Second second(){return _second;}
6     this(){_second = new Second;}
7 }
8 bool accessed;
9 if (Second s = safeAccess(new First).second)
10 {
11     assert(s);
12     accessed = true;
13 }
14 assert(accessed);

Meta