| 106 | } |
| 107 | |
| 108 | TF_Tensor* TF_NewTensor(TF_DataType dtype, const int64_t* dims, int num_dims, |
| 109 | void* data, size_t len, |
| 110 | void (*deallocator)(void* data, size_t len, void* arg), |
| 111 | void* deallocator_arg) { |
| 112 | std::vector<tensorflow::int64> dimvec(num_dims); |
| 113 | for (int i = 0; i < num_dims; ++i) { |
| 114 | dimvec[i] = static_cast<tensorflow::int64>(dims[i]); |
| 115 | } |
| 116 | |
| 117 | TF_ManagedBuffer* buf = nullptr; |
| 118 | if (dtype != TF_STRING && dtype != TF_RESOURCE && |
| 119 | tensorflow::DataTypeCanUseMemcpy( |
| 120 | static_cast<tensorflow::DataType>(dtype)) && |
| 121 | reinterpret_cast<intptr_t>(data) % std::max(1, EIGEN_MAX_ALIGN_BYTES) != |
| 122 | 0) { |
| 123 | // TF_STRING and TF_RESOURCE tensors have a different representation in |
| 124 | // TF_Tensor than they do in tensorflow::Tensor. So a copy here is a waste |
| 125 | // (any alignment requirements will be taken care of by TF_TensorToTensor |
| 126 | // and TF_TensorFromTensor). |
| 127 | // |
| 128 | // Other types have the same representation, so copy only if it is safe to |
| 129 | // do so. |
| 130 | buf = new TF_ManagedBuffer(tensorflow::allocate_tensor("TF_NewTensor", len), |
| 131 | len, tensorflow::deallocate_buffer, nullptr); |
| 132 | std::memcpy(buf->data(), data, len); |
| 133 | // Free the original buffer. |
| 134 | deallocator(data, len, deallocator_arg); |
| 135 | } else { |
| 136 | buf = new TF_ManagedBuffer(data, len, deallocator, deallocator_arg); |
| 137 | } |
| 138 | |
| 139 | TF_Tensor* ret = |
| 140 | new TF_Tensor{Tensor(static_cast<tensorflow::DataType>(dtype), |
| 141 | tensorflow::TensorShape(dimvec), buf)}; |
| 142 | buf->Unref(); |
| 143 | size_t elem_size = TF_DataTypeSize(dtype); |
| 144 | if (elem_size > 0 && len < (elem_size * ret->tensor.NumElements())) { |
| 145 | delete ret; |
| 146 | return nullptr; |
| 147 | } |
| 148 | return ret; |
| 149 | } |
| 150 | |
| 151 | TF_Tensor* TF_TensorMaybeMove(TF_Tensor* tensor) { |
| 152 | // It is safe to move the Tensor if and only if we own the unique reference to |