Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
Trac 18358: macro pyobject -> long conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
videlec committed May 5, 2015
1 parent 6a3cb27 commit f67ead5
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/sage/misc/long.pxd
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
r"""
Fast conversion macro to long
"""

from libc.limits cimport LONG_MIN

from cpython.int cimport PyInt_CheckExact, PyInt_AS_LONG
from cpython.long cimport PyLong_CheckExact, PyLong_AsLong
from cpython.number cimport PyNumber_Index

from sage.libs.gmp.mpz cimport mpz_fits_slong_p, mpz_get_si

from sage.rings.integer cimport Integer

cdef inline long pyobject_to_long(x) except LONG_MIN:
r"""
Given a Python object ``x`` cast it quickly to a C long.
If it fails, it either raises a ``TypeError`` or a ``OverflowError`` (and
the exceptional value is `LONG_MIN`)
"""
if PyInt_CheckExact(x):
return PyInt_AS_LONG(x)
elif type(x) is Integer:
if mpz_fits_slong_p((<Integer>x).value):
return mpz_get_si((<Integer>x).value)
else:
raise OverflowError
elif PyLong_CheckExact(x):
return PyLong_AsLong(x)

return PyNumber_Index(x)

0 comments on commit f67ead5

Please sign in to comment.