builtin_ord.pyx 1.83 KB
Newer Older
1 2 3

cimport cython

4 5
import sys

Stefan Behnel's avatar
Stefan Behnel committed
6
uspace = u' '
7 8 9
ustring_with_a = u'abcdefg'
ustring_without_a = u'bcdefg'

10 11 12 13 14 15

@cython.test_assert_path_exists(
    # ord() should receive and return a C value
    '//ReturnStatNode//CoerceToPyTypeNode//SimpleCallNode')
@cython.test_fail_if_path_exists(
    '//ReturnStatNode//SimpleCallNode//CoerceToPyTypeNode')
16 17
def ord_Py_UNICODE(unicode s):
    """
Stefan Behnel's avatar
Stefan Behnel committed
18
    >>> ord_Py_UNICODE(uspace)
19 20 21 22 23 24
    32
    """
    cdef Py_UNICODE u
    u = s[0]
    return ord(u)

25 26

@cython.test_assert_path_exists('//TupleNode//IntNode')
27 28 29
@cython.test_fail_if_path_exists('//SimpleCallNode')
def ord_const():
    """
30 31 32
    >>> ord(b' ')
    32
    >>> ord(' ')
33
    32
34 35
    >>> ord_const()
    (32, 32, 32, 255, 255, 4660, 0)
36
    """
37 38
    return ord(u' '), ord(b' '), ord(' '), ord('\xff'), ord(b'\xff'), ord(u'\u1234'), ord('\0')

39 40

@cython.test_assert_path_exists('//PrimaryCmpNode//IntNode')
41
#@cython.test_fail_if_path_exists('//SimpleCallNode')
42 43 44 45 46 47 48 49
def unicode_for_loop_ord(unicode s):
    """
    >>> unicode_for_loop_ord(ustring_with_a)
    True
    >>> unicode_for_loop_ord(ustring_without_a)
    False
    """
    for c in s:
50
        if ord(c) == ord(u'a'):
51 52
            return True
    return False
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92


def compare_to_char(s):
    """
    >>> compare_to_char(uspace)
    False
    >>> compare_to_char(b'a')
    False
    >>> compare_to_char(b'x')
    True
    >>> compare_to_char('x')
    True
    """
    cdef char c = b'x'
    return ord(s) == c


def ord_object(s):
    """
    >>> try: ord_object('abc')
    ... except ValueError: assert sys.version_info[0] >= 3
    ... except TypeError: assert sys.version_info[0] < 3
    >>> ord_object('a')
    97
    >>> ord_object(b'a')
    97
    """
    return ord(s)


def non_builtin_ord(s):
    """
    >>> non_builtin_ord('x')
    (123, 123)
    """
    def _ord(s):
        return 123

    ord = _ord
    return ord(s), _ord(s)