d: Merge upstream dmd 3982604c5, druntime bc58b1e9, phobos 12329adb6.
[official-gcc.git] / gcc / d / dmd / root / optional.d
bloba593ddd54fdf5fa4662e73301707847823f4aef3
1 /**
2 * Optional implementation.
4 * Copyright: Copyright (C) 1999-2021 by The D Language Foundation, All Rights Reserved
5 * Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
6 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/root/optional.d, root/_optional.d)
8 * Documentation: https://dlang.org/phobos/dmd_root_optional.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/root/optional.d
11 module dmd.root.optional;
13 ///
14 unittest
16 import core.exception : AssertError;
18 Optional!int opt;
19 assert( opt.isEmpty());
20 assert(!opt.isPresent());
21 assert(!opt.hasValue(1));
22 assert(!opt.hasValue(2));
24 bool caught;
25 try
26 cast(void) opt.get();
27 catch (AssertError)
28 caught = true;
29 assert(caught);
31 opt = Optional!int(1);
32 assert(!opt.isEmpty());
33 assert( opt.isPresent());
34 assert( opt.get() == 1);
35 assert( opt.hasValue(1));
36 assert(!opt.hasValue(2));
39 /// Optional type that is either `empty` or contains a value of type `T`
40 extern (C++) struct Optional(T)
42 /// the value (if present)
43 private T value;
45 /// whether `value` is set
46 private bool present;
48 /// Creates an `Optional` with the given value
49 this(T value)
51 this.value = value;
52 this.present = true;
55 // Ctor wrapper for the C++ interface (required by older host compilers)
56 /// ditto
57 static Optional!T create(T val)
59 return Optional!T(val);
62 /// Returns: Whether this `Optional` contains a value
63 bool isPresent() const
65 return this.present;
68 /// Returns: Whether this `Optional` does not contain a value
69 bool isEmpty() const
71 return !this.present;
74 /// Returns: The value if present
75 inout(T) get() inout
77 assert(present);
78 return value;
81 /// Returns: Whether this `Optional` contains the supplied value
82 bool hasValue(const T exp) const
84 return present && value == exp;