bufaccess.pyx 35.5 KB
Newer Older
1 2 3 4 5 6 7 8 9
# Tests the buffer access syntax functionality by constructing
# mock buffer objects.
#
# Note that the buffers are mock objects created for testing
# the buffer access behaviour -- for instance there is no flag
# checking in the buffer objects (why test our test case?), rather
# what we want to test is what is passed into the flags argument.
#

10
from __future__ import unicode_literals
11

12 13 14
from libc cimport stdlib
from libc cimport stdio
cimport cpython.buffer
15 16
cimport cython

17
from cpython cimport PyObject, Py_INCREF, Py_DECREF
18 19

__test__ = {}
20

Stefan Behnel's avatar
Stefan Behnel committed
21
import sys
22 23
import re
exclude = []#re.compile('object').search]
24

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
25
def testcase(func):
26 27 28
    for e in exclude:
        if e(func.__name__):
            return func
Stefan Behnel's avatar
Stefan Behnel committed
29 30 31 32 33
    doctest = func.__doc__
    if sys.version_info >= (3,1,1):
        doctest = doctest.replace('does not have the buffer interface',
                                  'does not support the buffer interface')
    __test__[func.__name__] = doctest
34 35
    return func

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
36
def testcas(a):
37 38
    pass

39 40 41 42 43

#
# Buffer acquire and release tests
#

44 45
def nousage():
    """
46 47
    The challenge here is just compilation.
    """
48
    cdef object[int, ndim=2] buf
49 50 51 52

def printbuf():
    """
    Just compilation.
53
    """
54
    cdef object[int, ndim=2] buf
55
    print buf
56 57
    return
    buf[0,0] = 0
58

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
59
@testcase
60 61
def acquire_release(o1, o2):
    """
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
62 63
    >>> A = IntMockBuffer("A", range(6))
    >>> B = IntMockBuffer("B", range(6))
64 65 66 67 68
    >>> acquire_release(A, B)
    acquired A
    released A
    acquired B
    released B
69 70 71 72
    >>> acquire_release(None, None)
    >>> acquire_release(None, B)
    acquired B
    released B
73 74 75 76
    """
    cdef object[int] buf
    buf = o1
    buf = o2
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
77

78
@testcase
79 80 81 82
def acquire_raise(o):
    """
    Apparently, doctest won't handle mixed exceptions and print
    stats, so need to circumvent this.
83

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
84
    >>> A = IntMockBuffer("A", range(6))
85 86
    >>> A.resetlog()
    >>> acquire_raise(A)
87 88 89
    Traceback (most recent call last):
        ...
    Exception: on purpose
90
    >>> A.printlog()
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
91 92
    acquired A
    released A
93

94 95 96 97 98
    """
    cdef object[int] buf
    buf = o
    raise Exception("on purpose")

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
@testcase
def acquire_failure1():
    """
    >>> acquire_failure1()
    acquired working
    0 3
    0 3
    released working
    """
    cdef object[int] buf
    buf = IntMockBuffer("working", range(4))
    print buf[0], buf[3]
    try:
        buf = ErrorBuffer()
        assert False
    except Exception:
        print buf[0], buf[3]

@testcase
def acquire_failure2():
    """
    >>> acquire_failure2()
    acquired working
    0 3
    0 3
    released working
    """
    cdef object[int] buf = IntMockBuffer("working", range(4))
    print buf[0], buf[3]
    try:
        buf = ErrorBuffer()
        assert False
    except Exception:
        print buf[0], buf[3]

@testcase
def acquire_failure3():
    """
    >>> acquire_failure3()
    acquired working
    0 3
    released working
    acquired working
    0 3
    released working
    """
    cdef object[int] buf
    buf = IntMockBuffer("working", range(4))
    print buf[0], buf[3]
    try:
        buf = 3
        assert False
    except Exception:
        print buf[0], buf[3]

@testcase
def acquire_failure4():
    """
    >>> acquire_failure4()
    acquired working
    0 3
    released working
    acquired working
    0 3
    released working
    """
    cdef object[int] buf = IntMockBuffer("working", range(4))
    print buf[0], buf[3]
    try:
        buf = 2
        assert False
    except Exception:
        print buf[0], buf[3]

@testcase
def acquire_failure5():
    """
    >>> acquire_failure5()
    Traceback (most recent call last):
       ...
    ValueError: Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!
    """
    cdef object[int] buf
    buf = IntMockBuffer("working", range(4))
    buf.fail = True
    buf = 3


@testcase
def acquire_nonbuffer1(first, second=None):
    """
    >>> acquire_nonbuffer1(3)
    Traceback (most recent call last):
      ...
    TypeError: 'int' does not have the buffer interface
    >>> acquire_nonbuffer1(type)
    Traceback (most recent call last):
      ...
    TypeError: 'type' does not have the buffer interface
    >>> acquire_nonbuffer1(None, 2)
    Traceback (most recent call last):
      ...
    TypeError: 'int' does not have the buffer interface
    """
    cdef object[int] buf
    buf = first
    buf = second

@testcase
def acquire_nonbuffer2():
    """
    >>> acquire_nonbuffer2()
    acquired working
    0 3
    released working
    acquired working
    0 3
    released working
    """
    cdef object[int] buf = IntMockBuffer("working", range(4))
    print buf[0], buf[3]
    try:
        buf = ErrorBuffer
        assert False
    except Exception:
        print buf[0], buf[3]


227 228 229
@testcase
def as_argument(object[int] bufarg, int n):
    """
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
230
    >>> A = IntMockBuffer("A", range(6))
231 232
    >>> as_argument(A, 6)
    acquired A
233
    0 1 2 3 4 5 END
234
    released A
235 236 237 238
    """
    cdef int i
    for i in range(n):
        print bufarg[i],
239
    print 'END'
240 241 242 243

@testcase
def as_argument_defval(object[int] bufarg=IntMockBuffer('default', range(6)), int n=6):
    """
244
    >>> as_argument_defval()
245
    acquired default
246
    0 1 2 3 4 5 END
247
    released default
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
248
    >>> A = IntMockBuffer("A", range(6))
249 250
    >>> as_argument_defval(A, 6)
    acquired A
251
    0 1 2 3 4 5 END
252
    released A
253
    """
254
    cdef int i
255 256
    for i in range(n):
        print bufarg[i],
257
    print 'END'
258

259 260 261
@testcase
def cdef_assignment(obj, n):
    """
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
262
    >>> A = IntMockBuffer("A", range(6))
263 264
    >>> cdef_assignment(A, 6)
    acquired A
265
    0 1 2 3 4 5 END
266
    released A
267

268 269 270 271 272
    """
    cdef object[int] buf = obj
    cdef int i
    for i in range(n):
        print buf[i],
273
    print 'END'
274

275 276 277
@testcase
def forin_assignment(objs, int pick):
    """
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
278 279
    >>> A = IntMockBuffer("A", range(6))
    >>> B = IntMockBuffer("B", range(6))
280 281 282 283 284 285 286
    >>> forin_assignment([A, B, A, A], 2)
    acquired A
    2
    released A
    acquired B
    2
    released B
287
    acquired A
288 289 290 291
    2
    released A
    acquired A
    2
292
    released A
293 294 295 296 297 298 299 300
    """
    cdef object[int] buf
    for buf in objs:
        print buf[pick]

@testcase
def cascaded_buffer_assignment(obj):
    """
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
301
    >>> A = IntMockBuffer("A", range(6))
302 303 304 305 306 307 308 309 310 311 312 313
    >>> cascaded_buffer_assignment(A)
    acquired A
    acquired A
    released A
    released A
    """
    cdef object[int] a, b
    a = b = obj

@testcase
def tuple_buffer_assignment1(a, b):
    """
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
314 315
    >>> A = IntMockBuffer("A", range(6))
    >>> B = IntMockBuffer("B", range(6))
316 317
    >>> tuple_buffer_assignment1(A, B)
    acquired A
318
    acquired B
319
    released A
320
    released B
321 322 323
    """
    cdef object[int] x, y
    x, y = a, b
324

325 326 327
@testcase
def tuple_buffer_assignment2(tup):
    """
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
328 329
    >>> A = IntMockBuffer("A", range(6))
    >>> B = IntMockBuffer("B", range(6))
330 331 332 333 334 335 336 337
    >>> tuple_buffer_assignment2((A, B))
    acquired A
    acquired B
    released A
    released B
    """
    cdef object[int] x, y
    x, y = tup
338 339 340 341 342 343 344 345 346 347 348 349 350 351

@testcase
def explicitly_release_buffer():
    """
    >>> explicitly_release_buffer()
    acquired A
    released A
    After release
    """
    cdef object[int] x = IntMockBuffer("A", range(10))
    x = None
    print "After release"

#
352
# Getting items and index bounds checking
353
#
354
@testcase
355
def get_int_2d(object[int, ndim=2] buf, int i, int j):
356
    """
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
357
    >>> C = IntMockBuffer("C", range(6), (2,3))
358
    >>> get_int_2d(C, 1, 1)
359 360
    acquired C
    released C
361
    4
362 363

    Check negative indexing:
364
    >>> get_int_2d(C, -1, 0)
365 366
    acquired C
    released C
367 368
    3
    >>> get_int_2d(C, -1, -2)
369 370
    acquired C
    released C
371 372
    4
    >>> get_int_2d(C, -2, -3)
373 374
    acquired C
    released C
375 376
    0

377
    Out-of-bounds errors:
378 379 380
    >>> get_int_2d(C, 2, 0)
    Traceback (most recent call last):
        ...
381 382 383 384 385
    IndexError: Out of bounds on buffer access (axis 0)
    >>> get_int_2d(C, 0, -4)
    Traceback (most recent call last):
        ...
    IndexError: Out of bounds on buffer access (axis 1)
386 387
    """
    return buf[i, j]
388

389
@testcase
390
def get_int_2d_uintindex(object[int, ndim=2] buf, unsigned int i, unsigned int j):
391 392
    """
    Unsigned indexing:
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
393
    >>> C = IntMockBuffer("C", range(6), (2,3))
394 395 396 397 398 399 400 401
    >>> get_int_2d_uintindex(C, 0, 0)
    acquired C
    released C
    0
    >>> get_int_2d_uintindex(C, 1, 2)
    acquired C
    released C
    5
402 403 404 405
    """
    # This is most interesting with regards to the C code
    # generated.
    return buf[i, j]
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
406

407
@testcase
408
def set_int_2d(object[int, ndim=2] buf, int i, int j, int value):
409 410 411
    """
    Uses get_int_2d to read back the value afterwards. For pure
    unit test, one should support reading in MockBuffer instead.
412

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
413
    >>> C = IntMockBuffer("C", range(6), (2,3))
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    >>> set_int_2d(C, 1, 1, 10)
    acquired C
    released C
    >>> get_int_2d(C, 1, 1)
    acquired C
    released C
    10

    Check negative indexing:
    >>> set_int_2d(C, -1, 0, 3)
    acquired C
    released C
    >>> get_int_2d(C, -1, 0)
    acquired C
    released C
    3

    >>> set_int_2d(C, -1, -2, 8)
    acquired C
    released C
    >>> get_int_2d(C, -1, -2)
    acquired C
    released C
    8
438

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    >>> set_int_2d(C, -2, -3, 9)
    acquired C
    released C
    >>> get_int_2d(C, -2, -3)
    acquired C
    released C
    9

    Out-of-bounds errors:
    >>> set_int_2d(C, 2, 0, 19)
    Traceback (most recent call last):
        ...
    IndexError: Out of bounds on buffer access (axis 0)
    >>> set_int_2d(C, 0, -4, 19)
    Traceback (most recent call last):
        ...
    IndexError: Out of bounds on buffer access (axis 1)
456

457 458
    """
    buf[i, j] = value
459

460 461 462 463 464 465 466
@testcase
def list_comprehension(object[int] buf, len):
    """
    >>> list_comprehension(IntMockBuffer(None, [1,2,3]), 3)
    1|2|3
    """
    cdef int i
467
    print u"|".join([unicode(buf[i]) for i in range(len)])
468

469 470 471 472 473 474 475 476
#
# The negative_indices buffer option
#
@testcase
def no_negative_indices(object[int, negative_indices=False] buf, int idx):
    """
    The most interesting thing here is to inspect the C source and
    make sure optimal code is produced.
477

478 479 480 481 482 483 484 485 486 487
    >>> A = IntMockBuffer(None, range(6))
    >>> no_negative_indices(A, 3)
    3
    >>> no_negative_indices(A, -1)
    Traceback (most recent call last):
        ...
    IndexError: Out of bounds on buffer access (axis 0)
    """
    return buf[idx]

488
@testcase
489 490
@cython.wraparound(False)
def wraparound_directive(object[int] buf, int pos_idx, int neg_idx):
491
    """
492
    Again, the most interesting thing here is to inspect the C source.
493

494 495 496 497
    >>> A = IntMockBuffer(None, range(4))
    >>> wraparound_directive(A, 2, -1)
    5
    >>> wraparound_directive(A, -1, 2)
498 499
    Traceback (most recent call last):
        ...
500
    IndexError: Out of bounds on buffer access (axis 0)
501
    """
502 503 504 505
    cdef int byneg
    with cython.wraparound(True):
        byneg = buf[neg_idx]
    return buf[pos_idx] + byneg
506 507


508 509 510 511 512 513 514 515 516 517 518
#
# Test which flags are passed.
#
@testcase
def readonly(obj):
    """
    >>> R = UnsignedShortMockBuffer("R", range(27), shape=(3, 3, 3))
    >>> readonly(R)
    acquired R
    25
    released R
519
    >>> [str(x) for x in R.recieved_flags]  # Works in both py2 and py3
520 521
    ['FORMAT', 'INDIRECT', 'ND', 'STRIDES']
    """
522
    cdef object[unsigned short int, ndim=3] buf = obj
523 524 525 526 527 528 529 530 531
    print buf[2, 2, 1]

@testcase
def writable(obj):
    """
    >>> R = UnsignedShortMockBuffer("R", range(27), shape=(3, 3, 3))
    >>> writable(R)
    acquired R
    released R
532
    >>> [str(x) for x in R.recieved_flags] # Py2/3
533 534
    ['FORMAT', 'INDIRECT', 'ND', 'STRIDES', 'WRITABLE']
    """
535
    cdef object[unsigned short int, ndim=3] buf = obj
536 537
    buf[2, 2, 1] = 23

538
@testcase
539
def strided(object[int, ndim=1, mode='strided'] buf):
540 541 542 543 544 545
    """
    >>> A = IntMockBuffer("A", range(4))
    >>> strided(A)
    acquired A
    released A
    2
546
    >>> [str(x) for x in A.recieved_flags] # Py2/3
547
    ['FORMAT', 'ND', 'STRIDES']
548 549 550 551

    Check that the suboffsets were patched back prior to release.
    >>> A.release_ok
    True
552 553 554
    """
    return buf[2]

555 556 557 558 559 560 561 562 563 564
@testcase
def c_contig(object[int, ndim=1, mode='c'] buf):
    """
    >>> A = IntMockBuffer(None, range(4))
    >>> c_contig(A)
    2
    >>> [str(x) for x in A.recieved_flags]
    ['FORMAT', 'ND', 'STRIDES', 'C_CONTIGUOUS']
    """
    return buf[2]
565

566 567 568 569
@testcase
def c_contig_2d(object[int, ndim=2, mode='c'] buf):
    """
    Multi-dim has seperate implementation
570

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    >>> A = IntMockBuffer(None, range(12), shape=(3,4))
    >>> c_contig_2d(A)
    7
    >>> [str(x) for x in A.recieved_flags]
    ['FORMAT', 'ND', 'STRIDES', 'C_CONTIGUOUS']
    """
    return buf[1, 3]

@testcase
def f_contig(object[int, ndim=1, mode='fortran'] buf):
    """
    >>> A = IntMockBuffer(None, range(4))
    >>> f_contig(A)
    2
    >>> [str(x) for x in A.recieved_flags]
    ['FORMAT', 'ND', 'STRIDES', 'F_CONTIGUOUS']
    """
    return buf[2]

@testcase
def f_contig_2d(object[int, ndim=2, mode='fortran'] buf):
    """
    Must set up strides manually to ensure Fortran ordering.
594

595 596 597 598 599 600 601 602
    >>> A = IntMockBuffer(None, range(12), shape=(4,3), strides=(1, 4))
    >>> f_contig_2d(A)
    7
    >>> [str(x) for x in A.recieved_flags]
    ['FORMAT', 'ND', 'STRIDES', 'F_CONTIGUOUS']
    """
    return buf[3, 1]

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
#
# Test compiler options for bounds checking. We create an array with a
# safe "boundary" (memory
# allocated outside of what it published) and then check whether we get back
# what we stored in the memory or an error.

@testcase
def safe_get(object[int] buf, int idx):
    """
    >>> A = IntMockBuffer(None, range(10), shape=(3,), offset=5)

    Validate our testing buffer...
    >>> safe_get(A, 0)
    5
    >>> safe_get(A, 2)
    7
    >>> safe_get(A, -3)
    5

    Access outside it. This is already done above for bounds check
    testing but we include it to tell the story right.
624

625 626 627 628 629 630 631 632 633 634 635 636
    >>> safe_get(A, -4)
    Traceback (most recent call last):
        ...
    IndexError: Out of bounds on buffer access (axis 0)
    >>> safe_get(A, 3)
    Traceback (most recent call last):
        ...
    IndexError: Out of bounds on buffer access (axis 0)
    """
    return buf[idx]

@testcase
637
@cython.boundscheck(False) # outer decorators should take precedence
638
@cython.boundscheck(True)
639 640 641 642 643 644 645 646 647 648 649 650 651
def unsafe_get(object[int] buf, int idx):
    """
    Access outside of the area the buffer publishes.
    >>> A = IntMockBuffer(None, range(10), shape=(3,), offset=5)
    >>> unsafe_get(A, -4)
    4
    >>> unsafe_get(A, -5)
    3
    >>> unsafe_get(A, 3)
    8
    """
    return buf[idx]

652 653 654 655 656
@testcase
@cython.boundscheck(False)
def unsafe_get_nonegative(object[int, negative_indices=False] buf, int idx):
    """
    Also inspect the C source to see that it is optimal...
657

658 659 660 661 662 663
    >>> A = IntMockBuffer(None, range(10), shape=(3,), offset=5)
    >>> unsafe_get_nonegative(A, -2)
    3
    """
    return buf[idx]

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
@testcase
def mixed_get(object[int] buf, int unsafe_idx, int safe_idx):
    """
    >>> A = IntMockBuffer(None, range(10), shape=(3,), offset=5)
    >>> mixed_get(A, -4, 0)
    (4, 5)
    >>> mixed_get(A, 0, -4)
    Traceback (most recent call last):
        ...
    IndexError: Out of bounds on buffer access (axis 0)
    """
    with cython.boundscheck(False):
        one = buf[unsafe_idx]
    with cython.boundscheck(True):
        two = buf[safe_idx]
    return (one, two)
680

681 682 683 684 685 686
#
# Coercions
#
@testcase
def coercions(object[unsigned char] uc):
    """
687
TODO
688 689 690 691 692 693
    """
    print type(uc[0])
    uc[0] = -1
    print uc[0]
    uc[0] = <int>3.14
    print uc[0]
694

Stefan Behnel's avatar
Stefan Behnel committed
695
    cdef char* ch = b"asfd"
696 697 698
    cdef object[object] objbuf
    objbuf[3] = ch

699 700 701 702 703 704

#
# Testing that accessing data using various types of buffer access
# all works.
#

705 706 707 708 709 710 711
def printbuf_int(object[int] buf, shape):
    # Utility func
    cdef int i
    for i in range(shape[0]):
        print buf[i],
    print 'END'

712 713 714 715 716

@testcase
def printbuf_int_2d(o, shape):
    """
    Strided:
717

718 719
    >>> printbuf_int_2d(IntMockBuffer("A", range(6), (2,3)), (2,3))
    acquired A
720 721
    0 1 2 END
    3 4 5 END
722 723 724
    released A
    >>> printbuf_int_2d(IntMockBuffer("A", range(100), (3,3), strides=(20,5)), (3,3))
    acquired A
725 726 727
    0 5 10 END
    20 25 30 END
    40 45 50 END
728 729 730 731 732
    released A

    Indirect:
    >>> printbuf_int_2d(IntMockBuffer("A", [[1,2],[3,4]]), (2,2))
    acquired A
733 734
    1 2 END
    3 4 END
735 736 737
    released A
    """
    # should make shape builtin
738
    cdef object[int, ndim=2] buf
739 740 741 742 743
    buf = o
    cdef int i, j
    for i in range(shape[0]):
        for j in range(shape[1]):
            print buf[i, j],
744
        print 'END'
745

746
@testcase
747
def printbuf_float(o, shape):
748 749 750
    """
    >>> printbuf_float(FloatMockBuffer("F", [1.0, 1.25, 0.75, 1.0]), (4,))
    acquired F
751
    1.0 1.25 0.75 1.0 END
752 753 754
    released F
    """

755
    # should make shape builtin
756 757 758 759 760
    cdef object[float] buf
    buf = o
    cdef int i, j
    for i in range(shape[0]):
        print buf[i],
761
    print "END"
762 763


764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
#
# Test assignments
#
@testcase
def inplace_operators(object[int] buf):
    """
    >>> buf = IntMockBuffer(None, [2, 2])
    >>> inplace_operators(buf)
    >>> printbuf_int(buf, (2,))
    0 3 END
    """
    cdef int j = 0
    buf[1] += 1
    buf[j] *= 2
    buf[0] -= 4



782 783 784
#
# Typedefs
#
785 786 787 788
# Test three layers of typedefs going through a h file for plain int, and
# simply a header file typedef for floats and unsigned.

ctypedef int td_cy_int
789
cdef extern from "bufaccess.h":
790 791 792 793
    ctypedef td_cy_int td_h_short # Defined as short, but Cython doesn't know this!
    ctypedef float td_h_double # Defined as double
    ctypedef unsigned int td_h_ushort # Defined as unsigned short
ctypedef td_h_short td_h_cy_short
794 795

@testcase
796
def printbuf_td_cy_int(object[td_cy_int] buf, shape):
797
    """
798
    >>> printbuf_td_cy_int(IntMockBuffer(None, range(3)), (3,))
799
    0 1 2 END
800
    >>> printbuf_td_cy_int(ShortMockBuffer(None, range(3)), (3,))
801 802
    Traceback (most recent call last):
       ...
803
    ValueError: Buffer dtype mismatch, expected 'td_cy_int' but got 'short'
804 805 806 807
    """
    cdef int i
    for i in range(shape[0]):
        print buf[i],
808
    print 'END'
809 810

@testcase
811
def printbuf_td_h_short(object[td_h_short] buf, shape):
812
    """
813
    >>> printbuf_td_h_short(ShortMockBuffer(None, range(3)), (3,))
814
    0 1 2 END
815
    >>> printbuf_td_h_short(IntMockBuffer(None, range(3)), (3,))
816 817
    Traceback (most recent call last):
       ...
818
    ValueError: Buffer dtype mismatch, expected 'td_h_short' but got 'int'
819
    """
820 821 822
    cdef int i
    for i in range(shape[0]):
        print buf[i],
823
    print 'END'
824 825

@testcase
826
def printbuf_td_h_cy_short(object[td_h_cy_short] buf, shape):
827
    """
828
    >>> printbuf_td_h_cy_short(ShortMockBuffer(None, range(3)), (3,))
829
    0 1 2 END
830
    >>> printbuf_td_h_cy_short(IntMockBuffer(None, range(3)), (3,))
831 832
    Traceback (most recent call last):
       ...
833
    ValueError: Buffer dtype mismatch, expected 'td_h_cy_short' but got 'int'
834 835 836 837
    """
    cdef int i
    for i in range(shape[0]):
        print buf[i],
838
    print 'END'
839

840 841 842 843 844 845 846 847
@testcase
def printbuf_td_h_ushort(object[td_h_ushort] buf, shape):
    """
    >>> printbuf_td_h_ushort(UnsignedShortMockBuffer(None, range(3)), (3,))
    0 1 2 END
    >>> printbuf_td_h_ushort(ShortMockBuffer(None, range(3)), (3,))
    Traceback (most recent call last):
       ...
848
    ValueError: Buffer dtype mismatch, expected 'td_h_ushort' but got 'short'
849 850 851 852 853 854 855 856 857 858 859 860 861 862
    """
    cdef int i
    for i in range(shape[0]):
        print buf[i],
    print 'END'

@testcase
def printbuf_td_h_double(object[td_h_double] buf, shape):
    """
    >>> printbuf_td_h_double(DoubleMockBuffer(None, [0.25, 1, 3.125]), (3,))
    0.25 1.0 3.125 END
    >>> printbuf_td_h_double(FloatMockBuffer(None, [0.25, 1, 3.125]), (3,))
    Traceback (most recent call last):
       ...
863
    ValueError: Buffer dtype mismatch, expected 'td_h_double' but got 'float'
864 865 866 867 868 869 870
    """
    cdef int i
    for i in range(shape[0]):
        print buf[i],
    print 'END'


871 872 873 874 875 876 877 878 879
#
# Object access
#
def addref(*args):
    for item in args: Py_INCREF(item)
def decref(*args):
    for item in args: Py_DECREF(item)

def get_refcount(x):
Robert Bradshaw's avatar
Robert Bradshaw committed
880
    return (<PyObject*>x).ob_refcnt
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902

@testcase
def printbuf_object(object[object] buf, shape):
    """
    Only play with unique objects, interned numbers etc. will have
    unpredictable refcounts.

    ObjectMockBuffer doesn't do anything about increfing/decrefing,
    we to the "buffer implementor" refcounting directly in the
    testcase.

    >>> a, b, c = "globally_unique_string_23234123", {4:23}, [34,3]
    >>> get_refcount(a), get_refcount(b), get_refcount(c)
    (2, 2, 2)
    >>> A = ObjectMockBuffer(None, [a, b, c])
    >>> printbuf_object(A, (3,))
    'globally_unique_string_23234123' 2
    {4: 23} 2
    [34, 3] 2
    """
    cdef int i
    for i in range(shape[0]):
Robert Bradshaw's avatar
Robert Bradshaw committed
903
        print repr(buf[i]), (<PyObject*>buf[i]).ob_refcnt
904 905 906 907 908 909 910 911 912 913

@testcase
def assign_to_object(object[object] buf, int idx, obj):
    """
    See comments on printbuf_object above.

    >>> a, b = [1, 2, 3], [4, 5, 6]
    >>> get_refcount(a), get_refcount(b)
    (2, 2)
    >>> addref(a)
914
    >>> A = ObjectMockBuffer(None, [1, a]) # 1, ...,otherwise it thinks nested lists...
915 916 917 918 919 920 921 922
    >>> get_refcount(a), get_refcount(b)
    (3, 2)
    >>> assign_to_object(A, 1, b)
    >>> get_refcount(a), get_refcount(b)
    (2, 3)
    >>> decref(b)
    """
    buf[idx] = obj
923

924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
@testcase
def assign_temporary_to_object(object[object] buf):
    """
    See comments on printbuf_object above.

    >>> a, b = [1, 2, 3], {4:23}
    >>> get_refcount(a)
    2
    >>> addref(a)
    >>> A = ObjectMockBuffer(None, [b, a])
    >>> get_refcount(a)
    3
    >>> assign_temporary_to_object(A)
    >>> get_refcount(a)
    2
939

940 941 942 943 944 945 946 947 948 949 950
    >>> printbuf_object(A, (2,))
    {4: 23} 2
    {1: 8} 2

    To avoid leaking a reference in our testcase we need to
    replace the temporary with something we can manually decref :-)
    >>> assign_to_object(A, 1, a)
    >>> decref(a)
    """
    buf[1] = {3-2: 2+(2*4)-2}

951 952 953 954 955 956 957
#
# cast option
#
@testcase
def buffer_cast(object[unsigned int, cast=True] buf, int idx):
    """
    Round-trip a signed int through unsigned int buffer access.
958

959 960 961 962 963 964
    >>> A = IntMockBuffer(None, [-100])
    >>> buffer_cast(A, 0)
    -100
    """
    cdef unsigned int data = buf[idx]
    return <int>data
965

966 967 968 969
@testcase
def buffer_cast_fails(object[char, cast=True] buf):
    """
    Cannot cast between datatype of different sizes.
970

971 972 973
    >>> buffer_cast_fails(IntMockBuffer(None, [0]))
    Traceback (most recent call last):
        ...
974
    ValueError: Item size of buffer (4 bytes) does not match size of 'char' (1 byte)
975 976
    """
    return buf[0]
977

978 979

#
980
# Testcase support code (more tests below!, because of scope rules)
981 982 983
#


984
available_flags = (
985 986 987 988 989 990 991
    ('FORMAT', cpython.buffer.PyBUF_FORMAT),
    ('INDIRECT', cpython.buffer.PyBUF_INDIRECT),
    ('ND', cpython.buffer.PyBUF_ND),
    ('STRIDES', cpython.buffer.PyBUF_STRIDES),
    ('C_CONTIGUOUS', cpython.buffer.PyBUF_C_CONTIGUOUS),
    ('F_CONTIGUOUS', cpython.buffer.PyBUF_F_CONTIGUOUS),
    ('WRITABLE', cpython.buffer.PyBUF_WRITABLE)
992 993
)

994
cdef class MockBuffer:
995
    cdef object format, offset
996
    cdef void* buffer
997 998 999
    cdef int len, itemsize, ndim
    cdef Py_ssize_t* strides
    cdef Py_ssize_t* shape
1000
    cdef Py_ssize_t* suboffsets
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1001
    cdef object label, log
1002

1003
    cdef readonly object recieved_flags, release_ok
1004
    cdef public object fail
1005

1006
    def __init__(self, label, data, shape=None, strides=None, format=None, offset=0):
1007 1008
        # It is important not to store references to data after the constructor
        # as refcounting is checked on object buffers.
1009
        self.label = label
1010
        self.release_ok = True
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1011
        self.log = ""
1012
        self.offset = offset
1013 1014
        self.itemsize = self.get_itemsize()
        if format is None: format = self.get_default_format()
1015 1016 1017 1018
        if shape is None: shape = (len(data),)
        if strides is None:
            strides = []
            cumprod = 1
1019 1020 1021
            rshape = list(shape)
            rshape.reverse()
            for s in rshape:
1022 1023 1024 1025
                strides.append(cumprod)
                cumprod *= s
            strides.reverse()
        strides = [x * self.itemsize for x in strides]
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
        suboffsets = [-1] * len(shape)
        datashape = [len(data)]
        p = data
        while True:
            p = p[0]
            if isinstance(p, list): datashape.append(len(p))
            else: break
        if len(datashape) > 1:
            # indirect access
            self.ndim = len(datashape)
            shape = datashape
            self.buffer = self.create_indirect_buffer(data, shape)
1038 1039
            suboffsets = [0] * (self.ndim-1) + [-1]
            strides = [sizeof(void*)] * (self.ndim-1) + [self.itemsize]
1040 1041 1042 1043 1044 1045
            self.suboffsets = self.list_to_sizebuf(suboffsets)
        else:
            # strided and/or simple access
            self.buffer = self.create_buffer(data)
            self.ndim = len(shape)
            self.suboffsets = NULL
Stefan Behnel's avatar
Stefan Behnel committed
1046 1047 1048 1049 1050

        try:
            format = format.encode('ASCII')
        except AttributeError:
            pass
1051 1052
        self.format = format
        self.len = len(data) * self.itemsize
1053 1054 1055

        self.strides = self.list_to_sizebuf(strides)
        self.shape = self.list_to_sizebuf(shape)
1056

1057 1058 1059
    def __dealloc__(self):
        stdlib.free(self.strides)
        stdlib.free(self.shape)
1060 1061 1062 1063 1064
        if self.suboffsets != NULL:
            stdlib.free(self.suboffsets)
            # must recursively free indirect...
        else:
            stdlib.free(self.buffer)
1065

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    cdef void* create_buffer(self, data):
        cdef char* buf = <char*>stdlib.malloc(len(data) * self.itemsize)
        cdef char* it = buf
        for value in data:
            self.write(it, value)
            it += self.itemsize
        return buf

    cdef void* create_indirect_buffer(self, data, shape):
        cdef void** buf
        assert shape[0] == len(data)
        if len(shape) == 1:
            return self.create_buffer(data)
        else:
            shape = shape[1:]
            buf = <void**>stdlib.malloc(len(data) * sizeof(void*))
            for idx, subdata in enumerate(data):
                buf[idx] = self.create_indirect_buffer(subdata, shape)
            return buf

    cdef Py_ssize_t* list_to_sizebuf(self, l):
        cdef Py_ssize_t* buf = <Py_ssize_t*>stdlib.malloc(len(l) * sizeof(Py_ssize_t))
        for i, x in enumerate(l):
            buf[i] = x
        return buf

1092
    def __getbuffer__(MockBuffer self, Py_buffer* buffer, int flags):
1093 1094
        if self.fail:
            raise ValueError("Failing on purpose")
1095 1096

        self.recieved_flags = []
1097
        cdef int value
1098 1099 1100
        for name, value in available_flags:
            if (value & flags) == value:
                self.recieved_flags.append(name)
1101

1102
        buffer.buf = <void*>(<char*>self.buffer + (<int>self.offset * self.itemsize))
1103
        buffer.obj = self
1104 1105 1106 1107 1108 1109
        buffer.len = self.len
        buffer.readonly = 0
        buffer.format = <char*>self.format
        buffer.ndim = self.ndim
        buffer.shape = self.shape
        buffer.strides = self.strides
1110
        buffer.suboffsets = self.suboffsets
1111 1112
        buffer.itemsize = self.itemsize
        buffer.internal = NULL
1113 1114 1115 1116
        if self.label:
            msg = "acquired %s" % self.label
            print msg
            self.log += msg + "\n"
1117 1118

    def __releasebuffer__(MockBuffer self, Py_buffer* buffer):
1119 1120
        if buffer.suboffsets != self.suboffsets:
            self.release_ok = False
1121 1122
        if self.label:
            msg = "released %s" % self.label
1123
            print msg
1124
            self.log += msg + "\n"
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1125 1126

    def printlog(self):
1127
        print self.log[:-1]
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1128 1129 1130

    def resetlog(self):
        self.log = ""
1131 1132 1133 1134 1135 1136

    cdef int write(self, char* buf, object value) except -1: raise Exception()
    cdef get_itemsize(self):
        print "ERROR, not subclassed", self.__class__
    cdef get_default_format(self):
        print "ERROR, not subclassed", self.__class__
1137

1138 1139 1140 1141 1142 1143 1144
cdef class CharMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        (<char*>buf)[0] = <int>value
        return 0
    cdef get_itemsize(self): return sizeof(char)
    cdef get_default_format(self): return b"@b"

1145 1146 1147 1148 1149
cdef class IntMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        (<int*>buf)[0] = <int>value
        return 0
    cdef get_itemsize(self): return sizeof(int)
1150
    cdef get_default_format(self): return b"@i"
1151

1152 1153 1154 1155 1156 1157 1158
cdef class UnsignedIntMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        (<unsigned int*>buf)[0] = <unsigned int>value
        return 0
    cdef get_itemsize(self): return sizeof(unsigned int)
    cdef get_default_format(self): return b"@I"

1159 1160 1161 1162 1163
cdef class ShortMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        (<short*>buf)[0] = <short>value
        return 0
    cdef get_itemsize(self): return sizeof(short)
1164
    cdef get_default_format(self): return b"h" # Try without endian specifier
1165

1166 1167 1168 1169 1170
cdef class UnsignedShortMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        (<unsigned short*>buf)[0] = <unsigned short>value
        return 0
    cdef get_itemsize(self): return sizeof(unsigned short)
1171
    cdef get_default_format(self): return b"@1H" # Try with repeat count
1172

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
cdef class FloatMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        (<float*>buf)[0] = <float>value
        return 0
    cdef get_itemsize(self): return sizeof(float)
    cdef get_default_format(self): return b"f"

cdef class DoubleMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        (<double*>buf)[0] = <double>value
        return 0
    cdef get_itemsize(self): return sizeof(double)
    cdef get_default_format(self): return b"d"

1187 1188 1189 1190 1191 1192 1193 1194 1195
cdef extern from *:
    void* addr_of_pyobject "(void*)"(object)

cdef class ObjectMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        (<void**>buf)[0] = addr_of_pyobject(value)
        return 0

    cdef get_itemsize(self): return sizeof(void*)
1196
    cdef get_default_format(self): return b"@O"
1197

1198

1199
cdef class IntStridedMockBuffer(IntMockBuffer):
1200
    cdef __cythonbufferdefaults__ = {"mode" : "strided"}
1201

1202 1203
cdef class ErrorBuffer:
    cdef object label
1204

1205 1206 1207
    def __init__(self, label):
        self.label = label

Andrew Straw's avatar
Andrew Straw committed
1208
    def __getbuffer__(ErrorBuffer self, Py_buffer* buffer, int flags):
1209 1210
        raise Exception("acquiring %s" % self.label)

Andrew Straw's avatar
Andrew Straw committed
1211
    def __releasebuffer__(ErrorBuffer self, Py_buffer* buffer):
1212
        raise Exception("releasing %s" % self.label)
1213

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
#
# Typed buffers
#
@testcase
def typedbuffer1(obj):
    """
    >>> typedbuffer1(IntMockBuffer("A", range(10)))
    acquired A
    released A
    >>> typedbuffer1(None)
    >>> typedbuffer1(4)
    Traceback (most recent call last):
       ...
    TypeError: Cannot convert int to bufaccess.IntMockBuffer
    """
1229
    cdef IntMockBuffer[int, ndim=1] buf = obj
1230 1231

@testcase
1232
def typedbuffer2(IntMockBuffer[int, ndim=1] obj):
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    """
    >>> typedbuffer2(IntMockBuffer("A", range(10)))
    acquired A
    released A
    >>> typedbuffer2(None)
    >>> typedbuffer2(4)
    Traceback (most recent call last):
       ...
    TypeError: Argument 'obj' has incorrect type (expected bufaccess.IntMockBuffer, got int)
    """
    pass

#
# Test __cythonbufferdefaults__
#
@testcase
1249
def bufdefaults1(IntStridedMockBuffer[int, ndim=1] buf):
1250
    """
1251 1252 1253
    For IntStridedMockBuffer, mode should be
    "strided" by defaults which should show
    up in the flags.
1254

1255 1256 1257 1258
    >>> A = IntStridedMockBuffer("A", range(10))
    >>> bufdefaults1(A)
    acquired A
    released A
1259
    >>> [str(x) for x in A.recieved_flags]
1260 1261 1262
    ['FORMAT', 'ND', 'STRIDES']
    """
    pass
1263

1264

1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
#
# Structs
#
cdef struct MyStruct:
    char a
    char b
    long long int c
    int d
    int e

1275 1276 1277 1278 1279 1280 1281 1282 1283
cdef struct SmallStruct:
    int a
    int b

cdef struct NestedStruct:
    SmallStruct x
    SmallStruct y
    int z

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
cdef packed struct PackedStruct:
    char a
    int b

cdef struct NestedPackedStruct:
    char a
    int b
    PackedStruct sub
    int c

1294 1295 1296 1297 1298 1299
cdef class MyStructMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        cdef MyStruct* s
        s = <MyStruct*>buf;
        s.a, s.b, s.c, s.d, s.e = value
        return 0
1300

1301 1302 1303
    cdef get_itemsize(self): return sizeof(MyStruct)
    cdef get_default_format(self): return b"2bq2i"

1304 1305 1306 1307 1308 1309
cdef class NestedStructMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        cdef NestedStruct* s
        s = <NestedStruct*>buf;
        s.x.a, s.x.b, s.y.a, s.y.b, s.z = value
        return 0
1310

1311 1312 1313
    cdef get_itemsize(self): return sizeof(NestedStruct)
    cdef get_default_format(self): return b"2T{ii}i"

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
cdef class PackedStructMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        cdef PackedStruct* s
        s = <PackedStruct*>buf;
        s.a, s.b = value
        return 0

    cdef get_itemsize(self): return sizeof(PackedStruct)
    cdef get_default_format(self): return b"^ci"

cdef class NestedPackedStructMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        cdef NestedPackedStruct* s
        s = <NestedPackedStruct*>buf;
        s.a, s.b, s.sub.a, s.sub.b, s.c = value
        return 0

    cdef get_itemsize(self): return sizeof(NestedPackedStruct)
    cdef get_default_format(self): return b"ci^ci@i"

1334 1335 1336
@testcase
def basic_struct(object[MyStruct] buf):
    """
1337
    See also buffmt.pyx
1338

1339
    >>> basic_struct(MyStructMockBuffer(None, [(1, 2, 3, 4, 5)]))
1340 1341 1342
    1 2 3 4 5
    >>> basic_struct(MyStructMockBuffer(None, [(1, 2, 3, 4, 5)], format="bbqii"))
    1 2 3 4 5
1343 1344 1345
    """
    print buf[0].a, buf[0].b, buf[0].c, buf[0].d, buf[0].e

1346 1347 1348
@testcase
def nested_struct(object[NestedStruct] buf):
    """
1349
    See also buffmt.pyx
1350

1351 1352 1353 1354 1355 1356 1357
    >>> nested_struct(NestedStructMockBuffer(None, [(1, 2, 3, 4, 5)]))
    1 2 3 4 5
    >>> nested_struct(NestedStructMockBuffer(None, [(1, 2, 3, 4, 5)], format="T{ii}T{2i}i"))
    1 2 3 4 5
    """
    print buf[0].x.a, buf[0].x.b, buf[0].y.a, buf[0].y.b, buf[0].z

1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
@testcase
def packed_struct(object[PackedStruct] buf):
    """
    See also buffmt.pyx

    >>> packed_struct(PackedStructMockBuffer(None, [(1, 2)]))
    1 2
    >>> packed_struct(PackedStructMockBuffer(None, [(1, 2)], format="T{c^i}"))
    1 2
    >>> packed_struct(PackedStructMockBuffer(None, [(1, 2)], format="T{c=i}"))
    1 2

    """
    print buf[0].a, buf[0].b

@testcase
def nested_packed_struct(object[NestedPackedStruct] buf):
    """
    See also buffmt.pyx

    >>> nested_packed_struct(NestedPackedStructMockBuffer(None, [(1, 2, 3, 4, 5)]))
    1 2 3 4 5
    >>> nested_packed_struct(NestedPackedStructMockBuffer(None, [(1, 2, 3, 4, 5)], format="ci^ci@i"))
    1 2 3 4 5
    >>> nested_packed_struct(NestedPackedStructMockBuffer(None, [(1, 2, 3, 4, 5)], format="^c@i^ci@i"))
    1 2 3 4 5
    """
    print buf[0].a, buf[0].b, buf[0].sub.a, buf[0].sub.b, buf[0].c

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
cdef struct LongComplex:
    long double real
    long double imag

cdef class LongComplexMockBuffer(MockBuffer):
    cdef int write(self, char* buf, object value) except -1:
        cdef LongComplex* s
        s = <LongComplex*>buf;
        s.real, s.imag = value
        return 0
1397

1398 1399 1400
    cdef get_itemsize(self): return sizeof(LongComplex)
    cdef get_default_format(self): return b"Zg"

1401 1402 1403
#cdef extern from "complex.h":
#    pass

1404
@testcase
1405
def complex_dtype(object[long double complex] buf):
1406
    """
1407 1408
    >>> complex_dtype(LongComplexMockBuffer(None, [(0, -1)]))
    -1j
1409
    """
1410
    print buf[0]
1411

1412
@testcase
1413
def complex_inplace(object[long double complex] buf):
1414
    """
1415 1416 1417 1418 1419 1420
    >>> complex_inplace(LongComplexMockBuffer(None, [(0, -1)]))
    (1+1j)
    """
    buf[0] = buf[0] + 1 + 2j
    print buf[0]

1421 1422 1423
@testcase
def complex_struct_dtype(object[LongComplex] buf):
    """
1424 1425
    Note that the format string is "Zg" rather than "2g", yet a struct
    is accessed.
1426 1427
    >>> complex_struct_dtype(LongComplexMockBuffer(None, [(0, -1)]))
    0.0 -1.0
1428 1429
    """
    print buf[0].real, buf[0].imag
1430 1431 1432 1433

@testcase
def complex_struct_inplace(object[LongComplex] buf):
    """
1434
    >>> complex_struct_inplace(LongComplexMockBuffer(None, [(0, -1)]))
1435 1436 1437 1438 1439
    1.0 1.0
    """
    buf[0].real += 1
    buf[0].imag += 2
    print buf[0].real, buf[0].imag
1440

1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
#
# Nogil
#
@testcase
@cython.boundscheck(False)
def buffer_nogil():
    """
    >>> buffer_nogil()
    10
    """
    cdef object[int] buf = IntMockBuffer(None, [1,2,3])
    with nogil:
        buf[1] = 10
    return buf[1]