1 /**
2  * Retrograde Engine
3  *
4  * Authors:
5  *  Mike Bierlee, m.bierlee@lostmoment.com
6  * Copyright: 2014-2021 Mike Bierlee
7  * License:
8  *  This software is licensed under the terms of the MIT license.
9  *  The full terms of the license can be found in the LICENSE.txt file.
10  */
11 
12 module retrograde.option;
13 
14 import std.exception;
15 import std.traits;
16 
17 abstract class Option(Type) {
18     public Type get();
19     public bool isEmpty();
20 
21     public Type getOrElse(Type delegate() fn) {
22         return isEmpty() ? fn() : get();
23     }
24 
25     public void ifNotEmpty(void delegate(Type instance) fn) {
26         if (!isEmpty()) {
27             fn(get());
28         }
29     }
30 }
31 
32 class Some(Type) : Option!Type {
33     private Type data;
34 
35     this(Type data) {
36         static if (__traits(compiles, data = null)) {
37             enforce!Exception(data !is null, "Data reference passed to option cannot be null");
38         }
39 
40         this.data = data;
41     }
42 
43     public override Type get() {
44         return data;
45     }
46 
47     public override bool isEmpty() {
48         return false;
49     }
50 
51     public static Some opCall(Type data) {
52         return new Some(data);
53     }
54 }
55 
56 class None(Type) : Option!Type {
57     public override Type get() {
58         throw new Exception("No data is available (Option type None)");
59     }
60 
61     public override bool isEmpty() {
62         return true;
63     }
64 
65     public static None opCall() {
66         return new None();
67     }
68 }