1 // Copyright 2017 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "brillo/proto_file_io.h"
6
7 #include <utility>
8
9 #include <base/files/file.h>
10 #include <base/macros.h>
11 #include <google/protobuf/io/zero_copy_stream_impl.h>
12 #include <google/protobuf/text_format.h>
13
14 namespace brillo {
15
ReadTextProtobuf(const base::FilePath & proto_file,google::protobuf::Message * out_proto)16 bool ReadTextProtobuf(const base::FilePath& proto_file,
17 google::protobuf::Message* out_proto) {
18 DCHECK(out_proto);
19
20 base::File file(proto_file, base::File::FLAG_OPEN | base::File::FLAG_READ);
21 if (!file.IsValid()) {
22 DLOG(ERROR) << "Could not open \"" << proto_file.value()
23 << "\": " << base::File::ErrorToString(file.error_details());
24 return false;
25 }
26
27 return ReadTextProtobuf(file.GetPlatformFile(), out_proto);
28 }
29
ReadTextProtobuf(int fd,google::protobuf::Message * out_proto)30 bool ReadTextProtobuf(int fd, google::protobuf::Message* out_proto) {
31 google::protobuf::io::FileInputStream input_stream(fd);
32 return google::protobuf::TextFormat::Parse(&input_stream, out_proto);
33 }
34
WriteTextProtobuf(int fd,const google::protobuf::Message & proto)35 bool WriteTextProtobuf(int fd, const google::protobuf::Message& proto) {
36 google::protobuf::io::FileOutputStream output_stream(fd);
37 return google::protobuf::TextFormat::Print(proto, &output_stream);
38 }
39
40 } // namespace brillo
41