Skip to content

Commit e67c579

Browse files
committed
Add nullable{,Ref} construction functions
1 parent 05e9cba commit e67c579

File tree

1 file changed

+42
-3
lines changed

1 file changed

+42
-3
lines changed

std/typecons.d

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2335,6 +2335,12 @@ $(D this) must not be in the null state.
23352335
alias get this;
23362336
}
23372337

2338+
/// ditto
2339+
auto nullable(T)(T t)
2340+
{
2341+
return Nullable!T(t);
2342+
}
2343+
23382344
///
23392345
@safe unittest
23402346
{
@@ -2367,6 +2373,20 @@ $(D this) must not be in the null state.
23672373
}
23682374
}
23692375

2376+
///
2377+
@system unittest
2378+
{
2379+
import std.exception : assertThrown;
2380+
2381+
auto a = 42.nullable;
2382+
assert(!a.isNull);
2383+
assert(a.get == 42);
2384+
2385+
a.nullify();
2386+
assert(a.isNull);
2387+
assertThrown!Throwable(a.get);
2388+
}
2389+
23702390
@system unittest
23712391
{
23722392
import std.exception : assertThrown;
@@ -2841,6 +2861,13 @@ $(D this) must not be in the null state.
28412861
alias get this;
28422862
}
28432863

2864+
/// ditto
2865+
auto nullable(alias nullValue, T)(T t)
2866+
if (is (typeof(nullValue) == T))
2867+
{
2868+
return Nullable!(T, nullValue)(t);
2869+
}
2870+
28442871
///
28452872
@safe unittest
28462873
{
@@ -2871,6 +2898,8 @@ $(D this) must not be in the null state.
28712898
//And there's no overhead
28722899
static assert(Nullable!(size_t, size_t.max).sizeof == size_t.sizeof);
28732900
}
2901+
2902+
///
28742903
@system unittest
28752904
{
28762905
import std.exception : assertThrown;
@@ -2883,13 +2912,16 @@ $(D this) must not be in the null state.
28832912
assert(a == 5);
28842913
static assert(a.sizeof == int.sizeof);
28852914
}
2915+
2916+
///
28862917
@safe unittest
28872918
{
2888-
auto a = Nullable!(int, int.min)(8);
2919+
auto a = nullable!(int.min)(8);
28892920
assert(a == 8);
28902921
a.nullify();
28912922
assert(a.isNull);
28922923
}
2924+
28932925
@safe unittest
28942926
{
28952927
static int f(in Nullable!(int, int.min) x) {
@@ -3162,12 +3194,19 @@ $(D this) must not be in the null state.
31623194
alias get this;
31633195
}
31643196

3197+
/// ditto
3198+
auto nullableRef(T)(T* t)
3199+
{
3200+
return NullableRef!T(t);
3201+
}
3202+
3203+
///
31653204
@system unittest
31663205
{
31673206
import std.exception : assertThrown;
31683207

31693208
int x = 5, y = 7;
3170-
auto a = NullableRef!(int)(&x);
3209+
auto a = nullableRef(&x);
31713210
assert(!a.isNull);
31723211
assert(a == 5);
31733212
assert(x == 5);
@@ -3191,7 +3230,7 @@ $(D this) must not be in the null state.
31913230
return x.isNull ? 42 : x.get;
31923231
}
31933232
int x = 5;
3194-
auto a = NullableRef!int(&x);
3233+
auto a = nullableRef(&x);
31953234
assert(f(a) == 5);
31963235
a.nullify();
31973236
assert(f(a) == 42);

0 commit comments

Comments
 (0)