| #ifndef PRODUCTION_BORG_MGMT_NODE_PROXY_SAFEPOWER_SAFEPOWER_AGENT_PROTO_READER_H_ |
| #define PRODUCTION_BORG_MGMT_NODE_PROXY_SAFEPOWER_SAFEPOWER_AGENT_PROTO_READER_H_ |
| |
| #include <fcntl.h> |
| |
| #include <cerrno> |
| #include <cstring> |
| #include <string> |
| |
| #include "absl/log/log.h" |
| #include "absl/status/status.h" |
| #include "absl/status/statusor.h" |
| #include "absl/strings/str_cat.h" |
| #include "absl/strings/string_view.h" |
| #include "google/protobuf/io/zero_copy_stream_impl.h" |
| |
| namespace proto_reader { |
| |
| template <typename T> |
| inline absl::StatusOr<T> ReadProto(const std::string& proto_path) { |
| int fd = open(proto_path.c_str(), O_RDONLY); |
| if (fd < 0) { |
| LOG(ERROR) << "Failed to open file " << proto_path; |
| return absl::InvalidArgumentError("Failed to open file"); |
| } |
| google::protobuf::io::FileInputStream stream(fd); |
| stream.SetCloseOnDelete(true); |
| |
| if (T proto; proto.ParseFromZeroCopyStream(&stream)) { |
| return proto; |
| } else { |
| LOG(ERROR) << "Failed to deserialize the proto file" << proto_path; |
| return absl::InvalidArgumentError("Failed to deserialize the proto file"); |
| } |
| } |
| |
| template <typename T> |
| inline absl::Status WriteProto(const std::string& proto_path, |
| const T& in_proto) { |
| int fd = open(proto_path.c_str(), O_WRONLY | O_CREAT, 0644); |
| if (fd < 0) { |
| LOG(ERROR) << "Failed to open file " << proto_path; |
| return absl::UnavailableError(absl::StrCat( |
| "Failed to open file: ", proto_path, ":", strerror(errno))); |
| } |
| google::protobuf::io::FileOutputStream stream(fd); |
| stream.SetCloseOnDelete(true); |
| if (!in_proto.SerializeToZeroCopyStream(&stream)) { |
| LOG(ERROR) << "Failed to serialize the proto file" << proto_path; |
| return absl::InvalidArgumentError("Failed to serialize the proto file"); |
| } |
| return absl::OkStatus(); |
| } |
| |
| } // namespace proto_reader |
| |
| #endif // PRODUCTION_BORG_MGMT_NODE_PROXY_SAFEPOWER_SAFEPOWER_AGENT_PROTO_READER_H_ |