1 /* Copyright 2015 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 #ifndef TENSORFLOW_PLATFORM_PROTOBUF_INTERNAL_H_ 17 #define TENSORFLOW_PLATFORM_PROTOBUF_INTERNAL_H_ 18 19 #include "google/protobuf/any.pb.h" 20 #include "tensorflow/core/lib/core/errors.h" 21 #include "tensorflow/core/platform/platform.h" 22 #include "tensorflow/core/platform/protobuf.h" 23 #include "tensorflow/core/platform/types.h" 24 25 namespace tensorflow { 26 27 // Returns the DebugString when available, or a stub message otherwise. Useful 28 // for messages that are incompatible with proto_text (e.g. those using Any). 29 #ifdef TENSORFLOW_LITE_PROTOS 30 template <class T> 31 string DebugStringIfAvailable(T proto) { 32 return "[DebugString not available with lite protos]"; 33 } 34 #else 35 template <class T> 36 auto DebugStringIfAvailable(T proto) -> decltype(proto.DebugString()) { 37 return proto.DebugString(); 38 } 39 #endif // defined(TENSORFLOW_LITE_PROTOS) 40 41 // Utility for parsing an Any value with full or lite protos. 42 template <class T> 43 Status ParseAny(const google::protobuf::Any& any, T* message, 44 const string& type_name) { 45 #ifdef TENSORFLOW_LITE_PROTOS 46 if (any.type_url() != strings::StrCat("type.googleapis.com/", type_name)) { 47 return errors::FailedPrecondition( 48 "Expected Any type_url for: ", type_name, 49 ". Got: ", string(any.type_url().data(), any.type_url().size()), "."); 50 } 51 if (!message->ParseFromString(any.value())) { 52 return errors::FailedPrecondition("Failed to unpack: ", 53 DebugStringIfAvailable(any)); 54 } 55 #else 56 CHECK_EQ(type_name, message->descriptor()->full_name()); 57 if (!any.Is<T>()) { 58 return errors::FailedPrecondition( 59 "Expected Any type_url for: ", message->descriptor()->full_name(), 60 ". Got: ", string(any.type_url().data(), any.type_url().size()), "."); 61 } 62 if (!any.UnpackTo(message)) { 63 return errors::FailedPrecondition("Failed to unpack: ", 64 DebugStringIfAvailable(any)); 65 } 66 #endif 67 return Status::OK(); 68 } 69 70 } // namespace tensorflow 71 72 #endif // TENSORFLOW_PLATFORM_PROTOBUF_INTERNAL_H_ 73