1 /**
2 * Copyright 2021 Huawei Technologies Co., Ltd
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef MINDSPORE_CORE_MINDRT_INCLUDE_ASYNC_OPTION_H
18 #define MINDSPORE_CORE_MINDRT_INCLUDE_ASYNC_OPTION_H
19
20 #include <type_traits>
21 #include <utility>
22
23 #include "actor/log.h"
24
25 namespace mindspore {
26
27 template <typename T>
28 struct InnerSome {
InnerSomeInnerSome29 explicit InnerSome(const T &t) : _t(std::move(t)) {}
30 T _t;
31 };
32
33 template <typename T>
Some(T && t)34 InnerSome<typename std::decay<T>::type> Some(T &&t) {
35 return InnerSome<typename std::decay<T>::type>(std::forward<T>(t));
36 }
37
38 struct MindrtNone {};
39
40 template <typename T>
41 class Option {
42 public:
Option()43 Option() : data(), state(NONE) {}
44
Option(const T t)45 explicit Option(const T t) : data(t), state(SOME) {}
46
Option(T && t)47 explicit Option(T &&t) : data(std::move(t)), state(SOME) {}
48
Option(const InnerSome<T> & some)49 explicit Option(const InnerSome<T> &some) : data(some._t), state(SOME) {}
50
Option(const MindrtNone & none)51 explicit Option(const MindrtNone &none) : data(), state(NONE) {}
52
Option(const Option<T> & that)53 Option(const Option<T> &that) : data(), state(that.state) {
54 if (that.IsSome()) {
55 data = that.data;
56 }
57 }
58
~Option()59 virtual ~Option() {}
60
IsNone()61 bool IsNone() const { return state == NONE; }
62
IsSome()63 bool IsSome() const { return state == SOME; }
64
Get()65 const T &Get() const & {
66 MINDRT_ASSERT(IsSome());
67 return data;
68 }
69
Get()70 T &&Get() && {
71 MINDRT_ASSERT(IsSome());
72 return std::move(data);
73 }
74
Get()75 const T &&Get() const && {
76 MINDRT_ASSERT(IsSome());
77 return std::move(data);
78 }
79
80 // oprerator override
81 Option<T> &operator=(const Option<T> &that) {
82 if (&that != this) {
83 state = that.state;
84 if (that.IsSome()) {
85 data = that.data;
86 }
87 }
88
89 return *this;
90 }
91
92 bool operator==(const Option<T> &that) const {
93 return (IsNone() && that.IsNone()) || (IsSome() && that.IsSome() && data == that.data);
94 }
95
96 bool operator!=(const Option<T> &that) const { return !(*this == that); }
97
98 bool operator==(const T &that) const { return IsSome() && data == that; }
99
100 bool operator!=(const T &that) const { return !(*this == that); }
101
102 private:
103 enum State { NONE = 0, SOME = 1 };
104
105 T data;
106 State state;
107 };
108
109 } // namespace mindspore
110
111 #endif
112