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