| 135 | |
| 136 | template <typename DT> |
| 137 | Result<DT*> ExportArrayImpl(const std::shared_ptr<Array>& arr, bool copy) { |
| 138 | if (arr->null_count() > 0) { |
| 139 | return Status::TypeError("Can only use DLPack on arrays with no nulls."); |
| 140 | } |
| 141 | ARROW_ASSIGN_OR_RAISE(auto device, ExportDevice(arr)); |
| 142 | |
| 143 | // Define the DLDataType struct, or fail if the type is not supported. |
| 144 | const auto& type = *arr->type(); |
| 145 | ARROW_ASSIGN_OR_RAISE(auto dtype, GetDLDataType(type)); |
| 146 | |
| 147 | auto params = ExportBufferParams<std::array<int64_t, 1>>{ |
| 148 | .size = arr->length(), |
| 149 | .ndim = 1, |
| 150 | .strides = {1}, |
| 151 | .shape = {arr->length()}, |
| 152 | .device = device, |
| 153 | .dtype = dtype, |
| 154 | }; |
| 155 | |
| 156 | const auto& data = *arr->data(); |
| 157 | if (copy) { |
| 158 | // We copy the buffer slice instead of using Array copy functions to avoid copying |
| 159 | // unused values outside of offset/length (e.g. with Slice). |
| 160 | const auto start = data.offset * type.byte_width(); |
| 161 | const auto nbytes = data.length * type.byte_width(); |
| 162 | ARROW_ASSIGN_OR_RAISE(params.buffer, data.buffers[1]->CopySlice(start, nbytes)); |
| 163 | // Since we make a copy only for the consumer, we do not need to mark it readonly. |
| 164 | params.flags = DLPACK_FLAG_BITMASK_IS_COPIED; |
| 165 | } else { |
| 166 | // Shared buffer with Arrow Array. Arrays are readonly once constructed. |
| 167 | params.buffer = data.buffers[1]; |
| 168 | params.buffer_offset = data.offset * type.byte_width(); |
| 169 | params.flags = DLPACK_FLAG_BITMASK_READ_ONLY; |
| 170 | } |
| 171 | |
| 172 | return ExportBuffer<DT>(std::move(params)); |
| 173 | } |
| 174 | |
| 175 | template <typename T> |
| 176 | Result<DLDevice> ExportDeviceImpl(const std::shared_ptr<T>& a) { |
nothing calls this directly
no test coverage detected