| 183 | } |
| 184 | |
| 185 | Status CheckTensorStridesValidity(const std::shared_ptr<Buffer>& data, |
| 186 | const std::vector<int64_t>& shape, |
| 187 | const std::vector<int64_t>& strides, |
| 188 | const std::shared_ptr<DataType>& type) { |
| 189 | if (strides.size() != shape.size()) { |
| 190 | return Status::Invalid("strides must have the same length as shape"); |
| 191 | } |
| 192 | if (data->size() == 0 && std::find(shape.begin(), shape.end(), 0) != shape.end()) { |
| 193 | return Status::OK(); |
| 194 | } |
| 195 | |
| 196 | // Check the largest offset can be computed without overflow |
| 197 | const size_t ndim = shape.size(); |
| 198 | int64_t largest_offset = 0; |
| 199 | for (size_t i = 0; i < ndim; ++i) { |
| 200 | if (shape[i] == 0) continue; |
| 201 | if (strides[i] < 0) { |
| 202 | // TODO(mrkn): Support negative strides for sharing views |
| 203 | return Status::Invalid("negative strides not supported"); |
| 204 | } |
| 205 | |
| 206 | int64_t dim_offset; |
| 207 | if (!internal::MultiplyWithOverflow(shape[i] - 1, strides[i], &dim_offset)) { |
| 208 | if (!internal::AddWithOverflow(largest_offset, dim_offset, &largest_offset)) { |
| 209 | continue; |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | return Status::Invalid( |
| 214 | "offsets computed from shape and strides would not fit in 64-bit integer"); |
| 215 | } |
| 216 | |
| 217 | const int byte_width = type->byte_width(); |
| 218 | if (largest_offset > data->size() - byte_width) { |
| 219 | return Status::Invalid("strides must not involve buffer over run"); |
| 220 | } |
| 221 | return Status::OK(); |
| 222 | } |
| 223 | } // namespace |
| 224 | } // namespace internal |
| 225 |
no test coverage detected