This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Trac 18358: macro pyobject -> long conversion
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |