1 /*
2  * Copyright (C) 2019 The Android Open Source Project
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 INCLUDE_PERFETTO_BASE_STATUS_H_
18 #define INCLUDE_PERFETTO_BASE_STATUS_H_
19 
20 #include <string>
21 
22 #include "perfetto/base/compiler.h"
23 #include "perfetto/base/export.h"
24 #include "perfetto/base/logging.h"
25 
26 namespace perfetto {
27 namespace base {
28 
29 // Represents either the success or the failure message of a function.
30 // This can used as the return type of functions which would usually return an
31 // bool for success or int for errno but also wants to add some string context
32 // (ususally for logging).
33 class PERFETTO_EXPORT Status {
34  public:
Status()35   Status() : ok_(true) {}
Status(std::string msg)36   explicit Status(std::string msg) : ok_(false), message_(std::move(msg)) {
37     PERFETTO_CHECK(!message_.empty());
38   }
39 
40   // Copy operations.
41   Status(const Status&) = default;
42   Status& operator=(const Status&) = default;
43 
44   // Move operations. The moved-from state is valid but unspecified.
45   Status(Status&&) noexcept = default;
46   Status& operator=(Status&&) = default;
47 
ok()48   bool ok() const { return ok_; }
49 
50   // When ok() is false this returns the error message. Returns the empty string
51   // otherwise.
message()52   const std::string& message() const { return message_; }
c_message()53   const char* c_message() const { return message_.c_str(); }
54 
55  private:
56   bool ok_ = false;
57   std::string message_;
58 };
59 
60 // Returns a status object which represents the Ok status.
OkStatus()61 inline Status OkStatus() {
62   return Status();
63 }
64 
65 PERFETTO_PRINTF_FORMAT(1, 2) Status ErrStatus(const char* format, ...);
66 
67 }  // namespace base
68 }  // namespace perfetto
69 
70 #endif  // INCLUDE_PERFETTO_BASE_STATUS_H_
71