1
/* -*- c -*- */
2
#define PY_SSIZE_T_CLEAN
3
#include "Python.h"
4
#include "structmember.h"
5

6
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
7
#ifndef _MULTIARRAYMODULE
8
#define _MULTIARRAYMODULE
9
#endif
10

11
#include "numpy/arrayobject.h"
12
#include "numpy/npy_math.h"
13
#include "numpy/halffloat.h"
14
#include "numpy/arrayscalars.h"
15

16
#include "npy_pycompat.h"
17

18
#include "npy_config.h"
19
#include "mapping.h"
20
#include "ctors.h"
21
#include "usertypes.h"
22
#include "numpyos.h"
23
#include "common.h"
24
#include "scalartypes.h"
25
#include "_datetime.h"
26
#include "datetime_strings.h"
27
#include "alloc.h"
28
#include "npy_import.h"
29
#include "dragon4.h"
30
#include "npy_longdouble.h"
31
#include "npy_buffer.h"
32

33
#include <stdlib.h>
34

35
#include "binop_override.h"
36

37
NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[] = {
38
    {PyObject_HEAD_INIT(&PyBoolArrType_Type) 0},
39
    {PyObject_HEAD_INIT(&PyBoolArrType_Type) 1},
40
};
41

42
/* TimeInteger is deleted, but still here to fill the API slot */
43
NPY_NO_EXPORT PyTypeObject PyTimeIntegerArrType_Type;
44

45
/*
46
 * Inheritance is established later when tp_bases is set (or tp_base for
47
 * single inheritance)
48
 */
49

50
/**begin repeat
51
 * #name = number, integer, signedinteger, unsignedinteger, inexact,
52
 *         floating, complexfloating, flexible, character#
53
 * #NAME = Number, Integer, SignedInteger, UnsignedInteger, Inexact,
54
 *         Floating, ComplexFloating, Flexible, Character#
55
 */
56
NPY_NO_EXPORT PyTypeObject Py@NAME@ArrType_Type = {
57
    PyVarObject_HEAD_INIT(NULL, 0)
58
    .tp_name = "numpy.@name@",
59
    .tp_basicsize = sizeof(PyObject),
60
};
61
/**end repeat**/
62

63
static PyObject *
64 1
gentype_alloc(PyTypeObject *type, Py_ssize_t nitems)
65
{
66
    PyObject *obj;
67 1
    const size_t size = _PyObject_VAR_SIZE(type, nitems + 1);
68

69 1
    obj = (PyObject *)PyObject_Malloc(size);
70
    /*
71
     * Fixme. Need to check for no memory.
72
     * If we don't need to zero memory, we could use
73
     * PyObject_{New, NewVar} for this whole function.
74
     */
75 1
    memset(obj, 0, size);
76 1
    if (type->tp_itemsize == 0) {
77 1
        PyObject_Init(obj, type);
78
    }
79
    else {
80 1
        (void) PyObject_InitVar((PyVarObject *)obj, type, nitems);
81
    }
82 1
    return obj;
83
}
84

85
static void
86 1
gentype_dealloc(PyObject *v)
87
{
88 1
    Py_TYPE(v)->tp_free(v);
89 1
}
90

91
static void
92 1
gentype_free(PyObject *v)
93
{
94
    /*
95
     * have an explicit tp_free to enforce inheritance from it.
96
     * PyObject_Free is also the tp_free of PyBaseObject so python does not
97
     * COPYSLOT it, instead it takes the next parent PyInt which has a
98
     * different allocator
99
     */
100 1
    PyObject_Free(v);
101 1
}
102

103

104
static PyObject *
105 0
gentype_power(PyObject *m1, PyObject *m2, PyObject *modulo)
106
{
107 0
    if (modulo != Py_None) {
108
        /* modular exponentiation is not implemented (gh-8804) */
109 0
        Py_INCREF(Py_NotImplemented);
110 0
        return Py_NotImplemented;
111
    }
112

113 0
    BINOP_GIVE_UP_IF_NEEDED(m1, m2, nb_power, gentype_power);
114 0
    return PyArray_Type.tp_as_number->nb_power(m1, m2, Py_None);
115
}
116

117
static PyObject *
118 1
gentype_generic_method(PyObject *self, PyObject *args, PyObject *kwds,
119
        char *str)
120
{
121
    PyObject *arr, *meth, *ret;
122

123 1
    arr = PyArray_FromScalar(self, NULL);
124 1
    if (arr == NULL) {
125
        return NULL;
126
    }
127 1
    meth = PyObject_GetAttrString(arr, str);
128 1
    if (meth == NULL) {
129 0
        Py_DECREF(arr);
130
        return NULL;
131
    }
132 1
    if (kwds == NULL) {
133 1
        ret = PyObject_CallObject(meth, args);
134
    }
135
    else {
136 1
        ret = PyObject_Call(meth, args, kwds);
137
    }
138 1
    Py_DECREF(meth);
139 1
    Py_DECREF(arr);
140 1
    if (ret && PyArray_Check(ret)) {
141 1
        return PyArray_Return((PyArrayObject *)ret);
142
    }
143
    else {
144
        return ret;
145
    }
146
}
147

148
static PyObject *
149 1
gentype_add(PyObject *m1, PyObject* m2)
150
{
151
    /* special case str.__radd__, which should not call array_add */
152 1
    if (PyBytes_Check(m1) || PyUnicode_Check(m1)) {
153 1
        Py_INCREF(Py_NotImplemented);
154 1
        return Py_NotImplemented;
155
    }
156 1
    BINOP_GIVE_UP_IF_NEEDED(m1, m2, nb_add, gentype_add);
157 1
    return PyArray_Type.tp_as_number->nb_add(m1, m2);
158
}
159

160
/**begin repeat
161
 *
162
 * #name = subtract, remainder, divmod, lshift, rshift,
163
 *         and, xor, or, floor_divide, true_divide#
164
 */
165
static PyObject *
166 1
gentype_@name@(PyObject *m1, PyObject *m2)
167
{
168 1
    BINOP_GIVE_UP_IF_NEEDED(m1, m2, nb_@name@, gentype_@name@);
169 1
    return PyArray_Type.tp_as_number->nb_@name@(m1, m2);
170
}
171

172
/**end repeat**/
173

174
/* Get a nested slot, or NULL if absent */
175
#define GET_NESTED_SLOT(type, group, slot) \
176
    ((type)->group == NULL ? NULL : (type)->group->slot)
177

178
static PyObject *
179 1
gentype_multiply(PyObject *m1, PyObject *m2)
180
{
181
    /*
182
     * If the other object supports sequence repeat and not number multiply
183
     * we fall back on the python builtin to invoke the sequence repeat, rather
184
     * than promoting both arguments to ndarray.
185
     * This covers a list repeat by numpy scalars.
186
     * A python defined class will always only have the nb_multiply slot and
187
     * some classes may have neither defined. For the latter we want need
188
     * to give the normal case a chance to convert the object to ndarray.
189
     * Probably no class has both defined, but if they do, prefer number.
190
     */
191 1
    if (!PyArray_IsScalar(m1, Generic) &&
192 1
            GET_NESTED_SLOT(Py_TYPE(m1), tp_as_sequence, sq_repeat) != NULL &&
193 1
            GET_NESTED_SLOT(Py_TYPE(m1), tp_as_number, nb_multiply) == NULL) {
194 1
        Py_INCREF(Py_NotImplemented);
195 1
        return Py_NotImplemented;
196
    }
197 1
    if (!PyArray_IsScalar(m2, Generic) &&
198 1
            GET_NESTED_SLOT(Py_TYPE(m2), tp_as_sequence, sq_repeat) != NULL &&
199 1
            GET_NESTED_SLOT(Py_TYPE(m2), tp_as_number, nb_multiply) == NULL) {
200 1
        Py_INCREF(Py_NotImplemented);
201 1
        return Py_NotImplemented;
202
    }
203
    /* All normal cases are handled by PyArray's multiply */
204 1
    BINOP_GIVE_UP_IF_NEEDED(m1, m2, nb_multiply, gentype_multiply);
205 1
    return PyArray_Type.tp_as_number->nb_multiply(m1, m2);
206
}
207

208
/**begin repeat
209
 *
210
 * #name = positive, negative, absolute, invert, int, float#
211
 */
212
static PyObject *
213 1
gentype_@name@(PyObject *m1)
214
{
215
    PyObject *arr, *ret;
216

217 1
    arr = PyArray_FromScalar(m1, NULL);
218 1
    if (arr == NULL) {
219
        return NULL;
220
    }
221 1
    ret = Py_TYPE(arr)->tp_as_number->nb_@name@(arr);
222 1
    Py_DECREF(arr);
223
    return ret;
224
}
225
/**end repeat**/
226

227
static int
228 1
gentype_nonzero_number(PyObject *m1)
229
{
230
    PyObject *arr;
231
    int ret;
232

233 1
    arr = PyArray_FromScalar(m1, NULL);
234 1
    if (arr == NULL) {
235
        return -1;
236
    }
237 1
    ret = Py_TYPE(arr)->tp_as_number->nb_bool(arr);
238 1
    Py_DECREF(arr);
239
    return ret;
240
}
241

242
static PyObject *
243 1
genint_type_str(PyObject *self)
244
{
245
    PyObject  *item, *item_str;
246 1
    item = gentype_generic_method(self, NULL, NULL, "item");
247 1
    if (item == NULL) {
248
        return NULL;
249
    }
250

251 1
    item_str = PyObject_Str(item);
252 1
    Py_DECREF(item);
253
    return item_str;
254
}
255

256
/*
257
 * The __format__ method for PEP 3101.
258
 */
259
static PyObject *
260 1
gentype_format(PyObject *self, PyObject *args)
261
{
262
    PyObject *format_spec;
263
    PyObject *obj, *ret;
264

265 1
    if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) {
266
        return NULL;
267
    }
268

269
    /*
270
     * Convert to an appropriate Python type and call its format.
271
     * TODO: For some types, like long double, this isn't right,
272
     *       because it throws away precision.
273
     */
274 1
    if (Py_TYPE(self) == &PyBoolArrType_Type) {
275 1
        obj = PyBool_FromLong(PyArrayScalar_VAL(self, Bool));
276
    }
277 1
    else if (PyArray_IsScalar(self, Integer)) {
278 1
        obj = Py_TYPE(self)->tp_as_number->nb_int(self);
279
    }
280 1
    else if (PyArray_IsScalar(self, Floating)) {
281 1
        obj = Py_TYPE(self)->tp_as_number->nb_float(self);
282
    }
283 1
    else if (PyArray_IsScalar(self, ComplexFloating)) {
284
        double val[2];
285 1
        PyArray_Descr *dtype = PyArray_DescrFromScalar(self);
286

287 1
        if (dtype == NULL) {
288 0
            return NULL;
289
        }
290 1
        if (PyArray_CastScalarDirect(self, dtype, &val[0], NPY_CDOUBLE) < 0) {
291 0
            Py_DECREF(dtype);
292
            return NULL;
293
        }
294 1
        obj = PyComplex_FromDoubles(val[0], val[1]);
295 1
        Py_DECREF(dtype);
296
    }
297
    else {
298 1
        obj = PyObject_Str(self);
299
    }
300

301 1
    if (obj == NULL) {
302
        return NULL;
303
    }
304

305 1
    ret = PyObject_Format(obj, format_spec);
306 1
    Py_DECREF(obj);
307
    return ret;
308
}
309

310
#ifdef FORCE_NO_LONG_DOUBLE_FORMATTING
311
#undef NPY_LONGDOUBLE_FMT
312
#define NPY_LONGDOUBLE_FMT NPY_DOUBLE_FMT
313
#endif
314

315
/**begin repeat
316
 * #name = half, float, double, longdouble#
317
 * #Name = Half, Float, Double, LongDouble#
318
 * #NAME = HALF, FLOAT, DOUBLE, LONGDOUBLE#
319
 * #type = npy_half, npy_float, npy_double, npy_longdouble#
320
 * #suff = h, f, d, l#
321
 */
322

323
NPY_NO_EXPORT PyObject *
324 1
format_@name@(@type@ val, npy_bool scientific,
325
              int precision, int sign, TrimMode trim,
326
              int pad_left, int pad_right, int exp_digits)
327
{
328 1
    if (scientific) {
329 1
        return Dragon4_Scientific_@Name@(&val,
330
                        DigitMode_Unique, precision,
331
                        sign, trim, pad_left, exp_digits);
332
    }
333
    else {
334 1
        return Dragon4_Positional_@Name@(&val,
335
                        DigitMode_Unique, CutoffMode_TotalLength, precision,
336
                        sign, trim, pad_left, pad_right);
337
    }
338
}
339

340

341
/**end repeat**/
342

343
/*
344
 * Over-ride repr and str of array-scalar byte strings to remove NULL bytes and
345
 * then call the corresponding functions of PyBytes_Type to generate the string
346
 */
347

348
/**begin repeat
349
 * #form = repr, str#
350
 */
351
static PyObject *
352 1
stringtype_@form@(PyObject *self)
353
{
354
    const npy_char *dptr, *ip;
355
    Py_ssize_t len;
356
    PyObject *new;
357
    PyObject *ret;
358

359 1
    ip = PyBytes_AS_STRING(self);
360 1
    len = PyBytes_GET_SIZE(self);
361 1
    for(dptr = ip + len - 1; len > 0 && *dptr == 0; len--, dptr--);
362 1
    new = PyBytes_FromStringAndSize(ip, len);
363 1
    if (new == NULL) {
364
        return NULL;
365
    }
366 1
    ret = PyBytes_Type.tp_@form@(new);
367 1
    Py_DECREF(new);
368
    return ret;
369
}
370
/**end repeat**/
371

372
/*
373
 * Over-ride repr and str of array-scalar strings to remove NULL code points and
374
 * then call the corresponding functions of PyUnicode_Type to generate the string
375
 */
376

377
/**begin repeat
378
 * #form = repr, str#
379
 */
380
static PyObject *
381 1
unicodetype_@form@(PyObject *self)
382
{
383
    Py_UCS4 *dptr, *ip;
384
    Py_ssize_t len;
385
    PyObject *new;
386
    PyObject *ret;
387

388
    /* PyUnicode_READY is called by PyUnicode_GetLength */
389 1
    len = PyUnicode_GetLength(self);
390 1
    ip = PyUnicode_AsUCS4Copy(self);
391 1
    if (ip == NULL) {
392
        return NULL;
393
    }
394 1
    for(dptr = ip + len - 1; len > 0 && *dptr == 0; len--, dptr--);
395 1
    new = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, ip, len);
396 1
    if (new == NULL) {
397 0
        PyMem_Free(ip);
398 0
        return NULL;
399
    }
400 1
    ret = PyUnicode_Type.tp_@form@(new);
401 1
    Py_DECREF(new);
402 1
    PyMem_Free(ip);
403 1
    return ret;
404
}
405
/**end repeat**/
406

407
/*
408
 * Convert array of bytes to a string representation much like bytes.__repr__,
409
 * but convert all bytes (including ASCII) to the `\x00` notation with
410
 * uppercase hex codes (FF not ff).
411
 *
412
 * Largely copied from _Py_strhex_impl in CPython implementation
413
 */
414
static NPY_INLINE PyObject *
415 1
_void_to_hex(const char* argbuf, const Py_ssize_t arglen,
416
             const char *schars, const char *bprefix, const char *echars)
417
{
418
    PyObject *retval;
419
    int extrachars, slen;
420
    char *retbuf;
421
    Py_ssize_t i, j;
422 1
    char const *hexdigits = "0123456789ABCDEF";
423

424 1
    extrachars = strlen(schars) + strlen(echars);
425 1
    slen = extrachars + arglen*(2 + strlen(bprefix));
426

427 1
    if (arglen > (PY_SSIZE_T_MAX / 2) - extrachars) {
428 0
        return PyErr_NoMemory();
429
    }
430

431 1
    retbuf = (char *)PyMem_Malloc(slen);
432 1
    if (!retbuf) {
433 0
        return PyErr_NoMemory();
434
    }
435

436 1
    memcpy(retbuf, schars, strlen(schars));
437 1
    j = strlen(schars);
438

439 1
    for (i = 0; i < arglen; i++) {
440
        unsigned char c;
441 1
        memcpy(&retbuf[j], bprefix, strlen(bprefix));
442 1
        j += strlen(bprefix);
443 1
        c = (argbuf[i] >> 4) & 0xf;
444 1
        retbuf[j++] = hexdigits[c];
445 1
        c = argbuf[i] & 0xf;
446 1
        retbuf[j++] = hexdigits[c];
447
    }
448 1
    memcpy(&retbuf[j], echars, strlen(echars));
449

450 1
    retval = PyUnicode_FromStringAndSize(retbuf, slen);
451 1
    PyMem_Free(retbuf);
452

453 1
    return retval;
454
}
455

456
static PyObject *
457 1
_void_scalar_repr(PyObject *obj) {
458
    static PyObject *reprfunc = NULL;
459 1
    npy_cache_import("numpy.core.arrayprint",
460
                     "_void_scalar_repr", &reprfunc);
461 1
    if (reprfunc == NULL) {
462
        return NULL;
463
    }
464 1
    return PyObject_CallFunction(reprfunc, "O", obj);
465
}
466

467
static PyObject *
468 1
voidtype_repr(PyObject *self)
469
{
470 1
    PyVoidScalarObject *s = (PyVoidScalarObject*) self;
471 1
    if (PyDataType_HASFIELDS(s->descr)) {
472 1
        return _void_scalar_repr(self);
473
    }
474 1
    return _void_to_hex(s->obval, s->descr->elsize, "void(b'", "\\x", "')");
475
}
476

477
static PyObject *
478 1
voidtype_str(PyObject *self)
479
{
480 1
    PyVoidScalarObject *s = (PyVoidScalarObject*) self;
481 1
    if (PyDataType_HASFIELDS(s->descr)) {
482 1
        return _void_scalar_repr(self);
483
    }
484 1
    return _void_to_hex(s->obval, s->descr->elsize, "b'", "\\x", "'");
485
}
486

487
static PyObject *
488 1
datetimetype_repr(PyObject *self)
489
{
490
    PyDatetimeScalarObject *scal;
491
    npy_datetimestruct dts;
492
    PyObject *ret;
493
    char iso[NPY_DATETIME_MAX_ISO8601_STRLEN];
494
    NPY_DATETIMEUNIT unit;
495

496 1
    if (!PyArray_IsScalar(self, Datetime)) {
497 0
        PyErr_SetString(PyExc_RuntimeError,
498
                "Called NumPy datetime repr on a non-datetime type");
499 0
        return NULL;
500
    }
501

502 1
    scal = (PyDatetimeScalarObject *)self;
503

504 1
    if (convert_datetime_to_datetimestruct(&scal->obmeta,
505
                scal->obval, &dts) < 0) {
506
        return NULL;
507
    }
508

509 1
    unit = scal->obmeta.base;
510 1
    if (make_iso_8601_datetime(&dts, iso, sizeof(iso), 0, 0,
511
                            unit, -1, NPY_SAFE_CASTING) < 0) {
512
        return NULL;
513
    }
514

515
    /*
516
     * For straight units or generic units, the unit will be deduced
517
     * from the string, so it's not necessary to specify it.
518
     */
519 1
    if ((scal->obmeta.num == 1 && scal->obmeta.base != NPY_FR_h) ||
520 1
            scal->obmeta.base == NPY_FR_GENERIC) {
521 1
        ret = PyUnicode_FromString("numpy.datetime64('");
522 1
        PyUString_ConcatAndDel(&ret,
523
                PyUnicode_FromString(iso));
524 1
        PyUString_ConcatAndDel(&ret,
525
                PyUnicode_FromString("')"));
526
    }
527
    else {
528 1
        ret = PyUnicode_FromString("numpy.datetime64('");
529 1
        PyUString_ConcatAndDel(&ret,
530
                PyUnicode_FromString(iso));
531 1
        PyUString_ConcatAndDel(&ret,
532
                PyUnicode_FromString("','"));
533 1
        ret = append_metastr_to_string(&scal->obmeta, 1, ret);
534 1
        PyUString_ConcatAndDel(&ret,
535
                PyUnicode_FromString("')"));
536
    }
537

538 1
    return ret;
539
}
540

541
static PyObject *
542 1
timedeltatype_repr(PyObject *self)
543
{
544
    PyTimedeltaScalarObject *scal;
545
    PyObject *ret;
546

547 1
    if (!PyArray_IsScalar(self, Timedelta)) {
548 0
        PyErr_SetString(PyExc_RuntimeError,
549
                "Called NumPy timedelta repr on a non-datetime type");
550 0
        return NULL;
551
    }
552

553 1
    scal = (PyTimedeltaScalarObject *)self;
554

555
    /* The value */
556 1
    if (scal->obval == NPY_DATETIME_NAT) {
557 1
        ret = PyUnicode_FromString("numpy.timedelta64('NaT'");
558
    }
559
    else {
560
        /*
561
         * Can't use "%lld" if HAVE_LONG_LONG is not defined
562
         */
563
#if defined(HAVE_LONG_LONG)
564 1
        ret = PyUnicode_FromFormat("numpy.timedelta64(%lld",
565
                                            (long long)scal->obval);
566
#else
567
        ret = PyUnicode_FromFormat("numpy.timedelta64(%ld",
568
                                            (long)scal->obval);
569
#endif
570
    }
571
    /* The metadata unit */
572 1
    if (scal->obmeta.base == NPY_FR_GENERIC) {
573 1
        PyUString_ConcatAndDel(&ret,
574
                PyUnicode_FromString(")"));
575
    }
576
    else {
577 1
        PyUString_ConcatAndDel(&ret,
578
                PyUnicode_FromString(",'"));
579 1
        ret = append_metastr_to_string(&scal->obmeta, 1, ret);
580 1
        PyUString_ConcatAndDel(&ret,
581
                PyUnicode_FromString("')"));
582
    }
583

584 1
    return ret;
585
}
586

587
static PyObject *
588 1
datetimetype_str(PyObject *self)
589
{
590
    PyDatetimeScalarObject *scal;
591
    npy_datetimestruct dts;
592
    char iso[NPY_DATETIME_MAX_ISO8601_STRLEN];
593
    NPY_DATETIMEUNIT unit;
594

595 1
    if (!PyArray_IsScalar(self, Datetime)) {
596 0
        PyErr_SetString(PyExc_RuntimeError,
597
                "Called NumPy datetime str on a non-datetime type");
598 0
        return NULL;
599
    }
600

601 1
    scal = (PyDatetimeScalarObject *)self;
602

603 1
    if (convert_datetime_to_datetimestruct(&scal->obmeta, scal->obval,
604
                                                            &dts) < 0) {
605
        return NULL;
606
    }
607

608 1
    unit = scal->obmeta.base;
609 1
    if (make_iso_8601_datetime(&dts, iso, sizeof(iso), 0, 0,
610
                            unit, -1, NPY_SAFE_CASTING) < 0) {
611
        return NULL;
612
    }
613

614 1
    return PyUnicode_FromString(iso);
615
}
616

617
static char *_datetime_verbose_strings[NPY_DATETIME_NUMUNITS] = {
618
    "years",
619
    "months",
620
    "weeks",
621
    "<invalid>",
622
    "days",
623
    "hours",
624
    "minutes",
625
    "seconds",
626
    "milliseconds",
627
    "microseconds",
628
    "nanoseconds",
629
    "picoseconds",
630
    "femtoseconds",
631
    "attoseconds",
632
    "generic time units"
633
};
634

635
static PyObject *
636 1
timedeltatype_str(PyObject *self)
637
{
638
    PyTimedeltaScalarObject *scal;
639
    PyObject *ret;
640 1
    char *basestr = "invalid";
641

642 1
    if (!PyArray_IsScalar(self, Timedelta)) {
643 0
        PyErr_SetString(PyExc_RuntimeError,
644
                "Called NumPy timedelta str on a non-datetime type");
645 0
        return NULL;
646
    }
647

648 1
    scal = (PyTimedeltaScalarObject *)self;
649

650 1
    if (scal->obmeta.base >= 0 && scal->obmeta.base < NPY_DATETIME_NUMUNITS) {
651 1
        basestr = _datetime_verbose_strings[scal->obmeta.base];
652
    }
653
    else {
654 0
        PyErr_SetString(PyExc_RuntimeError,
655
                "NumPy datetime metadata is corrupted");
656 0
        return NULL;
657
    }
658

659 1
    if (scal->obval == NPY_DATETIME_NAT) {
660 1
        ret = PyUnicode_FromString("NaT");
661
    }
662
    else {
663
        /*
664
         * Can't use "%lld" if HAVE_LONG_LONG is not defined
665
         */
666
#if defined(HAVE_LONG_LONG)
667 1
        ret = PyUnicode_FromFormat("%lld ",
668 1
                                (long long)(scal->obval * scal->obmeta.num));
669
#else
670
        ret = PyUnicode_FromFormat("%ld ",
671
                                (long)(scal->obval * scal->obmeta.num));
672
#endif
673 1
        PyUString_ConcatAndDel(&ret,
674
                PyUnicode_FromString(basestr));
675
    }
676

677 1
    return ret;
678
}
679

680
/*
681
 * float type str and repr
682
 *
683
 * These functions will return NULL if PyString creation fails.
684
 */
685

686

687
/*
688
 *               *** BEGIN LEGACY PRINTING MODE CODE ***
689
 *
690
 * This code is legacy code needed to reproduce the printing behavior of
691
 * scalars in numpy 1.13. One day we hope to remove it.
692
 */
693

694
/* determines if legacy mode is enabled, global set in multiarraymodule.c */
695
extern int npy_legacy_print_mode;
696

697
#define HALFPREC_REPR 5
698
#define HALFPREC_STR 5
699
#define FLOATPREC_REPR 8
700
#define FLOATPREC_STR 6
701
#define DOUBLEPREC_REPR 17
702
#define DOUBLEPREC_STR 12
703
#if NPY_SIZEOF_LONGDOUBLE == NPY_SIZEOF_DOUBLE
704
#define LONGDOUBLEPREC_REPR DOUBLEPREC_REPR
705
#define LONGDOUBLEPREC_STR DOUBLEPREC_STR
706
#else /* More than probably needed on Intel FP */
707
#define LONGDOUBLEPREC_REPR 20
708
#define LONGDOUBLEPREC_STR 12
709
#endif
710

711
/**begin repeat
712
 * #kind = str, repr#
713
 * #KIND = STR, REPR#
714
 */
715

716
/**begin repeat1
717
 * #name = cfloat, cdouble, clongdouble#
718
 * #NAME = FLOAT, DOUBLE, LONGDOUBLE#
719
 * #type = npy_cfloat, npy_cdouble, npy_clongdouble#
720
 * #suff = f, d, l#
721
 */
722

723
#define _FMT1 "%%.%i" NPY_@NAME@_FMT
724
#define _FMT2 "%%+.%i" NPY_@NAME@_FMT
725

726
static PyObject*
727 1
legacy_@name@_format@kind@(@type@ val)
728
{
729
    /* XXX: Find a correct size here for format string */
730
    char format[64], buf[100], *res;
731

732
    /*
733
     * Ideally, we should handle this nan/inf stuff in NumpyOS_ascii_format*
734
     */
735 1
    if (val.real == 0.0 && npy_signbit(val.real) == 0) {
736 0
        PyOS_snprintf(format, sizeof(format), _FMT1, @NAME@PREC_@KIND@);
737 0
        res = NumPyOS_ascii_format@suff@(buf, sizeof(buf) - 1, format, val.imag, 0);
738 0
        if (res == NULL) {
739 0
            PyErr_SetString(PyExc_RuntimeError, "Error while formatting");
740 0
            return NULL;
741
        }
742 0
        if (!npy_isfinite(val.imag)) {
743 0
            strncat(buf, "*", sizeof(buf) - strlen(buf) - 1);
744
        }
745 0
        strncat(buf, "j", sizeof(buf) - strlen(buf) - 1);
746
    }
747
    else {
748
        char re[64], im[64];
749

750 1
        if (npy_isfinite(val.real)) {
751 1
            PyOS_snprintf(format, sizeof(format), _FMT1, @NAME@PREC_@KIND@);
752 1
            res = NumPyOS_ascii_format@suff@(re, sizeof(re), format,
753
                                             val.real, 0);
754 1
            if (res == NULL) {
755 0
                PyErr_SetString(PyExc_RuntimeError, "Error while formatting");
756 0
                return NULL;
757
            }
758
        }
759
        else {
760 0
            if (npy_isnan(val.real)) {
761
                strcpy(re, "nan");
762
            }
763 0
            else if (val.real > 0){
764
                strcpy(re, "inf");
765
            }
766
            else {
767
                strcpy(re, "-inf");
768
            }
769
        }
770

771

772 1
        if (npy_isfinite(val.imag)) {
773 0
            PyOS_snprintf(format, sizeof(format), _FMT2, @NAME@PREC_@KIND@);
774 0
            res = NumPyOS_ascii_format@suff@(im, sizeof(im), format,
775
                                             val.imag, 0);
776 0
            if (res == NULL) {
777 0
                PyErr_SetString(PyExc_RuntimeError, "Error while formatting");
778 0
                return NULL;
779
            }
780
        }
781
        else {
782 1
            if (npy_isnan(val.imag)) {
783
                strcpy(im, "+nan");
784
            }
785 0
            else if (val.imag > 0){
786
                strcpy(im, "+inf");
787
            }
788
            else {
789
                strcpy(im, "-inf");
790
            }
791
            if (!npy_isfinite(val.imag)) {
792 1
                strncat(im, "*", sizeof(im) - strlen(im) - 1);
793
            }
794
        }
795 1
        PyOS_snprintf(buf, sizeof(buf), "(%s%sj)", re, im);
796
    }
797

798 1
    return PyUnicode_FromString(buf);
799
}
800

801
#undef _FMT1
802
#undef _FMT2
803

804
/**end repeat1**/
805

806
/**begin repeat1
807
 * #name = float, double, longdouble#
808
 * #Name = Float, Double, LongDouble#
809
 * #NAME = FLOAT, DOUBLE, LONGDOUBLE#
810
 * #suff = f, d, l#
811
 */
812

813
#define _FMT1 "%%.%i" NPY_@NAME@_FMT
814

815
static PyObject *
816 1
legacy_@name@_format@kind@(npy_@name@ val){
817
    /* XXX: Find a correct size here for format string */
818
    char format[64], buf[100], *res;
819
    size_t i, cnt;
820

821 1
    PyOS_snprintf(format, sizeof(format), _FMT1, @NAME@PREC_@KIND@);
822 1
    res = NumPyOS_ascii_format@suff@(buf, sizeof(buf), format, val, 0);
823 1
    if (res == NULL) {
824 0
        PyErr_SetString(PyExc_RuntimeError, "Error while formatting");
825 0
        return NULL;
826
    }
827

828
    /* If nothing but digits after sign, append ".0" */
829 1
    cnt = strlen(buf);
830 1
    for (i = (buf[0] == '-') ? 1 : 0; i < cnt; ++i) {
831 1
        if (!isdigit(Py_CHARMASK(buf[i]))) {
832
            break;
833
        }
834
    }
835 1
    if (i == cnt && sizeof(buf) >= cnt + 3) {
836 0
        strcpy(&buf[cnt],".0");
837
    }
838

839 1
    return PyUnicode_FromString(buf);
840
}
841

842
#undef _FMT1
843

844
/**end repeat1**/
845

846
/**end repeat**/
847

848

849
/*
850
 *               *** END LEGACY PRINTING MODE CODE ***
851
 */
852

853

854
/**begin repeat
855
 * #kind = str, repr#
856
 */
857

858
/**begin repeat1
859
 * #name = float, double, longdouble#
860
 * #Name = Float, Double, LongDouble#
861
 * #NAME = FLOAT, DOUBLE, LONGDOUBLE#
862
 */
863

864
/* helper function choose scientific of fractional output, based on a cutoff */
865
static PyObject *
866 1
@name@type_@kind@_either(npy_@name@ val, TrimMode trim_pos, TrimMode trim_sci,
867
                         npy_bool sign)
868
{
869
    npy_@name@ absval;
870

871 1
    if (npy_legacy_print_mode == 113) {
872 1
        return legacy_@name@_format@kind@(val);
873
    }
874

875 1
    absval = val < 0 ? -val : val;
876

877 1
    if (absval == 0 || (absval < 1.e16L && absval >= 1.e-4L) ) {
878 1
        return format_@name@(val, 0, -1, sign, trim_pos, -1, -1, -1);
879
    }
880 1
    return format_@name@(val, 1, -1, sign, trim_sci, -1, -1, -1);
881
}
882

883
static PyObject *
884 1
@name@type_@kind@(PyObject *self)
885
{
886 1
    return @name@type_@kind@_either(PyArrayScalar_VAL(self, @Name@),
887
                                  TrimMode_LeaveOneZero, TrimMode_DptZeros, 0);
888
}
889

890
static PyObject *
891 1
c@name@type_@kind@(PyObject *self)
892
{
893
    PyObject *rstr, *istr, *ret;
894 1
    npy_c@name@ val = PyArrayScalar_VAL(self, C@Name@);
895 1
    TrimMode trim = TrimMode_DptZeros;
896

897 1
    if (npy_legacy_print_mode == 113) {
898 1
        return legacy_c@name@_format@kind@(val);
899
    }
900

901 1
    if (val.real == 0.0 && npy_signbit(val.real) == 0) {
902 1
        istr = @name@type_@kind@_either(val.imag, trim, trim, 0);
903 1
        if (istr == NULL) {
904
            return NULL;
905
        }
906

907 1
        PyUString_ConcatAndDel(&istr, PyUnicode_FromString("j"));
908 1
        return istr;
909
    }
910

911 1
    if (npy_isfinite(val.real)) {
912 1
        rstr = @name@type_@kind@_either(val.real, trim, trim, 0);
913 1
        if (rstr == NULL) {
914
            return NULL;
915
        }
916
    }
917 1
    else if (npy_isnan(val.real)) {
918 1
        rstr = PyUnicode_FromString("nan");
919
    }
920 1
    else if (val.real > 0){
921 1
        rstr = PyUnicode_FromString("inf");
922
    }
923
    else {
924 1
        rstr = PyUnicode_FromString("-inf");
925
    }
926

927 1
    if (npy_isfinite(val.imag)) {
928 1
        istr = @name@type_@kind@_either(val.imag, trim, trim, 1);
929 1
        if (istr == NULL) {
930
            return NULL;
931
        }
932
    }
933 1
    else if (npy_isnan(val.imag)) {
934 1
        istr = PyUnicode_FromString("+nan");
935
    }
936 1
    else if (val.imag > 0){
937 1
        istr = PyUnicode_FromString("+inf");
938
    }
939
    else {
940 1
        istr = PyUnicode_FromString("-inf");
941
    }
942

943 1
    ret = PyUnicode_FromString("(");
944 1
    PyUString_ConcatAndDel(&ret, rstr);
945 1
    PyUString_ConcatAndDel(&ret, istr);
946 1
    PyUString_ConcatAndDel(&ret, PyUnicode_FromString("j)"));
947 1
    return ret;
948
}
949

950
#undef PREC
951

952
/**end repeat1**/
953

954

955
static PyObject *
956 1
halftype_@kind@(PyObject *self)
957
{
958 1
    npy_half val = PyArrayScalar_VAL(self, Half);
959 1
    float floatval = npy_half_to_float(val);
960
    float absval;
961

962 1
    if (npy_legacy_print_mode == 113) {
963 0
        return legacy_float_format@kind@(floatval);
964
    }
965

966 1
    absval = floatval < 0 ? -floatval : floatval;
967

968 1
    if (absval == 0 || (absval < 1.e16 && absval >= 1.e-4) ) {
969 1
        return format_half(val, 0, -1, 0, TrimMode_LeaveOneZero, -1, -1, -1);
970
    }
971 1
    return format_half(val, 1, -1, 0, TrimMode_DptZeros, -1, -1, -1);
972
}
973

974

975
/**end repeat**/
976

977
/**begin repeat
978
 * #char = ,c#
979
 * #CHAR = ,C#
980
 * #POST = ,.real#
981
 */
982
static PyObject *
983 0
@char@longdoubletype_float(PyObject *self)
984
{
985 0
    npy_longdouble val = PyArrayScalar_VAL(self, @CHAR@LongDouble)@POST@;
986 0
    return PyFloat_FromDouble((double) val);
987
}
988

989
static PyObject *
990 0
@char@longdoubletype_long(PyObject *self)
991
{
992 0
    npy_longdouble val = PyArrayScalar_VAL(self, @CHAR@LongDouble)@POST@;
993 0
    return npy_longdouble_to_PyLong(val);
994
}
995

996
/**end repeat**/
997

998
static PyNumberMethods gentype_as_number = {
999
    .nb_add = (binaryfunc)gentype_add,
1000
    .nb_subtract = (binaryfunc)gentype_subtract,
1001
    .nb_multiply = (binaryfunc)gentype_multiply,
1002
    .nb_remainder = (binaryfunc)gentype_remainder,
1003
    .nb_divmod = (binaryfunc)gentype_divmod,
1004
    .nb_power = (ternaryfunc)gentype_power,
1005
    .nb_negative = (unaryfunc)gentype_negative,
1006
    .nb_positive = (unaryfunc)gentype_positive,
1007
    .nb_absolute = (unaryfunc)gentype_absolute,
1008
    .nb_bool = (inquiry)gentype_nonzero_number,
1009
    .nb_invert = (unaryfunc)gentype_invert,
1010
    .nb_lshift = (binaryfunc)gentype_lshift,
1011
    .nb_rshift = (binaryfunc)gentype_rshift,
1012
    .nb_and = (binaryfunc)gentype_and,
1013
    .nb_xor = (binaryfunc)gentype_xor,
1014
    .nb_or = (binaryfunc)gentype_or,
1015
    .nb_int = (unaryfunc)gentype_int,
1016
    .nb_float = (unaryfunc)gentype_float,
1017
    .nb_floor_divide = (binaryfunc)gentype_floor_divide,
1018
    .nb_true_divide = (binaryfunc)gentype_true_divide,
1019
};
1020

1021

1022
static PyObject *
1023 1
gentype_richcompare(PyObject *self, PyObject *other, int cmp_op)
1024
{
1025
    PyObject *arr, *ret;
1026

1027
    /*
1028
     * If the other object is None, False is always right. This avoids
1029
     * the array None comparison, at least until deprecation it is fixed.
1030
     * After that, this may be removed and numpy false would be returned.
1031
     *
1032
     * NOTE: np.equal(NaT, None) evaluates to TRUE! This is an
1033
     *       an inconsistency, which may has to be considered
1034
     *       when the deprecation is finished.
1035
     */
1036 1
    if (other == Py_None) {
1037 1
        if (cmp_op == Py_EQ) {
1038 1
            Py_RETURN_FALSE;
1039
        }
1040 1
        if (cmp_op == Py_NE) {
1041 1
            Py_RETURN_TRUE;
1042
        }
1043
    }
1044

1045 1
    arr = PyArray_FromScalar(self, NULL);
1046 1
    if (arr == NULL) {
1047
        return NULL;
1048
    }
1049
    /*
1050
     * Call via PyObject_RichCompare to ensure that other.__eq__
1051
     * has a chance to run when necessary
1052
     */
1053 1
    ret = PyObject_RichCompare(arr, other, cmp_op);
1054 1
    Py_DECREF(arr);
1055
    return ret;
1056
}
1057

1058
static PyObject *
1059 1
gentype_ndim_get(PyObject *NPY_UNUSED(self))
1060
{
1061 1
    return PyLong_FromLong(0);
1062
}
1063

1064
static PyObject *
1065 1
gentype_flags_get(PyObject *NPY_UNUSED(self))
1066
{
1067 1
    return PyArray_NewFlagsObject(NULL);
1068
}
1069

1070
static PyObject *
1071 1
voidtype_flags_get(PyVoidScalarObject *self)
1072
{
1073
    PyObject *flagobj;
1074 1
    flagobj = PyArrayFlags_Type.tp_alloc(&PyArrayFlags_Type, 0);
1075 1
    if (flagobj == NULL) {
1076
        return NULL;
1077
    }
1078 1
    ((PyArrayFlagsObject *)flagobj)->arr = NULL;
1079 1
    ((PyArrayFlagsObject *)flagobj)->flags = self->flags;
1080 1
    return flagobj;
1081
}
1082

1083
static PyObject *
1084 1
voidtype_dtypedescr_get(PyVoidScalarObject *self)
1085
{
1086 1
    Py_INCREF(self->descr);
1087 1
    return (PyObject *)self->descr;
1088
}
1089

1090

1091
static PyObject *
1092 1
inttype_numerator_get(PyObject *self)
1093
{
1094 1
    Py_INCREF(self);
1095 1
    return self;
1096
}
1097

1098

1099
static PyObject *
1100 1
inttype_denominator_get(PyObject *self)
1101
{
1102 1
    return PyLong_FromLong(1);
1103
}
1104

1105

1106
static PyObject *
1107 1
gentype_data_get(PyObject *self)
1108
{
1109 1
    return PyMemoryView_FromObject(self);
1110
}
1111

1112

1113
static PyObject *
1114 1
gentype_itemsize_get(PyObject *self)
1115
{
1116
    PyArray_Descr *typecode;
1117
    PyObject *ret;
1118
    int elsize;
1119

1120 1
    typecode = PyArray_DescrFromScalar(self);
1121 1
    elsize = typecode->elsize;
1122 1
    ret = PyLong_FromLong((long) elsize);
1123 1
    Py_DECREF(typecode);
1124 1
    return ret;
1125
}
1126

1127
static PyObject *
1128 1
gentype_size_get(PyObject *NPY_UNUSED(self))
1129
{
1130 1
    return PyLong_FromLong(1);
1131
}
1132

1133
static PyObject *
1134 1
gentype_sizeof(PyObject *self)
1135
{
1136
    Py_ssize_t nbytes;
1137 1
    PyObject * isz = gentype_itemsize_get(self);
1138 1
    if (isz == NULL) {
1139
        return NULL;
1140
    }
1141 1
    nbytes = PyLong_AsLong(isz) + Py_TYPE(self)->tp_basicsize +
1142 1
        Py_SIZE(self) * Py_TYPE(self)->tp_itemsize;
1143 1
    Py_DECREF(isz);
1144 1
    return PyLong_FromSsize_t(nbytes);
1145
}
1146

1147
NPY_NO_EXPORT void
1148 1
gentype_struct_free(PyObject *ptr)
1149
{
1150 1
    PyArrayInterface *arrif = (PyArrayInterface*)PyCapsule_GetPointer(ptr, NULL);
1151 1
    if (arrif == NULL) {
1152 0
        PyErr_WriteUnraisable(ptr);
1153 0
        return;
1154
    }
1155 1
    PyObject *context = (PyObject *)PyCapsule_GetContext(ptr);
1156 1
    if (context == NULL && PyErr_Occurred()) {
1157 0
        PyErr_WriteUnraisable(ptr);
1158
    }
1159 1
    Py_XDECREF(context);
1160 1
    Py_XDECREF(arrif->descr);
1161 1
    PyArray_free(arrif->shape);
1162 1
    PyArray_free(arrif);
1163
}
1164

1165
static PyObject *
1166 0
gentype_struct_get(PyObject *self)
1167
{
1168
    PyArrayObject *arr;
1169
    PyArrayInterface *inter;
1170
    PyObject *ret;
1171

1172 0
    arr = (PyArrayObject *)PyArray_FromScalar(self, NULL);
1173 0
    inter = (PyArrayInterface *)PyArray_malloc(sizeof(PyArrayInterface));
1174 0
    inter->two = 2;
1175 0
    inter->nd = 0;
1176 0
    inter->flags = PyArray_FLAGS(arr);
1177 0
    inter->flags &= ~(NPY_ARRAY_UPDATEIFCOPY | NPY_ARRAY_WRITEBACKIFCOPY |
1178
                      NPY_ARRAY_OWNDATA);
1179 0
    inter->flags |= NPY_ARRAY_NOTSWAPPED;
1180 0
    inter->typekind = PyArray_DESCR(arr)->kind;
1181 0
    inter->itemsize = PyArray_DESCR(arr)->elsize;
1182 0
    inter->strides = NULL;
1183 0
    inter->shape = NULL;
1184 0
    inter->data = PyArray_DATA(arr);
1185 0
    inter->descr = NULL;
1186

1187 0
    ret = NpyCapsule_FromVoidPtrAndDesc(inter, arr, gentype_struct_free);
1188 0
    return ret;
1189
}
1190

1191
static PyObject *
1192 1
gentype_priority_get(PyObject *NPY_UNUSED(self))
1193
{
1194 1
    return PyFloat_FromDouble(NPY_SCALAR_PRIORITY);
1195
}
1196

1197
static PyObject *
1198 1
gentype_shape_get(PyObject *NPY_UNUSED(self))
1199
{
1200 1
    return PyTuple_New(0);
1201
}
1202

1203

1204
static PyObject *
1205 0
gentype_interface_get(PyObject *self)
1206
{
1207
    PyArrayObject *arr;
1208
    PyObject *inter;
1209

1210 0
    arr = (PyArrayObject *)PyArray_FromScalar(self, NULL);
1211 0
    if (arr == NULL) {
1212
        return NULL;
1213
    }
1214 0
    inter = PyObject_GetAttrString((PyObject *)arr, "__array_interface__");
1215 0
    if (inter != NULL) {
1216 0
        PyDict_SetItemString(inter, "__ref", (PyObject *)arr);
1217
    }
1218 0
    Py_DECREF(arr);
1219
    return inter;
1220
}
1221

1222

1223

1224
static PyObject *
1225 1
gentype_typedescr_get(PyObject *self)
1226
{
1227 1
    return (PyObject *)PyArray_DescrFromScalar(self);
1228
}
1229

1230

1231
static PyObject *
1232 0
gentype_base_get(PyObject *NPY_UNUSED(self))
1233
{
1234 0
    Py_RETURN_NONE;
1235
}
1236

1237
static PyObject *
1238 1
voidtype_base_get(PyVoidScalarObject *self)
1239
{
1240 1
    if (self->base == NULL) {
1241 0
        Py_RETURN_NONE;
1242
    }
1243
    else {
1244 1
        Py_INCREF(self->base);
1245 1
        return self->base;
1246
    }
1247
}
1248

1249

1250
static PyArray_Descr *
1251 1
_realdescr_fromcomplexscalar(PyObject *self, int *typenum)
1252
{
1253 1
    if (PyArray_IsScalar(self, CDouble)) {
1254 1
        *typenum = NPY_CDOUBLE;
1255 1
        return PyArray_DescrFromType(NPY_DOUBLE);
1256
    }
1257 1
    if (PyArray_IsScalar(self, CFloat)) {
1258 1
        *typenum = NPY_CFLOAT;
1259 1
        return PyArray_DescrFromType(NPY_FLOAT);
1260
    }
1261 1
    if (PyArray_IsScalar(self, CLongDouble)) {
1262 1
        *typenum = NPY_CLONGDOUBLE;
1263 1
        return PyArray_DescrFromType(NPY_LONGDOUBLE);
1264
    }
1265
    return NULL;
1266
}
1267

1268
static PyObject *
1269 1
gentype_real_get(PyObject *self)
1270
{
1271
    PyArray_Descr *typecode;
1272
    PyObject *ret;
1273
    int typenum;
1274

1275 1
    if (PyArray_IsScalar(self, ComplexFloating)) {
1276
        void *ptr;
1277 1
        typecode = _realdescr_fromcomplexscalar(self, &typenum);
1278 1
        ptr = scalar_value(self, NULL);
1279 1
        ret = PyArray_Scalar(ptr, typecode, NULL);
1280 1
        Py_DECREF(typecode);
1281
        return ret;
1282
    }
1283 1
    else if (PyArray_IsScalar(self, Object)) {
1284 0
        PyObject *obj = PyArrayScalar_VAL(self, Object);
1285 0
        ret = PyObject_GetAttrString(obj, "real");
1286 0
        if (ret != NULL) {
1287
            return ret;
1288
        }
1289 0
        PyErr_Clear();
1290
    }
1291 1
    Py_INCREF(self);
1292 1
    return (PyObject *)self;
1293
}
1294

1295
static PyObject *
1296 1
gentype_imag_get(PyObject *self)
1297
{
1298 1
    PyArray_Descr *typecode=NULL;
1299
    PyObject *ret;
1300
    int typenum;
1301

1302 1
    if (PyArray_IsScalar(self, ComplexFloating)) {
1303
        char *ptr;
1304 1
        typecode = _realdescr_fromcomplexscalar(self, &typenum);
1305 1
        ptr = (char *)scalar_value(self, NULL);
1306 1
        ret = PyArray_Scalar(ptr + typecode->elsize, typecode, NULL);
1307
    }
1308 1
    else if (PyArray_IsScalar(self, Object)) {
1309 0
        PyObject *obj = PyArrayScalar_VAL(self, Object);
1310
        PyArray_Descr *newtype;
1311 0
        ret = PyObject_GetAttrString(obj, "imag");
1312 0
        if (ret == NULL) {
1313 0
            PyErr_Clear();
1314 0
            obj = PyLong_FromLong(0);
1315 0
            newtype = PyArray_DescrFromType(NPY_OBJECT);
1316 0
            ret = PyArray_Scalar((char *)&obj, newtype, NULL);
1317 0
            Py_DECREF(newtype);
1318 0
            Py_DECREF(obj);
1319
        }
1320
    }
1321
    else {
1322
        char *temp;
1323
        int elsize;
1324 1
        typecode = PyArray_DescrFromScalar(self);
1325 1
        elsize = typecode->elsize;
1326 1
        temp = npy_alloc_cache_zero(elsize);
1327 1
        ret = PyArray_Scalar(temp, typecode, NULL);
1328 1
        npy_free_cache(temp, elsize);
1329
    }
1330

1331 1
    Py_XDECREF(typecode);
1332 1
    return ret;
1333
}
1334

1335
static PyObject *
1336 0
gentype_flat_get(PyObject *self)
1337
{
1338
    PyObject *ret, *arr;
1339

1340 0
    arr = PyArray_FromScalar(self, NULL);
1341 0
    if (arr == NULL) {
1342
        return NULL;
1343
    }
1344 0
    ret = PyArray_IterNew(arr);
1345 0
    Py_DECREF(arr);
1346
    return ret;
1347
}
1348

1349

1350
static PyObject *
1351 0
gentype_transpose_get(PyObject *self)
1352
{
1353 0
    Py_INCREF(self);
1354 0
    return self;
1355
}
1356

1357

1358
static PyGetSetDef gentype_getsets[] = {
1359
    {"ndim",
1360
        (getter)gentype_ndim_get,
1361
        (setter) 0, NULL, NULL},
1362
    {"flags",
1363
        (getter)gentype_flags_get,
1364
        (setter)0, NULL, NULL},
1365
    {"shape",
1366
        (getter)gentype_shape_get,
1367
        (setter)0, NULL, NULL},
1368
    {"strides",
1369
        (getter)gentype_shape_get,
1370
        (setter) 0, NULL, NULL},
1371
    {"data",
1372
        (getter)gentype_data_get,
1373
        (setter) 0, NULL, NULL},
1374
    {"itemsize",
1375
        (getter)gentype_itemsize_get,
1376
        (setter)0, NULL, NULL},
1377
    {"size",
1378
        (getter)gentype_size_get,
1379
        (setter)0, NULL, NULL},
1380
    {"nbytes",
1381
        (getter)gentype_itemsize_get,
1382
        (setter)0, NULL, NULL},
1383
    {"base",
1384
        (getter)gentype_base_get,
1385
        (setter)0, NULL, NULL},
1386
    {"dtype",
1387
        (getter)gentype_typedescr_get,
1388
        NULL, NULL, NULL},
1389
    {"real",
1390
        (getter)gentype_real_get,
1391
        (setter)0, NULL, NULL},
1392
    {"imag",
1393
        (getter)gentype_imag_get,
1394
        (setter)0, NULL, NULL},
1395
    {"flat",
1396
        (getter)gentype_flat_get,
1397
        (setter)0, NULL, NULL},
1398
    {"T",
1399
        (getter)gentype_transpose_get,
1400
        (setter)0, NULL, NULL},
1401
    {"__array_interface__",
1402
        (getter)gentype_interface_get,
1403
        NULL,
1404
        "Array protocol: Python side",
1405
        NULL},
1406
    {"__array_struct__",
1407
        (getter)gentype_struct_get,
1408
        NULL,
1409
        "Array protocol: struct",
1410
        NULL},
1411
    {"__array_priority__",
1412
        (getter)gentype_priority_get,
1413
        NULL,
1414
        "Array priority.",
1415
        NULL},
1416
    {NULL, NULL, NULL, NULL, NULL}  /* Sentinel */
1417
};
1418

1419

1420
/* 0-dim array from scalar object */
1421

1422
static char doc_getarray[] = "sc.__array__(dtype) return 0-dim array from "
1423
                             "scalar with specified dtype";
1424

1425
static PyObject *
1426 1
gentype_getarray(PyObject *scalar, PyObject *args)
1427
{
1428 1
    PyArray_Descr *outcode=NULL;
1429
    PyObject *ret;
1430

1431 1
    if (!PyArg_ParseTuple(args, "|O&:__array__", &PyArray_DescrConverter,
1432
                &outcode)) {
1433 0
        Py_XDECREF(outcode);
1434
        return NULL;
1435
    }
1436 1
    ret = PyArray_FromScalar(scalar, outcode);
1437 1
    return ret;
1438
}
1439

1440
static char doc_sc_wraparray[] = "sc.__array_wrap__(obj) return scalar from array";
1441

1442
static PyObject *
1443 1
gentype_wraparray(PyObject *NPY_UNUSED(scalar), PyObject *args)
1444
{
1445
    PyObject *obj;
1446
    PyArrayObject *arr;
1447

1448 1
    if (PyTuple_Size(args) < 1) {
1449 0
        PyErr_SetString(PyExc_TypeError,
1450
                "only accepts 1 argument.");
1451 0
        return NULL;
1452
    }
1453 1
    obj = PyTuple_GET_ITEM(args, 0);
1454 1
    if (!PyArray_Check(obj)) {
1455 0
        PyErr_SetString(PyExc_TypeError,
1456
                "can only be called with ndarray object");
1457 0
        return NULL;
1458
    }
1459 1
    arr = (PyArrayObject *)obj;
1460

1461 1
    return PyArray_Scalar(PyArray_DATA(arr),
1462
                    PyArray_DESCR(arr), (PyObject *)arr);
1463
}
1464

1465
/*
1466
 * These gentype_* functions do not take keyword arguments.
1467
 * The proper flag is METH_VARARGS.
1468
 */
1469
/**begin repeat
1470
 *
1471
 * #name = tolist, item, __deepcopy__, __copy__,
1472
 *         swapaxes, conj, conjugate, nonzero,
1473
 *         fill, transpose, newbyteorder#
1474
 */
1475
static PyObject *
1476 1
gentype_@name@(PyObject *self, PyObject *args)
1477
{
1478 1
    return gentype_generic_method(self, args, NULL, "@name@");
1479
}
1480
/**end repeat**/
1481

1482
static PyObject *
1483 0
gentype_itemset(PyObject *NPY_UNUSED(self), PyObject *NPY_UNUSED(args))
1484
{
1485 0
    PyErr_SetString(PyExc_ValueError, "array-scalars are immutable");
1486 0
    return NULL;
1487
}
1488

1489
static PyObject *
1490 1
gentype_byteswap(PyObject *self, PyObject *args, PyObject *kwds)
1491
{
1492 1
    npy_bool inplace = NPY_FALSE;
1493
    static char *kwlist[] = {"inplace", NULL};
1494

1495 1
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&:byteswap", kwlist,
1496
                                     PyArray_BoolConverter, &inplace)) {
1497
        return NULL;
1498
    }
1499 1
    if (inplace) {
1500 0
        PyErr_SetString(PyExc_ValueError,
1501
                "cannot byteswap a scalar in-place");
1502 0
        return NULL;
1503
    }
1504
    else {
1505
        /* get the data, copyswap it and pass it to a new Array scalar */
1506
        char *data;
1507
        PyArray_Descr *descr;
1508
        PyObject *new;
1509
        char *newmem;
1510

1511 1
        descr = PyArray_DescrFromScalar(self);
1512 1
        data = (void *)scalar_value(self, descr);
1513

1514 1
        newmem = PyObject_Malloc(descr->elsize);
1515 1
        if (newmem == NULL) {
1516 0
            Py_DECREF(descr);
1517 0
            return PyErr_NoMemory();
1518
        }
1519
        else {
1520 1
            descr->f->copyswap(newmem, data, 1, NULL);
1521
        }
1522 1
        new = PyArray_Scalar(newmem, descr, NULL);
1523 1
        PyObject_Free(newmem);
1524 1
        Py_DECREF(descr);
1525
        return new;
1526
    }
1527
}
1528

1529

1530
/*
1531
 * These gentype_* functions take keyword arguments.
1532
 * The proper flag is METH_VARARGS | METH_KEYWORDS.
1533
 */
1534
/**begin repeat
1535
 *
1536
 * #name = take, getfield, put, repeat, tofile, mean, trace, diagonal, clip,
1537
 *         std, var, sum, cumsum, prod, cumprod, compress, sort, argsort,
1538
 *         round, argmax, argmin, max, min, ptp, any, all, astype, resize,
1539
 *         reshape, choose, tostring, tobytes, copy, searchsorted, view,
1540
 *         flatten, ravel, squeeze#
1541
 */
1542
static PyObject *
1543 1
gentype_@name@(PyObject *self, PyObject *args, PyObject *kwds)
1544
{
1545 1
    return gentype_generic_method(self, args, kwds, "@name@");
1546
}
1547
/**end repeat**/
1548

1549

1550
/**begin repeat
1551
 * #name = integer, floating, complexfloating#
1552
 * #complex = 0, 0, 1#
1553
 */
1554
static PyObject *
1555 1
@name@type_dunder_round(PyObject *self, PyObject *args, PyObject *kwds)
1556
{
1557
    static char *kwlist[] = {"ndigits", NULL};
1558 1
    PyObject *ndigits = Py_None;
1559 1
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:__round__", kwlist, &ndigits)) {
1560
        return NULL;
1561
    }
1562

1563
#if @complex@
1564 0
    if (DEPRECATE("The Python built-in `round` is deprecated for complex "
1565
                  "scalars, and will raise a `TypeError` in a future release. "
1566
                  "Use `np.round` or `scalar.round` instead.") < 0) {
1567
        return NULL;
1568
    }
1569
#endif
1570

1571
    PyObject *tup;
1572 1
    if (ndigits == Py_None) {
1573 1
        tup = PyTuple_Pack(0);
1574
    }
1575
    else {
1576 1
        tup = PyTuple_Pack(1, ndigits);
1577
    }
1578

1579 1
    if (tup == NULL) {
1580
        return NULL;
1581
    }
1582

1583 1
    PyObject *obj = gentype_round(self, tup, NULL);
1584 1
    Py_DECREF(tup);
1585 1
    if (obj == NULL) {
1586
        return NULL;
1587
    }
1588

1589
#if !@complex@
1590 1
    if (ndigits == Py_None) {
1591 1
        PyObject *ret = PyNumber_Long(obj);
1592 1
        Py_DECREF(obj);
1593
        return ret;
1594
    }
1595
#endif
1596

1597 0
    return obj;
1598
}
1599
/**end repeat**/
1600

1601
static PyObject *
1602 1
voidtype_getfield(PyVoidScalarObject *self, PyObject *args, PyObject *kwds)
1603
{
1604
    /* Use ndarray's getfield to obtain the field safely */
1605 1
    return gentype_generic_method((PyObject *)self, args, kwds, "getfield");
1606
}
1607

1608
static PyObject *
1609 0
gentype_setfield(PyObject *NPY_UNUSED(self), PyObject *NPY_UNUSED(args),
1610
                 PyObject *NPY_UNUSED(kwds))
1611
{
1612 0
    PyErr_SetString(PyExc_TypeError,
1613
            "Can't set fields in a non-void array scalar.");
1614 0
    return NULL;
1615
}
1616

1617
static PyObject *
1618 1
voidtype_setfield(PyVoidScalarObject *self, PyObject *args, PyObject *kwds)
1619
{
1620
    /*
1621
     * We would like to use ndarray's setfield because it performs safety
1622
     * checks on the field datatypes and because it broadcasts properly.
1623
     * However, as a special case, void-scalar assignment broadcasts
1624
     * differently from ndarrays when assigning to an object field: Assignment
1625
     * to an ndarray object field broadcasts, but assignment to a void-scalar
1626
     * object-field should not, in order to allow nested ndarrays.
1627
     * These lines should then behave identically:
1628
     *
1629
     *     b = np.zeros(1, dtype=[('x', 'O')])
1630
     *     b[0]['x'] = arange(3)  # uses voidtype_setfield
1631
     *     b['x'][0] = arange(3)  # uses ndarray setitem
1632
     *
1633
     * Ndarray's setfield would try to broadcast the lhs. Instead we use
1634
     * ndarray getfield to get the field safely, then setitem with an empty
1635
     * tuple to set the value without broadcast. Note we also want subarrays to
1636
     * be set properly, ie
1637
     *
1638
     *     a = np.zeros(1, dtype=[('x', 'i', 5)])
1639
     *     a[0]['x'] = 1
1640
     *
1641
     * sets all values to 1. "getfield + setitem with empty tuple" takes
1642
     * care of both object arrays and subarrays.
1643
     */
1644
    PyObject *getfield_args, *value, *arr, *meth, *arr_field, *emptytuple;
1645

1646 1
    value = PyTuple_GetItem(args, 0);
1647 1
    if (value == NULL) {
1648
        return NULL;
1649
    }
1650 1
    getfield_args = PyTuple_GetSlice(args, 1, 3);
1651 1
    if (getfield_args == NULL) {
1652
        return NULL;
1653
    }
1654

1655
    /* 1. Convert to 0-d array and use getfield */
1656 1
    arr = PyArray_FromScalar((PyObject*)self, NULL);
1657 1
    if (arr == NULL) {
1658 0
        Py_DECREF(getfield_args);
1659
        return NULL;
1660
    }
1661 1
    meth = PyObject_GetAttrString(arr, "getfield");
1662 1
    if (meth == NULL) {
1663 0
        Py_DECREF(getfield_args);
1664 0
        Py_DECREF(arr);
1665
        return NULL;
1666
    }
1667 1
    if (kwds == NULL) {
1668 1
        arr_field = PyObject_CallObject(meth, getfield_args);
1669
    }
1670
    else {
1671 0
        arr_field = PyObject_Call(meth, getfield_args, kwds);
1672
    }
1673 1
    Py_DECREF(getfield_args);
1674 1
    Py_DECREF(meth);
1675 1
    Py_DECREF(arr);
1676

1677 1
    if(arr_field == NULL){
1678
        return NULL;
1679
    }
1680

1681
    /* 2. Assign the value using setitem with empty tuple. */
1682 1
    emptytuple = PyTuple_New(0);
1683 1
    if (PyObject_SetItem(arr_field, emptytuple, value) < 0) {
1684 0
        Py_DECREF(arr_field);
1685 0
        Py_DECREF(emptytuple);
1686
        return NULL;
1687
    }
1688 1
    Py_DECREF(emptytuple);
1689 1
    Py_DECREF(arr_field);
1690

1691 1
    Py_RETURN_NONE;
1692
}
1693

1694

1695
static PyObject *
1696 1
gentype_reduce(PyObject *self, PyObject *NPY_UNUSED(args))
1697
{
1698 1
    PyObject *ret = NULL, *obj = NULL, *mod = NULL;
1699
    Py_buffer view;
1700
    const char *buffer;
1701
    Py_ssize_t buflen;
1702

1703
    /* Return a tuple of (callable object, arguments) */
1704 1
    ret = PyTuple_New(2);
1705 1
    if (ret == NULL) {
1706
        return NULL;
1707
    }
1708

1709 1
    if (PyObject_GetBuffer(self, &view, PyBUF_SIMPLE) >= 0) {
1710 1
        buffer = view.buf;
1711 1
        buflen = view.len;
1712
        /*
1713
         * In Python 3 both of the deprecated functions PyObject_AsWriteBuffer and
1714
         * PyObject_AsReadBuffer that this code replaces release the buffer. It is
1715
         * up to the object that supplies the buffer to guarantee that the buffer
1716
         * sticks around after the release.
1717
         */
1718 1
        PyBuffer_Release(&view);
1719
    }
1720
    else {
1721 0
        Py_DECREF(ret);
1722
        return NULL;
1723
    }
1724

1725 1
    mod = PyImport_ImportModule("numpy.core._multiarray_umath");
1726 1
    if (mod == NULL) {
1727
        return NULL;
1728
    }
1729 1
    obj = PyObject_GetAttrString(mod, "scalar");
1730 1
    Py_DECREF(mod);
1731 1
    if (obj == NULL) {
1732
        return NULL;
1733
    }
1734 1
    PyTuple_SET_ITEM(ret, 0, obj);
1735 1
    obj = PyObject_GetAttrString((PyObject *)self, "dtype");
1736 1
    if (PyArray_IsScalar(self, Object)) {
1737 0
        PyObject *val = PyArrayScalar_VAL(self, Object);
1738 0
        PyObject *tup = Py_BuildValue("NO", obj, val);
1739 0
        if (tup == NULL) {
1740
            return NULL;
1741
        }
1742 0
        PyTuple_SET_ITEM(ret, 1, tup);
1743
    }
1744 1
    else if (obj && PyDataType_FLAGCHK((PyArray_Descr *)obj, NPY_LIST_PICKLE)) {
1745
        /* a structured dtype with an object in a field */
1746 1
        PyArrayObject *arr = (PyArrayObject *)PyArray_FromScalar(self, NULL);
1747 1
        if (arr == NULL) {
1748
            return NULL;
1749
        }
1750
        /* arr.item() */
1751 1
        PyObject *val = PyArray_GETITEM(arr, PyArray_DATA(arr));
1752 1
        Py_DECREF(arr);
1753 1
        if (val == NULL) {
1754
            return NULL;
1755
        }
1756 1
        PyObject *tup = Py_BuildValue("NN", obj, val);
1757 1
        if (tup == NULL) {
1758
            return NULL;
1759
        }
1760 1
        PyTuple_SET_ITEM(ret, 1, tup);
1761
    }
1762
    else {
1763 1
        mod = PyBytes_FromStringAndSize(buffer, buflen);
1764 1
        if (mod == NULL) {
1765 0
            Py_DECREF(ret);
1766
            return NULL;
1767
        }
1768 1
        PyTuple_SET_ITEM(ret, 1,
1769
                Py_BuildValue("NN", obj, mod));
1770
    }
1771
    return ret;
1772
}
1773

1774
/* ignores everything */
1775
static PyObject *
1776 0
gentype_setstate(PyObject *NPY_UNUSED(self), PyObject *NPY_UNUSED(args))
1777
{
1778 0
    Py_RETURN_NONE;
1779
}
1780

1781
static PyObject *
1782 0
gentype_dump(PyObject *self, PyObject *args)
1783
{
1784 0
    PyObject *file = NULL;
1785
    int ret;
1786

1787 0
    if (!PyArg_ParseTuple(args, "O:dump", &file)) {
1788
        return NULL;
1789
    }
1790 0
    ret = PyArray_Dump(self, file, 2);
1791 0
    if (ret < 0) {
1792
        return NULL;
1793
    }
1794 0
    Py_RETURN_NONE;
1795
}
1796

1797
static PyObject *
1798 0
gentype_dumps(PyObject *self, PyObject *args)
1799
{
1800 0
    if (!PyArg_ParseTuple(args, "")) {
1801
        return NULL;
1802
    }
1803 0
    return PyArray_Dumps(self, 2);
1804
}
1805

1806

1807
/* setting flags cannot be done for scalars */
1808
static PyObject *
1809 0
gentype_setflags(PyObject *NPY_UNUSED(self), PyObject *NPY_UNUSED(args),
1810
        PyObject *NPY_UNUSED(kwds))
1811
{
1812 0
    Py_RETURN_NONE;
1813
}
1814

1815
/*
1816
 * casting complex numbers (that don't inherit from Python complex)
1817
 * to Python complex
1818
 */
1819

1820
/**begin repeat
1821
 * #name = cfloat, clongdouble#
1822
 * #Name = CFloat, CLongDouble#
1823
 */
1824
static PyObject *
1825 1
@name@_complex(PyObject *self, PyObject *NPY_UNUSED(args),
1826
               PyObject *NPY_UNUSED(kwds))
1827
{
1828 1
    return PyComplex_FromDoubles(PyArrayScalar_VAL(self, @Name@).real,
1829 1
                                 PyArrayScalar_VAL(self, @Name@).imag);
1830
}
1831
/**end repeat**/
1832

1833
/**begin repeat
1834
 *  #name = half, float, double, longdouble#
1835
 *  #Name = Half, Float, Double, LongDouble#
1836
 *  #is_half = 1,0,0,0#
1837
 *  #c    = f, f, , l#
1838
 *  #convert = PyLong_FromDouble, PyLong_FromDouble, PyLong_FromDouble,
1839
 *             npy_longdouble_to_PyLong#
1840
 *  #
1841
 */
1842
/* Heavily copied from the builtin float.as_integer_ratio */
1843
static PyObject *
1844 1
@name@_as_integer_ratio(PyObject *self)
1845
{
1846
#if @is_half@
1847 1
    npy_double val = npy_half_to_double(PyArrayScalar_VAL(self, @Name@));
1848
    npy_double frac;
1849
#else
1850 1
    npy_@name@ val = PyArrayScalar_VAL(self, @Name@);
1851
    npy_@name@ frac;
1852
#endif
1853
    int exponent;
1854
    int i;
1855

1856 1
    PyObject *py_exponent = NULL;
1857 1
    PyObject *numerator = NULL;
1858 1
    PyObject *denominator = NULL;
1859 1
    PyObject *result_pair = NULL;
1860 1
    PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
1861

1862 1
    if (npy_isnan(val)) {
1863 1
        PyErr_SetString(PyExc_ValueError,
1864
                        "cannot convert NaN to integer ratio");
1865 1
        return NULL;
1866
    }
1867 1
    if (!npy_isfinite(val)) {
1868 1
        PyErr_SetString(PyExc_OverflowError,
1869
                        "cannot convert Infinity to integer ratio");
1870 1
        return NULL;
1871
    }
1872

1873 1
    frac = npy_frexp@c@(val, &exponent); /* val == frac * 2**exponent exactly */
1874

1875
    /* This relies on the floating point type being base 2 to converge */
1876 1
    for (i = 0; frac != npy_floor@c@(frac); i++) {
1877 1
        frac *= 2.0;
1878 1
        exponent--;
1879
    }
1880

1881
    /* self == frac * 2**exponent exactly and frac is integral. */
1882 1
    numerator = @convert@(frac);
1883 1
    if (numerator == NULL)
1884
        goto error;
1885 1
    denominator = PyLong_FromLong(1);
1886 1
    if (denominator == NULL)
1887
        goto error;
1888 1
    py_exponent = PyLong_FromLong(exponent < 0 ? -exponent : exponent);
1889 1
    if (py_exponent == NULL)
1890
        goto error;
1891

1892
    /* fold in 2**exponent */
1893 1
    if (exponent > 0) {
1894 1
        PyObject *temp = long_methods->nb_lshift(numerator, py_exponent);
1895 1
        if (temp == NULL)
1896
            goto error;
1897 1
        Py_DECREF(numerator);
1898
        numerator = temp;
1899
    }
1900
    else {
1901 1
        PyObject *temp = long_methods->nb_lshift(denominator, py_exponent);
1902 1
        if (temp == NULL)
1903
            goto error;
1904 1
        Py_DECREF(denominator);
1905
        denominator = temp;
1906
    }
1907

1908 1
    result_pair = PyTuple_Pack(2, numerator, denominator);
1909

1910 1
error:
1911 1
    Py_XDECREF(py_exponent);
1912 1
    Py_XDECREF(denominator);
1913 1
    Py_XDECREF(numerator);
1914
    return result_pair;
1915
}
1916
/**end repeat**/
1917

1918

1919
/*
1920
 * need to fill in doc-strings for these methods on import -- copy from
1921
 * array docstrings
1922
 */
1923
static PyMethodDef gentype_methods[] = {
1924
    {"tolist",
1925
        (PyCFunction)gentype_tolist,
1926
        METH_VARARGS, NULL},
1927
    {"item",
1928
        (PyCFunction)gentype_item,
1929
        METH_VARARGS, NULL},
1930
    {"itemset",
1931
        (PyCFunction)gentype_itemset,
1932
        METH_VARARGS, NULL},
1933
    {"tobytes",
1934
        (PyCFunction)gentype_tobytes,
1935
        METH_VARARGS | METH_KEYWORDS, NULL},
1936
    {"tofile",
1937
        (PyCFunction)gentype_tofile,
1938
        METH_VARARGS | METH_KEYWORDS, NULL},
1939
    {"tostring",
1940
        (PyCFunction)gentype_tostring,
1941
        METH_VARARGS | METH_KEYWORDS, NULL},
1942
    {"byteswap",
1943
        (PyCFunction)gentype_byteswap,
1944
        METH_VARARGS | METH_KEYWORDS, NULL},
1945
    {"astype",
1946
        (PyCFunction)gentype_astype,
1947
        METH_VARARGS | METH_KEYWORDS, NULL},
1948
    {"getfield",
1949
        (PyCFunction)gentype_getfield,
1950
        METH_VARARGS | METH_KEYWORDS, NULL},
1951
    {"setfield",
1952
        (PyCFunction)gentype_setfield,
1953
        METH_VARARGS | METH_KEYWORDS, NULL},
1954
    {"copy",
1955
        (PyCFunction)gentype_copy,
1956
        METH_VARARGS | METH_KEYWORDS, NULL},
1957
    {"resize",
1958
        (PyCFunction)gentype_resize,
1959
        METH_VARARGS | METH_KEYWORDS, NULL},
1960
    {"__array__",
1961
        (PyCFunction)gentype_getarray,
1962
        METH_VARARGS, doc_getarray},
1963
    {"__array_wrap__",
1964
        (PyCFunction)gentype_wraparray,
1965
        METH_VARARGS, doc_sc_wraparray},
1966

1967
    /* for the sys module */
1968
    {"__sizeof__",
1969
        (PyCFunction)gentype_sizeof,
1970
        METH_NOARGS, NULL},
1971

1972
    /* for the copy module */
1973
    {"__copy__",
1974
        (PyCFunction)gentype___copy__,
1975
        METH_VARARGS, NULL},
1976
    {"__deepcopy__",
1977
        (PyCFunction)gentype___deepcopy__,
1978
        METH_VARARGS, NULL},
1979

1980
    {"__reduce__",
1981
        (PyCFunction) gentype_reduce,
1982
        METH_VARARGS, NULL},
1983
    /* For consistency does nothing */
1984
    {"__setstate__",
1985
        (PyCFunction) gentype_setstate,
1986
        METH_VARARGS, NULL},
1987

1988
    {"dumps",
1989
        (PyCFunction) gentype_dumps,
1990
        METH_VARARGS, NULL},
1991
    {"dump",
1992
        (PyCFunction) gentype_dump,
1993
        METH_VARARGS, NULL},
1994

1995
    /* Methods for array */
1996
    {"fill",
1997
        (PyCFunction)gentype_fill,
1998
        METH_VARARGS, NULL},
1999
    {"transpose",
2000
        (PyCFunction)gentype_transpose,
2001
        METH_VARARGS, NULL},
2002
    {"take",
2003
        (PyCFunction)gentype_take,
2004
        METH_VARARGS | METH_KEYWORDS, NULL},
2005
    {"put",
2006
        (PyCFunction)gentype_put,
2007
        METH_VARARGS | METH_KEYWORDS, NULL},
2008
    {"repeat",
2009
        (PyCFunction)gentype_repeat,
2010
        METH_VARARGS | METH_KEYWORDS, NULL},
2011
    {"choose",
2012
        (PyCFunction)gentype_choose,
2013
        METH_VARARGS | METH_KEYWORDS, NULL},
2014
    {"sort",
2015
        (PyCFunction)gentype_sort,
2016
        METH_VARARGS | METH_KEYWORDS, NULL},
2017
    {"argsort",
2018
        (PyCFunction)gentype_argsort,
2019
        METH_VARARGS | METH_KEYWORDS, NULL},
2020
    {"searchsorted",
2021
        (PyCFunction)gentype_searchsorted,
2022
        METH_VARARGS | METH_KEYWORDS, NULL},
2023
    {"argmax",
2024
        (PyCFunction)gentype_argmax,
2025
        METH_VARARGS | METH_KEYWORDS, NULL},
2026
    {"argmin",
2027
        (PyCFunction)gentype_argmin,
2028
        METH_VARARGS | METH_KEYWORDS, NULL},
2029
    {"reshape",
2030
        (PyCFunction)gentype_reshape,
2031
        METH_VARARGS | METH_KEYWORDS, NULL},
2032
    {"squeeze",
2033
        (PyCFunction)gentype_squeeze,
2034
        METH_VARARGS | METH_KEYWORDS, NULL},
2035
    {"view",
2036
        (PyCFunction)gentype_view,
2037
        METH_VARARGS | METH_KEYWORDS, NULL},
2038
    {"swapaxes",
2039
        (PyCFunction)gentype_swapaxes,
2040
        METH_VARARGS, NULL},
2041
    {"max",
2042
        (PyCFunction)gentype_max,
2043
        METH_VARARGS | METH_KEYWORDS, NULL},
2044
    {"min",
2045
        (PyCFunction)gentype_min,
2046
        METH_VARARGS | METH_KEYWORDS, NULL},
2047
    {"ptp",
2048
        (PyCFunction)gentype_ptp,
2049
        METH_VARARGS | METH_KEYWORDS, NULL},
2050
    {"mean",
2051
        (PyCFunction)gentype_mean,
2052
        METH_VARARGS | METH_KEYWORDS, NULL},
2053
    {"trace",
2054
        (PyCFunction)gentype_trace,
2055
        METH_VARARGS | METH_KEYWORDS, NULL},
2056
    {"diagonal",
2057
        (PyCFunction)gentype_diagonal,
2058
        METH_VARARGS | METH_KEYWORDS, NULL},
2059
    {"clip",
2060
        (PyCFunction)gentype_clip,
2061
        METH_VARARGS | METH_KEYWORDS, NULL},
2062
    {"conj",
2063
        (PyCFunction)gentype_conj,
2064
        METH_VARARGS, NULL},
2065
    {"conjugate",
2066
        (PyCFunction)gentype_conjugate,
2067
        METH_VARARGS, NULL},
2068
    {"nonzero",
2069
        (PyCFunction)gentype_nonzero,
2070
        METH_VARARGS, NULL},
2071
    {"std",
2072
        (PyCFunction)gentype_std,
2073
        METH_VARARGS | METH_KEYWORDS, NULL},
2074
    {"var",
2075
        (PyCFunction)gentype_var,
2076
        METH_VARARGS | METH_KEYWORDS, NULL},
2077
    {"sum",
2078
        (PyCFunction)gentype_sum,
2079
        METH_VARARGS | METH_KEYWORDS, NULL},
2080
    {"cumsum",
2081
        (PyCFunction)gentype_cumsum,
2082
        METH_VARARGS | METH_KEYWORDS, NULL},
2083
    {"prod",
2084
        (PyCFunction)gentype_prod,
2085
        METH_VARARGS | METH_KEYWORDS, NULL},
2086
    {"cumprod",
2087
        (PyCFunction)gentype_cumprod,
2088
        METH_VARARGS | METH_KEYWORDS, NULL},
2089
    {"all",
2090
        (PyCFunction)gentype_all,
2091
        METH_VARARGS | METH_KEYWORDS, NULL},
2092
    {"any",
2093
        (PyCFunction)gentype_any,
2094
        METH_VARARGS | METH_KEYWORDS, NULL},
2095
    {"compress",
2096
        (PyCFunction)gentype_compress,
2097
        METH_VARARGS | METH_KEYWORDS, NULL},
2098
    {"flatten",
2099
        (PyCFunction)gentype_flatten,
2100
        METH_VARARGS | METH_KEYWORDS, NULL},
2101
    {"ravel",
2102
        (PyCFunction)gentype_ravel,
2103
        METH_VARARGS | METH_KEYWORDS, NULL},
2104
    {"round",
2105
        (PyCFunction)gentype_round,
2106
        METH_VARARGS | METH_KEYWORDS, NULL},
2107
    /* For the format function */
2108
    {"__format__",
2109
        gentype_format,
2110
        METH_VARARGS,
2111
        "NumPy array scalar formatter"},
2112
    {"setflags",
2113
        (PyCFunction)gentype_setflags,
2114
        METH_VARARGS | METH_KEYWORDS, NULL},
2115
    {"newbyteorder",
2116
        (PyCFunction)gentype_newbyteorder,
2117
        METH_VARARGS, NULL},
2118
    {NULL, NULL, 0, NULL} /* sentinel */
2119
};
2120

2121

2122
static PyGetSetDef voidtype_getsets[] = {
2123
    {"flags",
2124
        (getter)voidtype_flags_get,
2125
        (setter)0,
2126
        "integer value of flags",
2127
        NULL},
2128
    {"dtype",
2129
        (getter)voidtype_dtypedescr_get,
2130
        (setter)0,
2131
        "dtype object",
2132
        NULL},
2133
    {"base",
2134
        (getter)voidtype_base_get,
2135
        (setter)0,
2136
        "base object",
2137
        NULL},
2138
    {NULL, NULL, NULL, NULL, NULL}
2139
};
2140

2141
static PyMethodDef voidtype_methods[] = {
2142
    {"getfield",
2143
        (PyCFunction)voidtype_getfield,
2144
        METH_VARARGS | METH_KEYWORDS, NULL},
2145
    {"setfield",
2146
        (PyCFunction)voidtype_setfield,
2147
        METH_VARARGS | METH_KEYWORDS, NULL},
2148
    {NULL, NULL, 0, NULL}
2149
};
2150

2151
static PyGetSetDef inttype_getsets[] = {
2152
    {"numerator",
2153
        (getter)inttype_numerator_get,
2154
        (setter)0,
2155
        "numerator of value (the value itself)",
2156
        NULL},
2157
    {"denominator",
2158
        (getter)inttype_denominator_get,
2159
        (setter)0,
2160
        "denominator of value (1)",
2161
        NULL},
2162
    {NULL, NULL, NULL, NULL, NULL}
2163
};
2164

2165
/**begin repeat
2166
 * #name = cfloat,clongdouble#
2167
 */
2168
static PyMethodDef @name@type_methods[] = {
2169
    {"__complex__",
2170
        (PyCFunction)@name@_complex,
2171
        METH_VARARGS | METH_KEYWORDS, NULL},
2172
    {NULL, NULL, 0, NULL}
2173
};
2174
/**end repeat**/
2175

2176
/**begin repeat
2177
 * #name = integer,floating, complexfloating#
2178
 */
2179
static PyMethodDef @name@type_methods[] = {
2180
    /* Hook for the round() builtin */
2181
    {"__round__",
2182
        (PyCFunction)@name@type_dunder_round,
2183
        METH_VARARGS | METH_KEYWORDS, NULL},
2184
    {NULL, NULL, 0, NULL} /* sentinel */
2185
};
2186
/**end repeat**/
2187

2188
/**begin repeat
2189
 * #name = half,float,double,longdouble#
2190
 */
2191
static PyMethodDef @name@type_methods[] = {
2192
    {"as_integer_ratio",
2193
        (PyCFunction)@name@_as_integer_ratio,
2194
        METH_NOARGS, NULL},
2195
    {NULL, NULL, 0, NULL}
2196
};
2197
/**end repeat**/
2198

2199
/************* As_mapping functions for void array scalar ************/
2200

2201
static Py_ssize_t
2202 1
voidtype_length(PyVoidScalarObject *self)
2203
{
2204 1
    if (!PyDataType_HASFIELDS(self->descr)) {
2205
        return 0;
2206
    }
2207
    else {
2208
        /* return the number of fields */
2209 1
        return (Py_ssize_t) PyTuple_GET_SIZE(self->descr->names);
2210
    }
2211
}
2212

2213
static PyObject *
2214
voidtype_subscript(PyVoidScalarObject *self, PyObject *ind);
2215

2216
static PyObject *
2217 1
voidtype_item(PyVoidScalarObject *self, Py_ssize_t n)
2218
{
2219
    npy_intp m;
2220 1
    PyObject *flist=NULL;
2221

2222 1
    if (!(PyDataType_HASFIELDS(self->descr))) {
2223 0
        PyErr_SetString(PyExc_IndexError,
2224
                "can't index void scalar without fields");
2225 0
        return NULL;
2226
    }
2227 1
    flist = self->descr->names;
2228 1
    m = PyTuple_GET_SIZE(flist);
2229 1
    if (n < 0) {
2230 1
        n += m;
2231
    }
2232 1
    if (n < 0 || n >= m) {
2233 1
        PyErr_Format(PyExc_IndexError, "invalid index (%d)", (int) n);
2234 1
        return NULL;
2235
    }
2236

2237 1
    return voidtype_subscript(self, PyTuple_GetItem(flist, n));
2238
}
2239

2240
/* get field by name or number */
2241
static PyObject *
2242 1
voidtype_subscript(PyVoidScalarObject *self, PyObject *ind)
2243
{
2244
    npy_intp n;
2245
    PyObject *ret, *res;
2246

2247
    /* structured voids will accept an integer index */
2248 1
    if (PyDataType_HASFIELDS(self->descr)) {
2249 1
        n = PyArray_PyIntAsIntp(ind);
2250 1
        if (!error_converting(n)) {
2251 1
            return voidtype_item(self, (Py_ssize_t)n);
2252
        }
2253 1
        PyErr_Clear();
2254
    }
2255

2256 1
    res = PyArray_FromScalar((PyObject*)self, NULL);
2257

2258
    /* ellipsis should return 0d array */
2259 1
    if(ind == Py_Ellipsis){
2260
        return res;
2261
    }
2262

2263
    /*
2264
     * other cases (field names, empty tuple) will return either
2265
     * scalar or non-0d array. Compute this using ndarray subscript.
2266
     */
2267 1
    ret = array_subscript((PyArrayObject *)res, ind);
2268 1
    Py_DECREF(res);
2269 1
    return PyArray_Return((PyArrayObject*)ret);
2270
}
2271

2272
static int
2273
voidtype_ass_subscript(PyVoidScalarObject *self, PyObject *ind, PyObject *val);
2274

2275
static int
2276 0
voidtype_ass_item(PyVoidScalarObject *self, Py_ssize_t n, PyObject *val)
2277
{
2278
    npy_intp m;
2279 0
    PyObject *flist=NULL;
2280

2281 0
    if (!(PyDataType_HASFIELDS(self->descr))) {
2282 0
        PyErr_SetString(PyExc_IndexError,
2283
                "can't index void scalar without fields");
2284 0
        return -1;
2285
    }
2286

2287 0
    flist = self->descr->names;
2288 0
    m = PyTuple_GET_SIZE(flist);
2289 0
    if (n < 0) {
2290 0
        n += m;
2291
    }
2292 0
    if (n < 0 || n >= m) {
2293 0
        PyErr_Format(PyExc_IndexError, "invalid index (%d)", (int) n);
2294 0
        return -1;
2295
    }
2296

2297 0
    return voidtype_ass_subscript(self, PyTuple_GetItem(flist, n), val);
2298
}
2299

2300
static int
2301 1
voidtype_ass_subscript(PyVoidScalarObject *self, PyObject *ind, PyObject *val)
2302
{
2303
    npy_intp n;
2304 1
    char *msg = "invalid index";
2305
    PyObject *args;
2306

2307 1
    if (!PyDataType_HASFIELDS(self->descr)) {
2308 0
        PyErr_SetString(PyExc_IndexError,
2309
                "can't index void scalar without fields");
2310 0
        return -1;
2311
    }
2312

2313 1
    if (!val) {
2314 1
        PyErr_SetString(PyExc_ValueError,
2315
                "cannot delete scalar field");
2316 1
        return -1;
2317
    }
2318

2319 1
    if (PyUnicode_Check(ind)) {
2320
        /*
2321
         * Much like in voidtype_setfield, we cannot simply use ndarray's
2322
         * __setitem__ since assignment to void scalars should not broadcast
2323
         * the lhs. Instead we get a view through __getitem__ and then assign
2324
         * the value using setitem with an empty tuple (which treats both
2325
         * object arrays and subarrays properly).
2326
         *
2327
         * Also we do not want to use voidtype_setfield here, since we do
2328
         * not need to do the (slow) view safety checks, since we already
2329
         * know the dtype/offset are safe.
2330
         */
2331

2332
        PyObject *arr, *arr_field, *meth, *emptytuple;
2333

2334
        /* 1. Convert to 0-d array and use getitem */
2335 1
        arr = PyArray_FromScalar((PyObject*)self, NULL);
2336 1
        if (arr == NULL) {
2337
            return -1;
2338
        }
2339 1
        meth = PyObject_GetAttrString(arr, "__getitem__");
2340 1
        if (meth == NULL) {
2341 0
            Py_DECREF(arr);
2342
            return -1;
2343
        }
2344 1
        args = Py_BuildValue("(O)", ind);
2345 1
        arr_field = PyObject_CallObject(meth, args);
2346 1
        Py_DECREF(meth);
2347 1
        Py_DECREF(arr);
2348 1
        Py_DECREF(args);
2349

2350 1
        if(arr_field == NULL){
2351
            return -1;
2352
        }
2353

2354
        /* 2. Assign the value using setitem with empty tuple. */
2355 1
        emptytuple = PyTuple_New(0);
2356 1
        if (PyObject_SetItem(arr_field, emptytuple, val) < 0) {
2357 1
            Py_DECREF(arr_field);
2358 1
            Py_DECREF(emptytuple);
2359
            return -1;
2360
        }
2361 1
        Py_DECREF(emptytuple);
2362 1
        Py_DECREF(arr_field);
2363
        return 0;
2364
    }
2365

2366
    /* try to convert it to a number */
2367 0
    n = PyArray_PyIntAsIntp(ind);
2368 0
    if (error_converting(n)) {
2369
        goto fail;
2370
    }
2371 0
    return voidtype_ass_item(self, (Py_ssize_t)n, val);
2372

2373 0
fail:
2374 0
    PyErr_SetString(PyExc_IndexError, msg);
2375 0
    return -1;
2376
}
2377

2378
static PyMappingMethods voidtype_as_mapping = {
2379
    .mp_length = (lenfunc)voidtype_length,
2380
    .mp_subscript = (binaryfunc)voidtype_subscript,
2381
    .mp_ass_subscript = (objobjargproc)voidtype_ass_subscript,
2382
};
2383

2384

2385
static PySequenceMethods voidtype_as_sequence = {
2386
    .sq_length = (lenfunc)voidtype_length,
2387
    .sq_item = (ssizeargfunc)voidtype_item,
2388
    .sq_ass_item = (ssizeobjargproc)voidtype_ass_item,
2389
};
2390

2391

2392

2393
/**begin repeat
2394
 * #name = bool, byte, short, int, long, longlong, ubyte, ushort, uint, ulong,
2395
 *         ulonglong, half, float, double, longdouble, cfloat, cdouble,
2396
 *         clongdouble#
2397
 * #Name = Bool, Byte, Short, Int, Long, LongLong, UByte, UShort, UInt, ULong,
2398
 *         ULongLong, Half, Float, Double, LongDouble, CFloat, CDouble,
2399
 *         CLongDouble#
2400
 * #NAME = BOOL, BYTE, SHORT, INT, LONG, LONGLONG, UBYTE, USHORT, UINT, ULONG,
2401
 *         ULONGLONG, HALF, FLOAT, DOUBLE, LONGDOUBLE, CFLOAT, CDOUBLE,
2402
 *         CLONGDOUBLE#
2403
 * #fmt = ?, b, h, i, l, q, B, H, I, L, Q, e, f, d, g, Zf, Zd, Zg#
2404
 */
2405

2406
static int
2407 1
@name@_getbuffer(PyObject *self, Py_buffer *view, int flags)
2408
{
2409 1
    if ((flags & PyBUF_WRITEABLE) == PyBUF_WRITEABLE) {
2410
        return -1;
2411
    }
2412 1
    Py@Name@ScalarObject *scalar = (Py@Name@ScalarObject *)self;
2413

2414
    static char fmt[3] = "@fmt@";
2415

2416 1
    view->ndim = 0;
2417 1
    view->len = sizeof(scalar->obval);
2418 1
    view->itemsize = sizeof(scalar->obval);
2419 1
    view->shape = NULL;
2420 1
    view->strides = NULL;
2421 1
    view->suboffsets = NULL;
2422 1
    Py_INCREF(self);
2423 1
    view->obj = self;
2424 1
    view->buf = &(scalar->obval);
2425

2426 1
    if ((flags & PyBUF_FORMAT) != PyBUF_FORMAT) {
2427
        /* It is unnecessary to find the correct format */
2428 1
        view->format = NULL;
2429 1
        return 0;
2430
    }
2431

2432 1
    view->format = fmt;
2433

2434 1
    return 0;
2435
}
2436

2437
static PyBufferProcs @name@_arrtype_as_buffer = {
2438
    .bf_getbuffer = @name@_getbuffer,
2439
    /* No need to release the buffer */
2440
};
2441

2442
/**end repeat**/
2443

2444
static int
2445 1
unicode_getbuffer(PyObject *self, Py_buffer *view, int flags)
2446
{
2447 1
    if ((flags & PyBUF_WRITEABLE) == PyBUF_WRITEABLE) {
2448
        return -1;
2449
    }
2450 1
    PyUnicodeScalarObject *scalar = (PyUnicodeScalarObject *)self;
2451 1
    Py_ssize_t length = PyUnicode_GetLength(self);
2452

2453 1
    view->ndim = 0;
2454 1
    view->len = length * 4;
2455 1
    view->itemsize = length * 4;
2456 1
    view->shape = NULL;
2457 1
    view->strides = NULL;
2458 1
    view->suboffsets = NULL;
2459 1
    Py_INCREF(self);
2460 1
    view->obj = self;
2461

2462 1
    if (scalar->obval == NULL) {
2463
        /*
2464
         * Unicode may not have the representation available, `scalar_value`
2465
         * ensures materialization.
2466
         */
2467 1
        PyArray_Descr *descr = PyArray_DescrFromType(NPY_UNICODE);
2468 1
        scalar_value(self, descr);
2469 1
        Py_DECREF(descr);
2470 1
        if (scalar->obval == NULL) {
2471
            /* allocating memory failed */
2472 0
            Py_SETREF(view->obj, NULL);
2473
            return -1;
2474
        }
2475
    }
2476 1
    view->buf = scalar->obval;
2477

2478 1
    if ((flags & PyBUF_FORMAT) != PyBUF_FORMAT) {
2479
        /* It is unnecessary to find the correct format */
2480 1
        view->format = NULL;
2481 1
        return 0;
2482
    }
2483

2484 1
    if (scalar->buffer_fmt != NULL) {
2485 0
        view->format = scalar->buffer_fmt;
2486
    }
2487
    else {
2488 1
        scalar->buffer_fmt = PyObject_Malloc(22);
2489 1
        if (scalar->buffer_fmt == NULL) {
2490 0
            Py_SETREF(view->obj, NULL);
2491
            return -1;
2492
        }
2493 1
        PyOS_snprintf(scalar->buffer_fmt, 22, "%" NPY_INTP_FMT "w", length);
2494 1
        view->format = scalar->buffer_fmt;
2495
    }
2496

2497
    return 0;
2498
}
2499

2500
static PyBufferProcs unicode_arrtype_as_buffer = {
2501
    .bf_getbuffer = unicode_getbuffer,
2502
    /* No need to release the buffer */
2503
};
2504

2505

2506
/**begin repeat
2507
 * #name = datetime, timedelta#
2508
 * #Name = Datetime, Timedelta#
2509
 */
2510

2511
static int
2512 1
@name@_getbuffer(PyObject *self, Py_buffer *view, int flags)
2513
{
2514 1
    if ((flags & PyBUF_WRITEABLE) == PyBUF_WRITEABLE) {
2515
        return -1;
2516
    }
2517 1
    Py@Name@ScalarObject *scalar = (Py@Name@ScalarObject *)self;
2518

2519 1
    view->ndim = 1;
2520 1
    view->len = 8;
2521 1
    view->itemsize = 1;
2522
    static Py_ssize_t length = 8;
2523 1
    view->shape = &length;
2524 1
    view->strides = NULL;
2525 1
    view->suboffsets = NULL;
2526 1
    Py_INCREF(self);
2527 1
    view->obj = self;
2528

2529 1
    view->buf = &(scalar->obval);
2530

2531 1
    if ((flags & PyBUF_FORMAT) != PyBUF_FORMAT) {
2532
        /* It is unnecessary to find the correct format */
2533 1
        view->format = NULL;
2534 1
        return 0;
2535
    }
2536

2537
    /* export datetime scalars as bytes (although arrays are not exported) */
2538 1
    view->format = "B";
2539

2540 1
    return 0;
2541
}
2542

2543
static PyBufferProcs @name@_arrtype_as_buffer = {
2544
        .bf_getbuffer = @name@_getbuffer,
2545
        /* No need to release the buffer */
2546
};
2547

2548
/**end repeat**/
2549

2550
static PyBufferProcs void_arrtype_as_buffer = {
2551
        .bf_getbuffer = void_getbuffer,  /* defined in buffer.c */
2552
        /* No need to release the buffer */
2553
};
2554

2555

2556
#define BASEFLAGS Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
2557
#define LEAFFLAGS  Py_TPFLAGS_DEFAULT
2558

2559
NPY_NO_EXPORT PyTypeObject PyGenericArrType_Type = {
2560
    PyVarObject_HEAD_INIT(NULL, 0)
2561
    .tp_name = "numpy.generic",
2562
    .tp_basicsize = sizeof(PyObject),
2563
};
2564

2565
static void
2566 1
void_dealloc(PyVoidScalarObject *v)
2567
{
2568 1
    _dealloc_cached_buffer_info((PyObject *)v);
2569

2570 1
    if (v->flags & NPY_ARRAY_OWNDATA) {
2571 1
        npy_free_cache(v->obval, Py_SIZE(v));
2572
    }
2573 1
    Py_XDECREF(v->descr);
2574 1
    Py_XDECREF(v->base);
2575 1
    Py_TYPE(v)->tp_free(v);
2576 1
}
2577

2578

2579
static PyObject *
2580 0
object_arrtype_alloc(PyTypeObject *type, Py_ssize_t items)
2581
{
2582
    /*
2583
     * Object scalars should not actually exist, if they exist we should
2584
     * consider it to be a bug.
2585
     */
2586
    static PyObject *visibleDeprecationWarning = NULL;
2587 0
    npy_cache_import("numpy", "VisibleDeprecationWarning",
2588
                     &visibleDeprecationWarning);
2589 0
    if (visibleDeprecationWarning == NULL) {
2590
        return NULL;
2591
    }
2592 0
    if (PyErr_WarnEx(visibleDeprecationWarning,
2593
            "Creating a NumPy object scalar.  NumPy object scalars should "
2594
            "never be created.  If you see this message please inform the "
2595
            "NumPy developers.  Since this message should never be shown "
2596
            "this will raise a TypeError in the future.", 1) < 0) {
2597
        return NULL;
2598
    }
2599 0
    return gentype_alloc(type, items);
2600
}
2601

2602

2603
static void
2604 0
object_arrtype_dealloc(PyObject *v)
2605
{
2606 0
    Py_XDECREF(PyArrayScalar_VAL(v, Object));
2607 0
    Py_TYPE(v)->tp_free(v);
2608 0
}
2609

2610
static void
2611 1
unicode_arrtype_dealloc(PyObject *v)
2612
{
2613
    /* note: may be null if it was never requested */
2614 1
    PyMem_Free(PyArrayScalar_VAL(v, Unicode));
2615
    /* delegate to the base class */
2616 1
    PyUnicode_Type.tp_dealloc(v);
2617 1
}
2618

2619
/**begin repeat
2620
 * #name = byte, short, int, long, longlong, ubyte, ushort, uint, ulong,
2621
 *         ulonglong, half, float, double, longdouble, cfloat, cdouble,
2622
 *         clongdouble, string, unicode#
2623
 * #Name = Byte, Short, Int, Long, LongLong, UByte, UShort, UInt, ULong,
2624
 *         ULongLong, Half, Float, Double, LongDouble, CFloat, CDouble,
2625
 *         CLongDouble, String, Unicode#
2626
 * #TYPE = BYTE, SHORT, INT, LONG, LONGLONG, UBYTE, USHORT, UINT, ULONG,
2627
 *         ULONGLONG, HALF, FLOAT, DOUBLE, LONGDOUBLE, CFLOAT, CDOUBLE,
2628
 *         CLONGDOUBLE, STRING, UNICODE#
2629
 */
2630

2631
/* used as a pattern for testing token equality */
2632
#define _@TYPE@_IS_@TYPE@
2633

2634
static PyObject *
2635 1
@name@_arrtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2636
{
2637
    /* allow base-class (if any) to do conversion */
2638
#if defined(_@TYPE@_IS_UNICODE)
2639 1
    PyObject *from_superclass = PyUnicode_Type.tp_new(type, args, kwds);
2640
#elif defined(_@TYPE@_IS_STRING)
2641 1
    PyObject *from_superclass = PyBytes_Type.tp_new(type, args, kwds);
2642
#elif defined(_@TYPE@_IS_DOUBLE)
2643 1
    PyObject *from_superclass = PyFloat_Type.tp_new(type, args, kwds);
2644
#endif
2645
#if defined(_@TYPE@_IS_UNICODE) || defined(_@TYPE@_IS_STRING) || defined(_@TYPE@_IS_DOUBLE)
2646 1
    if (from_superclass == NULL) {
2647
        /* don't clear the exception unless numpy can handle the arguments */
2648 1
        if (PyTuple_GET_SIZE(args) != 1 || (kwds && PyDict_Size(kwds) != 0)) {
2649
            return NULL;
2650
        }
2651 1
        PyErr_Clear();
2652
    }
2653
    else {
2654
#if defined(_@TYPE@_IS_UNICODE)
2655 1
        PyArrayScalar_VAL(from_superclass, Unicode) = NULL;
2656
#endif
2657 1
        return from_superclass;
2658
    }
2659
#endif
2660

2661
    /* TODO: include type name in error message, which is not @name@ */
2662 1
    PyObject *obj = NULL;
2663 1
    char *kwnames[] = {"", NULL};  /* positional-only */
2664 1
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwnames, &obj)) {
2665
        return NULL;
2666
    }
2667 1
    PyArray_Descr *typecode = PyArray_DescrFromType(NPY_@TYPE@);
2668 1
    if (typecode == NULL) {
2669
        return NULL;
2670
    }
2671 1
    if (obj == NULL) {
2672 1
        PyObject *robj = PyArray_Scalar(NULL, typecode, NULL);
2673 1
        Py_DECREF(typecode);
2674 1
        if (robj == NULL) {
2675
            return NULL;
2676
        }
2677
#if !defined(_@TYPE@_IS_STRING) && !defined(_@TYPE@_IS_UNICODE)
2678 1
        memset(&PyArrayScalar_VAL(robj, @Name@), 0, sizeof(npy_@name@));
2679
#endif
2680 1
        return robj;
2681
    }
2682

2683
    /* PyArray_FromAny steals a reference, reclaim it before it's gone */
2684 1
    Py_INCREF(typecode);
2685 1
    PyArrayObject *arr = (PyArrayObject *)PyArray_FromAny(
2686
            obj, typecode, 0, 0, NPY_ARRAY_FORCECAST, NULL);
2687 1
    if (arr == NULL) {
2688 1
        Py_DECREF(typecode);
2689
        return NULL;
2690
    }
2691 1
    if (PyArray_NDIM(arr) > 0) {
2692 1
        Py_DECREF(typecode);
2693
        return (PyObject *)arr;
2694
    }
2695

2696
    /* Convert the 0-d array to a scalar*/
2697 1
    PyObject *robj = PyArray_ToScalar(PyArray_DATA(arr), arr);
2698 1
    Py_DECREF(arr);
2699

2700 1
    if (robj == NULL || Py_TYPE(robj) == type) {
2701 1
        Py_DECREF(typecode);
2702
        return robj;
2703
    }
2704

2705
    /*
2706
     * `typecode` does not contain any subclass information, as it was thrown
2707
     * out by the call to `PyArray_DescrFromType` - we need to add this back.
2708
     *
2709
     * FIXME[gh-15467]: This branch is also hit for the "shadowed" builtin
2710
     * types like `longdouble` (which on platforms where they are the same size
2711
     * is shadowed by `double`), because `PyArray_FromAny` returns the
2712
     * shadowing type rather than the requested one.
2713
     */
2714

2715
    /* Need to allocate new type and copy data-area over */
2716
    int itemsize;
2717 0
    if (type->tp_itemsize) {
2718 0
        itemsize = PyBytes_GET_SIZE(robj);
2719
    }
2720
    else {
2721
        itemsize = 0;
2722
    }
2723 0
    PyObject *new_obj = type->tp_alloc(type, itemsize);
2724 0
    if (new_obj == NULL) {
2725 0
        Py_DECREF(robj);
2726 0
        Py_DECREF(typecode);
2727
        return NULL;
2728
    }
2729 0
    void *dest = scalar_value(new_obj, typecode);
2730 0
    void *src = scalar_value(robj, typecode);
2731 0
    Py_DECREF(typecode);
2732
#if defined(_@TYPE@_IS_STRING) || defined(_@TYPE@_IS_UNICODE)
2733 0
    if (itemsize == 0) { /* unicode */
2734 0
        itemsize = PyUnicode_GetLength(robj) * PyUnicode_KIND(robj);
2735
    }
2736 0
    memcpy(dest, src, itemsize);
2737
#else
2738 0
    *((npy_@name@ *)dest) = *((npy_@name@ *)src);
2739
#endif
2740 0
    Py_DECREF(robj);
2741
    return new_obj;
2742
}
2743
#undef _@TYPE@_IS_@TYPE@
2744

2745
/**end repeat**/
2746

2747
static PyObject *
2748 1
object_arrtype_new(PyTypeObject *NPY_UNUSED(type), PyObject *args, PyObject *kwds)
2749
{
2750 1
    PyObject *obj = Py_None;
2751 1
    char *kwnames[] = {"", NULL};  /* positional-only */
2752 1
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:object_", kwnames, &obj)) {
2753
        return NULL;
2754
    }
2755 1
    PyArray_Descr *typecode = PyArray_DescrFromType(NPY_OBJECT);
2756 1
    if (typecode == NULL) {
2757
        return NULL;
2758
    }
2759 1
    PyArrayObject *arr = (PyArrayObject *)PyArray_FromAny(obj, typecode,
2760
                                    0, 0, NPY_ARRAY_FORCECAST, NULL);
2761 1
    return PyArray_Return(arr);
2762
}
2763

2764
/**begin repeat
2765
 * #name = datetime, timedelta#
2766
 * #Name = Datetime, Timedelta#
2767
 * #NAME = DATETIME, TIMEDELTA#
2768
 * #is_datetime = 1, 0#
2769
 */
2770

2771
static PyObject *
2772 1
@name@_arrtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2773
{
2774 1
    PyObject *obj = NULL, *meta_obj = NULL;
2775
    Py@Name@ScalarObject *ret;
2776

2777 1
    char *kwnames[] = {"", "", NULL};  /* positional-only */
2778 1
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwnames, &obj, &meta_obj)) {
2779
        return NULL;
2780
    }
2781

2782
    /* Allocate the return scalar */
2783 1
    ret = (Py@Name@ScalarObject *)Py@Name@ArrType_Type.tp_alloc(
2784
                                            &Py@Name@ArrType_Type, 0);
2785 1
    if (ret == NULL) {
2786
        return NULL;
2787
    }
2788

2789
    /* Incorporate the metadata if its provided */
2790 1
    if (meta_obj != NULL) {
2791
        /* Parse the provided metadata input */
2792 1
        if (convert_pyobject_to_datetime_metadata(meta_obj, &ret->obmeta)
2793
                                                                    < 0) {
2794 1
            Py_DECREF(ret);
2795
            return NULL;
2796
        }
2797
    }
2798
    else {
2799
        /*
2800
         * A unit of -1 signals that convert_pyobject_to_datetime
2801
         * should populate.
2802
         */
2803 1
        ret->obmeta.base = -1;
2804
    }
2805

2806 1
    if (obj == NULL) {
2807 1
        if (ret->obmeta.base == -1) {
2808 1
            ret->obmeta.base = NPY_DATETIME_DEFAULTUNIT;
2809 1
            ret->obmeta.num = 1;
2810
        }
2811

2812
        /* Make datetime default to NaT, timedelta default to zero */
2813
#if @is_datetime@
2814 1
        ret->obval = NPY_DATETIME_NAT;
2815
#else
2816 1
        ret->obval = 0;
2817
#endif
2818
    }
2819 1
    else if (convert_pyobject_to_@name@(&ret->obmeta, obj,
2820
                            NPY_SAME_KIND_CASTING, &ret->obval) < 0) {
2821 1
        Py_DECREF(ret);
2822
        return NULL;
2823
    }
2824

2825
    return (PyObject *)ret;
2826
}
2827
/**end repeat**/
2828

2829
/* bool->tp_new only returns Py_True or Py_False */
2830
static PyObject *
2831 1
bool_arrtype_new(PyTypeObject *NPY_UNUSED(type), PyObject *args, PyObject *kwds)
2832
{
2833 1
    PyObject *obj = NULL;
2834
    PyArrayObject *arr;
2835

2836 1
    char *kwnames[] = {"", NULL};  /* positional-only */
2837 1
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:bool_", kwnames, &obj)) {
2838
        return NULL;
2839
    }
2840 1
    if (obj == NULL) {
2841 1
        PyArrayScalar_RETURN_FALSE;
2842
    }
2843 1
    if (obj == Py_False) {
2844 1
        PyArrayScalar_RETURN_FALSE;
2845
    }
2846 1
    if (obj == Py_True) {
2847 1
        PyArrayScalar_RETURN_TRUE;
2848
    }
2849 1
    arr = (PyArrayObject *)PyArray_FROM_OTF(obj,
2850
                                NPY_BOOL, NPY_ARRAY_FORCECAST);
2851 1
    if (arr && 0 == PyArray_NDIM(arr)) {
2852 1
        npy_bool val = *((npy_bool *)PyArray_DATA(arr));
2853 1
        Py_DECREF(arr);
2854 1
        PyArrayScalar_RETURN_BOOL_FROM_LONG(val);
2855
    }
2856 1
    return PyArray_Return((PyArrayObject *)arr);
2857
}
2858

2859
static PyObject *
2860 1
bool_arrtype_and(PyObject *a, PyObject *b)
2861
{
2862 1
    if (PyArray_IsScalar(a, Bool) && PyArray_IsScalar(b, Bool)) {
2863 1
        PyArrayScalar_RETURN_BOOL_FROM_LONG
2864
            ((a == PyArrayScalar_True) & (b == PyArrayScalar_True));
2865
    }
2866 1
    return PyGenericArrType_Type.tp_as_number->nb_and(a, b);
2867
}
2868

2869
static PyObject *
2870 1
bool_arrtype_or(PyObject *a, PyObject *b)
2871
{
2872 1
    if (PyArray_IsScalar(a, Bool) && PyArray_IsScalar(b, Bool)) {
2873 1
        PyArrayScalar_RETURN_BOOL_FROM_LONG
2874
            ((a == PyArrayScalar_True)|(b == PyArrayScalar_True));
2875
    }
2876 1
    return PyGenericArrType_Type.tp_as_number->nb_or(a, b);
2877
}
2878

2879
static PyObject *
2880 1
bool_arrtype_xor(PyObject *a, PyObject *b)
2881
{
2882 1
    if (PyArray_IsScalar(a, Bool) && PyArray_IsScalar(b, Bool)) {
2883 1
        PyArrayScalar_RETURN_BOOL_FROM_LONG
2884
            ((a == PyArrayScalar_True)^(b == PyArrayScalar_True));
2885
    }
2886 0
    return PyGenericArrType_Type.tp_as_number->nb_xor(a, b);
2887
}
2888

2889
static int
2890 1
bool_arrtype_nonzero(PyObject *a)
2891
{
2892 1
    return a == PyArrayScalar_True;
2893
}
2894

2895
/**begin repeat
2896
 * #name = byte, short, int, long, ubyte, ushort, longlong, uint,
2897
 *         ulong, ulonglong#
2898
 * #Name = Byte, Short, Int, Long, UByte, UShort, LongLong, UInt,
2899
 *         ULong, ULongLong#
2900
 * #type = PyLong_FromLong*6, PyLong_FromLongLong*1,
2901
 *         PyLong_FromUnsignedLong*2, PyLong_FromUnsignedLongLong#
2902
 */
2903
static PyNumberMethods @name@_arrtype_as_number;
2904
static PyObject *
2905 1
@name@_index(PyObject *self)
2906
{
2907 1
    return @type@(PyArrayScalar_VAL(self, @Name@));
2908
}
2909
/**end repeat**/
2910

2911
/**begin repeat
2912
 *  #name = half, float, double, longdouble,
2913
 *          cfloat, cdouble, clongdouble#
2914
 *  #NAME = Half, Float, Double, LongDouble,
2915
 *          CFloat, CDouble, CLongDouble#
2916
 */
2917
static PyNumberMethods @name@_arrtype_as_number;
2918
/**end repeat**/
2919

2920
static PyObject *
2921 1
bool_index(PyObject *a)
2922
{
2923 1
    if (DEPRECATE(
2924
            "In future, it will be an error for 'np.bool_' scalars to be "
2925
            "interpreted as an index") < 0) {
2926
        return NULL;
2927
    }
2928
    else {
2929 1
        return PyLong_FromLong(PyArrayScalar_VAL(a, Bool));
2930
    }
2931
}
2932

2933
/* Arithmetic methods -- only so we can override &, |, ^. */
2934
NPY_NO_EXPORT PyNumberMethods bool_arrtype_as_number = {
2935
    .nb_bool = (inquiry)bool_arrtype_nonzero,
2936
    .nb_and = (binaryfunc)bool_arrtype_and,
2937
    .nb_xor = (binaryfunc)bool_arrtype_xor,
2938
    .nb_or = (binaryfunc)bool_arrtype_or,
2939
};
2940

2941
static PyObject *
2942 1
void_arrtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2943
{
2944
    PyObject *obj, *arr;
2945 1
    PyObject *new = NULL;
2946

2947 1
    char *kwnames[] = {"", NULL};  /* positional-only */
2948 1
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:void", kwnames, &obj)) {
2949
        return NULL;
2950
    }
2951
    /*
2952
     * For a VOID scalar first see if obj is an integer or long
2953
     * and create new memory of that size (filled with 0) for the scalar
2954
     */
2955 1
    if (PyLong_Check(obj) || PyInt_Check(obj) ||
2956 1
            PyArray_IsScalar(obj, Integer) ||
2957 1
            (PyArray_Check(obj) &&
2958 0
                     PyArray_NDIM((PyArrayObject *)obj)==0 &&
2959 0
                     PyArray_ISINTEGER((PyArrayObject *)obj))) {
2960 1
        new = Py_TYPE(obj)->tp_as_number->nb_int(obj);
2961
    }
2962 1
    if (new && PyLong_Check(new)) {
2963
        PyObject *ret;
2964
        char *destptr;
2965 1
        npy_ulonglong memu = PyLong_AsUnsignedLongLong(new);
2966 1
        Py_DECREF(new);
2967 1
        if (PyErr_Occurred() || (memu > NPY_MAX_INT)) {
2968 0
            PyErr_Clear();
2969 0
            PyErr_Format(PyExc_OverflowError,
2970
                    "size must be non-negative and not greater than %d",
2971
                    (int) NPY_MAX_INT);
2972 0
            return NULL;
2973
        }
2974 1
        destptr = npy_alloc_cache_zero(memu);
2975 1
        if (destptr == NULL) {
2976 0
            return PyErr_NoMemory();
2977
        }
2978 1
        ret = type->tp_alloc(type, 0);
2979 1
        if (ret == NULL) {
2980 0
            npy_free_cache(destptr, memu);
2981 0
            return PyErr_NoMemory();
2982
        }
2983 1
        ((PyVoidScalarObject *)ret)->obval = destptr;
2984 1
        Py_SET_SIZE((PyVoidScalarObject *)ret, (int) memu);
2985 1
        ((PyVoidScalarObject *)ret)->descr =
2986 1
            PyArray_DescrNewFromType(NPY_VOID);
2987 1
        ((PyVoidScalarObject *)ret)->descr->elsize = (int) memu;
2988 1
        ((PyVoidScalarObject *)ret)->flags = NPY_ARRAY_BEHAVED |
2989
                                             NPY_ARRAY_OWNDATA;
2990 1
        ((PyVoidScalarObject *)ret)->base = NULL;
2991 1
        return ret;
2992
    }
2993

2994 1
    arr = PyArray_FROM_OTF(obj, NPY_VOID, NPY_ARRAY_FORCECAST);
2995 1
    return PyArray_Return((PyArrayObject *)arr);
2996
}
2997

2998

2999
/****************  Define Hash functions ********************/
3000

3001
/**begin repeat
3002
 * #lname = bool, ubyte, ushort#
3003
 * #name = Bool,UByte, UShort#
3004
 */
3005
static npy_hash_t
3006 1
@lname@_arrtype_hash(PyObject *obj)
3007
{
3008 1
    return (npy_hash_t)(PyArrayScalar_VAL(obj, @name@));
3009
}
3010
/**end repeat**/
3011

3012
/**begin repeat
3013
 * #lname = byte, short, uint#
3014
 * #name = Byte, Short, UInt#
3015
 */
3016
static npy_hash_t
3017 1
@lname@_arrtype_hash(PyObject *obj)
3018
{
3019 1
    npy_hash_t x = (npy_hash_t)(PyArrayScalar_VAL(obj, @name@));
3020 1
    if (x == -1) {
3021 0
        x = -2;
3022
    }
3023 1
    return x;
3024
}
3025
/**end repeat**/
3026

3027
static npy_hash_t
3028 1
ulong_arrtype_hash(PyObject *obj)
3029
{
3030 1
    PyObject * l = PyLong_FromUnsignedLong(PyArrayScalar_VAL(obj, ULong));
3031 1
    npy_hash_t x = PyObject_Hash(l);
3032 1
    Py_DECREF(l);
3033 1
    return x;
3034
}
3035

3036
static npy_hash_t
3037 1
int_arrtype_hash(PyObject *obj)
3038
{
3039 1
    npy_hash_t x = (npy_hash_t)(PyArrayScalar_VAL(obj, Int));
3040 1
    if (x == -1) {
3041 0
        x = -2;
3042
    }
3043 1
    return x;
3044
}
3045

3046
static npy_hash_t
3047 1
long_arrtype_hash(PyObject *obj)
3048
{
3049 1
    PyObject * l = PyLong_FromLong(PyArrayScalar_VAL(obj, Long));
3050 1
    npy_hash_t x = PyObject_Hash(l);
3051 1
    Py_DECREF(l);
3052 1
    return x;
3053
}
3054

3055
/**begin repeat
3056
 * #char = ,u#
3057
 * #Char = ,U#
3058
 * #Word = ,Unsigned#
3059
 */
3060
static NPY_INLINE npy_hash_t
3061 1
@char@longlong_arrtype_hash(PyObject *obj)
3062
{
3063 1
    PyObject * l = PyLong_From@Word@LongLong(
3064
                                 PyArrayScalar_VAL(obj, @Char@LongLong));
3065 1
    npy_hash_t x = PyObject_Hash(l);
3066 1
    Py_DECREF(l);
3067 1
    return x;
3068
}
3069
/**end repeat**/
3070

3071

3072
/**begin repeat
3073
 * #lname = datetime, timedelta#
3074
 * #name = Datetime, Timedelta#
3075
 */
3076
#if NPY_SIZEOF_HASH_T==NPY_SIZEOF_DATETIME
3077
static npy_hash_t
3078 1
@lname@_arrtype_hash(PyObject *obj)
3079
{
3080 1
    npy_hash_t x = (npy_hash_t)(PyArrayScalar_VAL(obj, @name@));
3081 1
    if (x == -1) {
3082 0
        x = -2;
3083
    }
3084 1
    return x;
3085
}
3086
#elif NPY_SIZEOF_LONGLONG==NPY_SIZEOF_DATETIME
3087
static npy_hash_t
3088
@lname@_arrtype_hash(PyObject *obj)
3089
{
3090
    npy_hash_t y;
3091
    npy_longlong x = (PyArrayScalar_VAL(obj, @name@));
3092

3093
    if ((x <= LONG_MAX)) {
3094
        y = (npy_hash_t) x;
3095
    }
3096
    else {
3097
        union Mask {
3098
            long hashvals[2];
3099
            npy_longlong v;
3100
        } both;
3101

3102
        both.v = x;
3103
        y = both.hashvals[0] + (1000003)*both.hashvals[1];
3104
    }
3105
    if (y == -1) {
3106
        y = -2;
3107
    }
3108
    return y;
3109
}
3110
#endif
3111
/**end repeat**/
3112

3113

3114

3115
/* Wrong thing to do for longdouble, but....*/
3116

3117
/**begin repeat
3118
 * #lname = float, longdouble#
3119
 * #name = Float, LongDouble#
3120
 */
3121
static npy_hash_t
3122 1
@lname@_arrtype_hash(PyObject *obj)
3123
{
3124 1
    return _Py_HashDouble((double) PyArrayScalar_VAL(obj, @name@));
3125
}
3126

3127
/* borrowed from complex_hash */
3128
static npy_hash_t
3129 1
c@lname@_arrtype_hash(PyObject *obj)
3130
{
3131
    npy_hash_t hashreal, hashimag, combined;
3132 1
    hashreal = _Py_HashDouble((double)
3133 1
            PyArrayScalar_VAL(obj, C@name@).real);
3134

3135 1
    if (hashreal == -1) {
3136
        return -1;
3137
    }
3138 1
    hashimag = _Py_HashDouble((double)
3139 1
            PyArrayScalar_VAL(obj, C@name@).imag);
3140 1
    if (hashimag == -1) {
3141
        return -1;
3142
    }
3143 1
    combined = hashreal + 1000003 * hashimag;
3144 1
    if (combined == -1) {
3145 0
        combined = -2;
3146
    }
3147
    return combined;
3148
}
3149
/**end repeat**/
3150

3151
static npy_hash_t
3152 1
half_arrtype_hash(PyObject *obj)
3153
{
3154 1
    return _Py_HashDouble(npy_half_to_double(PyArrayScalar_VAL(obj, Half)));
3155
}
3156

3157
static npy_hash_t
3158 0
object_arrtype_hash(PyObject *obj)
3159
{
3160 0
    return PyObject_Hash(PyArrayScalar_VAL(obj, Object));
3161
}
3162

3163
/* we used to just hash the pointer */
3164
/* now use tuplehash algorithm using voidtype_item to get the object
3165
*/
3166
static npy_hash_t
3167 1
void_arrtype_hash(PyObject *obj)
3168
{
3169
    npy_hash_t x, y;
3170
    Py_ssize_t len, n;
3171
    PyVoidScalarObject *p;
3172
    PyObject *element;
3173 1
    npy_hash_t mult = 1000003L;
3174 1
    x = 0x345678L;
3175 1
    p = (PyVoidScalarObject *)obj;
3176
    /* Cannot hash mutable void scalars */
3177 1
    if (p->flags & NPY_ARRAY_WRITEABLE) {
3178 1
       PyErr_SetString(PyExc_TypeError, "unhashable type: 'writeable void-scalar'");
3179 1
       return -1;
3180
    }
3181 1
    len = voidtype_length(p);
3182 1
    for (n=0; n < len; n++) {
3183 1
        element = voidtype_item(p, n);
3184 1
        y = PyObject_Hash(element);
3185 1
        Py_DECREF(element);
3186 1
        if (y == -1)
3187
           return -1;
3188 1
        x = (x ^ y) * mult;
3189 1
        mult += (npy_hash_t)(82520L + len + len);
3190
    }
3191 1
    x += 97531L;
3192 1
    if (x == -1)
3193 0
        x = -2;
3194
    return x;
3195
}
3196

3197
/*object arrtype getattro and setattro */
3198
static PyObject *
3199 0
object_arrtype_getattro(PyObjectScalarObject *obj, PyObject *attr) {
3200
    PyObject *res;
3201

3202
    /* first look in object and then hand off to generic type */
3203

3204 0
    res = PyObject_GenericGetAttr(obj->obval, attr);
3205 0
    if (res) {
3206
        return res;
3207
    }
3208 0
    PyErr_Clear();
3209 0
    return  PyObject_GenericGetAttr((PyObject *)obj, attr);
3210
}
3211

3212
static int
3213 0
object_arrtype_setattro(PyObjectScalarObject *obj, PyObject *attr, PyObject *val) {
3214
    int res;
3215
    /* first look in object and then hand off to generic type */
3216

3217 0
    res = PyObject_GenericSetAttr(obj->obval, attr, val);
3218 0
    if (res >= 0) {
3219
        return res;
3220
    }
3221 0
    PyErr_Clear();
3222 0
    return PyObject_GenericSetAttr((PyObject *)obj, attr, val);
3223
}
3224

3225
static PyObject *
3226 0
object_arrtype_concat(PyObjectScalarObject *self, PyObject *other)
3227
{
3228 0
    return PySequence_Concat(self->obval, other);
3229
}
3230

3231
static Py_ssize_t
3232 0
object_arrtype_length(PyObjectScalarObject *self)
3233
{
3234 0
    return PyObject_Length(self->obval);
3235
}
3236

3237
static PyObject *
3238 0
object_arrtype_repeat(PyObjectScalarObject *self, Py_ssize_t count)
3239
{
3240 0
    return PySequence_Repeat(self->obval, count);
3241
}
3242

3243
static PyObject *
3244 0
object_arrtype_subscript(PyObjectScalarObject *self, PyObject *key)
3245
{
3246 0
    return PyObject_GetItem(self->obval, key);
3247
}
3248

3249
static int
3250 0
object_arrtype_ass_subscript(PyObjectScalarObject *self, PyObject *key,
3251
                             PyObject *value)
3252
{
3253 0
    return PyObject_SetItem(self->obval, key, value);
3254
}
3255

3256
static int
3257 0
object_arrtype_contains(PyObjectScalarObject *self, PyObject *ob)
3258
{
3259 0
    return PySequence_Contains(self->obval, ob);
3260
}
3261

3262
static PyObject *
3263 0
object_arrtype_inplace_concat(PyObjectScalarObject *self, PyObject *o)
3264
{
3265 0
    return PySequence_InPlaceConcat(self->obval, o);
3266
}
3267

3268
static PyObject *
3269 0
object_arrtype_inplace_repeat(PyObjectScalarObject *self, Py_ssize_t count)
3270
{
3271 0
    return PySequence_InPlaceRepeat(self->obval, count);
3272
}
3273

3274
static PySequenceMethods object_arrtype_as_sequence = {
3275
    .sq_length = (lenfunc)object_arrtype_length,
3276
    .sq_concat = (binaryfunc)object_arrtype_concat,
3277
    .sq_repeat = (ssizeargfunc)object_arrtype_repeat,
3278
    .sq_contains = (objobjproc)object_arrtype_contains,
3279
    .sq_inplace_concat = (binaryfunc)object_arrtype_inplace_concat,
3280
    .sq_inplace_repeat = (ssizeargfunc)object_arrtype_inplace_repeat,
3281
};
3282

3283
static PyMappingMethods object_arrtype_as_mapping = {
3284
    .mp_length = (lenfunc)object_arrtype_length,
3285
    .mp_subscript = (binaryfunc)object_arrtype_subscript,
3286
    .mp_ass_subscript = (objobjargproc)object_arrtype_ass_subscript,
3287
};
3288

3289
static int
3290 0
object_arrtype_getbuffer(PyObjectScalarObject *self, Py_buffer *view, int flags)
3291
{
3292 0
    PyBufferProcs *pb = Py_TYPE(self->obval)->tp_as_buffer;
3293 0
    if (pb == NULL || pb->bf_getbuffer == NULL) {
3294 0
        PyErr_SetString(PyExc_TypeError,
3295
                        "expected a readable buffer object");
3296 0
        return -1;
3297
    }
3298 0
    return (*pb->bf_getbuffer)(self->obval, view, flags);
3299
}
3300

3301
static void
3302 0
object_arrtype_releasebuffer(PyObjectScalarObject *self, Py_buffer *view)
3303
{
3304 0
    PyBufferProcs *pb = Py_TYPE(self->obval)->tp_as_buffer;
3305 0
    if (pb == NULL) {
3306 0
        PyErr_SetString(PyExc_TypeError,
3307
                        "expected a readable buffer object");
3308 0
        return;
3309
    }
3310 0
    if (pb->bf_releasebuffer != NULL) {
3311 0
        (*pb->bf_releasebuffer)(self->obval, view);
3312
    }
3313
}
3314

3315
static PyBufferProcs object_arrtype_as_buffer = {
3316
    .bf_getbuffer = (getbufferproc)object_arrtype_getbuffer,
3317
    .bf_releasebuffer = (releasebufferproc)object_arrtype_releasebuffer,
3318
};
3319

3320
static PyObject *
3321 0
object_arrtype_call(PyObjectScalarObject *obj, PyObject *args, PyObject *kwds)
3322
{
3323 0
    return PyObject_Call(obj->obval, args, kwds);
3324
}
3325

3326
NPY_NO_EXPORT PyTypeObject PyObjectArrType_Type = {
3327
    PyVarObject_HEAD_INIT(NULL, 0)
3328
    .tp_name = "numpy.object_",
3329
    .tp_basicsize = sizeof(PyObjectScalarObject),
3330
    .tp_alloc = object_arrtype_alloc,
3331
    .tp_dealloc = (destructor)object_arrtype_dealloc,
3332
    .tp_as_sequence = &object_arrtype_as_sequence,
3333
    .tp_as_mapping = &object_arrtype_as_mapping,
3334
    .tp_call = (ternaryfunc)object_arrtype_call,
3335
    .tp_getattro = (getattrofunc)object_arrtype_getattro,
3336
    .tp_setattro = (setattrofunc)object_arrtype_setattro,
3337
    .tp_as_buffer = &object_arrtype_as_buffer,
3338
};
3339

3340
static PyObject *
3341 1
gen_arrtype_subscript(PyObject *self, PyObject *key)
3342
{
3343
    /*
3344
     * Only [...], [...,<???>], [<???>, ...],
3345
     * is allowed for indexing a scalar
3346
     *
3347
     * These return a new N-d array with a copy of
3348
     * the data where N is the number of None's in <???>.
3349
     */
3350
    PyObject *res, *ret;
3351

3352 1
    res = PyArray_FromScalar(self, NULL);
3353

3354 1
    ret = array_subscript((PyArrayObject *)res, key);
3355 1
    Py_DECREF(res);
3356 1
    if (ret == NULL) {
3357 1
        PyErr_SetString(PyExc_IndexError,
3358
                        "invalid index to scalar variable.");
3359
    }
3360 1
    return ret;
3361
}
3362

3363

3364
#define NAME_bool "bool"
3365
#define NAME_void "void"
3366
#define NAME_string "bytes"
3367
#define NAME_unicode "str"
3368

3369
/**begin repeat
3370
 * #name = bool, string, unicode, void#
3371
 * #NAME = Bool, String, Unicode, Void#
3372
 * #ex = _,_,_,#
3373
 */
3374
NPY_NO_EXPORT PyTypeObject Py@NAME@ArrType_Type = {
3375
    PyVarObject_HEAD_INIT(NULL, 0)
3376
    .tp_name = "numpy." NAME_@name@ "@ex@",
3377
    .tp_basicsize = sizeof(Py@NAME@ScalarObject),
3378
};
3379
/**end repeat**/
3380

3381
#undef NAME_bool
3382
#undef NAME_void
3383
#undef NAME_string
3384
#undef NAME_unicode
3385

3386
/**begin repeat
3387
 * #NAME = Byte, Short, Int, Long, LongLong, UByte, UShort, UInt, ULong,
3388
 *         ULongLong, Half, Float, Double, LongDouble, Datetime, Timedelta#
3389
 * #name = int*5, uint*5, float*4, datetime, timedelta#
3390
 * #CNAME = (CHAR, SHORT, INT, LONG, LONGLONG)*2, HALF, FLOAT, DOUBLE,
3391
 *          LONGDOUBLE, DATETIME, TIMEDELTA#
3392
 */
3393
#if NPY_BITSOF_@CNAME@ == 8
3394
#define _THIS_SIZE "8"
3395
#elif NPY_BITSOF_@CNAME@ == 16
3396
#define _THIS_SIZE "16"
3397
#elif NPY_BITSOF_@CNAME@ == 32
3398
#define _THIS_SIZE "32"
3399
#elif NPY_BITSOF_@CNAME@ == 64
3400
#define _THIS_SIZE "64"
3401
#elif NPY_BITSOF_@CNAME@ == 80
3402
#define _THIS_SIZE "80"
3403
#elif NPY_BITSOF_@CNAME@ == 96
3404
#define _THIS_SIZE "96"
3405
#elif NPY_BITSOF_@CNAME@ == 128
3406
#define _THIS_SIZE "128"
3407
#elif NPY_BITSOF_@CNAME@ == 256
3408
#define _THIS_SIZE "256"
3409
#endif
3410
NPY_NO_EXPORT PyTypeObject Py@NAME@ArrType_Type = {
3411
    PyVarObject_HEAD_INIT(NULL, 0)
3412
    .tp_name = "numpy.@name@" _THIS_SIZE,
3413
    .tp_basicsize = sizeof(Py@NAME@ScalarObject),
3414
};
3415

3416

3417
#undef _THIS_SIZE
3418
/**end repeat**/
3419

3420

3421
static PyMappingMethods gentype_as_mapping = {
3422
    .mp_subscript = (binaryfunc)gen_arrtype_subscript,
3423
};
3424

3425

3426
/**begin repeat
3427
 * #NAME = CFloat, CDouble, CLongDouble#
3428
 * #name = complex*3#
3429
 * #CNAME = FLOAT, DOUBLE, LONGDOUBLE#
3430
 */
3431
#if NPY_BITSOF_@CNAME@ == 16
3432
#define _THIS_SIZE "32"
3433
#elif NPY_BITSOF_@CNAME@ == 32
3434
#define _THIS_SIZE "64"
3435
#elif NPY_BITSOF_@CNAME@ == 64
3436
#define _THIS_SIZE "128"
3437
#elif NPY_BITSOF_@CNAME@ == 80
3438
#define _THIS_SIZE "160"
3439
#elif NPY_BITSOF_@CNAME@ == 96
3440
#define _THIS_SIZE "192"
3441
#elif NPY_BITSOF_@CNAME@ == 128
3442
#define _THIS_SIZE "256"
3443
#elif NPY_BITSOF_@CNAME@ == 256
3444
#define _THIS_SIZE "512"
3445
#endif
3446

3447
NPY_NO_EXPORT PyTypeObject Py@NAME@ArrType_Type = {
3448
    PyVarObject_HEAD_INIT(0, 0)
3449
    .tp_name = "numpy.@name@" _THIS_SIZE,
3450
    .tp_basicsize = sizeof(Py@NAME@ScalarObject),
3451
    .tp_flags = Py_TPFLAGS_DEFAULT,
3452
};
3453
#undef _THIS_SIZE
3454

3455
/**end repeat**/
3456

3457
/*
3458
 * This table maps the built-in type numbers to their scalar
3459
 * type numbers.  Note that signed integers are mapped to INTNEG_SCALAR,
3460
 * which is different than what PyArray_ScalarKind returns.
3461
 */
3462
NPY_NO_EXPORT signed char
3463
_npy_scalar_kinds_table[NPY_NTYPES];
3464

3465
/*
3466
 * This table maps a scalar kind (excluding NPY_NOSCALAR)
3467
 * to the smallest type number of that kind.
3468
 */
3469
NPY_NO_EXPORT signed char
3470
_npy_smallest_type_of_kind_table[NPY_NSCALARKINDS];
3471

3472
/*
3473
 * This table gives the type of the same kind, but next in the sequence
3474
 * of sizes.
3475
 */
3476
NPY_NO_EXPORT signed char
3477
_npy_next_larger_type_table[NPY_NTYPES];
3478

3479
/*
3480
 * This table describes safe casting for small type numbers,
3481
 * and is used by PyArray_CanCastSafely.
3482
 */
3483
NPY_NO_EXPORT unsigned char
3484
_npy_can_cast_safely_table[NPY_NTYPES][NPY_NTYPES];
3485

3486
/*
3487
 * This table gives the smallest-size and smallest-kind type to which
3488
 * the input types may be safely cast, according to _npy_can_cast_safely.
3489
 */
3490
NPY_NO_EXPORT signed char
3491
_npy_type_promotion_table[NPY_NTYPES][NPY_NTYPES];
3492

3493
NPY_NO_EXPORT void
3494 1
initialize_casting_tables(void)
3495
{
3496
    int i, j;
3497

3498 1
    _npy_smallest_type_of_kind_table[NPY_BOOL_SCALAR] = NPY_BOOL;
3499 1
    _npy_smallest_type_of_kind_table[NPY_INTPOS_SCALAR] = NPY_UBYTE;
3500 1
    _npy_smallest_type_of_kind_table[NPY_INTNEG_SCALAR] = NPY_BYTE;
3501 1
    _npy_smallest_type_of_kind_table[NPY_FLOAT_SCALAR] = NPY_HALF;
3502 1
    _npy_smallest_type_of_kind_table[NPY_COMPLEX_SCALAR] = NPY_CFLOAT;
3503 1
    _npy_smallest_type_of_kind_table[NPY_OBJECT_SCALAR] = NPY_OBJECT;
3504

3505
    /* Default for built-in types is object scalar */
3506 1
    memset(_npy_scalar_kinds_table, NPY_OBJECT_SCALAR,
3507
                                        sizeof(_npy_scalar_kinds_table));
3508
    /* Default for next largest type is -1, signalling no bigger */
3509 1
    memset(_npy_next_larger_type_table, -1,
3510
                                        sizeof(_npy_next_larger_type_table));
3511

3512
    /* Compile-time loop of scalar kinds */
3513

3514
    /**begin repeat
3515
     * #NAME = BOOL,
3516
     *         BYTE, UBYTE, SHORT, USHORT, INT, UINT,
3517
     *         LONG, ULONG, LONGLONG, ULONGLONG,
3518
     *         HALF, FLOAT, DOUBLE, LONGDOUBLE,
3519
     *         CFLOAT, CDOUBLE, CLONGDOUBLE#
3520
     * #BIGGERTYPE = -1,
3521
     *         NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT, NPY_LONG, NPY_ULONG,
3522
     *         NPY_LONGLONG, NPY_ULONGLONG, -1, -1,
3523
     *         NPY_FLOAT, NPY_DOUBLE, NPY_LONGDOUBLE, -1,
3524
     *         NPY_CDOUBLE, NPY_CLONGDOUBLE, -1#
3525
     * #SCKIND = BOOL,
3526
     *           (INTNEG, INTPOS)*5,
3527
     *           FLOAT*4,
3528
     *           COMPLEX*3#
3529
     */
3530

3531 1
    _npy_scalar_kinds_table[NPY_@NAME@] = NPY_@SCKIND@_SCALAR;
3532 1
    _npy_next_larger_type_table[NPY_@NAME@] = @BIGGERTYPE@;
3533

3534
    /**end repeat**/
3535

3536 1
    memset(_npy_can_cast_safely_table, 0, sizeof(_npy_can_cast_safely_table));
3537

3538 1
    for (i = 0; i < NPY_NTYPES; ++i) {
3539
        /* Identity */
3540 1
        _npy_can_cast_safely_table[i][i] = 1;
3541 1
        if (i != NPY_DATETIME) {
3542
            /*
3543
             * Bool -> <Anything> except datetime (since
3544
             *                    it conceptually has no zero)
3545
             */
3546 1
            _npy_can_cast_safely_table[NPY_BOOL][i] = 1;
3547
        }
3548
        /* <Anything> -> Object */
3549 1
        _npy_can_cast_safely_table[i][NPY_OBJECT] = 1;
3550
        /* <Anything> -> Void */
3551 1
        _npy_can_cast_safely_table[i][NPY_VOID] = 1;
3552
    }
3553

3554 1
    _npy_can_cast_safely_table[NPY_STRING][NPY_UNICODE] = 1;
3555

3556
#ifndef NPY_SIZEOF_BYTE
3557
#define NPY_SIZEOF_BYTE 1
3558
#endif
3559

3560
    /* Compile-time loop of casting rules */
3561

3562
    /**begin repeat
3563
     * #FROM_NAME = BYTE, UBYTE, SHORT, USHORT, INT, UINT,
3564
     *              LONG, ULONG, LONGLONG, ULONGLONG,
3565
     *              HALF, FLOAT, DOUBLE, LONGDOUBLE,
3566
     *              CFLOAT, CDOUBLE, CLONGDOUBLE#
3567
     * #FROM_BASENAME = BYTE, BYTE, SHORT, SHORT, INT, INT,
3568
     *                  LONG, LONG, LONGLONG, LONGLONG,
3569
     *                  HALF, FLOAT, DOUBLE, LONGDOUBLE,
3570
     *                  FLOAT, DOUBLE, LONGDOUBLE#
3571
     * #from_isint = 1, 0, 1, 0, 1, 0, 1, 0,
3572
     *               1, 0, 0, 0, 0, 0,
3573
     *               0, 0, 0#
3574
     * #from_isuint = 0, 1, 0, 1, 0, 1, 0, 1,
3575
     *                0, 1, 0, 0, 0, 0,
3576
     *                0, 0, 0#
3577
     * #from_isfloat = 0, 0, 0, 0, 0, 0, 0, 0,
3578
     *                 0, 0, 1, 1, 1, 1,
3579
     *                 0, 0, 0#
3580
     * #from_iscomplex = 0, 0, 0, 0, 0, 0, 0, 0,
3581
     *                   0, 0, 0, 0, 0, 0,
3582
     *                   1, 1, 1#
3583
     */
3584

3585
#define _FROM_BSIZE NPY_SIZEOF_@FROM_BASENAME@
3586
#define _FROM_NUM   (NPY_@FROM_NAME@)
3587

3588 1
    _npy_can_cast_safely_table[_FROM_NUM][NPY_STRING] = 1;
3589 1
    _npy_can_cast_safely_table[_FROM_NUM][NPY_UNICODE] = 1;
3590

3591
#if @from_isint@ && NPY_SIZEOF_TIMEDELTA >= _FROM_BSIZE
3592
    /* Allow casts from smaller or equal signed integers to the TIMEDELTA type */
3593 1
    _npy_can_cast_safely_table[_FROM_NUM][NPY_TIMEDELTA] = 1;
3594
#elif @from_isuint@ && NPY_SIZEOF_TIMEDELTA > _FROM_BSIZE
3595
    /* Allow casts from smaller unsigned integers to the TIMEDELTA type */
3596 1
    _npy_can_cast_safely_table[_FROM_NUM][NPY_TIMEDELTA] = 1;
3597
#endif
3598

3599
    /**begin repeat1
3600
     * #TO_NAME = BYTE, UBYTE, SHORT, USHORT, INT, UINT,
3601
     *            LONG, ULONG, LONGLONG, ULONGLONG,
3602
     *            HALF, FLOAT, DOUBLE, LONGDOUBLE,
3603
     *            CFLOAT, CDOUBLE, CLONGDOUBLE#
3604
     * #TO_BASENAME = BYTE, BYTE, SHORT, SHORT, INT, INT,
3605
     *                LONG, LONG, LONGLONG, LONGLONG,
3606
     *                HALF, FLOAT, DOUBLE, LONGDOUBLE,
3607
     *                FLOAT, DOUBLE, LONGDOUBLE#
3608
     * #to_isint = 1, 0, 1, 0, 1, 0, 1, 0,
3609
     *             1, 0, 0, 0, 0, 0,
3610
     *             0, 0, 0#
3611
     * #to_isuint = 0, 1, 0, 1, 0, 1, 0, 1,
3612
     *              0, 1, 0, 0, 0, 0,
3613
     *              0, 0, 0#
3614
     * #to_isfloat = 0, 0, 0, 0, 0, 0, 0, 0,
3615
     *               0, 0, 1, 1, 1, 1,
3616
     *               0, 0, 0#
3617
     * #to_iscomplex = 0, 0, 0, 0, 0, 0, 0, 0,
3618
     *                 0, 0, 0, 0, 0, 0,
3619
     *                 1, 1, 1#
3620
     */
3621
#define _TO_BSIZE NPY_SIZEOF_@TO_BASENAME@
3622
#define _TO_NUM   (NPY_@TO_NAME@)
3623

3624
    /*
3625
     * NOTE: _FROM_BSIZE and _TO_BSIZE are the sizes of the "base type"
3626
     *       which is the same as the size of the type except for
3627
     *       complex, where it is the size of the real type.
3628
     */
3629

3630
#if @from_isint@
3631

3632
#  if @to_isint@ && (_TO_BSIZE >= _FROM_BSIZE)
3633
    /* int -> int */
3634 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3635
#  elif @to_isfloat@ && (_FROM_BSIZE < 8) && (_TO_BSIZE > _FROM_BSIZE)
3636
    /* int -> float */
3637 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3638
#  elif @to_isfloat@ && (_FROM_BSIZE >= 8) && (_TO_BSIZE >= _FROM_BSIZE)
3639
    /* int -> float */
3640 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3641
#  elif @to_iscomplex@ && (_FROM_BSIZE < 8) && (_TO_BSIZE > _FROM_BSIZE)
3642
    /* int -> complex */
3643 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3644
#  elif @to_iscomplex@ && (_FROM_BSIZE >= 8) && (_TO_BSIZE >= _FROM_BSIZE)
3645
    /* int -> complex */
3646 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3647
#  endif
3648

3649
#elif @from_isuint@
3650

3651
#  if @to_isint@ && (_TO_BSIZE > _FROM_BSIZE)
3652
    /* uint -> int */
3653 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3654
#  elif @to_isuint@ && (_TO_BSIZE >= _FROM_BSIZE)
3655
    /* uint -> uint */
3656 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3657
#  elif @to_isfloat@ && (_FROM_BSIZE < 8) && (_TO_BSIZE > _FROM_BSIZE)
3658
    /* uint -> float */
3659 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3660
#  elif @to_isfloat@ && (_FROM_BSIZE >= 8) && (_TO_BSIZE >= _FROM_BSIZE)
3661
    /* uint -> float */
3662 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3663
#  elif @to_iscomplex@ && (_FROM_BSIZE < 8) && (_TO_BSIZE > _FROM_BSIZE)
3664
    /* uint -> complex */
3665 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3666
#  elif @to_iscomplex@ && (_FROM_BSIZE >= 8) && (_TO_BSIZE >= _FROM_BSIZE)
3667
    /* uint -> complex */
3668 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3669
#  endif
3670

3671

3672
#elif @from_isfloat@
3673

3674
#  if @to_isfloat@ && (_TO_BSIZE >= _FROM_BSIZE)
3675
    /* float -> float */
3676 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3677
#  elif @to_iscomplex@ && (_TO_BSIZE >= _FROM_BSIZE)
3678
    /* float -> complex */
3679 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3680
#  endif
3681

3682
#elif @from_iscomplex@
3683

3684
#  if @to_iscomplex@ && (_TO_BSIZE >= _FROM_BSIZE)
3685
    /* complex -> complex */
3686 1
    _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1;
3687
#  endif
3688

3689
#endif
3690

3691
#undef _TO_NUM
3692
#undef _TO_BSIZE
3693

3694
/**end repeat1**/
3695

3696
#undef _FROM_NUM
3697
#undef _FROM_BSIZE
3698

3699
/**end repeat**/
3700

3701
    /*
3702
     * Now that the _can_cast_safely table is finished, we can
3703
     * use it to build the _type_promotion table
3704
     */
3705 1
    for (i = 0; i < NPY_NTYPES; ++i) {
3706 1
        _npy_type_promotion_table[i][i] = i;
3707
        /* Don't let number promote to string/unicode/void/datetime/timedelta */
3708 1
        if (i == NPY_STRING || i == NPY_UNICODE || i == NPY_VOID ||
3709 1
                i == NPY_DATETIME || i == NPY_TIMEDELTA) {
3710
            /* Promoting these types requires examining their contents */
3711 1
            _npy_type_promotion_table[i][i] = -1;
3712 1
            for (j = i + 1; j < NPY_NTYPES; ++j) {
3713 1
                _npy_type_promotion_table[i][j] = -1;
3714 1
                _npy_type_promotion_table[j][i] = -1;
3715
            }
3716
            /* Except they can convert to OBJECT */
3717 1
            _npy_type_promotion_table[i][NPY_OBJECT] = NPY_OBJECT;
3718 1
            _npy_type_promotion_table[NPY_OBJECT][i] = NPY_OBJECT;
3719
        }
3720
        else {
3721 1
            for (j = i + 1; j < NPY_NTYPES; ++j) {
3722
                /* Don't let number promote to string/unicode/void */
3723 1
                if (j == NPY_STRING || j == NPY_UNICODE || j == NPY_VOID) {
3724 1
                    _npy_type_promotion_table[i][j] = -1;
3725 1
                    _npy_type_promotion_table[j][i] = -1;
3726
                }
3727 1
                else if (_npy_can_cast_safely_table[i][j]) {
3728 1
                    _npy_type_promotion_table[i][j] = j;
3729 1
                    _npy_type_promotion_table[j][i] = j;
3730
                }
3731 1
                else if (_npy_can_cast_safely_table[j][i]) {
3732 1
                    _npy_type_promotion_table[i][j] = i;
3733 1
                    _npy_type_promotion_table[j][i] = i;
3734
                }
3735
                else {
3736
                    int k, iskind, jskind, skind;
3737 1
                    iskind = _npy_scalar_kinds_table[i];
3738 1
                    jskind = _npy_scalar_kinds_table[j];
3739
                    /* If there's no kind (void/string/etc) */
3740 1
                    if (iskind == NPY_NOSCALAR || jskind == NPY_NOSCALAR) {
3741
                        k = -1;
3742
                    }
3743
                    else {
3744
                        /* Start with the type of larger kind */
3745 1
                        if (iskind > jskind) {
3746
                            skind = iskind;
3747
                            k = i;
3748
                        }
3749
                        else {
3750 1
                            skind = jskind;
3751 1
                            k = j;
3752
                        }
3753
                        for (;;) {
3754
                            /* Try the next larger type of this kind */
3755 1
                            k = _npy_next_larger_type_table[k];
3756

3757
                            /* If there is no larger, try a larger kind */
3758 1
                            if (k < 0) {
3759 1
                                ++skind;
3760
                                /* Use -1 to signal no promoted type found */
3761 1
                                if (skind < NPY_NSCALARKINDS) {
3762 1
                                    k = _npy_smallest_type_of_kind_table[skind];
3763
                                }
3764
                                else {
3765
                                    k = -1;
3766
                                    break;
3767
                                }
3768
                            }
3769

3770 1
                            if (_npy_can_cast_safely_table[i][k] &&
3771 1
                                            _npy_can_cast_safely_table[j][k]) {
3772
                                break;
3773
                            }
3774
                        }
3775
                    }
3776 1
                    _npy_type_promotion_table[i][j] = k;
3777 1
                    _npy_type_promotion_table[j][i] = k;
3778
                }
3779
            }
3780
        }
3781
    }
3782 1
}
3783

3784
static PyNumberMethods longdoubletype_as_number;
3785
static PyNumberMethods clongdoubletype_as_number;
3786
static void init_basetypes(void);
3787

3788

3789
NPY_NO_EXPORT void
3790 1
initialize_numeric_types(void)
3791
{
3792
    init_basetypes();
3793 1
    PyGenericArrType_Type.tp_dealloc = (destructor)gentype_dealloc;
3794 1
    PyGenericArrType_Type.tp_as_number = &gentype_as_number;
3795 1
    PyGenericArrType_Type.tp_as_mapping = &gentype_as_mapping;
3796 1
    PyGenericArrType_Type.tp_flags = BASEFLAGS;
3797 1
    PyGenericArrType_Type.tp_methods = gentype_methods;
3798 1
    PyGenericArrType_Type.tp_getset = gentype_getsets;
3799 1
    PyGenericArrType_Type.tp_new = NULL;
3800 1
    PyGenericArrType_Type.tp_alloc = gentype_alloc;
3801 1
    PyGenericArrType_Type.tp_free = (freefunc)gentype_free;
3802 1
    PyGenericArrType_Type.tp_richcompare = gentype_richcompare;
3803

3804 1
    PyBoolArrType_Type.tp_as_number = &bool_arrtype_as_number;
3805
    /*
3806
     * need to add dummy versions with filled-in nb_index
3807
     * in-order for PyType_Ready to fill in .__index__() method
3808
     * also fill array_type_as_number struct with reasonable defaults
3809
     */
3810

3811
    /**begin repeat
3812
     * #name = byte, short, int, long, longlong, ubyte, ushort,
3813
     *         uint, ulong, ulonglong#
3814
     * #NAME = Byte, Short, Int, Long, LongLong, UByte, UShort,
3815
     *         UInt, ULong, ULongLong#
3816
     */
3817 1
    @name@_arrtype_as_number = gentype_as_number;
3818 1
    Py@NAME@ArrType_Type.tp_as_number = &@name@_arrtype_as_number;
3819 1
    Py@NAME@ArrType_Type.tp_as_number->nb_index = (unaryfunc)@name@_index;
3820

3821
    /**end repeat**/
3822

3823
    /**begin repeat
3824
     *  #name = half, float, double, longdouble,
3825
     *          cfloat, cdouble, clongdouble#
3826
     *  #NAME = Half, Float, Double, LongDouble,
3827
     *          CFloat, CDouble, CLongDouble#
3828
     */
3829 1
    @name@_arrtype_as_number = gentype_as_number;
3830 1
    Py@NAME@ArrType_Type.tp_as_number = &@name@_arrtype_as_number;
3831

3832
    /**end repeat**/
3833

3834 1
    PyBoolArrType_Type.tp_as_number->nb_index = (unaryfunc)bool_index;
3835

3836 1
    PyStringArrType_Type.tp_alloc = NULL;
3837 1
    PyStringArrType_Type.tp_free = NULL;
3838

3839 1
    PyStringArrType_Type.tp_repr = stringtype_repr;
3840 1
    PyStringArrType_Type.tp_str = stringtype_str;
3841

3842 1
    PyUnicodeArrType_Type.tp_repr = unicodetype_repr;
3843 1
    PyUnicodeArrType_Type.tp_str = unicodetype_str;
3844

3845 1
    PyVoidArrType_Type.tp_methods = voidtype_methods;
3846 1
    PyVoidArrType_Type.tp_getset = voidtype_getsets;
3847 1
    PyVoidArrType_Type.tp_as_mapping = &voidtype_as_mapping;
3848 1
    PyVoidArrType_Type.tp_as_sequence = &voidtype_as_sequence;
3849 1
    PyVoidArrType_Type.tp_repr = voidtype_repr;
3850 1
    PyVoidArrType_Type.tp_str = voidtype_str;
3851

3852 1
    PyIntegerArrType_Type.tp_getset = inttype_getsets;
3853

3854
    /**begin repeat
3855
     * #NAME= Number, Integer, SignedInteger, UnsignedInteger, Inexact,
3856
     *        Floating, ComplexFloating, Flexible, Character#
3857
     */
3858

3859 1
    Py@NAME@ArrType_Type.tp_flags = BASEFLAGS;
3860

3861
    /**end repeat**/
3862

3863
    /**begin repeat
3864
     * #name = bool, byte, short, int, long, longlong, ubyte, ushort, uint,
3865
     *         ulong, ulonglong, half, float, double, longdouble, cfloat,
3866
     *         cdouble, clongdouble, string, unicode, void, object, datetime,
3867
     *         timedelta#
3868
     * #NAME = Bool, Byte, Short, Int, Long, LongLong, UByte, UShort, UInt,
3869
     *         ULong, ULongLong, Half, Float, Double, LongDouble, CFloat,
3870
     *         CDouble, CLongDouble, String, Unicode, Void, Object, Datetime,
3871
     *         Timedelta#
3872
     */
3873

3874 1
    Py@NAME@ArrType_Type.tp_flags = BASEFLAGS;
3875 1
    Py@NAME@ArrType_Type.tp_new = @name@_arrtype_new;
3876 1
    Py@NAME@ArrType_Type.tp_richcompare = gentype_richcompare;
3877

3878
#define _IS_@NAME@  /* inherit string buffer */
3879
#if !defined(_IS_String)
3880 1
    Py@NAME@ArrType_Type.tp_as_buffer = &@name@_arrtype_as_buffer;
3881
#endif
3882
#undef _IS_@NAME@
3883

3884
    /**end repeat**/
3885

3886 1
    PyUnicodeArrType_Type.tp_dealloc = unicode_arrtype_dealloc;
3887

3888
    /**begin repeat
3889
     * #name = bool, byte, short, ubyte, ushort, uint, ulong, ulonglong,
3890
     *         half, float, longdouble, cfloat, clongdouble, void, object,
3891
     *         datetime, timedelta#
3892
     * #NAME = Bool, Byte, Short, UByte, UShort, UInt, ULong, ULongLong,
3893
     *         Half, Float, LongDouble, CFloat, CLongDouble, Void, Object,
3894
     *         Datetime, Timedelta#
3895
     */
3896

3897 1
    Py@NAME@ArrType_Type.tp_hash = @name@_arrtype_hash;
3898

3899
    /**end repeat**/
3900

3901
    /**begin repeat
3902
     * #name = cfloat, clongdouble, floating, integer, complexfloating#
3903
     * #NAME = CFloat, CLongDouble, Floating, Integer, ComplexFloating#
3904
     */
3905

3906 1
    Py@NAME@ArrType_Type.tp_methods = @name@type_methods;
3907

3908
    /**end repeat**/
3909

3910
    /**begin repeat
3911
     * #name = half, float, double, longdouble#
3912
     * #Name = Half, Float, Double, LongDouble#
3913
     */
3914

3915 1
    Py@Name@ArrType_Type.tp_methods = @name@type_methods;
3916

3917
    /**end repeat**/
3918

3919
    /* We won't be inheriting from Python Int type. */
3920 1
    PyIntArrType_Type.tp_hash = int_arrtype_hash;
3921

3922
    /* We won't be inheriting from Python Int type. */
3923 1
    PyLongArrType_Type.tp_hash = long_arrtype_hash;
3924

3925
    /* We won't be inheriting from Python Int type. */
3926 1
    PyLongLongArrType_Type.tp_hash = longlong_arrtype_hash;
3927

3928
    /**begin repeat
3929
     * #name = repr, str#
3930
     */
3931

3932 1
    PyHalfArrType_Type.tp_@name@ = halftype_@name@;
3933

3934 1
    PyFloatArrType_Type.tp_@name@ = floattype_@name@;
3935 1
    PyCFloatArrType_Type.tp_@name@ = cfloattype_@name@;
3936

3937 1
    PyDoubleArrType_Type.tp_@name@ = doubletype_@name@;
3938 1
    PyCDoubleArrType_Type.tp_@name@  = cdoubletype_@name@;
3939

3940 1
    PyDatetimeArrType_Type.tp_@name@ = datetimetype_@name@;
3941 1
    PyTimedeltaArrType_Type.tp_@name@ = timedeltatype_@name@;
3942

3943
    /**end repeat**/
3944

3945

3946
    /**begin repeat
3947
     * #Type = Bool, Byte, UByte, Short, UShort, Int, UInt, Long,
3948
     *         ULong, LongLong, ULongLong#
3949
     */
3950

3951
    /* both str/repr use genint_type_str to avoid trailing "L" of longs */
3952 1
    Py@Type@ArrType_Type.tp_str = genint_type_str;
3953 1
    Py@Type@ArrType_Type.tp_repr = genint_type_str;
3954

3955
    /**end repeat**/
3956

3957

3958

3959
    /**begin repeat
3960
     * #char = ,c#
3961
     * #CHAR = ,C#
3962
     */
3963

3964
    /*
3965
     * These need to be coded specially because longdouble/clongdouble getitem
3966
     * does not return a normal Python type
3967
     */
3968 1
    @char@longdoubletype_as_number.nb_float = @char@longdoubletype_float;
3969 1
    @char@longdoubletype_as_number.nb_int  = @char@longdoubletype_long;
3970

3971 1
    Py@CHAR@LongDoubleArrType_Type.tp_as_number = &@char@longdoubletype_as_number;
3972 1
    Py@CHAR@LongDoubleArrType_Type.tp_repr = @char@longdoubletype_repr;
3973 1
    Py@CHAR@LongDoubleArrType_Type.tp_str = @char@longdoubletype_str;
3974

3975
    /**end repeat**/
3976

3977 1
    PyStringArrType_Type.tp_itemsize = sizeof(char);
3978 1
    PyVoidArrType_Type.tp_dealloc = (destructor) void_dealloc;
3979

3980 1
    PyArrayIter_Type.tp_iter = PyObject_SelfIter;
3981 1
    PyArrayMapIter_Type.tp_iter = PyObject_SelfIter;
3982

3983
    /*
3984
     * Give types different names when they are the same size (gh-9799).
3985
     * `np.intX` always refers to the first int of that size in the sequence
3986
     * `['LONG', 'LONGLONG', 'INT', 'SHORT', 'BYTE']`.
3987
     */
3988
#if (NPY_SIZEOF_BYTE == NPY_SIZEOF_SHORT)
3989
    PyByteArrType_Type.tp_name = "numpy.byte";
3990
    PyUByteArrType_Type.tp_name = "numpy.ubyte";
3991
#endif
3992
#if (NPY_SIZEOF_SHORT == NPY_SIZEOF_INT)
3993
    PyShortArrType_Type.tp_name = "numpy.short";
3994
    PyUShortArrType_Type.tp_name = "numpy.ushort";
3995
#endif
3996
#if (NPY_SIZEOF_INT == NPY_SIZEOF_LONG)
3997
    PyIntArrType_Type.tp_name = "numpy.intc";
3998
    PyUIntArrType_Type.tp_name = "numpy.uintc";
3999
#endif
4000
#if (NPY_SIZEOF_LONGLONG == NPY_SIZEOF_LONG)
4001 1
    PyLongLongArrType_Type.tp_name = "numpy.longlong";
4002 1
    PyULongLongArrType_Type.tp_name = "numpy.ulonglong";
4003
#endif
4004

4005
    /*
4006
    Do the same for longdouble
4007
    */
4008
#if (NPY_SIZEOF_LONGDOUBLE == NPY_SIZEOF_DOUBLE)
4009
    PyLongDoubleArrType_Type.tp_name = "numpy.longdouble";
4010
    PyCLongDoubleArrType_Type.tp_name = "numpy.clongdouble";
4011
#endif
4012 1
}
4013

4014
typedef struct {
4015
    PyTypeObject * type;
4016
    int typenum;
4017
} scalar_type;
4018

4019
static scalar_type typeobjects[] = {
4020
    {&PyBoolArrType_Type, NPY_BOOL},
4021
    {&PyByteArrType_Type, NPY_BYTE},
4022
    {&PyUByteArrType_Type, NPY_UBYTE},
4023
    {&PyShortArrType_Type, NPY_SHORT},
4024
    {&PyUShortArrType_Type, NPY_USHORT},
4025
    {&PyIntArrType_Type, NPY_INT},
4026
    {&PyUIntArrType_Type, NPY_UINT},
4027
    {&PyLongArrType_Type, NPY_LONG},
4028
    {&PyULongArrType_Type, NPY_ULONG},
4029
    {&PyLongLongArrType_Type, NPY_LONGLONG},
4030
    {&PyULongLongArrType_Type, NPY_ULONGLONG},
4031
    {&PyFloatArrType_Type, NPY_FLOAT},
4032
    {&PyDoubleArrType_Type, NPY_DOUBLE},
4033
    {&PyLongDoubleArrType_Type, NPY_LONGDOUBLE},
4034
    {&PyCFloatArrType_Type, NPY_CFLOAT},
4035
    {&PyCDoubleArrType_Type, NPY_CDOUBLE},
4036
    {&PyCLongDoubleArrType_Type, NPY_CLONGDOUBLE},
4037
    {&PyObjectArrType_Type, NPY_OBJECT},
4038
    {&PyStringArrType_Type, NPY_STRING},
4039
    {&PyUnicodeArrType_Type, NPY_UNICODE},
4040
    {&PyVoidArrType_Type, NPY_VOID},
4041
    {&PyDatetimeArrType_Type, NPY_DATETIME},
4042
    {&PyTimedeltaArrType_Type, NPY_TIMEDELTA},
4043
    {&PyHalfArrType_Type, NPY_HALF}
4044
};
4045

4046 1
static int compare_types(const void * a_, const void * b_)
4047
{
4048 1
    const PyTypeObject * a = ((const scalar_type *)a_)->type;
4049 1
    const PyTypeObject * b = ((const scalar_type *)b_)->type;
4050 1
    if (a < b) {
4051
        return -1;
4052
    }
4053 1
    else if (a > b) {
4054
        return 1;
4055
    }
4056 0
    return 0;
4057
}
4058

4059
static void init_basetypes(void)
4060
{
4061 1
    qsort(typeobjects, sizeof(typeobjects) / sizeof(typeobjects[0]),
4062
          sizeof(typeobjects[0]),
4063
          compare_types);
4064
}
4065

4066

4067
NPY_NO_EXPORT int
4068 0
get_typeobj_idx(PyTypeObject * obj)
4069
{
4070 1
    npy_intp imin = 0, imax = sizeof(typeobjects) / sizeof(typeobjects[0]) - 1;
4071 1
    while (imax >= imin)
4072
    {
4073 1
        npy_intp imid = ((imax - imin) / 2) + imin;
4074 1
        if(typeobjects[imid].type == obj) {
4075 1
            return imid;
4076
        }
4077 1
        else if (typeobjects[imid].type < obj) {
4078 1
            imin = imid + 1;
4079
        }
4080
        else {
4081 1
            imax = imid - 1;
4082
        }
4083
    }
4084

4085
    return -1;
4086
}
4087

4088
NPY_NO_EXPORT int
4089 1
is_anyscalar_exact(PyObject *obj)
4090
{
4091 1
    return get_typeobj_idx(Py_TYPE(obj)) >= 0;
4092
}
4093

4094
NPY_NO_EXPORT int
4095 1
_typenum_fromtypeobj(PyObject *type, int user)
4096
{
4097
    int typenum, i;
4098

4099 1
    typenum = NPY_NOTYPE;
4100 1
    i = get_typeobj_idx((PyTypeObject*)type);
4101 1
    if (i >= 0) {
4102 1
        typenum = typeobjects[i].typenum;
4103
    }
4104

4105 1
    if (!user) {
4106
        return typenum;
4107
    }
4108
    /* Search any registered types */
4109
    i = 0;
4110 1
    while (i < NPY_NUMUSERTYPES) {
4111 1
        if (type == (PyObject *)(userdescrs[i]->typeobj)) {
4112 1
            typenum = i + NPY_USERDEF;
4113 1
            break;
4114
        }
4115 1
        i++;
4116
    }
4117
    return typenum;
4118
}

Read our documentation on viewing source code .

Loading