1 module vtypechoice;
2 
3 public import vtypechoice.result;
4 public import vtypechoice.optional;
5 public import std.sumtype;
6 
7 
8   // ==============================
9  // # Result to Optional interop #
10 // ==============================
11 
12 auto optional(T, E)(auto ref scope Result!(T, E) result)
13 {
14 	return result.match!(
15 		(in Err!E) => Optional!T.none(),
16 		(in T ok) => Optional!T.some(ok),
17 	);
18 }
19 
20 ///
21 version(vtypechoice_unittest)
22 @safe pure nothrow @nogc unittest
23 {
24 	assert(Result!int.ok(3).optional == 3.some);
25 	assert(Result!int.err("failure").optional == none);
26 }
27 
28 
29   // ==============================
30  // # Optional to Result interop #
31 // ==============================
32 
33 auto result(E, T)(auto ref scope Optional!T optional, E err)
34 {
35 	return optional.match!(
36 		(in None _) => Result!(T, E).err(err),
37 		(in T value) => Result!(T, E).ok(value),
38 	);
39 }
40 
41 ///
42 version(vtypechoice_unittest)
43 @safe pure nothrow @nogc unittest
44 {
45 	assert(Optional!int.some(3).result("failure") == 3.ok);
46 	assert(Optional!int.none.result("failure") == "failure".err);
47 }
48 
49 
50 auto result(alias pred, T)(auto ref scope Optional!T optional)
51 {
52 	static if (isErr!(typeof(pred())))
53 	{
54 		alias R = Result!(T, typeof(pred().get));
55 		enum call = "pred().get";
56 	}
57 	else
58 	{
59 		alias R = Result!(T, typeof(pred()));
60 		enum call = "pred()";
61 	}
62 
63 	return optional.match!(
64 		function R (in None _) => mixin(call).err,
65 		function R (in T value) => value.ok,
66 	);
67 }
68 
69 ///
70 version(vtypechoice_unittest)
71 @safe pure nothrow @nogc unittest
72 {
73 	assert(Optional!int.some(3).result!(() => "failure") == 3.ok);
74 	assert(Optional!int.none.result!(() => "failure") == "failure".err);
75 	assert(Optional!int.none.result!(() => "failure".err) == "failure".err);
76 }