Tests fixes for Py3.
[cython.git] / tests / run / slice_ptr.pyx
1 from libc.stdlib cimport malloc, free
2 from cpython.object cimport Py_EQ, Py_NE
3
4 def double_ptr_slice(x, L, int a, int b):
5     """
6     >>> L = list(range(10))
7     >>> double_ptr_slice(5, L, 0, 10)
8     >>> double_ptr_slice(6, L, 0, 10)
9     >>> double_ptr_slice(None, L, 0, 10)
10     >>> double_ptr_slice(0, L, 3, 7)
11     >>> double_ptr_slice(5, L, 3, 7)
12     >>> double_ptr_slice(9, L, 3, 7)
13     
14     >>> double_ptr_slice(EqualsEvens(), L, 0, 10)
15     >>> double_ptr_slice(EqualsEvens(), L, 1, 10)
16     """
17     cdef double *L_c = NULL
18     try:
19         L_c = <double*>malloc(len(L) * sizeof(double))
20         for i, a in enumerate(L):
21             L_c[i] = L[i]
22         assert (x in L_c[:b]) == (x in L[:b])
23         assert (x in L_c[a:b]) == (x in L[a:b])
24         assert (x in L_c[a:b:2]) == (x in L[a:b:2])
25     finally:
26         free(L_c)
27
28 def void_ptr_slice(py_x, L, int a, int b):
29     """
30     >>> L = list(range(10))
31     >>> void_ptr_slice(5, L, 0, 10)
32     >>> void_ptr_slice(6, L, 0, 10)
33     >>> void_ptr_slice(None, L, 0, 10)
34     >>> void_ptr_slice(0, L, 3, 7)
35     >>> void_ptr_slice(5, L, 3, 7)
36     >>> void_ptr_slice(9, L, 3, 7)
37     """
38     # I'm using the fact that small Python ints are cached.
39     cdef void **L_c = NULL
40     cdef void *x = <void*>py_x
41     try:
42         L_c = <void**>malloc(len(L) * sizeof(void*))
43         for i, a in enumerate(L):
44             L_c[i] = <void*>L[i]
45         assert (x in L_c[:b]) == (py_x in L[:b])
46         assert (x in L_c[a:b]) == (py_x in L[a:b])
47 #        assert (x in L_c[a:b:2]) == (py_x in L[a:b:2])
48     finally:
49         free(L_c)
50
51 cdef class EqualsEvens:
52     """
53     >>> e = EqualsEvens()
54     >>> e == 2
55     True
56     >>> e == 5
57     False
58     >>> [e == k for k in range(4)]
59     [True, False, True, False]
60     """
61     def __richcmp__(self, other, int op):
62         if op == Py_EQ:
63             return other % 2 == 0
64         elif op == Py_NE:
65             return other % 2 == 1
66         else:
67             return False