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