1 | /* |
2 | * SPDX-License-Identifier: Apache-2.0 |
3 | */ |
4 | |
5 | #pragma once |
6 | |
7 | #include <memory> |
8 | #include <ostream> |
9 | #include <string> |
10 | |
11 | namespace ONNX_NAMESPACE { |
12 | namespace Common { |
13 | |
14 | enum StatusCategory { |
15 | NONE = 0, |
16 | CHECKER = 1, |
17 | OPTIMIZER = 2, |
18 | }; |
19 | |
20 | enum StatusCode { |
21 | OK = 0, |
22 | FAIL = 1, |
23 | INVALID_ARGUMENT = 2, |
24 | INVALID_PROTOBUF = 3, |
25 | }; |
26 | |
27 | class Status { |
28 | public: |
29 | Status() noexcept {} |
30 | |
31 | Status(StatusCategory category, int code, const std::string& msg); |
32 | |
33 | Status(StatusCategory category, int code); |
34 | |
35 | Status(const Status& other) { |
36 | *this = other; |
37 | } |
38 | |
39 | void operator=(const Status& other) { |
40 | if (&other != this) { |
41 | if (nullptr == other.state_) { |
42 | state_.reset(); |
43 | } else if (state_ != other.state_) { |
44 | state_.reset(new State(*other.state_)); |
45 | } |
46 | } |
47 | } |
48 | |
49 | Status(Status&&) = default; |
50 | Status& operator=(Status&&) = default; |
51 | ~Status() = default; |
52 | |
53 | bool IsOK() const noexcept; |
54 | |
55 | int Code() const noexcept; |
56 | |
57 | StatusCategory Category() const noexcept; |
58 | |
59 | const std::string& ErrorMessage() const; |
60 | |
61 | std::string ToString() const; |
62 | |
63 | bool operator==(const Status& other) const { |
64 | return (this->state_ == other.state_) || (ToString() == other.ToString()); |
65 | } |
66 | |
67 | bool operator!=(const Status& other) const { |
68 | return !(*this == other); |
69 | } |
70 | |
71 | static const Status& OK() noexcept; |
72 | |
73 | private: |
74 | struct State { |
75 | State(StatusCategory cat_, int code_, std::string msg_) : category(cat_), code(code_), msg(std::move(msg_)) {} |
76 | |
77 | StatusCategory category = StatusCategory::NONE; |
78 | int code = 0; |
79 | std::string msg; |
80 | }; |
81 | |
82 | static const std::string& EmptyString(); |
83 | |
84 | // state_ == nullptr when if status code is OK. |
85 | std::unique_ptr<State> state_; |
86 | }; |
87 | |
88 | inline std::ostream& operator<<(std::ostream& out, const Status& status) { |
89 | return out << status.ToString(); |
90 | } |
91 | |
92 | } // namespace Common |
93 | } // namespace ONNX_NAMESPACE |
94 | |