blob: de372dbf5db993d883355726d73e244a478cfa32 [file] [log] [blame]
James Kuszmaul847927d2024-05-23 15:33:18 -07001#include "aos/util/status.h"
2
3namespace aos {
4Status::Status(StatusCode code, std::string_view message,
5 std::optional<std::source_location> source_location)
6 : code_(code),
7 owned_message_(message.begin(), message.end()),
8 message_(owned_message_.data(), owned_message_.size()),
9 source_location_(std::move(source_location)) {}
10Status::Status(StatusCode code, const char *message,
11 std::optional<std::source_location> source_location)
12 : code_(code),
13 message_(message),
14 source_location_(std::move(source_location)) {}
15
16Status::Status(Status &&other)
17 : code_(other.code_),
18 owned_message_(std::move(other.owned_message_)),
19 message_(MakeStringViewFromBufferOrView(owned_message_, other.message_)),
20 source_location_(std::move(other.source_location_)) {
21 // Because the internal string view contains a pointer to the owned_message_
22 // buffer, we need to have a manually written move constructor to manage it.
23 other.message_ = {};
24}
25Status &Status::operator=(Status &&other) {
26 std::swap(*this, other);
27 return *this;
28}
29Status::Status(const Status &other)
30 : code_(other.code_),
31 owned_message_(other.owned_message_),
32 message_(MakeStringViewFromBufferOrView(owned_message_, other.message_)),
33 source_location_(other.source_location_) {}
34
35std::string Status::ToString() const {
36 std::string source_info = "";
37 if (source_location_.has_value()) {
38 source_info = absl::StrFormat(
39 "%s:%d in %s: ", source_location_->file_name(),
40 source_location_->line(), source_location_->function_name());
41 }
42
43 return absl::StrFormat("%sStatus is %s with code of %d and message: %s",
44 source_info, ok() ? "okay" : "errored", code(),
45 message());
46}
47
48template <>
49void CheckExpected<void>(const tl::expected<void, Status> &expected) {
50 if (expected.has_value()) {
51 return;
52 }
53 LOG(FATAL) << expected.error().ToString();
54}
55} // namespace aos