Buffer.py 41.4 KB
Newer Older
1 2 3 4 5 6 7
from Visitor import VisitorTransform, CythonTransform
from ModuleNode import ModuleNode
from Nodes import *
from ExprNodes import *
from StringEncoding import EncodedString
from Errors import CompileError
from Code import UtilityCode
8
import Interpreter
9
import PyrexTypes
Stefan Behnel's avatar
Stefan Behnel committed
10 11
import Naming
import Symtab
12 13 14 15 16 17 18 19 20

import textwrap

def dedent(text, reindent=0):
    text = textwrap.dedent(text)
    if reindent > 0:
        indent = " " * reindent
        text = '\n'.join([indent + x for x in text.split('\n')])
    return text
21 22 23 24 25 26 27 28 29 30 31

class IntroduceBufferAuxiliaryVars(CythonTransform):

    #
    # Entry point
    #

    buffers_exists = False

    def __call__(self, node):
        assert isinstance(node, ModuleNode)
32
        self.max_ndim = 0
33 34 35
        result = super(IntroduceBufferAuxiliaryVars, self).__call__(node)
        if self.buffers_exists:
            use_py2_buffer_functions(node.scope)
36
            use_empty_bufstruct_code(node.scope, self.max_ndim)
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
        return result


    #
    # Basic operations for transforms
    #
    def handle_scope(self, node, scope):
        # For all buffers, insert extra variables in the scope.
        # The variables are also accessible from the buffer_info
        # on the buffer entry
        bufvars = [entry for name, entry
                   in scope.entries.iteritems()
                   if entry.type.is_buffer]
        if len(bufvars) > 0:
            self.buffers_exists = True


        if isinstance(node, ModuleNode) and len(bufvars) > 0:
55
            # for now...note that pos is wrong
56 57
            raise CompileError(node.pos, "Buffer vars not allowed in module scope")
        for entry in bufvars:
58 59
            if entry.type.dtype.is_ptr:
                raise CompileError(node.pos, "Buffers with pointer types not yet supported.")
60

61 62
            name = entry.name
            buftype = entry.type
63 64
            if buftype.ndim > self.max_ndim:
                self.max_ndim = buftype.ndim
65 66 67 68 69

            # Declare auxiliary vars
            cname = scope.mangle(Naming.bufstruct_prefix, name)
            bufinfo = scope.declare_var(name="$%s" % cname, cname=cname,
                                        type=PyrexTypes.c_py_buffer_type, pos=node.pos)
70 71
            if entry.is_arg:
                bufinfo.used = True # otherwise, NameNode will mark whether it is used
72

73
            def var(prefix, idx, initval):
74 75 76 77
                cname = scope.mangle(prefix, "%d_%s" % (idx, name))
                result = scope.declare_var("$%s" % cname, PyrexTypes.c_py_ssize_t_type,
                                         node.pos, cname=cname, is_cdef=True)

78
                result.init = initval
79 80 81
                if entry.is_arg:
                    result.used = True
                return result
82

83

84
            stridevars = [var(Naming.bufstride_prefix, i, "0") for i in range(entry.type.ndim)]
85
            shapevars = [var(Naming.bufshape_prefix, i, "0") for i in range(entry.type.ndim)]
86 87 88
            mode = entry.type.mode
            if mode == 'full':
                suboffsetvars = [var(Naming.bufsuboffset_prefix, i, "-1") for i in range(entry.type.ndim)]
89
            else:
90 91
                suboffsetvars = None

92
            entry.buffer_aux = Symtab.BufferAux(bufinfo, stridevars, shapevars, suboffsetvars)
93

94 95 96 97 98 99 100 101 102 103 104 105 106
        scope.buffer_entries = bufvars
        self.scope = scope

    def visit_ModuleNode(self, node):
        self.handle_scope(node, node.scope)
        self.visitchildren(node)
        return node

    def visit_FuncDefNode(self, node):
        self.handle_scope(node, node.local_scope)
        self.visitchildren(node)
        return node

107 108 109
#
# Analysis
#
110 111
buffer_options = ("dtype", "ndim", "mode", "negative_indices", "cast") # ordered!
buffer_defaults = {"ndim": 1, "mode": "full", "negative_indices": True, "cast": False}
112
buffer_positional_options_count = 1 # anything beyond this needs keyword argument
113 114 115 116 117

ERR_BUF_OPTION_UNKNOWN = '"%s" is not a buffer option'
ERR_BUF_TOO_MANY = 'Too many buffer options'
ERR_BUF_DUP = '"%s" buffer option already supplied'
ERR_BUF_MISSING = '"%s" missing'
118
ERR_BUF_MODE = 'Only allowed buffer modes are: "c", "fortran", "full", "strided" (as a compile-time string)'
119
ERR_BUF_NDIM = 'ndim must be a non-negative integer'
120
ERR_BUF_DTYPE = 'dtype must be "object", numeric type or a struct'
121
ERR_BUF_BOOL = '"%s" must be a boolean'
122 123 124 125 126 127 128 129 130 131 132 133 134 135

def analyse_buffer_options(globalpos, env, posargs, dictargs, defaults=None, need_complete=True):
    """
    Must be called during type analysis, as analyse is called
    on the dtype argument.

    posargs and dictargs should consist of a list and a dict
    of tuples (value, pos). Defaults should be a dict of values.

    Returns a dict containing all the options a buffer can have and
    its value (with the positions stripped).
    """
    if defaults is None:
        defaults = buffer_defaults
136

137
    posargs, dictargs = Interpreter.interpret_compiletime_options(posargs, dictargs, type_env=env, type_args = (0,'dtype'))
138

139
    if len(posargs) > buffer_positional_options_count:
140 141 142
        raise CompileError(posargs[-1][1], ERR_BUF_TOO_MANY)

    options = {}
Stefan Behnel's avatar
Stefan Behnel committed
143
    for name, (value, pos) in dictargs.iteritems():
144 145
        if not name in buffer_options:
            raise CompileError(pos, ERR_BUF_OPTION_UNKNOWN % name)
Stefan Behnel's avatar
Stefan Behnel committed
146 147
        options[name] = value

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    for name, (value, pos) in zip(buffer_options, posargs):
        if not name in buffer_options:
            raise CompileError(pos, ERR_BUF_OPTION_UNKNOWN % name)
        if name in options:
            raise CompileError(pos, ERR_BUF_DUP % name)
        options[name] = value

    # Check that they are all there and copy defaults
    for name in buffer_options:
        if not name in options:
            try:
                options[name] = defaults[name]
            except KeyError:
                if need_complete:
                    raise CompileError(globalpos, ERR_BUF_MISSING % name)

164 165 166 167 168 169
    dtype = options.get("dtype")
    if dtype and dtype.is_extension_type:
        raise CompileError(globalpos, ERR_BUF_DTYPE)

    ndim = options.get("ndim")
    if ndim and (not isinstance(ndim, int) or ndim < 0):
170 171
        raise CompileError(globalpos, ERR_BUF_NDIM)

172
    mode = options.get("mode")
173
    if mode and not (mode in ('full', 'strided', 'c', 'fortran')):
174 175
        raise CompileError(globalpos, ERR_BUF_MODE)

176 177 178 179 180 181 182
    def assert_bool(name):
        x = options.get(name)
        if not isinstance(x, bool):
            raise CompileError(globalpos, ERR_BUF_BOOL % name)

    assert_bool('negative_indices')
    assert_bool('cast')
183

184
    return options
185

186 187 188 189

#
# Code generation
#
190 191


192
def get_flags(buffer_aux, buffer_type):
193
    flags = 'PyBUF_FORMAT'
194 195
    mode = buffer_type.mode
    if mode == 'full':
196
        flags += '| PyBUF_INDIRECT'
197
    elif mode == 'strided':
198
        flags += '| PyBUF_STRIDES'
199 200 201 202
    elif mode == 'c':
        flags += '| PyBUF_C_CONTIGUOUS'
    elif mode == 'fortran':
        flags += '| PyBUF_F_CONTIGUOUS'
203 204
    else:
        assert False
205 206
    if buffer_aux.writable_needed: flags += "| PyBUF_WRITABLE"
    return flags
207

208 209 210 211 212
def used_buffer_aux_vars(entry):
    buffer_aux = entry.buffer_aux
    buffer_aux.buffer_info_var.used = True
    for s in buffer_aux.shapevars: s.used = True
    for s in buffer_aux.stridevars: s.used = True
213 214
    if buffer_aux.suboffsetvars:
        for s in buffer_aux.suboffsetvars: s.used = True
215

216 217 218
def put_unpack_buffer_aux_into_scope(buffer_aux, mode, code):
    # Generate code to copy the needed struct info into local
    # variables.
219 220
    bufstruct = buffer_aux.buffer_info_var.cname

221 222 223 224
    varspec = [("strides", buffer_aux.stridevars),
               ("shape", buffer_aux.shapevars)]
    if mode == 'full':
        varspec.append(("suboffsets", buffer_aux.suboffsetvars))
225

226
    for field, vars in varspec:
227 228 229
        code.putln(" ".join(["%s = %s.%s[%d];" %
                             (s.cname, bufstruct, field, idx)
                             for idx, s in enumerate(vars)]))
230 231

def put_acquire_arg_buffer(entry, code, pos):
232
    code.globalstate.use_utility_code(acquire_utility_code)
233
    buffer_aux = entry.buffer_aux
234
    getbuffer = get_getbuffer_call(code, entry.cname, buffer_aux, entry.type)
235

236
    # Acquire any new buffer
237
    code.putln("{")
238
    code.putln("__Pyx_BufFmt_StackElem __pyx_stack[%d];" % entry.type.dtype.struct_nesting_depth())
239 240
    code.putln(code.error_goto_if("%s == -1" % getbuffer, pos))
    code.putln("}")
241
    # An exception raised in arg parsing cannot be catched, so no
242
    # need to care about the buffer then.
243
    put_unpack_buffer_aux_into_scope(buffer_aux, entry.type.mode, code)
244

245 246 247
def put_release_buffer_code(code, entry):
    code.globalstate.use_utility_code(acquire_utility_code)
    code.putln("__Pyx_SafeReleaseBuffer(&%s);" % entry.buffer_aux.buffer_info_var.cname)
248

249 250 251 252 253 254 255
def get_getbuffer_call(code, obj_cname, buffer_aux, buffer_type):
    ndim = buffer_type.ndim
    cast = int(buffer_type.cast)
    flags = get_flags(buffer_aux, buffer_type)
    bufstruct = buffer_aux.buffer_info_var.cname

    dtype_typeinfo = get_type_information_cname(code, buffer_type.dtype)
256

257 258
    return ("__Pyx_GetBufferAndValidate(&%(bufstruct)s, "
            "(PyObject*)%(obj_cname)s, &%(dtype_typeinfo)s, %(flags)s, %(ndim)d, "
259
            "%(cast)d, __pyx_stack)" % locals())
260

261
def put_assign_to_buffer(lhs_cname, rhs_cname, buffer_aux, buffer_type,
262
                         is_initialized, pos, code):
263 264 265 266 267 268 269
    """
    Generate code for reassigning a buffer variables. This only deals with getting
    the buffer auxiliary structure and variables set up correctly, the assignment
    itself and refcounting is the responsibility of the caller.

    However, the assignment operation may throw an exception so that the reassignment
    never happens.
270

271 272 273 274 275
    Depending on the circumstances there are two possible outcomes:
    - Old buffer released, new acquired, rhs assigned to lhs
    - Old buffer released, new acquired which fails, reaqcuire old lhs buffer
      (which may or may not succeed).
    """
276

277
    code.globalstate.use_utility_code(acquire_utility_code)
278
    bufstruct = buffer_aux.buffer_info_var.cname
279
    flags = get_flags(buffer_aux, buffer_type)
280

281
    code.putln("{")  # Set up necesarry stack for getbuffer
282
    code.putln("__Pyx_BufFmt_StackElem __pyx_stack[%d];" % buffer_type.dtype.struct_nesting_depth())
283

284
    getbuffer = get_getbuffer_call(code, "%s", buffer_aux, buffer_type) # fill in object below
285

286 287
    if is_initialized:
        # Release any existing buffer
288
        code.putln('__Pyx_SafeReleaseBuffer(&%s);' % bufstruct)
289
        # Acquire
290
        retcode_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
291
        code.putln("%s = %s;" % (retcode_cname, getbuffer % rhs_cname))
Stefan Behnel's avatar
Stefan Behnel committed
292
        code.putln('if (%s) {' % (code.unlikely("%s < 0" % retcode_cname)))
293 294 295 296
        # If acquisition failed, attempt to reacquire the old buffer
        # before raising the exception. A failure of reacquisition
        # will cause the reacquisition exception to be reported, one
        # can consider working around this later.
297
        type, value, tb = [code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=False)
298 299
                           for i in range(3)]
        code.putln('PyErr_Fetch(&%s, &%s, &%s);' % (type, value, tb))
Stefan Behnel's avatar
Stefan Behnel committed
300
        code.putln('if (%s) {' % code.unlikely("%s == -1" % (getbuffer % lhs_cname)))
301
        code.putln('Py_XDECREF(%s); Py_XDECREF(%s); Py_XDECREF(%s);' % (type, value, tb)) # Do not refnanny these!
302
        code.globalstate.use_utility_code(raise_buffer_fallback_code)
303
        code.putln('__Pyx_RaiseBufferFallbackError();')
304
        code.putln('} else {')
305 306
        code.putln('PyErr_Restore(%s, %s, %s);' % (type, value, tb))
        for t in (type, value, tb):
307
            code.funcstate.release_temp(t)
Stefan Behnel's avatar
Stefan Behnel committed
308 309
        code.putln('}')
        code.putln('}')
310
        # Unpack indices
311
        put_unpack_buffer_aux_into_scope(buffer_aux, buffer_type.mode, code)
312
        code.putln(code.error_goto_if_neg(retcode_cname, pos))
313
        code.funcstate.release_temp(retcode_cname)
314
    else:
315 316 317 318
        # Our entry had no previous value, so set to None when acquisition fails.
        # In this case, auxiliary vars should be set up right in initialization to a zero-buffer,
        # so it suffices to set the buf field to NULL.
        code.putln('if (%s) {' % code.unlikely("%s == -1" % (getbuffer % rhs_cname)))
319
        code.putln('%s = %s; __Pyx_INCREF(Py_None); %s.buf = NULL;' %
320 321 322
                   (lhs_cname,
                    PyrexTypes.typecast(buffer_type, PyrexTypes.py_object_type, "Py_None"),
                    bufstruct))
323 324 325
        code.putln(code.error_goto(pos))
        code.put('} else {')
        # Unpack indices
326
        put_unpack_buffer_aux_into_scope(buffer_aux, buffer_type.mode, code)
327
        code.putln('}')
328

329
    code.putln("}") # Release stack
330

331
def put_buffer_lookup_code(entry, index_signeds, index_cnames, directives, pos, code):
332 333 334 335 336
    """
    Generates code to process indices and calculate an offset into
    a buffer. Returns a C string which gives a pointer which can be
    read from or written to at will (it is an expression so caller should
    store it in a temporary if it is used more than once).
337 338 339 340 341

    As the bounds checking can have any number of combinations of unsigned
    arguments, smart optimizations etc. we insert it directly in the function
    body. The lookup however is delegated to a inline function that is instantiated
    once per ndim (lookup with suboffsets tend to get quite complicated).
342

343
    """
344 345
    bufaux = entry.buffer_aux
    bufstruct = bufaux.buffer_info_var.cname
346
    negative_indices = directives['wraparound'] and entry.type.negative_indices
347

348
    if directives['boundscheck']:
349 350 351 352
        # Check bounds and fix negative indices.
        # We allocate a temporary which is initialized to -1, meaning OK (!).
        # If an error occurs, the temp is set to the dimension index the
        # error is occuring at.
353
        tmp_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
354
        code.putln("%s = -1;" % tmp_cname)
355 356 357 358 359
        for dim, (signed, cname, shape) in enumerate(zip(index_signeds, index_cnames,
                                                         bufaux.shapevars)):
            if signed != 0:
                # not unsigned, deal with negative index
                code.putln("if (%s < 0) {" % cname)
360 361 362 363 364 365
                if negative_indices:
                    code.putln("%s += %s;" % (cname, shape.cname))
                    code.putln("if (%s) %s = %d;" % (
                        code.unlikely("%s < 0" % cname), tmp_cname, dim))
                else:
                    code.putln("%s = %d;" % (tmp_cname, dim))
366
                code.put("} else ")
367
            # check bounds in positive direction
368
            if signed != 0:
369 370 371
                cast = ""
            else:
                cast = "(size_t)"
372
            code.putln("if (%s) %s = %d;" % (
373
                code.unlikely("%s >= %s%s" % (cname, cast, shape.cname)),
374 375
                tmp_cname, dim))
        code.globalstate.use_utility_code(raise_indexerror_code)
Stefan Behnel's avatar
Stefan Behnel committed
376
        code.putln("if (%s) {" % code.unlikely("%s != -1" % tmp_cname))
377
        code.putln('__Pyx_RaiseBufferIndexError(%s);' % tmp_cname)
378
        code.putln(code.error_goto(pos))
Stefan Behnel's avatar
Stefan Behnel committed
379
        code.putln('}')
380
        code.funcstate.release_temp(tmp_cname)
381
    elif negative_indices:
382 383 384 385 386
        # Only fix negative indices.
        for signed, cname, shape in zip(index_signeds, index_cnames,
                                        bufaux.shapevars):
            if signed != 0:
                code.putln("if (%s < 0) %s += %s;" % (cname, cname, shape.cname))
387

388
    # Create buffer lookup and return it
389 390
    # This is done via utility macros/inline functions, which vary
    # according to the access mode used.
391
    params = []
392
    nd = entry.type.ndim
393 394
    mode = entry.type.mode
    if mode == 'full':
395 396 397 398
        for i, s, o in zip(index_cnames, bufaux.stridevars, bufaux.suboffsetvars):
            params.append(i)
            params.append(s.cname)
            params.append(o.cname)
399 400
        funcname = "__Pyx_BufPtrFull%dd" % nd
        funcgen = buf_lookup_full_code
401
    else:
402 403 404 405 406 407 408 409 410 411 412
        if mode == 'strided':
            funcname = "__Pyx_BufPtrStrided%dd" % nd
            funcgen = buf_lookup_strided_code
        elif mode == 'c':
            funcname = "__Pyx_BufPtrCContig%dd" % nd
            funcgen = buf_lookup_c_code
        elif mode == 'fortran':
            funcname = "__Pyx_BufPtrFortranContig%dd" % nd
            funcgen = buf_lookup_fortran_code
        else:
            assert False
413 414 415
        for i, s in zip(index_cnames, bufaux.stridevars):
            params.append(i)
            params.append(s.cname)
416

417
    # Make sure the utility code is available
418 419 420 421 422
    if funcname not in code.globalstate.utility_codes:
        code.globalstate.utility_codes.add(funcname)
        protocode = code.globalstate['utility_code_proto']
        defcode = code.globalstate['utility_code_def']
        funcgen(protocode, defcode, name=funcname, nd=nd)
423

424 425 426 427 428 429
    ptr_type = entry.type.buffer_ptr_type
    ptrcode = "%s(%s, %s.buf, %s)" % (funcname,
                                      ptr_type.declaration_code(""),
                                      bufstruct,
                                      ", ".join(params))
    return ptrcode
430

431 432 433 434 435 436

def use_empty_bufstruct_code(env, max_ndim):
    code = dedent("""
        Py_ssize_t __Pyx_zeros[] = {%s};
        Py_ssize_t __Pyx_minusones[] = {%s};
    """) % (", ".join(["0"] * max_ndim), ", ".join(["-1"] * max_ndim))
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
437
    env.use_utility_code(UtilityCode(proto=code))
438

439

440
def buf_lookup_full_code(proto, defin, name, nd):
441
    """
442
    Generates a buffer lookup function for the right number
443 444
    of dimensions. The function gives back a void* at the right location.
    """
445
    # _i_ndex, _s_tride, sub_o_ffset
446 447 448 449
    macroargs = ", ".join(["i%d, s%d, o%d" % (i, i, i) for i in range(nd)])
    proto.putln("#define %s(type, buf, %s) (type)(%s_imp(buf, %s))" % (name, macroargs, name, macroargs))

    funcargs = ", ".join(["Py_ssize_t i%d, Py_ssize_t s%d, Py_ssize_t o%d" % (i, i, i) for i in range(nd)])
450
    proto.putln("static CYTHON_INLINE void* %s_imp(void* buf, %s);" % (name, funcargs))
451
    defin.putln(dedent("""
452
        static CYTHON_INLINE void* %s_imp(void* buf, %s) {
453
          char* ptr = (char*)buf;
454
        """) % (name, funcargs) + "".join([dedent("""\
455
          ptr += s%d * i%d;
456
          if (o%d >= 0) ptr = *((char**)ptr) + o%d;
457
        """) % (i, i, i, i) for i in range(nd)]
458
        ) + "\nreturn ptr;\n}")
459

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
def buf_lookup_strided_code(proto, defin, name, nd):
    """
    Generates a buffer lookup function for the right number
    of dimensions. The function gives back a void* at the right location.
    """
    # _i_ndex, _s_tride
    args = ", ".join(["i%d, s%d" % (i, i) for i in range(nd)])
    offset = " + ".join(["i%d * s%d" % (i, i) for i in range(nd)])
    proto.putln("#define %s(type, buf, %s) (type)((char*)buf + %s)" % (name, args, offset))

def buf_lookup_c_code(proto, defin, name, nd):
    """
    Similar to strided lookup, but can assume that the last dimension
    doesn't need a multiplication as long as.
    Still we keep the same signature for now.
    """
    if nd == 1:
        proto.putln("#define %s(type, buf, i0, s0) ((type)buf + i0)" % name)
    else:
        args = ", ".join(["i%d, s%d" % (i, i) for i in range(nd)])
        offset = " + ".join(["i%d * s%d" % (i, i) for i in range(nd - 1)])
        proto.putln("#define %s(type, buf, %s) ((type)((char*)buf + %s) + i%d)" % (name, args, offset, nd - 1))

def buf_lookup_fortran_code(proto, defin, name, nd):
    """
    Like C lookup, but the first index is optimized instead.
    """
    if nd == 1:
        proto.putln("#define %s(type, buf, i0, s0) ((type)buf + i0)" % name)
    else:
        args = ", ".join(["i%d, s%d" % (i, i) for i in range(nd)])
        offset = " + ".join(["i%d * s%d" % (i, i) for i in range(1, nd)])
        proto.putln("#define %s(type, buf, %s) ((type)((char*)buf + %s) + i%d)" % (name, args, offset, 0))
493

494 495

def use_py2_buffer_functions(env):
496 497 498
    # Emulation of PyObject_GetBuffer and PyBuffer_Release for Python 2.
    # For >= 2.6 we do double mode -- use the new buffer interface on objects
    # which has the right tp_flags set, but emulation otherwise.
499 500 501

    # Search all types for __getbuffer__ overloads
    types = []
502
    visited_scopes = set()
503
    def find_buffer_types(scope):
504 505 506
        if scope in visited_scopes:
            return
        visited_scopes.add(scope)
507 508 509 510 511 512 513 514 515 516 517 518 519 520
        for m in scope.cimported_modules:
            find_buffer_types(m)
        for e in scope.type_entries:
            t = e.type
            if t.is_extension_type:
                release = get = None
                for x in t.scope.pyfunc_entries:
                    if x.name == u"__getbuffer__": get = x.func_cname
                    elif x.name == u"__releasebuffer__": release = x.func_cname
                if get:
                    types.append((t.typeptr_cname, get, release))

    find_buffer_types(env)

521
    code = dedent("""
522
        #if PY_MAJOR_VERSION < 3
523
        static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) {
524
          #if PY_VERSION_HEX >= 0x02060000
525
          if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags);
526
          #endif
527
    """)
528 529 530 531 532 533
    if len(types) > 0:
        clause = "if"
        for t, get, release in types:
            code += "  %s (PyObject_TypeCheck(obj, %s)) return %s(obj, view, flags);\n" % (clause, t, get)
            clause = "else if"
        code += "  else {\n"
534 535 536 537
    code += dedent("""\
        PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name);
        return -1;
    """, 2)
538
    if len(types) > 0: code += "  }"
539 540
    code += dedent("""
        }
541

542 543 544
        static void __Pyx_ReleaseBuffer(Py_buffer *view) {
          PyObject* obj = view->obj;
          if (obj) {
545 546 547
            #if PY_VERSION_HEX >= 0x02060000
            if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;}
            #endif
548
    """)
549 550 551 552
    if len(types) > 0:
        clause = "if"
        for t, get, release in types:
            if release:
553
                code += "    "
554 555
                code += "%s (PyObject_TypeCheck(obj, %s)) %s(obj, view);" % (clause, t, release)
                clause = "else if"
556
    code += dedent("""
557 558 559
            Py_DECREF(obj);
            view->obj = NULL;
          }
560 561 562 563
        }

        #endif
    """)
564

565 566
    env.use_utility_code(UtilityCode(
            proto = dedent("""\
567
        #if PY_MAJOR_VERSION < 3
568
        static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags);
569
        static void __Pyx_ReleaseBuffer(Py_buffer *view);
570 571
        #else
        #define __Pyx_GetBuffer PyObject_GetBuffer
572
        #define __Pyx_ReleaseBuffer PyBuffer_Release
573
        #endif
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
574
    """), impl = code))
575 576


577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
def mangle_dtype_name(dtype):
    # Use prefixes to seperate user defined types from builtins
    # (consider "typedef float unsigned_int")
    if dtype.is_pyobject:
        return "object"
    elif dtype.is_ptr:
        return "ptr"
    else:
        if dtype.is_typedef or dtype.is_struct_or_union:
            prefix = "nn_"
        else:
            prefix = ""
        return prefix + dtype.declaration_code("").replace(" ", "_")

def get_type_information_cname(code, dtype, maxdepth=None):
592
    # Output the run-time type information (__Pyx_TypeInfo) for given dtype,
593 594
    # and return the name of the type info struct.
    #
595 596
    # Structs with two floats of the same size are encoded as complex numbers.
    # One can seperate between complex numbers declared as struct or with native
597 598
    # encoding by inspecting to see if the fields field of the type is
    # filled in.
599 600 601
    namesuffix = mangle_dtype_name(dtype)
    name = "__Pyx_TypeInfo_%s" % namesuffix
    structinfo_name = "__Pyx_StructFields_%s" % namesuffix
602

603
    if dtype.is_error: return "<error>"
604

605 606 607
    # It's critical that walking the type info doesn't use more stack
    # depth than dtype.struct_nesting_depth() returns, so use an assertion for this
    if maxdepth is None: maxdepth = dtype.struct_nesting_depth()
608 609 610
    if maxdepth <= 0:
        assert False

611 612 613
    if name not in code.globalstate.utility_codes:
        code.globalstate.utility_codes.add(name)
        typecode = code.globalstate['typeinfo']
614

615
        complex_possible = dtype.is_struct_or_union and dtype.can_be_complex()
616

617 618 619 620 621 622 623 624
        declcode = dtype.declaration_code("")
        if dtype.is_simple_buffer_dtype():
            structinfo_name = "NULL"
        elif dtype.is_struct:
            fields = dtype.scope.var_entries
            # Must pre-call all used types in order not to recurse utility code
            # writing.
            assert len(fields) > 0
625
            types = [get_type_information_cname(code, f.type, maxdepth - 1)
626 627 628 629 630 631 632 633 634
                     for f in fields]
            typecode.putln("static __Pyx_StructField %s[] = {" % structinfo_name, safe=True)
            for f, typeinfo in zip(fields, types):
                typecode.putln('  {&%s, "%s", offsetof(%s, %s)},' %
                           (typeinfo, f.name, dtype.declaration_code(""), f.cname), safe=True)
            typecode.putln('  {NULL, NULL, 0}', safe=True)
            typecode.putln("};", safe=True)
        else:
            assert False
635

636 637 638 639 640 641
        rep = str(dtype)
        if dtype.is_int:
            if dtype.signed == 0:
                typegroup = 'U'
            else:
                typegroup = 'I'
642
        elif complex_possible or dtype.is_complex:
643 644 645 646 647 648 649
            typegroup = 'C'
        elif dtype.is_float:
            typegroup = 'R'
        elif dtype.is_struct:
            typegroup = 'S'
        elif dtype.is_pyobject:
            typegroup = 'O'
650
        else:
651 652
            print dtype
            assert False
653

654 655 656 657 658 659 660 661
        typecode.putln(('static __Pyx_TypeInfo %s = { "%s", %s, sizeof(%s), \'%s\' };'
                        ) % (name,
                             rep,
                             structinfo_name,
                             declcode,
                             typegroup,
                        ), safe=True)
    return name
662 663


664 665
# Utility function to set the right exception
# The caller should immediately goto_error
666 667
raise_indexerror_code = UtilityCode(
proto = """\
668
static void __Pyx_RaiseBufferIndexError(int axis); /*proto*/
669 670
""",
impl = """\
671
static void __Pyx_RaiseBufferIndexError(int axis) {
672 673
  PyErr_Format(PyExc_IndexError,
     "Out of bounds on buffer access (axis %d)", axis);
674
}
675

676
""")
677

678 679 680 681 682
parse_typestring_repeat_code = UtilityCode(
proto = """
""",
impl = """
""")
683

684 685
raise_buffer_fallback_code = UtilityCode(
proto = """
686
static void __Pyx_RaiseBufferFallbackError(void); /*proto*/
687 688
""",
impl = """
689 690 691 692 693
static void __Pyx_RaiseBufferFallbackError(void) {
  PyErr_Format(PyExc_ValueError,
     "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!");
}

694
""")
695 696 697 698 699 700 701 702 703 704 705 706



#
# Buffer format string checking
#
# Buffer type checking. Utility code for checking that acquired
# buffers match our assumptions. We only need to check ndim and
# the format string; the access mode/flags is checked by the
# exporter.
#
# The alignment code is copied from _struct.c in Python.
707
acquire_utility_code = UtilityCode(proto="""
708 709 710 711 712 713 714 715 716 717 718 719 720
/* Run-time type information about structs used with buffers */
struct __Pyx_StructField_;

typedef struct {
  const char* name; /* for error messages only */
  struct __Pyx_StructField_* fields;
  size_t size;     /* sizeof(type) */
  char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */
} __Pyx_TypeInfo;

typedef struct __Pyx_StructField_ {
  __Pyx_TypeInfo* type;
  const char* name;
721
  size_t offset;
722 723
} __Pyx_StructField;

724 725 726 727
typedef struct {
  __Pyx_StructField* field;
  size_t parent_offset;
} __Pyx_BufFmt_StackElem;
728

729

730
static CYTHON_INLINE int  __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack);
731
static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info);
732
""", impl="""
733
static CYTHON_INLINE int __Pyx_IsLittleEndian(void) {
734 735 736 737 738 739
  unsigned int n = 1;
  return *(unsigned char*)(&n) != 0;
}

typedef struct {
  __Pyx_StructField root;
740 741
  __Pyx_BufFmt_StackElem* head;
  size_t fmt_offset;
742
  size_t new_count, enc_count;
743 744
  int is_complex;
  char enc_type;
745 746
  char new_packmode;
  char enc_packmode;
747 748 749
} __Pyx_BufFmt_Context;

static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx,
750
                              __Pyx_BufFmt_StackElem* stack,
751
                              __Pyx_TypeInfo* type) {
752 753
  stack[0].field = &ctx->root;
  stack[0].parent_offset = 0;
754 755 756 757
  ctx->root.type = type;
  ctx->root.name = "buffer dtype";
  ctx->root.offset = 0;
  ctx->head = stack;
758
  ctx->head->field = &ctx->root;
759 760
  ctx->fmt_offset = 0;
  ctx->head->parent_offset = 0;
761 762
  ctx->new_packmode = '@';
  ctx->enc_packmode = '@';
763 764 765 766 767 768
  ctx->new_count = 1;
  ctx->enc_count = 0;
  ctx->enc_type = 0;
  ctx->is_complex = 0;
  while (type->typegroup == 'S') {
    ++ctx->head;
769
    ctx->head->field = type->fields;
770
    ctx->head->parent_offset = 0;
771 772 773 774 775 776 777 778
    type = type->fields->type;
  }
}

static int __Pyx_BufFmt_ParseNumber(const char** ts) {
    int count;
    const char* t = *ts;
    if (*t < '0' || *t > '9') {
779
      return -1;
780 781 782 783 784 785 786 787 788 789 790 791
    } else {
        count = *t++ - '0';
        while (*t >= '0' && *t < '9') {
            count *= 10;
            count += *t++ - '0';
        }
    }
    *ts = t;
    return count;
}

static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) {
792 793
  PyErr_Format(PyExc_ValueError,
               "Unexpected format string character: '%c'", ch);
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
}

static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) {
  switch (ch) {
    case 'b': return "'char'";
    case 'B': return "'unsigned char'";
    case 'h': return "'short'";
    case 'H': return "'unsigned short'";
    case 'i': return "'int'";
    case 'I': return "'unsigned int'";
    case 'l': return "'long'";
    case 'L': return "'unsigned long'";
    case 'q': return "'long long'";
    case 'Q': return "'unsigned long long'";
    case 'f': return (is_complex ? "'complex float'" : "'float'");
    case 'd': return (is_complex ? "'complex double'" : "'double'");
    case 'g': return (is_complex ? "'complex long double'" : "'long double'");
    case 'T': return "a struct";
    case 'O': return "Python object";
    case 'P': return "a pointer";
    case 0: return "end";
    default: return "unparseable format string";
  }
}

static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) {
  switch (ch) {
    case '?': case 'c': case 'b': case 'B': return 1;
    case 'h': case 'H': return 2;
    case 'i': case 'I': case 'l': case 'L': return 4;
    case 'q': case 'Q': return 8;
    case 'f': return (is_complex ? 8 : 4);
    case 'd': return (is_complex ? 16 : 8);
    case 'g': {
      PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g')..");
      return 0;
    }
    case 'O': case 'P': return sizeof(void*);
    default:
      __Pyx_BufFmt_RaiseUnexpectedChar(ch);
      return 0;
    }
}

static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) {
  switch (ch) {
    case 'c': case 'b': case 'B': return 1;
    case 'h': case 'H': return sizeof(short);
    case 'i': case 'I': return sizeof(int);
    case 'l': case 'L': return sizeof(long);
    #ifdef HAVE_LONG_LONG
    case 'q': case 'Q': return sizeof(PY_LONG_LONG);
    #endif
    case 'f': return sizeof(float) * (is_complex ? 2 : 1);
    case 'd': return sizeof(double) * (is_complex ? 2 : 1);
    case 'g': return sizeof(long double) * (is_complex ? 2 : 1);
    case 'O': case 'P': return sizeof(void*);
    default: {
      __Pyx_BufFmt_RaiseUnexpectedChar(ch);
      return 0;
854
    }
855 856 857
  }
}

858 859 860 861 862 863 864 865
typedef struct { char c; short x; } __Pyx_st_short;
typedef struct { char c; int x; } __Pyx_st_int;
typedef struct { char c; long x; } __Pyx_st_long;
typedef struct { char c; float x; } __Pyx_st_float;
typedef struct { char c; double x; } __Pyx_st_double;
typedef struct { char c; long double x; } __Pyx_st_longdouble;
typedef struct { char c; void *x; } __Pyx_st_void_p;
#ifdef HAVE_LONG_LONG
866
typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong;
867 868 869 870 871 872 873 874 875
#endif

static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) {
  switch (ch) {
    case '?': case 'c': case 'b': case 'B': return 1;
    case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short);
    case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int);
    case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long);
#ifdef HAVE_LONG_LONG
876
    case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG);
877 878 879 880 881 882 883 884 885 886 887
#endif
    case 'f': return sizeof(__Pyx_st_float) - sizeof(float);
    case 'd': return sizeof(__Pyx_st_double) - sizeof(double);
    case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double);
    case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*);
    default:
      __Pyx_BufFmt_RaiseUnexpectedChar(ch);
      return 0;
    }
}

888
static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) {
889 890 891 892 893 894 895 896 897
  switch (ch) {
    case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I';
    case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U';
    case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R');
    case 'O': return 'O';
    case 'P': return 'P';
    default: {
      __Pyx_BufFmt_RaiseUnexpectedChar(ch);
      return 0;
898
    }
899 900 901 902
  }
}

static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) {
903
  if (ctx->head == NULL || ctx->head->field == &ctx->root) {
904 905 906 907 908 909
    const char* expected;
    const char* quote;
    if (ctx->head == NULL) {
      expected = "end";
      quote = "";
    } else {
910
      expected = ctx->head->field->type->name;
911 912 913 914 915 916 917
      quote = "'";
    }
    PyErr_Format(PyExc_ValueError,
                 "Buffer dtype mismatch, expected %s%s%s but got %s",
                 quote, expected, quote,
                 __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex));
  } else {
918 919
    __Pyx_StructField* field = ctx->head->field;
    __Pyx_StructField* parent = (ctx->head - 1)->field;
920 921 922 923 924 925 926 927
    PyErr_Format(PyExc_ValueError,
                 "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'",
                 field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex),
                 parent->type->name, field->name);
  }
}

static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) {
928
  char group;
929
  size_t size, offset;
930 931
  if (ctx->enc_type == 0) return 0;
  group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex);
932
  do {
933
    __Pyx_StructField* field = ctx->head->field;
934
    __Pyx_TypeInfo* type = field->type;
935

936
    if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') {
937 938 939 940
      size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex);
    } else {
      size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex);
    }
941
    if (ctx->enc_packmode == '@') {
942 943
      size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex);
      size_t align_mod_offset;
944 945 946 947 948
      if (align_at == 0) return -1;
      align_mod_offset = ctx->fmt_offset % align_at;
      if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset;
    }

949 950 951
    if (type->size != size || type->typegroup != group) {
      if (type->typegroup == 'C' && type->fields != NULL) {
        /* special case -- treat as struct rather than complex number */
952
        size_t parent_offset = ctx->head->parent_offset + field->offset;
953
        ++ctx->head;
954
        ctx->head->field = type->fields;
955
        ctx->head->parent_offset = parent_offset;
956 957
        continue;
      }
958

959
      __Pyx_BufFmt_RaiseExpected(ctx);
960
      return -1;
961 962
    }

963
    offset = ctx->head->parent_offset + field->offset;
964
    if (ctx->fmt_offset != offset) {
965
      PyErr_Format(PyExc_ValueError,
966 967
                   "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected",
                   (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset);
968
      return -1;
969
    }
970 971

    ctx->fmt_offset += size;
972

973 974 975 976 977 978 979 980
    --ctx->enc_count; /* Consume from buffer string */

    /* Done checking, move to next field, pushing or popping struct stack if needed */
    while (1) {
      if (field == &ctx->root) {
        ctx->head = NULL;
        if (ctx->enc_count != 0) {
          __Pyx_BufFmt_RaiseExpected(ctx);
981
          return -1;
982 983 984
        }
        break; /* breaks both loops as ctx->enc_count == 0 */
      }
985
      ctx->head->field = ++field;
986 987
      if (field->type == NULL) {
        --ctx->head;
988
        field = ctx->head->field;
989 990
        continue;
      } else if (field->type->typegroup == 'S') {
991
        size_t parent_offset = ctx->head->parent_offset + field->offset;
992 993 994
        if (field->type->fields->type == NULL) continue; /* empty struct */
        field = field->type->fields;
        ++ctx->head;
995 996
        ctx->head->field = field;
        ctx->head->parent_offset = parent_offset;
997 998 999 1000 1001 1002 1003 1004
        break;
      } else {
        break;
      }
    }
  } while (ctx->enc_count);
  ctx->enc_type = 0;
  ctx->is_complex = 0;
1005
  return 0;
1006 1007 1008 1009 1010 1011 1012
}

static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) {
  int got_Z = 0;
  while (1) {
    switch(*ts) {
      case 0:
1013 1014 1015
        if (ctx->enc_type != 0 && ctx->head == NULL) {
          __Pyx_BufFmt_RaiseExpected(ctx);
          return NULL;
1016
        }
1017
        if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
        if (ctx->head != NULL) {
          __Pyx_BufFmt_RaiseExpected(ctx);
          return NULL;
        }
        return ts;
      case ' ':
      case 10:
      case 13:
        ++ts;
        break;
      case '<':
        if (!__Pyx_IsLittleEndian()) {
          PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler");
          return NULL;
        }
1033
        ctx->new_packmode = '=';
1034 1035 1036 1037 1038 1039 1040 1041
        ++ts;
        break;
      case '>':
      case '!':
        if (__Pyx_IsLittleEndian()) {
          PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler");
          return NULL;
        }
1042
        ctx->new_packmode = '=';
1043 1044 1045 1046 1047
        ++ts;
        break;
      case '=':
      case '@':
      case '^':
1048
        ctx->new_packmode = *ts++;
1049 1050 1051 1052
        break;
      case 'T': /* substruct */
        {
          const char* ts_after_sub;
1053
          size_t i, struct_count = ctx->new_count;
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
          ctx->new_count = 1;
          ++ts;
          if (*ts != '{') {
            PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'");
            return NULL;
          }
          ++ts;
          ts_after_sub = ts;
          for (i = 0; i != struct_count; ++i) {
            ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts);
            if (!ts_after_sub) return NULL;
          }
          ts = ts_after_sub;
        }
        break;
      case '}': /* end of substruct; either repeat or move on */
        ++ts;
        return ts;
1072 1073 1074 1075 1076 1077
      case 'x':
        if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
        ctx->fmt_offset += ctx->new_count;
        ctx->new_count = 1;
        ctx->enc_count = 0;
        ctx->enc_type = 0;
1078
        ctx->enc_packmode = ctx->new_packmode;
1079 1080
        ++ts;
        break;
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
      case 'Z':
        got_Z = 1;
        ++ts;
        if (*ts != 'f' && *ts != 'd' && *ts != 'g') {
          __Pyx_BufFmt_RaiseUnexpectedChar('Z');
          return NULL;
        }        /* fall through */
      case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I':
      case 'l': case 'L': case 'q': case 'Q':
      case 'f': case 'd': case 'g':
      case 'O':
1092 1093
        if (ctx->enc_type == *ts && got_Z == ctx->is_complex &&
            ctx->enc_packmode == ctx->new_packmode) {
1094 1095 1096 1097
          /* Continue pooling same type */
          ctx->enc_count += ctx->new_count;
        } else {
          /* New type */
1098
          if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
1099
          ctx->enc_count = ctx->new_count;
1100
          ctx->enc_packmode = ctx->new_packmode;
1101 1102 1103 1104 1105 1106 1107
          ctx->enc_type = *ts;
          ctx->is_complex = got_Z;
        }
        ++ts;
        ctx->new_count = 1;
        got_Z = 0;
        break;
1108
      case ':':
1109 1110 1111 1112
        ++ts;
        while(*ts != ':') ++ts;
        ++ts;
        break;
1113 1114
      default:
        {
1115 1116
          int number = __Pyx_BufFmt_ParseNumber(&ts);
          if (number == -1) { /* First char was not a digit */
1117
            PyErr_Format(PyExc_ValueError,
1118
                         "Does not understand character buffer dtype format string ('%c')", *ts);
1119 1120
            return NULL;
          }
1121
          ctx->new_count = (size_t)number; 
1122 1123 1124 1125 1126
        }
    }
  }
}

1127
static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) {
1128 1129 1130 1131 1132 1133
  buf->buf = NULL;
  buf->obj = NULL;
  buf->strides = __Pyx_zeros;
  buf->shape = __Pyx_zeros;
  buf->suboffsets = __Pyx_minusones;
}
1134

1135
static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) {
1136
  if (obj == Py_None || obj == NULL) {
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    __Pyx_ZeroBuffer(buf);
    return 0;
  }
  buf->buf = NULL;
  if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail;
  if (buf->ndim != nd) {
    PyErr_Format(PyExc_ValueError,
                 "Buffer has wrong number of dimensions (expected %d, got %d)",
                 nd, buf->ndim);
    goto fail;
  }
  if (!cast) {
    __Pyx_BufFmt_Context ctx;
    __Pyx_BufFmt_Init(&ctx, stack, dtype);
    if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail;
  }
1153
  if ((unsigned)buf->itemsize != dtype->size) {
1154 1155 1156
    PyErr_Format(PyExc_ValueError,
      "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)",
      buf->itemsize, (buf->itemsize > 1) ? "s" : "",
1157
      dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : "");
1158 1159 1160 1161 1162 1163 1164 1165
    goto fail;
  }
  if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones;
  return 0;
fail:;
  __Pyx_ZeroBuffer(buf);
  return -1;
}
1166

1167
static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) {
1168 1169 1170 1171 1172
  if (info->buf == NULL) return;
  if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL;
  __Pyx_ReleaseBuffer(info);
}
""")
1173