summaryrefslogtreecommitdiff
path: root/tests/run/setjmp.pyx
blob: 73cfef3a9ed13a68a4df99254ef9400ba398e3fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from libc.setjmp cimport *

cdef void check_nonzero(jmp_buf ctx, int x) nogil:
    if x == 0:
        longjmp(ctx, 1)

def nonzero(int x):
    """
    >>> nonzero(-1)
    True
    >>> nonzero(0)
    False
    >>> nonzero(1)
    True
    >>> nonzero(2)
    True

    """
    cdef jmp_buf ctx
    if setjmp(ctx) == 0:
        check_nonzero(ctx, x)
        return True
    else:
        return False


from libc.string cimport strcpy
cdef char[256] error_msg
cdef jmp_buf error_ctx
cdef void error(char msg[]) nogil:
    strcpy(error_msg,msg)
    longjmp(error_ctx, 1)

cdef void c_call(int x) nogil:
    if x<=0:
        error(b"expected a positive value")

def execute_c_call(int x):
    """
    >>> execute_c_call(+2)
    >>> execute_c_call(+1)
    >>> execute_c_call(+0)
    Traceback (most recent call last):
      ...
    RuntimeError: expected a positive value
    >>> execute_c_call(-1)
    Traceback (most recent call last):
      ...
    RuntimeError: expected a positive value
    """
    if not setjmp(error_ctx):
        c_call(x)
    else:
        raise RuntimeError(error_msg.decode())