| 269 | namespace { |
| 270 | |
| 271 | class CppDLTensor { |
| 272 | public: |
| 273 | using value_type = DLManagedTensorVersioned; |
| 274 | using pointer_type = value_type*; |
| 275 | |
| 276 | static Result<CppDLTensor> TakeOwnership(pointer_type ptr) { |
| 277 | if (ARROW_PREDICT_FALSE(ptr == nullptr)) { |
| 278 | return Status::Invalid("Received null pointer."); |
| 279 | } |
| 280 | // Create the wrapper before checking the version as the spec mandates that the |
| 281 | // deleter MUST be called on version major mismatch. |
| 282 | auto out = CppDLTensor(ptr); |
| 283 | if (ARROW_PREDICT_FALSE(out.ptr_->version.major != kVersion.major)) { |
| 284 | return Status::Invalid("Unsupported DLPack major version ", out.ptr_->version.major, |
| 285 | ", expected ", kVersion.major); |
| 286 | } |
| 287 | if (ARROW_PREDICT_FALSE(out.tensor().ndim < 0)) { |
| 288 | return Status::Invalid("Invalid DLPack tensor: ndim must be >= 0"); |
| 289 | } |
| 290 | if (ARROW_PREDICT_FALSE(out.tensor().ndim != 0 && out.tensor().shape == nullptr)) { |
| 291 | return Status::Invalid( |
| 292 | "Invalid DLPack tensor: shape must be non-null when ndim != 0"); |
| 293 | } |
| 294 | // Null strides are handled as row major |
| 295 | return out; |
| 296 | } |
| 297 | |
| 298 | const DLTensor& tensor() const { return ptr_->dl_tensor; } |
| 299 | |
| 300 | int64_t ndim() const { |
| 301 | DCHECK_GE(tensor().ndim, 0); |
| 302 | return tensor().ndim; |
| 303 | } |
| 304 | |
| 305 | template <typename T> |
| 306 | T* data_as() { |
| 307 | return static_cast<T*>(tensor().data); |
| 308 | } |
| 309 | |
| 310 | std::span<const int64_t> shape() const { |
| 311 | return {tensor().shape, static_cast<std::size_t>(ndim())}; |
| 312 | } |
| 313 | |
| 314 | /// Strides or empty span for old DLPack row-major convention. |
| 315 | std::span<const int64_t> strides() const { |
| 316 | if (auto strides = tensor().strides; strides != nullptr) { |
| 317 | return {strides, static_cast<std::size_t>(ndim())}; |
| 318 | } |
| 319 | return {}; |
| 320 | } |
| 321 | |
| 322 | bool flag_is_set(uint8_t bits) const { return (ptr_->flags & bits) == bits; } |
| 323 | |
| 324 | bool is_readonly() const { return flag_is_set(DLPACK_FLAG_BITMASK_READ_ONLY); } |
| 325 | |
| 326 | int32_t byte_width() const { return tensor().dtype.bits / 8; } |
| 327 | |
| 328 | /// Number of element in this tensor's buffer. |