NUMPY_API * Get 0-dim array from scalar * * 0-dim array from array-scalar object * always contains a copy of the data * unless outcode is NULL, it is of void type and the referrer does * not own it either. * * steals reference to outcode */
| 234 | * steals reference to outcode |
| 235 | */ |
| 236 | NPY_NO_EXPORT PyObject * |
| 237 | PyArray_FromScalar(PyObject *scalar, PyArray_Descr *outcode) |
| 238 | { |
| 239 | /* convert to 0-dim array of scalar typecode */ |
| 240 | PyArray_Descr *typecode = PyArray_DescrFromScalar(scalar); |
| 241 | if (typecode == NULL) { |
| 242 | Py_XDECREF(outcode); |
| 243 | return NULL; |
| 244 | } |
| 245 | if ((typecode->type_num == NPY_VOID) && |
| 246 | !(((PyVoidScalarObject *)scalar)->flags & NPY_ARRAY_OWNDATA) && |
| 247 | outcode == NULL) { |
| 248 | return PyArray_NewFromDescrAndBase( |
| 249 | &PyArray_Type, typecode, |
| 250 | 0, NULL, NULL, |
| 251 | ((PyVoidScalarObject *)scalar)->obval, |
| 252 | ((PyVoidScalarObject *)scalar)->flags, |
| 253 | NULL, (PyObject *)scalar); |
| 254 | } |
| 255 | |
| 256 | PyArrayObject *r = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, |
| 257 | typecode, |
| 258 | 0, NULL, |
| 259 | NULL, NULL, 0, NULL); |
| 260 | if (r == NULL) { |
| 261 | Py_XDECREF(outcode); |
| 262 | return NULL; |
| 263 | } |
| 264 | /* the dtype used by the array may be different to the one requested */ |
| 265 | typecode = PyArray_DESCR(r); |
| 266 | if (PyDataType_FLAGCHK(typecode, NPY_USE_SETITEM)) { |
| 267 | if (typecode->f->setitem(scalar, PyArray_DATA(r), r) < 0) { |
| 268 | Py_DECREF(r); |
| 269 | Py_XDECREF(outcode); |
| 270 | return NULL; |
| 271 | } |
| 272 | } |
| 273 | else { |
| 274 | char *memptr = scalar_value(scalar, typecode); |
| 275 | |
| 276 | memcpy(PyArray_DATA(r), memptr, PyArray_ITEMSIZE(r)); |
| 277 | if (PyDataType_FLAGCHK(typecode, NPY_ITEM_HASOBJECT)) { |
| 278 | /* Need to INCREF just the PyObject portion */ |
| 279 | PyArray_Item_INCREF(memptr, typecode); |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | if (outcode == NULL) { |
| 284 | return (PyObject *)r; |
| 285 | } |
| 286 | if (PyArray_EquivTypes(outcode, typecode)) { |
| 287 | if (!PyTypeNum_ISEXTENDED(typecode->type_num) |
| 288 | || (outcode->elsize == typecode->elsize)) { |
| 289 | /* |
| 290 | * Since the type is equivalent, and we haven't handed the array |
| 291 | * to anyone yet, let's fix the dtype to be what was requested, |
| 292 | * even if it is equivalent to what was passed in. |
| 293 | */ |
no test coverage detected