1 /**
2  * Complements the std.typecons package.
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <ae@cy.md>
12  */
13 
14 module ae.utils.typecons;
15 
16 import std.typecons;
17 
18 /// If `value` is not null, return its contents.
19 /// If `value` is null, set it to `defaultValue` and return it.
20 /// Similar to `object.require` for associative arrays, and
21 /// Rust's `Option::get_or_insert`.
22 ref T require(T)(ref Nullable!T value, lazy T defaultValue)
23 {
24 	if (value.isNull)
25 		value = defaultValue;
26 	return value.get();
27 }
28 
29 ///
30 unittest
31 {
32 	Nullable!int i;
33 	assert(i.require(3) == 3);
34 	assert(i.require(4) == 3);
35 }
36 
37 deprecated alias map = std.typecons.apply;
38 
39 deprecated unittest
40 {
41 	assert(Nullable!int( ).map!(n => n+1).isNull);
42 	assert(Nullable!int(1).map!(n => n+1).get() == 2);
43 }
44 
45 /// Flatten two levels of Nullable.
46 // Cf. https://doc.rust-lang.org/std/option/enum.Option.html#method.flatten
47 Nullable!T flatten(T)(Nullable!(Nullable!T) value)
48 {
49 	return value.isNull
50 		? Nullable!T.init
51 		: value.get();
52 }
53 
54 ///
55 unittest
56 {
57 	auto i = 3.nullable.nullable;
58 	assert(i.flatten.get == 3);
59 }