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 #include "tensorflow/core/platform/tensor_coding.h" 17 18 #include <vector> 19 #include "tensorflow/core/framework/resource_handle.pb.h" 20 #include "tensorflow/core/lib/core/coding.h" 21 #include "tensorflow/core/lib/core/stringpiece.h" 22 23 namespace tensorflow { 24 namespace port { 25 26 void AssignRefCounted(StringPiece src, core::RefCounted* obj, string* out) { 27 out->assign(src.data(), src.size()); 28 } 29 30 void EncodeStringList(const string* strings, int64 n, string* out) { 31 out->clear(); 32 for (int i = 0; i < n; ++i) { 33 core::PutVarint32(out, strings[i].size()); 34 } 35 for (int i = 0; i < n; ++i) { 36 out->append(strings[i]); 37 } 38 } 39 40 bool DecodeStringList(const string& src, string* strings, int64 n) { 41 std::vector<uint32> sizes(n); 42 StringPiece reader(src); 43 int64 tot = 0; 44 for (auto& v : sizes) { 45 if (!core::GetVarint32(&reader, &v)) return false; 46 tot += v; 47 } 48 if (tot != static_cast<int64>(reader.size())) { 49 return false; 50 } 51 52 string* data = strings; 53 for (int64 i = 0; i < n; ++i, ++data) { 54 auto size = sizes[i]; 55 if (size > reader.size()) { 56 return false; 57 } 58 data->assign(reader.data(), size); 59 reader.remove_prefix(size); 60 } 61 62 return true; 63 } 64 65 void CopyFromArray(string* s, const char* base, size_t bytes) { 66 s->assign(base, bytes); 67 } 68 69 void EncodeResourceHandleList(const ResourceHandle* p, int64 n, string* out) { 70 out->clear(); 71 string rest; 72 ResourceHandleProto proto; 73 for (int i = 0; i < n; ++i) { 74 p[i].AsProto(&proto); 75 core::PutVarint32(out, proto.ByteSize()); 76 proto.AppendToString(&rest); 77 } 78 *out += rest; 79 } 80 81 bool DecodeResourceHandleList(const string& in, ResourceHandle* ps, int64 n) { 82 std::vector<uint32> sizes(n); 83 StringPiece reader(in); 84 int64 total = 0; 85 for (auto& size : sizes) { 86 if (!core::GetVarint32(&reader, &size)) return false; 87 total += size; 88 } 89 if (total != static_cast<int64>(reader.size())) { 90 return false; 91 } 92 ResourceHandleProto proto; 93 for (int i = 0; i < n; ++i) { 94 if (!proto.ParseFromArray(reader.data(), sizes[i])) { 95 return false; 96 } 97 ps[i].FromProto(proto); 98 reader.remove_prefix(sizes[i]); 99 } 100 return true; 101 } 102 103 } // namespace port 104 } // namespace tensorflow 105