[pypy-svn] r72973 - in pypy/branch/cpython-extension/pypy/module/cpyext: . test

fijal at codespeak.net fijal at codespeak.net
Sat Mar 27 20:57:22 CET 2010


Author: fijal
Date: Sat Mar 27 20:57:21 2010
New Revision: 72973

Modified:
   pypy/branch/cpython-extension/pypy/module/cpyext/intobject.py
   pypy/branch/cpython-extension/pypy/module/cpyext/test/test_intobject.py
Log:
(zooko, fijal) PyInt_FromLong and PyInt_AsLong


Modified: pypy/branch/cpython-extension/pypy/module/cpyext/intobject.py
==============================================================================
--- pypy/branch/cpython-extension/pypy/module/cpyext/intobject.py	(original)
+++ pypy/branch/cpython-extension/pypy/module/cpyext/intobject.py	Sat Mar 27 20:57:21 2010
@@ -10,3 +10,18 @@
     
     Allowed subtypes to be accepted."""
     return general_check(space, w_obj, space.w_int)
+
+ at cpython_api([lltype.Signed], PyObject)
+def PyInt_FromLong(space, ival):
+    """Create a new integer object with a value of ival.
+    
+    """
+    return space.wrap(ival)
+
+ at cpython_api([PyObject], lltype.Signed, error=-1)
+def PyInt_AsLong(space, w_obj):
+    """Will first attempt to cast the object to a PyIntObject, if it is not
+    already one, and then return its value. If there is an error, -1 is
+    returned, and the caller should check PyErr_Occurred() to find out whether
+    there was an error, or whether the value just happened to be -1."""
+    return space.int_w(w_obj)

Modified: pypy/branch/cpython-extension/pypy/module/cpyext/test/test_intobject.py
==============================================================================
--- pypy/branch/cpython-extension/pypy/module/cpyext/test/test_intobject.py	(original)
+++ pypy/branch/cpython-extension/pypy/module/cpyext/test/test_intobject.py	Sat Mar 27 20:57:21 2010
@@ -3,6 +3,7 @@
 
 class AppTestIntObject(AppTestCpythonExtensionBase):
     def test_intobject(self):
+        import sys
         module = self.import_extension('foo', [
             ("check_int", "METH_VARARGS",
              """
@@ -11,7 +12,25 @@
                  Py_RETURN_TRUE;
              }
              Py_RETURN_FALSE;
-             """)])
+             """),
+            ("add_one", "METH_VARARGS",
+             """
+             PyObject *a = PyTuple_GetItem(args, 0);
+             long x = PyInt_AsLong(a);
+             if (x == -1) {
+                if (PyErr_Occurred()) {
+                   return NULL;
+                }
+             }
+             PyObject *ret = PyInt_FromLong(x + 1);
+             return ret;
+             """
+             )
+            ])
         assert module.check_int(3)
         assert module.check_int(True)
         assert not module.check_int((1, 2, 3))
+        for i in [3, -5, -1, -sys.maxint, sys.maxint - 1]:
+            assert module.add_one(i) == i + 1
+        assert type(module.add_one(3)) is int
+        raises(TypeError, module.add_one, None)



More information about the Pypy-commit mailing list