enforceNotNull

A convenience function to check for null t.

If you pass null to t, it will throw an exception. Otherwise, return NotNull!T.

enforceNotNull
(
T
string file = __FILE__
size_t line = __LINE__
)
(
T t
)
if (
is(T == class) ||
is(T == interface)
||
is(T == U*,
U
) &&
__traits(isScalar, T)
)

Examples

import core.exception;
import std.exception;

void NotNullCompilationTest1()() // I'm making these templates to defer compiling them
{
	NotNull!(int*) defaultInitiliation; // should fail because this would be null otherwise
}
assert(!__traits(compiles, NotNullCompilationTest1!()()));

void NotNullCompiliationTest2()() {
	NotNull!(int*) defaultInitiliation = null; // should fail here too at compile time
}
assert(!__traits(compiles, NotNullCompiliationTest2!()()));

int dummy;
NotNull!(int*) foo = &dummy;

assert(!__traits(compiles, foo = null)); // again, literal null is caught at compile time

int* test;

test = &dummy;

foo = test.assumeNotNull; // should be fine

void bar(int* a) {}

// these should both compile, since NotNull!T is a subtype of T
bar(test);
bar(foo);

void takesNotNull(NotNull!(int*) a) { }

assert(!__traits(compiles, takesNotNull(test))); // should not work; plain int might be null
takesNotNull(foo); // should be fine

takesNotNull(test.assumeNotNull); // this should work too
assert(!__traits(compiles, takesNotNull(null.assumeNotNull))); // notNull(null) shouldn't compile
test = null; // reset our pointer

assertThrown!AssertError(takesNotNull(test.assumeNotNull)); // test is null now, so this should throw an assert failure

void takesConstNotNull(in NotNull!(int *) a) {}

test = &dummy; // make it valid again
takesConstNotNull(test.assumeNotNull); // should Just Work

NotNull!(int*) foo2 = foo; // we should be able to assign NotNull to other NotNulls too
foo2 = foo; // including init and assignment
class A {}
class B : A {}
NotNull!B b = (new B).assumeNotNull;
NotNull!A a = (new A).assumeNotNull;
assert(a && b);
a = b;
assert(a is b);
class A {}
class B : A {}
auto b = assumeNotNull(new B);
auto a = assumeNotNull(new A);
a = b;
assert(a is b);

See_Also: http://forum.dlang.org/thread/mxpfzghydhirdtltmmvo@forum.dlang.org?page=3#post-ngtuwqiqumommfrlngjy:40forum.dlang.org

class A {}
class B : A {}
void f(NotNull!A a) {}
NotNull!B b = assumeNotNull(new B);
static assert(!__traits(compiles, { f(b); })); /+ TODO: I don't want this to fail. +/

Meta