1 /* Copyright 2020 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 #ifndef TENSORFLOW_CORE_FRAMEWORK_TENSOR_KEY_H_ 16 #define TENSORFLOW_CORE_FRAMEWORK_TENSOR_KEY_H_ 17 18 #include "tensorflow/core/framework/tensor.h" 19 20 namespace tensorflow { 21 22 class TensorKey : public Tensor { 23 public: 24 using Tensor::Tensor; 25 TensorKey(const Tensor & t)26 TensorKey(const Tensor& t) : Tensor(t) {} 27 28 // Equality operator. Needed for absl hashing. 29 friend bool operator==(const TensorKey& t1, const TensorKey& t2) { 30 if (t1.dtype() != t2.dtype() || t1.shape() != t2.shape()) { 31 return false; 32 } 33 if (DataTypeCanUseMemcpy(t1.dtype())) { 34 return t1.tensor_data() == t2.tensor_data(); 35 } 36 if (t1.dtype() == DT_STRING) { 37 const auto s1 = t1.unaligned_flat<tstring>(); 38 const auto s2 = t2.unaligned_flat<tstring>(); 39 for (int64 i = 0, n = t1.NumElements(); i < n; ++i) { 40 if (TF_PREDICT_FALSE(s1(i) != s2(i))) { 41 return false; 42 } 43 } 44 return true; 45 } 46 return false; 47 } 48 49 friend bool operator!=(const TensorKey& t1, const TensorKey& t2) { 50 return !(t1 == t2); 51 } 52 53 // Needed for absl hash function. 54 template <typename H> AbslHashValue(H h,const TensorKey & k)55 friend H AbslHashValue(H h, const TensorKey& k) { 56 const uint8* d = static_cast<uint8*>(k.data()); 57 size_t s = k.AllocatedBytes(); 58 std::vector<uint8> vec; 59 vec.reserve(s); 60 for (int i = 0; i < s; i++) { 61 vec.push_back(d[i]); 62 } 63 return H::combine(std::move(h), s); 64 } 65 }; 66 67 } // namespace tensorflow 68 69 #endif 70