1 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/compiler/xla/protobuf_util.h"
17
18 #include "tensorflow/compiler/xla/status_macros.h"
19 #include "tensorflow/compiler/xla/types.h"
20 #include "tensorflow/compiler/xla/util.h"
21 #include "tensorflow/core/lib/io/path.h"
22 #include "tensorflow/core/platform/env.h"
23 #include "tensorflow/core/platform/protobuf.h"
24
25 namespace xla {
26 namespace protobuf_util {
27
ProtobufEquals(const tensorflow::protobuf::Message & m1,const tensorflow::protobuf::Message & m2)28 bool ProtobufEquals(const tensorflow::protobuf::Message& m1,
29 const tensorflow::protobuf::Message& m2) {
30 // This is a bit fast and loose, but avoids introducing a dependency on
31 // the much more complex protobuf::util::MessageDifferencer class. For
32 // our purposes we just say that two protobufs are equal if their serialized
33 // representations are equal.
34 string serialized1, serialized2;
35 m1.AppendToString(&serialized1);
36 m2.AppendToString(&serialized2);
37 return (serialized1 == serialized2);
38 }
39
40 namespace {
41
SanitizeFilename(const string & file_name)42 string SanitizeFilename(const string& file_name) {
43 string safe_file_name = file_name;
44 for (char& c : safe_file_name) {
45 if (c == '/' || c == '\\') {
46 c = '_';
47 }
48 }
49 return safe_file_name;
50 }
51
52 } // namespace
53
DumpProtoToDirectory(const tensorflow::protobuf::Message & message,const string & directory,const string & file_name)54 Status DumpProtoToDirectory(const tensorflow::protobuf::Message& message,
55 const string& directory, const string& file_name) {
56 tensorflow::Env* env = tensorflow::Env::Default();
57 TF_RETURN_IF_ERROR(env->RecursivelyCreateDir(directory));
58 string safe_file_name = SanitizeFileName(file_name) + ".pb";
59 const string path = tensorflow::io::JoinPath(directory, safe_file_name);
60 return tensorflow::WriteBinaryProto(env, path, message);
61 }
62
63 } // namespace protobuf_util
64 } // namespace xla
65