1 // Copyright 2017 The Draco Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 #ifndef DRACO_CORE_STATUS_H_
16 #define DRACO_CORE_STATUS_H_
17
18 #include <string>
19
20 namespace draco {
21
22 // Class encapsulating a return status of an operation with an optional error
23 // message. Intended to be used as a return type for functions instead of bool.
24 class Status {
25 public:
26 enum Code {
27 OK = 0,
28 DRACO_ERROR = -1, // Used for general errors.
29 IO_ERROR = -2, // Error when handling input or output stream.
30 INVALID_PARAMETER = -3, // Invalid parameter passed to a function.
31 UNSUPPORTED_VERSION = -4, // Input not compatible with the current version.
32 UNKNOWN_VERSION = -5, // Input was created with an unknown version of
33 // the library.
34 UNSUPPORTED_FEATURE = -6, // Input contains feature that is not supported.
35 };
36
Status()37 Status() : code_(OK) {}
38 Status(const Status &status) = default;
39 Status(Status &&status) = default;
Status(Code code)40 explicit Status(Code code) : code_(code) {}
Status(Code code,const std::string & error_msg)41 Status(Code code, const std::string &error_msg)
42 : code_(code), error_msg_(error_msg) {}
43
code()44 Code code() const { return code_; }
error_msg_string()45 const std::string &error_msg_string() const { return error_msg_; }
error_msg()46 const char *error_msg() const { return error_msg_.c_str(); }
47
48 bool operator==(Code code) const { return code == code_; }
ok()49 bool ok() const { return code_ == OK; }
50
51 Status &operator=(const Status &) = default;
52
53 private:
54 Code code_;
55 std::string error_msg_;
56 };
57
58 inline std::ostream &operator<<(std::ostream &os, const Status &status) {
59 os << status.error_msg_string();
60 return os;
61 }
62
OkStatus()63 inline Status OkStatus() { return Status(Status::OK); }
64
65 // Evaluates an expression that returns draco::Status. If the status is not OK,
66 // the macro returns the status object.
67 #define DRACO_RETURN_IF_ERROR(expression) \
68 { \
69 const draco::Status _local_status = (expression); \
70 if (!_local_status.ok()) { \
71 return _local_status; \
72 } \
73 }
74
75 } // namespace draco
76
77 #endif // DRACO_CORE_STATUS_H_
78