1 //
2 // Copyright 2015 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 // Optional.h:
7 //   Represents a type that may be invalid, similar to std::optional.
8 //
9 
10 #ifndef COMMON_OPTIONAL_H_
11 #define COMMON_OPTIONAL_H_
12 
13 #include <utility>
14 
15 template <class T>
16 struct Optional
17 {
OptionalOptional18     Optional() : mValid(false), mValue(T()) {}
19 
OptionalOptional20     Optional(const T &valueIn) : mValid(true), mValue(valueIn) {}
21 
OptionalOptional22     Optional(const Optional &other) : mValid(other.mValid), mValue(other.mValue) {}
23 
24     Optional &operator=(const Optional &other)
25     {
26         this->mValid = other.mValid;
27         this->mValue = other.mValue;
28         return *this;
29     }
30 
31     Optional &operator=(const T &value)
32     {
33         mValue = value;
34         mValid = true;
35         return *this;
36     }
37 
38     Optional &operator=(T &&value)
39     {
40         mValue = std::move(value);
41         mValid = true;
42         return *this;
43     }
44 
resetOptional45     void reset() { mValid = false; }
releaseOptional46     T &&release()
47     {
48         mValid = false;
49         return std::move(mValue);
50     }
51 
InvalidOptional52     static Optional Invalid() { return Optional(); }
53 
validOptional54     bool valid() const { return mValid; }
valueOptional55     T &value() { return mValue; }
valueOptional56     const T &value() const { return mValue; }
57 
58     bool operator==(const Optional &other) const
59     {
60         return ((mValid == other.mValid) && (!mValid || (mValue == other.mValue)));
61     }
62 
63     bool operator!=(const Optional &other) const { return !(*this == other); }
64 
65     bool operator==(const T &value) const { return mValid && (mValue == value); }
66 
67     bool operator!=(const T &value) const { return !(*this == value); }
68 
69   private:
70     bool mValid;
71     T mValue;
72 };
73 
74 #endif  // COMMON_OPTIONAL_H_
75