Home | History | Annotate | Download | only in platform
      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/variant_coding.h"
     17 
     18 #include <vector>
     19 #include "tensorflow/core/framework/tensor.pb.h"
     20 #include "tensorflow/core/framework/variant_op_registry.h"
     21 #include "tensorflow/core/lib/core/coding.h"
     22 #include "tensorflow/core/lib/core/stringpiece.h"
     23 #include "tensorflow/core/lib/strings/strcat.h"
     24 
     25 namespace tensorflow {
     26 namespace port {
     27 
     28 void EncodeVariantList(const Variant* variant_array, int64 n, string* out) {
     29   out->clear();
     30   string rest;
     31   for (int i = 0; i < n; ++i) {
     32     string s;
     33     variant_array[i].Encode(&s);
     34     core::PutVarint32(out, s.length());
     35     strings::StrAppend(&rest, s);
     36   }
     37   strings::StrAppend(out, rest);
     38 }
     39 
     40 bool DecodeVariantList(const string& in, Variant* variant_array, int64 n) {
     41   std::vector<uint32> sizes(n);
     42   StringPiece reader(in);
     43   int64 total = 0;
     44   for (auto& size : sizes) {
     45     if (!core::GetVarint32(&reader, &size)) return false;
     46     total += size;
     47   }
     48   if (total != static_cast<int64>(reader.size())) {
     49     return false;
     50   }
     51 
     52   for (int i = 0; i < n; ++i) {
     53     if (variant_array[i].is_empty()) {
     54       variant_array[i] = VariantTensorDataProto();
     55     }
     56     string str(reader.data(), sizes[i]);
     57     if (!variant_array[i].Decode(str)) return false;
     58     if (!DecodeUnaryVariant(&variant_array[i])) {
     59       LOG(ERROR) << "Could not decode variant with type_name: \""
     60                  << variant_array[i].TypeName()
     61                  << "\".  Perhaps you forgot to register a "
     62                     "decoder via REGISTER_UNARY_VARIANT_DECODE_FUNCTION?";
     63       return false;
     64     }
     65     reader.remove_prefix(sizes[i]);
     66   }
     67   return true;
     68 }
     69 
     70 }  // end namespace port
     71 }  // end namespace tensorflow
     72