1 /*
2     pybind11/numpy.h: Basic NumPy support, vectorize() wrapper
3 
4     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6     All rights reserved. Use of this source code is governed by a
7     BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #pragma once
11 
12 #include "pybind11.h"
13 #include "complex.h"
14 #include <numeric>
15 #include <algorithm>
16 #include <array>
17 #include <cstdint>
18 #include <cstdlib>
19 #include <cstring>
20 #include <sstream>
21 #include <string>
22 #include <functional>
23 #include <type_traits>
24 #include <utility>
25 #include <vector>
26 #include <typeindex>
27 
28 #if defined(_MSC_VER)
29 #  pragma warning(push)
30 #  pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
31 #endif
32 
33 /* This will be true on all flat address space platforms and allows us to reduce the
34    whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size
35    and dimension types (e.g. shape, strides, indexing), instead of inflicting this
36    upon the library user. */
37 static_assert(sizeof(::pybind11::ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t");
38 static_assert(std::is_signed<Py_intptr_t>::value, "Py_intptr_t must be signed");
39 // We now can reinterpret_cast between py::ssize_t and Py_intptr_t (MSVC + PyPy cares)
40 
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)41 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
42 
43 class array; // Forward declaration
44 
45 PYBIND11_NAMESPACE_BEGIN(detail)
46 
47 template <> struct handle_type_name<array> { static constexpr auto name = _("numpy.ndarray"); };
48 
49 template <typename type, typename SFINAE = void> struct npy_format_descriptor;
50 
51 struct PyArrayDescr_Proxy {
52     PyObject_HEAD
53     PyObject *typeobj;
54     char kind;
55     char type;
56     char byteorder;
57     char flags;
58     int type_num;
59     int elsize;
60     int alignment;
61     char *subarray;
62     PyObject *fields;
63     PyObject *names;
64 };
65 
66 struct PyArray_Proxy {
67     PyObject_HEAD
68     char *data;
69     int nd;
70     ssize_t *dimensions;
71     ssize_t *strides;
72     PyObject *base;
73     PyObject *descr;
74     int flags;
75 };
76 
77 struct PyVoidScalarObject_Proxy {
78     PyObject_VAR_HEAD
79     char *obval;
80     PyArrayDescr_Proxy *descr;
81     int flags;
82     PyObject *base;
83 };
84 
85 struct numpy_type_info {
86     PyObject* dtype_ptr;
87     std::string format_str;
88 };
89 
90 struct numpy_internals {
91     std::unordered_map<std::type_index, numpy_type_info> registered_dtypes;
92 
93     numpy_type_info *get_type_info(const std::type_info& tinfo, bool throw_if_missing = true) {
94         auto it = registered_dtypes.find(std::type_index(tinfo));
95         if (it != registered_dtypes.end())
96             return &(it->second);
97         if (throw_if_missing)
98             pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name());
99         return nullptr;
100     }
101 
102     template<typename T> numpy_type_info *get_type_info(bool throw_if_missing = true) {
103         return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing);
104     }
105 };
106 
load_numpy_internals(numpy_internals * & ptr)107 inline PYBIND11_NOINLINE void load_numpy_internals(numpy_internals* &ptr) {
108     ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals");
109 }
110 
get_numpy_internals()111 inline numpy_internals& get_numpy_internals() {
112     static numpy_internals* ptr = nullptr;
113     if (!ptr)
114         load_numpy_internals(ptr);
115     return *ptr;
116 }
117 
118 template <typename T> struct same_size {
119     template <typename U> using as = bool_constant<sizeof(T) == sizeof(U)>;
120 };
121 
platform_lookup()122 template <typename Concrete> constexpr int platform_lookup() { return -1; }
123 
124 // Lookup a type according to its size, and return a value corresponding to the NumPy typenum.
125 template <typename Concrete, typename T, typename... Ts, typename... Ints>
platform_lookup(int I,Ints...Is)126 constexpr int platform_lookup(int I, Ints... Is) {
127     return sizeof(Concrete) == sizeof(T) ? I : platform_lookup<Concrete, Ts...>(Is...);
128 }
129 
130 struct npy_api {
131     enum constants {
132         NPY_ARRAY_C_CONTIGUOUS_ = 0x0001,
133         NPY_ARRAY_F_CONTIGUOUS_ = 0x0002,
134         NPY_ARRAY_OWNDATA_ = 0x0004,
135         NPY_ARRAY_FORCECAST_ = 0x0010,
136         NPY_ARRAY_ENSUREARRAY_ = 0x0040,
137         NPY_ARRAY_ALIGNED_ = 0x0100,
138         NPY_ARRAY_WRITEABLE_ = 0x0400,
139         NPY_BOOL_ = 0,
140         NPY_BYTE_, NPY_UBYTE_,
141         NPY_SHORT_, NPY_USHORT_,
142         NPY_INT_, NPY_UINT_,
143         NPY_LONG_, NPY_ULONG_,
144         NPY_LONGLONG_, NPY_ULONGLONG_,
145         NPY_FLOAT_, NPY_DOUBLE_, NPY_LONGDOUBLE_,
146         NPY_CFLOAT_, NPY_CDOUBLE_, NPY_CLONGDOUBLE_,
147         NPY_OBJECT_ = 17,
148         NPY_STRING_, NPY_UNICODE_, NPY_VOID_,
149         // Platform-dependent normalization
150         NPY_INT8_ = NPY_BYTE_,
151         NPY_UINT8_ = NPY_UBYTE_,
152         NPY_INT16_ = NPY_SHORT_,
153         NPY_UINT16_ = NPY_USHORT_,
154         // `npy_common.h` defines the integer aliases. In order, it checks:
155         // NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR
156         // and assigns the alias to the first matching size, so we should check in this order.
157         NPY_INT32_ = platform_lookup<std::int32_t, long, int, short>(
158             NPY_LONG_, NPY_INT_, NPY_SHORT_),
159         NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>(
160             NPY_ULONG_, NPY_UINT_, NPY_USHORT_),
161         NPY_INT64_ = platform_lookup<std::int64_t, long, long long, int>(
162             NPY_LONG_, NPY_LONGLONG_, NPY_INT_),
163         NPY_UINT64_ = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>(
164             NPY_ULONG_, NPY_ULONGLONG_, NPY_UINT_),
165     };
166 
167     typedef struct {
168         Py_intptr_t *ptr;
169         int len;
170     } PyArray_Dims;
171 
getnpy_api172     static npy_api& get() {
173         static npy_api api = lookup();
174         return api;
175     }
176 
PyArray_Check_npy_api177     bool PyArray_Check_(PyObject *obj) const {
178         return (bool) PyObject_TypeCheck(obj, PyArray_Type_);
179     }
PyArrayDescr_Check_npy_api180     bool PyArrayDescr_Check_(PyObject *obj) const {
181         return (bool) PyObject_TypeCheck(obj, PyArrayDescr_Type_);
182     }
183 
184     unsigned int (*PyArray_GetNDArrayCFeatureVersion_)();
185     PyObject *(*PyArray_DescrFromType_)(int);
186     PyObject *(*PyArray_NewFromDescr_)
187         (PyTypeObject *, PyObject *, int, Py_intptr_t const *,
188          Py_intptr_t const *, void *, int, PyObject *);
189     // Unused. Not removed because that affects ABI of the class.
190     PyObject *(*PyArray_DescrNewFromType_)(int);
191     int (*PyArray_CopyInto_)(PyObject *, PyObject *);
192     PyObject *(*PyArray_NewCopy_)(PyObject *, int);
193     PyTypeObject *PyArray_Type_;
194     PyTypeObject *PyVoidArrType_Type_;
195     PyTypeObject *PyArrayDescr_Type_;
196     PyObject *(*PyArray_DescrFromScalar_)(PyObject *);
197     PyObject *(*PyArray_FromAny_) (PyObject *, PyObject *, int, int, int, PyObject *);
198     int (*PyArray_DescrConverter_) (PyObject *, PyObject **);
199     bool (*PyArray_EquivTypes_) (PyObject *, PyObject *);
200     int (*PyArray_GetArrayParamsFromObject_)(PyObject *, PyObject *, unsigned char, PyObject **, int *,
201                                              Py_intptr_t *, PyObject **, PyObject *);
202     PyObject *(*PyArray_Squeeze_)(PyObject *);
203     // Unused. Not removed because that affects ABI of the class.
204     int (*PyArray_SetBaseObject_)(PyObject *, PyObject *);
205     PyObject* (*PyArray_Resize_)(PyObject*, PyArray_Dims*, int, int);
206 private:
207     enum functions {
208         API_PyArray_GetNDArrayCFeatureVersion = 211,
209         API_PyArray_Type = 2,
210         API_PyArrayDescr_Type = 3,
211         API_PyVoidArrType_Type = 39,
212         API_PyArray_DescrFromType = 45,
213         API_PyArray_DescrFromScalar = 57,
214         API_PyArray_FromAny = 69,
215         API_PyArray_Resize = 80,
216         API_PyArray_CopyInto = 82,
217         API_PyArray_NewCopy = 85,
218         API_PyArray_NewFromDescr = 94,
219         API_PyArray_DescrNewFromType = 96,
220         API_PyArray_DescrConverter = 174,
221         API_PyArray_EquivTypes = 182,
222         API_PyArray_GetArrayParamsFromObject = 278,
223         API_PyArray_Squeeze = 136,
224         API_PyArray_SetBaseObject = 282
225     };
226 
lookupnpy_api227     static npy_api lookup() {
228         module_ m = module_::import("numpy.core.multiarray");
229         auto c = m.attr("_ARRAY_API");
230 #if PY_MAJOR_VERSION >= 3
231         void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), NULL);
232 #else
233         void **api_ptr = (void **) PyCObject_AsVoidPtr(c.ptr());
234 #endif
235         npy_api api;
236 #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
237         DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion);
238         if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7)
239             pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0");
240         DECL_NPY_API(PyArray_Type);
241         DECL_NPY_API(PyVoidArrType_Type);
242         DECL_NPY_API(PyArrayDescr_Type);
243         DECL_NPY_API(PyArray_DescrFromType);
244         DECL_NPY_API(PyArray_DescrFromScalar);
245         DECL_NPY_API(PyArray_FromAny);
246         DECL_NPY_API(PyArray_Resize);
247         DECL_NPY_API(PyArray_CopyInto);
248         DECL_NPY_API(PyArray_NewCopy);
249         DECL_NPY_API(PyArray_NewFromDescr);
250         DECL_NPY_API(PyArray_DescrNewFromType);
251         DECL_NPY_API(PyArray_DescrConverter);
252         DECL_NPY_API(PyArray_EquivTypes);
253         DECL_NPY_API(PyArray_GetArrayParamsFromObject);
254         DECL_NPY_API(PyArray_Squeeze);
255         DECL_NPY_API(PyArray_SetBaseObject);
256 #undef DECL_NPY_API
257         return api;
258     }
259 };
260 
array_proxy(void * ptr)261 inline PyArray_Proxy* array_proxy(void* ptr) {
262     return reinterpret_cast<PyArray_Proxy*>(ptr);
263 }
264 
array_proxy(const void * ptr)265 inline const PyArray_Proxy* array_proxy(const void* ptr) {
266     return reinterpret_cast<const PyArray_Proxy*>(ptr);
267 }
268 
array_descriptor_proxy(PyObject * ptr)269 inline PyArrayDescr_Proxy* array_descriptor_proxy(PyObject* ptr) {
270    return reinterpret_cast<PyArrayDescr_Proxy*>(ptr);
271 }
272 
array_descriptor_proxy(const PyObject * ptr)273 inline const PyArrayDescr_Proxy* array_descriptor_proxy(const PyObject* ptr) {
274    return reinterpret_cast<const PyArrayDescr_Proxy*>(ptr);
275 }
276 
check_flags(const void * ptr,int flag)277 inline bool check_flags(const void* ptr, int flag) {
278     return (flag == (array_proxy(ptr)->flags & flag));
279 }
280 
281 template <typename T> struct is_std_array : std::false_type { };
282 template <typename T, size_t N> struct is_std_array<std::array<T, N>> : std::true_type { };
283 template <typename T> struct is_complex : std::false_type { };
284 template <typename T> struct is_complex<std::complex<T>> : std::true_type { };
285 
286 template <typename T> struct array_info_scalar {
287     using type = T;
288     static constexpr bool is_array = false;
289     static constexpr bool is_empty = false;
290     static constexpr auto extents = _("");
291     static void append_extents(list& /* shape */) { }
292 };
293 // Computes underlying type and a comma-separated list of extents for array
294 // types (any mix of std::array and built-in arrays). An array of char is
295 // treated as scalar because it gets special handling.
296 template <typename T> struct array_info : array_info_scalar<T> { };
297 template <typename T, size_t N> struct array_info<std::array<T, N>> {
298     using type = typename array_info<T>::type;
299     static constexpr bool is_array = true;
300     static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty;
301     static constexpr size_t extent = N;
302 
303     // appends the extents to shape
304     static void append_extents(list& shape) {
305         shape.append(N);
306         array_info<T>::append_extents(shape);
307     }
308 
309     static constexpr auto extents = _<array_info<T>::is_array>(
310         concat(_<N>(), array_info<T>::extents), _<N>()
311     );
312 };
313 // For numpy we have special handling for arrays of characters, so we don't include
314 // the size in the array extents.
315 template <size_t N> struct array_info<char[N]> : array_info_scalar<char[N]> { };
316 template <size_t N> struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> { };
317 template <typename T, size_t N> struct array_info<T[N]> : array_info<std::array<T, N>> { };
318 template <typename T> using remove_all_extents_t = typename array_info<T>::type;
319 
320 template <typename T> using is_pod_struct = all_of<
321     std::is_standard_layout<T>,     // since we're accessing directly in memory we need a standard layout type
322 #if !defined(__GNUG__) || defined(_LIBCPP_VERSION) || defined(_GLIBCXX_USE_CXX11_ABI)
323     // _GLIBCXX_USE_CXX11_ABI indicates that we're using libstdc++ from GCC 5 or newer, independent
324     // of the actual compiler (Clang can also use libstdc++, but it always defines __GNUC__ == 4).
325     std::is_trivially_copyable<T>,
326 #else
327     // GCC 4 doesn't implement is_trivially_copyable, so approximate it
328     std::is_trivially_destructible<T>,
329     satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>,
330 #endif
331     satisfies_none_of<T, std::is_reference, std::is_array, is_std_array, std::is_arithmetic, is_complex, std::is_enum>
332 >;
333 
334 // Replacement for std::is_pod (deprecated in C++20)
335 template <typename T> using is_pod = all_of<
336     std::is_standard_layout<T>,
337     std::is_trivial<T>
338 >;
339 
340 template <ssize_t Dim = 0, typename Strides> ssize_t byte_offset_unsafe(const Strides &) { return 0; }
341 template <ssize_t Dim = 0, typename Strides, typename... Ix>
342 ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) {
343     return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...);
344 }
345 
346 /**
347  * Proxy class providing unsafe, unchecked const access to array data.  This is constructed through
348  * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`.  `Dims`
349  * will be -1 for dimensions determined at runtime.
350  */
351 template <typename T, ssize_t Dims>
352 class unchecked_reference {
353 protected:
354     static constexpr bool Dynamic = Dims < 0;
355     const unsigned char *data_;
356     // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to
357     // make large performance gains on big, nested loops, but requires compile-time dimensions
358     conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>>
359             shape_, strides_;
360     const ssize_t dims_;
361 
362     friend class pybind11::array;
363     // Constructor for compile-time dimensions:
364     template <bool Dyn = Dynamic>
365     unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<!Dyn, ssize_t>)
366     : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
367         for (size_t i = 0; i < (size_t) dims_; i++) {
368             shape_[i] = shape[i];
369             strides_[i] = strides[i];
370         }
371     }
372     // Constructor for runtime dimensions:
373     template <bool Dyn = Dynamic>
374     unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<Dyn, ssize_t> dims)
375     : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides}, dims_{dims} {}
376 
377 public:
378     /**
379      * Unchecked const reference access to data at the given indices.  For a compile-time known
380      * number of dimensions, this requires the correct number of arguments; for run-time
381      * dimensionality, this is not checked (and so is up to the caller to use safely).
382      */
383     template <typename... Ix> const T &operator()(Ix... index) const {
384         static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
385                 "Invalid number of indices for unchecked array reference");
386         return *reinterpret_cast<const T *>(data_ + byte_offset_unsafe(strides_, ssize_t(index)...));
387     }
388     /**
389      * Unchecked const reference access to data; this operator only participates if the reference
390      * is to a 1-dimensional array.  When present, this is exactly equivalent to `obj(index)`.
391      */
392     template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
393     const T &operator[](ssize_t index) const { return operator()(index); }
394 
395     /// Pointer access to the data at the given indices.
396     template <typename... Ix> const T *data(Ix... ix) const { return &operator()(ssize_t(ix)...); }
397 
398     /// Returns the item size, i.e. sizeof(T)
399     constexpr static ssize_t itemsize() { return sizeof(T); }
400 
401     /// Returns the shape (i.e. size) of dimension `dim`
402     ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; }
403 
404     /// Returns the number of dimensions of the array
405     ssize_t ndim() const { return dims_; }
406 
407     /// Returns the total number of elements in the referenced array, i.e. the product of the shapes
408     template <bool Dyn = Dynamic>
409     enable_if_t<!Dyn, ssize_t> size() const {
410         return std::accumulate(shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());
411     }
412     template <bool Dyn = Dynamic>
413     enable_if_t<Dyn, ssize_t> size() const {
414         return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
415     }
416 
417     /// Returns the total number of bytes used by the referenced data.  Note that the actual span in
418     /// memory may be larger if the referenced array has non-contiguous strides (e.g. for a slice).
419     ssize_t nbytes() const {
420         return size() * itemsize();
421     }
422 };
423 
424 template <typename T, ssize_t Dims>
425 class unchecked_mutable_reference : public unchecked_reference<T, Dims> {
426     friend class pybind11::array;
427     using ConstBase = unchecked_reference<T, Dims>;
428     using ConstBase::ConstBase;
429     using ConstBase::Dynamic;
430 public:
431     // Bring in const-qualified versions from base class
432     using ConstBase::operator();
433     using ConstBase::operator[];
434 
435     /// Mutable, unchecked access to data at the given indices.
436     template <typename... Ix> T& operator()(Ix... index) {
437         static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
438                 "Invalid number of indices for unchecked array reference");
439         return const_cast<T &>(ConstBase::operator()(index...));
440     }
441     /**
442      * Mutable, unchecked access data at the given index; this operator only participates if the
443      * reference is to a 1-dimensional array (or has runtime dimensions).  When present, this is
444      * exactly equivalent to `obj(index)`.
445      */
446     template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
447     T &operator[](ssize_t index) { return operator()(index); }
448 
449     /// Mutable pointer access to the data at the given indices.
450     template <typename... Ix> T *mutable_data(Ix... ix) { return &operator()(ssize_t(ix)...); }
451 };
452 
453 template <typename T, ssize_t Dim>
454 struct type_caster<unchecked_reference<T, Dim>> {
455     static_assert(Dim == 0 && Dim > 0 /* always fail */, "unchecked array proxy object is not castable");
456 };
457 template <typename T, ssize_t Dim>
458 struct type_caster<unchecked_mutable_reference<T, Dim>> : type_caster<unchecked_reference<T, Dim>> {};
459 
460 PYBIND11_NAMESPACE_END(detail)
461 
462 class dtype : public object {
463 public:
464     PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_);
465 
466     explicit dtype(const buffer_info &info) {
467         dtype descr(_dtype_from_pep3118()(PYBIND11_STR_TYPE(info.format)));
468         // If info.itemsize == 0, use the value calculated from the format string
469         m_ptr = descr.strip_padding(info.itemsize ? info.itemsize : descr.itemsize()).release().ptr();
470     }
471 
472     explicit dtype(const std::string &format) {
473         m_ptr = from_args(pybind11::str(format)).release().ptr();
474     }
475 
476     dtype(const char *format) : dtype(std::string(format)) { }
477 
478     dtype(list names, list formats, list offsets, ssize_t itemsize) {
479         dict args;
480         args["names"] = names;
481         args["formats"] = formats;
482         args["offsets"] = offsets;
483         args["itemsize"] = pybind11::int_(itemsize);
484         m_ptr = from_args(args).release().ptr();
485     }
486 
487     /// This is essentially the same as calling numpy.dtype(args) in Python.
488     static dtype from_args(object args) {
489         PyObject *ptr = nullptr;
490         if (!detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) || !ptr)
491             throw error_already_set();
492         return reinterpret_steal<dtype>(ptr);
493     }
494 
495     /// Return dtype associated with a C++ type.
496     template <typename T> static dtype of() {
497         return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype();
498     }
499 
500     /// Size of the data type in bytes.
501     ssize_t itemsize() const {
502         return detail::array_descriptor_proxy(m_ptr)->elsize;
503     }
504 
505     /// Returns true for structured data types.
506     bool has_fields() const {
507         return detail::array_descriptor_proxy(m_ptr)->names != nullptr;
508     }
509 
510     /// Single-character type code.
511     char kind() const {
512         return detail::array_descriptor_proxy(m_ptr)->kind;
513     }
514 
515 private:
516     static object _dtype_from_pep3118() {
517         static PyObject *obj = module_::import("numpy.core._internal")
518             .attr("_dtype_from_pep3118").cast<object>().release().ptr();
519         return reinterpret_borrow<object>(obj);
520     }
521 
522     dtype strip_padding(ssize_t itemsize) {
523         // Recursively strip all void fields with empty names that are generated for
524         // padding fields (as of NumPy v1.11).
525         if (!has_fields())
526             return *this;
527 
528         struct field_descr { PYBIND11_STR_TYPE name; object format; pybind11::int_ offset; };
529         std::vector<field_descr> field_descriptors;
530 
531         for (auto field : attr("fields").attr("items")()) {
532             auto spec = field.cast<tuple>();
533             auto name = spec[0].cast<pybind11::str>();
534             auto format = spec[1].cast<tuple>()[0].cast<dtype>();
535             auto offset = spec[1].cast<tuple>()[1].cast<pybind11::int_>();
536             if (!len(name) && format.kind() == 'V')
537                 continue;
538             field_descriptors.push_back({(PYBIND11_STR_TYPE) name, format.strip_padding(format.itemsize()), offset});
539         }
540 
541         std::sort(field_descriptors.begin(), field_descriptors.end(),
542                   [](const field_descr& a, const field_descr& b) {
543                       return a.offset.cast<int>() < b.offset.cast<int>();
544                   });
545 
546         list names, formats, offsets;
547         for (auto& descr : field_descriptors) {
548             names.append(descr.name);
549             formats.append(descr.format);
550             offsets.append(descr.offset);
551         }
552         return dtype(names, formats, offsets, itemsize);
553     }
554 };
555 
556 class array : public buffer {
557 public:
558     PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array)
559 
560     enum {
561         c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_,
562         f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_,
563         forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_
564     };
565 
566     array() : array(0, static_cast<const double *>(nullptr)) {}
567 
568     using ShapeContainer = detail::any_container<ssize_t>;
569     using StridesContainer = detail::any_container<ssize_t>;
570 
571     // Constructs an array taking shape/strides from arbitrary container types
572     array(const pybind11::dtype &dt, ShapeContainer shape, StridesContainer strides,
573           const void *ptr = nullptr, handle base = handle()) {
574 
575         if (strides->empty())
576             *strides = detail::c_strides(*shape, dt.itemsize());
577 
578         auto ndim = shape->size();
579         if (ndim != strides->size())
580             pybind11_fail("NumPy: shape ndim doesn't match strides ndim");
581         auto descr = dt;
582 
583         int flags = 0;
584         if (base && ptr) {
585             if (isinstance<array>(base))
586                 /* Copy flags from base (except ownership bit) */
587                 flags = reinterpret_borrow<array>(base).flags() & ~detail::npy_api::NPY_ARRAY_OWNDATA_;
588             else
589                 /* Writable by default, easy to downgrade later on if needed */
590                 flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;
591         }
592 
593         auto &api = detail::npy_api::get();
594         auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_(
595             api.PyArray_Type_, descr.release().ptr(), (int) ndim,
596             // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
597             reinterpret_cast<Py_intptr_t*>(shape->data()),
598             reinterpret_cast<Py_intptr_t*>(strides->data()),
599             const_cast<void *>(ptr), flags, nullptr));
600         if (!tmp)
601             throw error_already_set();
602         if (ptr) {
603             if (base) {
604                 api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr());
605             } else {
606                 tmp = reinterpret_steal<object>(api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));
607             }
608         }
609         m_ptr = tmp.release().ptr();
610     }
611 
612     array(const pybind11::dtype &dt, ShapeContainer shape, const void *ptr = nullptr, handle base = handle())
613         : array(dt, std::move(shape), {}, ptr, base) { }
614 
615     template <typename T, typename = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>>
616     array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle())
617         : array(dt, {{count}}, ptr, base) { }
618 
619     template <typename T>
620     array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle())
621         : array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) { }
622 
623     template <typename T>
624     array(ShapeContainer shape, const T *ptr, handle base = handle())
625         : array(std::move(shape), {}, ptr, base) { }
626 
627     template <typename T>
628     explicit array(ssize_t count, const T *ptr, handle base = handle()) : array({count}, {}, ptr, base) { }
629 
630     explicit array(const buffer_info &info, handle base = handle())
631     : array(pybind11::dtype(info), info.shape, info.strides, info.ptr, base) { }
632 
633     /// Array descriptor (dtype)
634     pybind11::dtype dtype() const {
635         return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr);
636     }
637 
638     /// Total number of elements
639     ssize_t size() const {
640         return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
641     }
642 
643     /// Byte size of a single element
644     ssize_t itemsize() const {
645         return detail::array_descriptor_proxy(detail::array_proxy(m_ptr)->descr)->elsize;
646     }
647 
648     /// Total number of bytes
649     ssize_t nbytes() const {
650         return size() * itemsize();
651     }
652 
653     /// Number of dimensions
654     ssize_t ndim() const {
655         return detail::array_proxy(m_ptr)->nd;
656     }
657 
658     /// Base object
659     object base() const {
660         return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base);
661     }
662 
663     /// Dimensions of the array
664     const ssize_t* shape() const {
665         return detail::array_proxy(m_ptr)->dimensions;
666     }
667 
668     /// Dimension along a given axis
669     ssize_t shape(ssize_t dim) const {
670         if (dim >= ndim())
671             fail_dim_check(dim, "invalid axis");
672         return shape()[dim];
673     }
674 
675     /// Strides of the array
676     const ssize_t* strides() const {
677         return detail::array_proxy(m_ptr)->strides;
678     }
679 
680     /// Stride along a given axis
681     ssize_t strides(ssize_t dim) const {
682         if (dim >= ndim())
683             fail_dim_check(dim, "invalid axis");
684         return strides()[dim];
685     }
686 
687     /// Return the NumPy array flags
688     int flags() const {
689         return detail::array_proxy(m_ptr)->flags;
690     }
691 
692     /// If set, the array is writeable (otherwise the buffer is read-only)
693     bool writeable() const {
694         return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_);
695     }
696 
697     /// If set, the array owns the data (will be freed when the array is deleted)
698     bool owndata() const {
699         return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_);
700     }
701 
702     /// Pointer to the contained data. If index is not provided, points to the
703     /// beginning of the buffer. May throw if the index would lead to out of bounds access.
704     template<typename... Ix> const void* data(Ix... index) const {
705         return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
706     }
707 
708     /// Mutable pointer to the contained data. If index is not provided, points to the
709     /// beginning of the buffer. May throw if the index would lead to out of bounds access.
710     /// May throw if the array is not writeable.
711     template<typename... Ix> void* mutable_data(Ix... index) {
712         check_writeable();
713         return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
714     }
715 
716     /// Byte offset from beginning of the array to a given index (full or partial).
717     /// May throw if the index would lead to out of bounds access.
718     template<typename... Ix> ssize_t offset_at(Ix... index) const {
719         if ((ssize_t) sizeof...(index) > ndim())
720             fail_dim_check(sizeof...(index), "too many indices for an array");
721         return byte_offset(ssize_t(index)...);
722     }
723 
724     ssize_t offset_at() const { return 0; }
725 
726     /// Item count from beginning of the array to a given index (full or partial).
727     /// May throw if the index would lead to out of bounds access.
728     template<typename... Ix> ssize_t index_at(Ix... index) const {
729         return offset_at(index...) / itemsize();
730     }
731 
732     /**
733      * Returns a proxy object that provides access to the array's data without bounds or
734      * dimensionality checking.  Will throw if the array is missing the `writeable` flag.  Use with
735      * care: the array must not be destroyed or reshaped for the duration of the returned object,
736      * and the caller must take care not to access invalid dimensions or dimension indices.
737      */
738     template <typename T, ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
739         if (Dims >= 0 && ndim() != Dims)
740             throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) +
741                     "; expected " + std::to_string(Dims));
742         return detail::unchecked_mutable_reference<T, Dims>(mutable_data(), shape(), strides(), ndim());
743     }
744 
745     /**
746      * Returns a proxy object that provides const access to the array's data without bounds or
747      * dimensionality checking.  Unlike `mutable_unchecked()`, this does not require that the
748      * underlying array have the `writable` flag.  Use with care: the array must not be destroyed or
749      * reshaped for the duration of the returned object, and the caller must take care not to access
750      * invalid dimensions or dimension indices.
751      */
752     template <typename T, ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & {
753         if (Dims >= 0 && ndim() != Dims)
754             throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) +
755                     "; expected " + std::to_string(Dims));
756         return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());
757     }
758 
759     /// Return a new view with all of the dimensions of length 1 removed
760     array squeeze() {
761         auto& api = detail::npy_api::get();
762         return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));
763     }
764 
765     /// Resize array to given shape
766     /// If refcheck is true and more that one reference exist to this array
767     /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change
768     void resize(ShapeContainer new_shape, bool refcheck = true) {
769         detail::npy_api::PyArray_Dims d = {
770             // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
771             reinterpret_cast<Py_intptr_t*>(new_shape->data()),
772             int(new_shape->size())
773         };
774         // try to resize, set ordering param to -1 cause it's not used anyway
775         object new_array = reinterpret_steal<object>(
776             detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1)
777         );
778         if (!new_array) throw error_already_set();
779         if (isinstance<array>(new_array)) { *this = std::move(new_array); }
780     }
781 
782     /// Ensure that the argument is a NumPy array
783     /// In case of an error, nullptr is returned and the Python error is cleared.
784     static array ensure(handle h, int ExtraFlags = 0) {
785         auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));
786         if (!result)
787             PyErr_Clear();
788         return result;
789     }
790 
791 protected:
792     template<typename, typename> friend struct detail::npy_format_descriptor;
793 
794     void fail_dim_check(ssize_t dim, const std::string& msg) const {
795         throw index_error(msg + ": " + std::to_string(dim) +
796                           " (ndim = " + std::to_string(ndim()) + ")");
797     }
798 
799     template<typename... Ix> ssize_t byte_offset(Ix... index) const {
800         check_dimensions(index...);
801         return detail::byte_offset_unsafe(strides(), ssize_t(index)...);
802     }
803 
804     void check_writeable() const {
805         if (!writeable())
806             throw std::domain_error("array is not writeable");
807     }
808 
809     template<typename... Ix> void check_dimensions(Ix... index) const {
810         check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);
811     }
812 
813     void check_dimensions_impl(ssize_t, const ssize_t*) const { }
814 
815     template<typename... Ix> void check_dimensions_impl(ssize_t axis, const ssize_t* shape, ssize_t i, Ix... index) const {
816         if (i >= *shape) {
817             throw index_error(std::string("index ") + std::to_string(i) +
818                               " is out of bounds for axis " + std::to_string(axis) +
819                               " with size " + std::to_string(*shape));
820         }
821         check_dimensions_impl(axis + 1, shape + 1, index...);
822     }
823 
824     /// Create array from any object -- always returns a new reference
825     static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) {
826         if (ptr == nullptr) {
827             PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array from a nullptr");
828             return nullptr;
829         }
830         return detail::npy_api::get().PyArray_FromAny_(
831             ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
832     }
833 };
834 
835 template <typename T, int ExtraFlags = array::forcecast> class array_t : public array {
836 private:
837     struct private_ctor {};
838     // Delegating constructor needed when both moving and accessing in the same constructor
839     array_t(private_ctor, ShapeContainer &&shape, StridesContainer &&strides, const T *ptr, handle base)
840         : array(std::move(shape), std::move(strides), ptr, base) {}
841 public:
842     static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t");
843 
844     using value_type = T;
845 
846     array_t() : array(0, static_cast<const T *>(nullptr)) {}
847     array_t(handle h, borrowed_t) : array(h, borrowed_t{}) { }
848     array_t(handle h, stolen_t) : array(h, stolen_t{}) { }
849 
850     PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead")
851     array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) {
852         if (!m_ptr) PyErr_Clear();
853         if (!is_borrowed) Py_XDECREF(h.ptr());
854     }
855 
856     array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {
857         if (!m_ptr) throw error_already_set();
858     }
859 
860     explicit array_t(const buffer_info& info, handle base = handle()) : array(info, base) { }
861 
862     array_t(ShapeContainer shape, StridesContainer strides, const T *ptr = nullptr, handle base = handle())
863         : array(std::move(shape), std::move(strides), ptr, base) { }
864 
865     explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
866         : array_t(private_ctor{}, std::move(shape),
867                 ExtraFlags & f_style
868                 ? detail::f_strides(*shape, itemsize())
869                 : detail::c_strides(*shape, itemsize()),
870                 ptr, base) { }
871 
872     explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle())
873         : array({count}, {}, ptr, base) { }
874 
875     constexpr ssize_t itemsize() const {
876         return sizeof(T);
877     }
878 
879     template<typename... Ix> ssize_t index_at(Ix... index) const {
880         return offset_at(index...) / itemsize();
881     }
882 
883     template<typename... Ix> const T* data(Ix... index) const {
884         return static_cast<const T*>(array::data(index...));
885     }
886 
887     template<typename... Ix> T* mutable_data(Ix... index) {
888         return static_cast<T*>(array::mutable_data(index...));
889     }
890 
891     // Reference to element at a given index
892     template<typename... Ix> const T& at(Ix... index) const {
893         if ((ssize_t) sizeof...(index) != ndim())
894             fail_dim_check(sizeof...(index), "index dimension mismatch");
895         return *(static_cast<const T*>(array::data()) + byte_offset(ssize_t(index)...) / itemsize());
896     }
897 
898     // Mutable reference to element at a given index
899     template<typename... Ix> T& mutable_at(Ix... index) {
900         if ((ssize_t) sizeof...(index) != ndim())
901             fail_dim_check(sizeof...(index), "index dimension mismatch");
902         return *(static_cast<T*>(array::mutable_data()) + byte_offset(ssize_t(index)...) / itemsize());
903     }
904 
905     /**
906      * Returns a proxy object that provides access to the array's data without bounds or
907      * dimensionality checking.  Will throw if the array is missing the `writeable` flag.  Use with
908      * care: the array must not be destroyed or reshaped for the duration of the returned object,
909      * and the caller must take care not to access invalid dimensions or dimension indices.
910      */
911     template <ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
912         return array::mutable_unchecked<T, Dims>();
913     }
914 
915     /**
916      * Returns a proxy object that provides const access to the array's data without bounds or
917      * dimensionality checking.  Unlike `unchecked()`, this does not require that the underlying
918      * array have the `writable` flag.  Use with care: the array must not be destroyed or reshaped
919      * for the duration of the returned object, and the caller must take care not to access invalid
920      * dimensions or dimension indices.
921      */
922     template <ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & {
923         return array::unchecked<T, Dims>();
924     }
925 
926     /// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert
927     /// it).  In case of an error, nullptr is returned and the Python error is cleared.
928     static array_t ensure(handle h) {
929         auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));
930         if (!result)
931             PyErr_Clear();
932         return result;
933     }
934 
935     static bool check_(handle h) {
936         const auto &api = detail::npy_api::get();
937         return api.PyArray_Check_(h.ptr())
938                && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr, dtype::of<T>().ptr())
939                && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style));
940     }
941 
942 protected:
943     /// Create array from any object -- always returns a new reference
944     static PyObject *raw_array_t(PyObject *ptr) {
945         if (ptr == nullptr) {
946             PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr");
947             return nullptr;
948         }
949         return detail::npy_api::get().PyArray_FromAny_(
950             ptr, dtype::of<T>().release().ptr(), 0, 0,
951             detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
952     }
953 };
954 
955 template <typename T>
956 struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
957     static std::string format() {
958         return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::format();
959     }
960 };
961 
962 template <size_t N> struct format_descriptor<char[N]> {
963     static std::string format() { return std::to_string(N) + "s"; }
964 };
965 template <size_t N> struct format_descriptor<std::array<char, N>> {
966     static std::string format() { return std::to_string(N) + "s"; }
967 };
968 
969 template <typename T>
970 struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> {
971     static std::string format() {
972         return format_descriptor<
973             typename std::remove_cv<typename std::underlying_type<T>::type>::type>::format();
974     }
975 };
976 
977 template <typename T>
978 struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {
979     static std::string format() {
980         using namespace detail;
981         static constexpr auto extents = _("(") + array_info<T>::extents + _(")");
982         return extents.text + format_descriptor<remove_all_extents_t<T>>::format();
983     }
984 };
985 
986 PYBIND11_NAMESPACE_BEGIN(detail)
987 template <typename T, int ExtraFlags>
988 struct pyobject_caster<array_t<T, ExtraFlags>> {
989     using type = array_t<T, ExtraFlags>;
990 
991     bool load(handle src, bool convert) {
992         if (!convert && !type::check_(src))
993             return false;
994         value = type::ensure(src);
995         return static_cast<bool>(value);
996     }
997 
998     static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
999         return src.inc_ref();
1000     }
1001     PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
1002 };
1003 
1004 template <typename T>
1005 struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1006     static bool compare(const buffer_info& b) {
1007         return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());
1008     }
1009 };
1010 
1011 template <typename T, typename = void>
1012 struct npy_format_descriptor_name;
1013 
1014 template <typename T>
1015 struct npy_format_descriptor_name<T, enable_if_t<std::is_integral<T>::value>> {
1016     static constexpr auto name = _<std::is_same<T, bool>::value>(
1017         _("bool"), _<std::is_signed<T>::value>("numpy.int", "numpy.uint") + _<sizeof(T)*8>()
1018     );
1019 };
1020 
1021 template <typename T>
1022 struct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> {
1023     static constexpr auto name = _<std::is_same<T, float>::value || std::is_same<T, double>::value>(
1024         _("numpy.float") + _<sizeof(T)*8>(), _("numpy.longdouble")
1025     );
1026 };
1027 
1028 template <typename T>
1029 struct npy_format_descriptor_name<T, enable_if_t<is_complex<T>::value>> {
1030     static constexpr auto name = _<std::is_same<typename T::value_type, float>::value
1031                                    || std::is_same<typename T::value_type, double>::value>(
1032         _("numpy.complex") + _<sizeof(typename T::value_type)*16>(), _("numpy.longcomplex")
1033     );
1034 };
1035 
1036 template <typename T>
1037 struct npy_format_descriptor<T, enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>>
1038     : npy_format_descriptor_name<T> {
1039 private:
1040     // NB: the order here must match the one in common.h
1041     constexpr static const int values[15] = {
1042         npy_api::NPY_BOOL_,
1043         npy_api::NPY_BYTE_,   npy_api::NPY_UBYTE_,   npy_api::NPY_INT16_,    npy_api::NPY_UINT16_,
1044         npy_api::NPY_INT32_,  npy_api::NPY_UINT32_,  npy_api::NPY_INT64_,    npy_api::NPY_UINT64_,
1045         npy_api::NPY_FLOAT_,  npy_api::NPY_DOUBLE_,  npy_api::NPY_LONGDOUBLE_,
1046         npy_api::NPY_CFLOAT_, npy_api::NPY_CDOUBLE_, npy_api::NPY_CLONGDOUBLE_
1047     };
1048 
1049 public:
1050     static constexpr int value = values[detail::is_fmt_numeric<T>::index];
1051 
1052     static pybind11::dtype dtype() {
1053         if (auto ptr = npy_api::get().PyArray_DescrFromType_(value))
1054             return reinterpret_steal<pybind11::dtype>(ptr);
1055         pybind11_fail("Unsupported buffer format!");
1056     }
1057 };
1058 
1059 #define PYBIND11_DECL_CHAR_FMT \
1060     static constexpr auto name = _("S") + _<N>(); \
1061     static pybind11::dtype dtype() { return pybind11::dtype(std::string("S") + std::to_string(N)); }
1062 template <size_t N> struct npy_format_descriptor<char[N]> { PYBIND11_DECL_CHAR_FMT };
1063 template <size_t N> struct npy_format_descriptor<std::array<char, N>> { PYBIND11_DECL_CHAR_FMT };
1064 #undef PYBIND11_DECL_CHAR_FMT
1065 
1066 template<typename T> struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> {
1067 private:
1068     using base_descr = npy_format_descriptor<typename array_info<T>::type>;
1069 public:
1070     static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported");
1071 
1072     static constexpr auto name = _("(") + array_info<T>::extents + _(")") + base_descr::name;
1073     static pybind11::dtype dtype() {
1074         list shape;
1075         array_info<T>::append_extents(shape);
1076         return pybind11::dtype::from_args(pybind11::make_tuple(base_descr::dtype(), shape));
1077     }
1078 };
1079 
1080 template<typename T> struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> {
1081 private:
1082     using base_descr = npy_format_descriptor<typename std::underlying_type<T>::type>;
1083 public:
1084     static constexpr auto name = base_descr::name;
1085     static pybind11::dtype dtype() { return base_descr::dtype(); }
1086 };
1087 
1088 struct field_descriptor {
1089     const char *name;
1090     ssize_t offset;
1091     ssize_t size;
1092     std::string format;
1093     dtype descr;
1094 };
1095 
1096 inline PYBIND11_NOINLINE void register_structured_dtype(
1097     any_container<field_descriptor> fields,
1098     const std::type_info& tinfo, ssize_t itemsize,
1099     bool (*direct_converter)(PyObject *, void *&)) {
1100 
1101     auto& numpy_internals = get_numpy_internals();
1102     if (numpy_internals.get_type_info(tinfo, false))
1103         pybind11_fail("NumPy: dtype is already registered");
1104 
1105     // Use ordered fields because order matters as of NumPy 1.14:
1106     // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays
1107     std::vector<field_descriptor> ordered_fields(std::move(fields));
1108     std::sort(ordered_fields.begin(), ordered_fields.end(),
1109         [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
1110 
1111     list names, formats, offsets;
1112     for (auto& field : ordered_fields) {
1113         if (!field.descr)
1114             pybind11_fail(std::string("NumPy: unsupported field dtype: `") +
1115                             field.name + "` @ " + tinfo.name());
1116         names.append(PYBIND11_STR_TYPE(field.name));
1117         formats.append(field.descr);
1118         offsets.append(pybind11::int_(field.offset));
1119     }
1120     auto dtype_ptr = pybind11::dtype(names, formats, offsets, itemsize).release().ptr();
1121 
1122     // There is an existing bug in NumPy (as of v1.11): trailing bytes are
1123     // not encoded explicitly into the format string. This will supposedly
1124     // get fixed in v1.12; for further details, see these:
1125     // - https://github.com/numpy/numpy/issues/7797
1126     // - https://github.com/numpy/numpy/pull/7798
1127     // Because of this, we won't use numpy's logic to generate buffer format
1128     // strings and will just do it ourselves.
1129     ssize_t offset = 0;
1130     std::ostringstream oss;
1131     // mark the structure as unaligned with '^', because numpy and C++ don't
1132     // always agree about alignment (particularly for complex), and we're
1133     // explicitly listing all our padding. This depends on none of the fields
1134     // overriding the endianness. Putting the ^ in front of individual fields
1135     // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049
1136     oss << "^T{";
1137     for (auto& field : ordered_fields) {
1138         if (field.offset > offset)
1139             oss << (field.offset - offset) << 'x';
1140         oss << field.format << ':' << field.name << ':';
1141         offset = field.offset + field.size;
1142     }
1143     if (itemsize > offset)
1144         oss << (itemsize - offset) << 'x';
1145     oss << '}';
1146     auto format_str = oss.str();
1147 
1148     // Sanity check: verify that NumPy properly parses our buffer format string
1149     auto& api = npy_api::get();
1150     auto arr =  array(buffer_info(nullptr, itemsize, format_str, 1));
1151     if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr()))
1152         pybind11_fail("NumPy: invalid buffer descriptor!");
1153 
1154     auto tindex = std::type_index(tinfo);
1155     numpy_internals.registered_dtypes[tindex] = { dtype_ptr, format_str };
1156     get_internals().direct_conversions[tindex].push_back(direct_converter);
1157 }
1158 
1159 template <typename T, typename SFINAE> struct npy_format_descriptor {
1160     static_assert(is_pod_struct<T>::value, "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
1161 
1162     static constexpr auto name = make_caster<T>::name;
1163 
1164     static pybind11::dtype dtype() {
1165         return reinterpret_borrow<pybind11::dtype>(dtype_ptr());
1166     }
1167 
1168     static std::string format() {
1169         static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;
1170         return format_str;
1171     }
1172 
1173     static void register_dtype(any_container<field_descriptor> fields) {
1174         register_structured_dtype(std::move(fields), typeid(typename std::remove_cv<T>::type),
1175                                   sizeof(T), &direct_converter);
1176     }
1177 
1178 private:
1179     static PyObject* dtype_ptr() {
1180         static PyObject* ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
1181         return ptr;
1182     }
1183 
1184     static bool direct_converter(PyObject *obj, void*& value) {
1185         auto& api = npy_api::get();
1186         if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_))
1187             return false;
1188         if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {
1189             if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {
1190                 value = ((PyVoidScalarObject_Proxy *) obj)->obval;
1191                 return true;
1192             }
1193         }
1194         return false;
1195     }
1196 };
1197 
1198 #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
1199 # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void)0)
1200 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void)0)
1201 #else
1202 
1203 #define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name)                                          \
1204     ::pybind11::detail::field_descriptor {                                                    \
1205         Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)),                  \
1206         ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(),           \
1207         ::pybind11::detail::npy_format_descriptor<decltype(std::declval<T>().Field)>::dtype() \
1208     }
1209 
1210 // Extract name, offset and format descriptor for a struct field
1211 #define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
1212 
1213 // The main idea of this macro is borrowed from https://github.com/swansontec/map-macro
1214 // (C) William Swanson, Paul Fultz
1215 #define PYBIND11_EVAL0(...) __VA_ARGS__
1216 #define PYBIND11_EVAL1(...) PYBIND11_EVAL0 (PYBIND11_EVAL0 (PYBIND11_EVAL0 (__VA_ARGS__)))
1217 #define PYBIND11_EVAL2(...) PYBIND11_EVAL1 (PYBIND11_EVAL1 (PYBIND11_EVAL1 (__VA_ARGS__)))
1218 #define PYBIND11_EVAL3(...) PYBIND11_EVAL2 (PYBIND11_EVAL2 (PYBIND11_EVAL2 (__VA_ARGS__)))
1219 #define PYBIND11_EVAL4(...) PYBIND11_EVAL3 (PYBIND11_EVAL3 (PYBIND11_EVAL3 (__VA_ARGS__)))
1220 #define PYBIND11_EVAL(...)  PYBIND11_EVAL4 (PYBIND11_EVAL4 (PYBIND11_EVAL4 (__VA_ARGS__)))
1221 #define PYBIND11_MAP_END(...)
1222 #define PYBIND11_MAP_OUT
1223 #define PYBIND11_MAP_COMMA ,
1224 #define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
1225 #define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
1226 #define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0 (test, next, 0)
1227 #define PYBIND11_MAP_NEXT(test, next)  PYBIND11_MAP_NEXT1 (PYBIND11_MAP_GET_END test, next)
1228 #if defined(_MSC_VER) && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround
1229 #define PYBIND11_MAP_LIST_NEXT1(test, next) \
1230     PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0))
1231 #else
1232 #define PYBIND11_MAP_LIST_NEXT1(test, next) \
1233     PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)
1234 #endif
1235 #define PYBIND11_MAP_LIST_NEXT(test, next) \
1236     PYBIND11_MAP_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next)
1237 #define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
1238     f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST1) (f, t, peek, __VA_ARGS__)
1239 #define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
1240     f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST0) (f, t, peek, __VA_ARGS__)
1241 // PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...
1242 #define PYBIND11_MAP_LIST(f, t, ...) \
1243     PYBIND11_EVAL (PYBIND11_MAP_LIST1 (f, t, __VA_ARGS__, (), 0))
1244 
1245 #define PYBIND11_NUMPY_DTYPE(Type, ...) \
1246     ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \
1247         (::std::vector<::pybind11::detail::field_descriptor> \
1248          {PYBIND11_MAP_LIST (PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
1249 
1250 #if defined(_MSC_VER) && !defined(__clang__)
1251 #define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1252     PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0))
1253 #else
1254 #define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1255     PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)
1256 #endif
1257 #define PYBIND11_MAP2_LIST_NEXT(test, next) \
1258     PYBIND11_MAP2_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next)
1259 #define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
1260     f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST1) (f, t, peek, __VA_ARGS__)
1261 #define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
1262     f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST0) (f, t, peek, __VA_ARGS__)
1263 // PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...
1264 #define PYBIND11_MAP2_LIST(f, t, ...) \
1265     PYBIND11_EVAL (PYBIND11_MAP2_LIST1 (f, t, __VA_ARGS__, (), 0))
1266 
1267 #define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
1268     ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \
1269         (::std::vector<::pybind11::detail::field_descriptor> \
1270          {PYBIND11_MAP2_LIST (PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
1271 
1272 #endif // __CLION_IDE__
1273 
1274 class common_iterator {
1275 public:
1276     using container_type = std::vector<ssize_t>;
1277     using value_type = container_type::value_type;
1278     using size_type = container_type::size_type;
1279 
1280     common_iterator() : p_ptr(0), m_strides() {}
1281 
1282     common_iterator(void* ptr, const container_type& strides, const container_type& shape)
1283         : p_ptr(reinterpret_cast<char*>(ptr)), m_strides(strides.size()) {
1284         m_strides.back() = static_cast<value_type>(strides.back());
1285         for (size_type i = m_strides.size() - 1; i != 0; --i) {
1286             size_type j = i - 1;
1287             auto s = static_cast<value_type>(shape[i]);
1288             m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
1289         }
1290     }
1291 
1292     void increment(size_type dim) {
1293         p_ptr += m_strides[dim];
1294     }
1295 
1296     void* data() const {
1297         return p_ptr;
1298     }
1299 
1300 private:
1301     char* p_ptr;
1302     container_type m_strides;
1303 };
1304 
1305 template <size_t N> class multi_array_iterator {
1306 public:
1307     using container_type = std::vector<ssize_t>;
1308 
1309     multi_array_iterator(const std::array<buffer_info, N> &buffers,
1310                          const container_type &shape)
1311         : m_shape(shape.size()), m_index(shape.size(), 0),
1312           m_common_iterator() {
1313 
1314         // Manual copy to avoid conversion warning if using std::copy
1315         for (size_t i = 0; i < shape.size(); ++i)
1316             m_shape[i] = shape[i];
1317 
1318         container_type strides(shape.size());
1319         for (size_t i = 0; i < N; ++i)
1320             init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
1321     }
1322 
1323     multi_array_iterator& operator++() {
1324         for (size_t j = m_index.size(); j != 0; --j) {
1325             size_t i = j - 1;
1326             if (++m_index[i] != m_shape[i]) {
1327                 increment_common_iterator(i);
1328                 break;
1329             } else {
1330                 m_index[i] = 0;
1331             }
1332         }
1333         return *this;
1334     }
1335 
1336     template <size_t K, class T = void> T* data() const {
1337         return reinterpret_cast<T*>(m_common_iterator[K].data());
1338     }
1339 
1340 private:
1341 
1342     using common_iter = common_iterator;
1343 
1344     void init_common_iterator(const buffer_info &buffer,
1345                               const container_type &shape,
1346                               common_iter &iterator,
1347                               container_type &strides) {
1348         auto buffer_shape_iter = buffer.shape.rbegin();
1349         auto buffer_strides_iter = buffer.strides.rbegin();
1350         auto shape_iter = shape.rbegin();
1351         auto strides_iter = strides.rbegin();
1352 
1353         while (buffer_shape_iter != buffer.shape.rend()) {
1354             if (*shape_iter == *buffer_shape_iter)
1355                 *strides_iter = *buffer_strides_iter;
1356             else
1357                 *strides_iter = 0;
1358 
1359             ++buffer_shape_iter;
1360             ++buffer_strides_iter;
1361             ++shape_iter;
1362             ++strides_iter;
1363         }
1364 
1365         std::fill(strides_iter, strides.rend(), 0);
1366         iterator = common_iter(buffer.ptr, strides, shape);
1367     }
1368 
1369     void increment_common_iterator(size_t dim) {
1370         for (auto &iter : m_common_iterator)
1371             iter.increment(dim);
1372     }
1373 
1374     container_type m_shape;
1375     container_type m_index;
1376     std::array<common_iter, N> m_common_iterator;
1377 };
1378 
1379 enum class broadcast_trivial { non_trivial, c_trivial, f_trivial };
1380 
1381 // Populates the shape and number of dimensions for the set of buffers.  Returns a broadcast_trivial
1382 // enum value indicating whether the broadcast is "trivial"--that is, has each buffer being either a
1383 // singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous (`f_trivial`) storage
1384 // buffer; returns `non_trivial` otherwise.
1385 template <size_t N>
1386 broadcast_trivial broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
1387     ndim = std::accumulate(buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
1388         return std::max(res, buf.ndim);
1389     });
1390 
1391     shape.clear();
1392     shape.resize((size_t) ndim, 1);
1393 
1394     // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1 or
1395     // the full size).
1396     for (size_t i = 0; i < N; ++i) {
1397         auto res_iter = shape.rbegin();
1398         auto end = buffers[i].shape.rend();
1399         for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end; ++shape_iter, ++res_iter) {
1400             const auto &dim_size_in = *shape_iter;
1401             auto &dim_size_out = *res_iter;
1402 
1403             // Each input dimension can either be 1 or `n`, but `n` values must match across buffers
1404             if (dim_size_out == 1)
1405                 dim_size_out = dim_size_in;
1406             else if (dim_size_in != 1 && dim_size_in != dim_size_out)
1407                 pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
1408         }
1409     }
1410 
1411     bool trivial_broadcast_c = true;
1412     bool trivial_broadcast_f = true;
1413     for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {
1414         if (buffers[i].size == 1)
1415             continue;
1416 
1417         // Require the same number of dimensions:
1418         if (buffers[i].ndim != ndim)
1419             return broadcast_trivial::non_trivial;
1420 
1421         // Require all dimensions be full-size:
1422         if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin()))
1423             return broadcast_trivial::non_trivial;
1424 
1425         // Check for C contiguity (but only if previous inputs were also C contiguous)
1426         if (trivial_broadcast_c) {
1427             ssize_t expect_stride = buffers[i].itemsize;
1428             auto end = buffers[i].shape.crend();
1429             for (auto shape_iter = buffers[i].shape.crbegin(), stride_iter = buffers[i].strides.crbegin();
1430                     trivial_broadcast_c && shape_iter != end; ++shape_iter, ++stride_iter) {
1431                 if (expect_stride == *stride_iter)
1432                     expect_stride *= *shape_iter;
1433                 else
1434                     trivial_broadcast_c = false;
1435             }
1436         }
1437 
1438         // Check for Fortran contiguity (if previous inputs were also F contiguous)
1439         if (trivial_broadcast_f) {
1440             ssize_t expect_stride = buffers[i].itemsize;
1441             auto end = buffers[i].shape.cend();
1442             for (auto shape_iter = buffers[i].shape.cbegin(), stride_iter = buffers[i].strides.cbegin();
1443                     trivial_broadcast_f && shape_iter != end; ++shape_iter, ++stride_iter) {
1444                 if (expect_stride == *stride_iter)
1445                     expect_stride *= *shape_iter;
1446                 else
1447                     trivial_broadcast_f = false;
1448             }
1449         }
1450     }
1451 
1452     return
1453         trivial_broadcast_c ? broadcast_trivial::c_trivial :
1454         trivial_broadcast_f ? broadcast_trivial::f_trivial :
1455         broadcast_trivial::non_trivial;
1456 }
1457 
1458 template <typename T>
1459 struct vectorize_arg {
1460     static_assert(!std::is_rvalue_reference<T>::value, "Functions with rvalue reference arguments cannot be vectorized");
1461     // The wrapped function gets called with this type:
1462     using call_type = remove_reference_t<T>;
1463     // Is this a vectorized argument?
1464     static constexpr bool vectorize =
1465         satisfies_any_of<call_type, std::is_arithmetic, is_complex, is_pod>::value &&
1466         satisfies_none_of<call_type, std::is_pointer, std::is_array, is_std_array, std::is_enum>::value &&
1467         (!std::is_reference<T>::value ||
1468          (std::is_lvalue_reference<T>::value && std::is_const<call_type>::value));
1469     // Accept this type: an array for vectorized types, otherwise the type as-is:
1470     using type = conditional_t<vectorize, array_t<remove_cv_t<call_type>, array::forcecast>, T>;
1471 };
1472 
1473 
1474 // py::vectorize when a return type is present
1475 template <typename Func, typename Return, typename... Args>
1476 struct vectorize_returned_array {
1477     using Type = array_t<Return>;
1478 
1479     static Type create(broadcast_trivial trivial, const std::vector<ssize_t> &shape) {
1480         if (trivial == broadcast_trivial::f_trivial)
1481             return array_t<Return, array::f_style>(shape);
1482         else
1483             return array_t<Return>(shape);
1484     }
1485 
1486     static Return *mutable_data(Type &array) {
1487         return array.mutable_data();
1488     }
1489 
1490     static Return call(Func &f, Args &... args) {
1491         return f(args...);
1492     }
1493 
1494     static void call(Return *out, size_t i, Func &f, Args &... args) {
1495         out[i] = f(args...);
1496     }
1497 };
1498 
1499 // py::vectorize when a return type is not present
1500 template <typename Func, typename... Args>
1501 struct vectorize_returned_array<Func, void, Args...> {
1502     using Type = none;
1503 
1504     static Type create(broadcast_trivial, const std::vector<ssize_t> &) {
1505         return none();
1506     }
1507 
1508     static void *mutable_data(Type &) {
1509         return nullptr;
1510     }
1511 
1512     static detail::void_type call(Func &f, Args &... args) {
1513         f(args...);
1514         return {};
1515     }
1516 
1517     static void call(void *, size_t, Func &f, Args &... args) {
1518         f(args...);
1519     }
1520 };
1521 
1522 
1523 template <typename Func, typename Return, typename... Args>
1524 struct vectorize_helper {
1525 
1526 // NVCC for some reason breaks if NVectorized is private
1527 #ifdef __CUDACC__
1528 public:
1529 #else
1530 private:
1531 #endif
1532 
1533     static constexpr size_t N = sizeof...(Args);
1534     static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);
1535     static_assert(NVectorized >= 1,
1536             "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
1537 
1538 public:
1539     template <typename T>
1540     explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) { }
1541 
1542     object operator()(typename vectorize_arg<Args>::type... args) {
1543         return run(args...,
1544                    make_index_sequence<N>(),
1545                    select_indices<vectorize_arg<Args>::vectorize...>(),
1546                    make_index_sequence<NVectorized>());
1547     }
1548 
1549 private:
1550     remove_reference_t<Func> f;
1551 
1552     // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling with "/permissive-" flag
1553     // when arg_call_types is manually inlined.
1554     using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>;
1555     template <size_t Index> using param_n_t = typename std::tuple_element<Index, arg_call_types>::type;
1556 
1557     using returned_array = vectorize_returned_array<Func, Return, Args...>;
1558 
1559     // Runs a vectorized function given arguments tuple and three index sequences:
1560     //     - Index is the full set of 0 ... (N-1) argument indices;
1561     //     - VIndex is the subset of argument indices with vectorized parameters, letting us access
1562     //       vectorized arguments (anything not in this sequence is passed through)
1563     //     - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that
1564     //       we can store vectorized buffer_infos in an array (argument VIndex has its buffer at
1565     //       index BIndex in the array).
1566     template <size_t... Index, size_t... VIndex, size_t... BIndex> object run(
1567             typename vectorize_arg<Args>::type &...args,
1568             index_sequence<Index...> i_seq, index_sequence<VIndex...> vi_seq, index_sequence<BIndex...> bi_seq) {
1569 
1570         // Pointers to values the function was called with; the vectorized ones set here will start
1571         // out as array_t<T> pointers, but they will be changed them to T pointers before we make
1572         // call the wrapped function.  Non-vectorized pointers are left as-is.
1573         std::array<void *, N> params{{ &args... }};
1574 
1575         // The array of `buffer_info`s of vectorized arguments:
1576         std::array<buffer_info, NVectorized> buffers{{ reinterpret_cast<array *>(params[VIndex])->request()... }};
1577 
1578         /* Determine dimensions parameters of output array */
1579         ssize_t nd = 0;
1580         std::vector<ssize_t> shape(0);
1581         auto trivial = broadcast(buffers, nd, shape);
1582         auto ndim = (size_t) nd;
1583 
1584         size_t size = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
1585 
1586         // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.
1587         // not wrapped in an array).
1588         if (size == 1 && ndim == 0) {
1589             PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);
1590             return cast(returned_array::call(f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...));
1591         }
1592 
1593         auto result = returned_array::create(trivial, shape);
1594 
1595         if (size == 0) return std::move(result);
1596 
1597         /* Call the function */
1598         auto mutable_data = returned_array::mutable_data(result);
1599         if (trivial == broadcast_trivial::non_trivial)
1600             apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq);
1601         else
1602             apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq);
1603 
1604         return std::move(result);
1605     }
1606 
1607     template <size_t... Index, size_t... VIndex, size_t... BIndex>
1608     void apply_trivial(std::array<buffer_info, NVectorized> &buffers,
1609                        std::array<void *, N> &params,
1610                        Return *out,
1611                        size_t size,
1612                        index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) {
1613 
1614         // Initialize an array of mutable byte references and sizes with references set to the
1615         // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size
1616         // (except for singletons, which get an increment of 0).
1617         std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{{
1618             std::pair<unsigned char *&, const size_t>(
1619                     reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
1620                     buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>)
1621             )...
1622         }};
1623 
1624         for (size_t i = 0; i < size; ++i) {
1625             returned_array::call(out, i, f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...);
1626             for (auto &x : vecparams) x.first += x.second;
1627         }
1628     }
1629 
1630     template <size_t... Index, size_t... VIndex, size_t... BIndex>
1631     void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,
1632                          std::array<void *, N> &params,
1633                          Return *out,
1634                          size_t size,
1635                          const std::vector<ssize_t> &output_shape,
1636                          index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) {
1637 
1638         multi_array_iterator<NVectorized> input_iter(buffers, output_shape);
1639 
1640         for (size_t i = 0; i < size; ++i, ++input_iter) {
1641             PYBIND11_EXPAND_SIDE_EFFECTS((
1642                 params[VIndex] = input_iter.template data<BIndex>()
1643             ));
1644             returned_array::call(out, i, f, *reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
1645         }
1646     }
1647 };
1648 
1649 template <typename Func, typename Return, typename... Args>
1650 vectorize_helper<Func, Return, Args...>
1651 vectorize_extractor(const Func &f, Return (*) (Args ...)) {
1652     return detail::vectorize_helper<Func, Return, Args...>(f);
1653 }
1654 
1655 template <typename T, int Flags> struct handle_type_name<array_t<T, Flags>> {
1656     static constexpr auto name = _("numpy.ndarray[") + npy_format_descriptor<T>::name + _("]");
1657 };
1658 
1659 PYBIND11_NAMESPACE_END(detail)
1660 
1661 // Vanilla pointer vectorizer:
1662 template <typename Return, typename... Args>
1663 detail::vectorize_helper<Return (*)(Args...), Return, Args...>
1664 vectorize(Return (*f) (Args ...)) {
1665     return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);
1666 }
1667 
1668 // lambda vectorizer:
1669 template <typename Func, detail::enable_if_t<detail::is_lambda<Func>::value, int> = 0>
1670 auto vectorize(Func &&f) -> decltype(
1671         detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr)) {
1672     return detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr);
1673 }
1674 
1675 // Vectorize a class method (non-const):
1676 template <typename Return, typename Class, typename... Args,
1677           typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())), Return, Class *, Args...>>
1678 Helper vectorize(Return (Class::*f)(Args...)) {
1679     return Helper(std::mem_fn(f));
1680 }
1681 
1682 // Vectorize a class method (const):
1683 template <typename Return, typename Class, typename... Args,
1684           typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())), Return, const Class *, Args...>>
1685 Helper vectorize(Return (Class::*f)(Args...) const) {
1686     return Helper(std::mem_fn(f));
1687 }
1688 
1689 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
1690 
1691 #if defined(_MSC_VER)
1692 #pragma warning(pop)
1693 #endif
1694