Commits

Guido van Rossum  committed 4aee3f6

Merged the int/long unification branch, by very crude means (sorry Thomas!).
I banged on the code (beyond what's in that branch) to make fewer tests fail;
the only tests that fail now are:
test_descr -- can't pickle ints?!
test_pickletools -- ???
test_socket -- See python.org/sf/1619659
test_sqlite -- ???
I'll deal with those later.

  • Participants
  • Parent commits 426f1d3

Comments (0)

Files changed (46)

File BROKEN_TESTS

+test_descr -- can't pickle int objects?!?!
+test_pickletools -- ???
+test_socket -- OverflowError: can't convert negative value to unsigned int
+test_sqlite -- ???
+Measurements of _testcapi.profile_int, on an 800MHz G3, OSX 10.4.7
+best of three runs
+
+r51476 (original p3yk)
+Test 1: 1.601978s
+Test 2: 1.696623s
+Test 3: 1.900683s
+Test 4: 5.307155s
+Test 5: 2.546707s
+Test 6: 1.670252s
+Test 7: 1.910734s
+
+r51506 (int type dropped)
+Test 1: 4.134757s
+Test 2: 4.398235s
+Test 3: 4.611636s
+Test 4: 10.665429s
+
+r51509 (small int cache)
+Test 1: 3.457184s
+Test 2: 4.514800s
+Test 3: 4.999010s
+Test 4: 10.818277s
+
+r51452 (special-casing medium int allocation)
+Test 1: 3.258219s
+Test 2: 4.255007s
+Test 3: 4.547923s
+Test 4: 10.615123s
+Test 5: 5.255545s
+Test 6: 3.775941s
+Test 7: 4.001805s
+
+r51562 (special-case one-digit operations)
+Test 1: 3.527860s
+Test 2: 3.975953s
+Test 3: 4.226751s
+Test 4: 10.605721s
+Test 5: 5.233576s
+Test 6: 2.161525s
+Test 7: 3.421624s
+
+r51573 (speed up PyLong_FromLong)
+Test 1: 3.149116s
+Test 2: 3.948204s
+Test 3: 4.012080s
+Test 4: 8.589921s
+Test 5: 4.481723s
+Test 6: 2.259849s
+Test 7: 3.453212s

File Include/abstract.h

         is cleared and the value is clipped. 
        */
 
-     PyAPI_FUNC(PyObject *) PyNumber_Int(PyObject *o);
+     #define PyNumber_Int PyNumber_Long
 
        /*
 	 Returns the o converted to an integer object on success, or

File Include/boolobject.h

 #endif
 
 
-typedef PyIntObject PyBoolObject;
-
 PyAPI_DATA(PyTypeObject) PyBool_Type;
 
 #define PyBool_Check(x) ((x)->ob_type == &PyBool_Type)
 Don't forget to apply Py_INCREF() when returning either!!! */
 
 /* Don't use these directly */
-PyAPI_DATA(PyIntObject) _Py_ZeroStruct, _Py_TrueStruct;
+PyAPI_DATA(struct _longobject) _Py_FalseStruct, _Py_TrueStruct;
 
 /* Use these macros */
-#define Py_False ((PyObject *) &_Py_ZeroStruct)
+#define Py_False ((PyObject *) &_Py_FalseStruct)
 #define Py_True ((PyObject *) &_Py_TrueStruct)
 
 /* Macros for returning Py_True or Py_False, respectively */

File Include/intobject.h

 extern "C" {
 #endif
 
+/*
 typedef struct {
     PyObject_HEAD
     long ob_ival;
 } PyIntObject;
 
 PyAPI_DATA(PyTypeObject) PyInt_Type;
+*/
 
-#define PyInt_Check(op) PyObject_TypeCheck(op, &PyInt_Type)
-#define PyInt_CheckExact(op) ((op)->ob_type == &PyInt_Type)
+#define PyInt_Check(op) PyLong_Check(op)
+#define PyInt_CheckExact(op) (PyLong_CheckExact(op) && _PyLong_FitsInLong(op))
 
-PyAPI_FUNC(PyObject *) PyInt_FromString(char*, char**, int);
-#ifdef Py_USING_UNICODE
-PyAPI_FUNC(PyObject *) PyInt_FromUnicode(Py_UNICODE*, Py_ssize_t, int);
-#endif
-PyAPI_FUNC(PyObject *) PyInt_FromLong(long);
-PyAPI_FUNC(PyObject *) PyInt_FromSize_t(size_t);
-PyAPI_FUNC(PyObject *) PyInt_FromSsize_t(Py_ssize_t);
-PyAPI_FUNC(long) PyInt_AsLong(PyObject *);
-PyAPI_FUNC(Py_ssize_t) PyInt_AsSsize_t(PyObject *);
-PyAPI_FUNC(unsigned long) PyInt_AsUnsignedLongMask(PyObject *);
-#ifdef HAVE_LONG_LONG
-PyAPI_FUNC(unsigned PY_LONG_LONG) PyInt_AsUnsignedLongLongMask(PyObject *);
-#endif
+#define PyInt_FromString PyLong_FromString
+#define PyInt_FromUnicode PyLong_FromUnicode
+#define PyInt_FromLong PyLong_FromLong
+#define PyInt_FromSize_t PyLong_FromSize_t
+#define PyInt_FromSsize_t PyLong_FromSsize_t
+#define PyInt_AsLong PyLong_AsLong
+#define PyInt_AsSsize_t PyLong_AsSsize_t
+#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
+#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
 
 PyAPI_FUNC(long) PyInt_GetMax(void);
 
-/* Macro, trading safety for speed */
-#define PyInt_AS_LONG(op) (((PyIntObject *)(op))->ob_ival)
+#define PyInt_AS_LONG(op) PyLong_AsLong(op)
 
 /* These aren't really part of the Int object, but they're handy; the protos
  * are necessary for systems that need the magic of PyAPI_FUNC and that want

File Include/longobject.h

 
 PyAPI_FUNC(PyObject *) PyLong_FromLong(long);
 PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLong(unsigned long);
+PyAPI_FUNC(PyObject *) PyLong_FromSize_t(size_t);
+PyAPI_FUNC(PyObject *) PyLong_FromSsize_t(Py_ssize_t);
 PyAPI_FUNC(PyObject *) PyLong_FromDouble(double);
 PyAPI_FUNC(long) PyLong_AsLong(PyObject *);
+PyAPI_FUNC(ssize_t) PyLong_AsSsize_t(PyObject *);
+PyAPI_FUNC(size_t) PyLong_AsSize_t(PyObject *);
 PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLong(PyObject *);
 PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLongMask(PyObject *);
 
 /* For use by intobject.c only */
-PyAPI_FUNC(Py_ssize_t) _PyLong_AsSsize_t(PyObject *);
-PyAPI_FUNC(PyObject *) _PyLong_FromSize_t(size_t);
-PyAPI_FUNC(PyObject *) _PyLong_FromSsize_t(Py_ssize_t);
 PyAPI_DATA(int) _PyLong_DigitValue[256];
 
 /* _PyLong_AsScaledDouble returns a double x and an exponent e such that
    be multiplied by SHIFT!  There may not be enough room in an int to store
    e*SHIFT directly. */
 PyAPI_FUNC(double) _PyLong_AsScaledDouble(PyObject *vv, int *e);
+  PyAPI_FUNC(int) _PyLong_FitsInLong(PyObject* vv);
 
 PyAPI_FUNC(double) PyLong_AsDouble(PyObject *);
 PyAPI_FUNC(PyObject *) PyLong_FromVoidPtr(void *);

File Lib/pickle.py

                 return
         # Text pickle, or int too big to fit in signed 4-byte format.
         self.write(INT + repr(obj) + '\n')
-    dispatch[IntType] = save_int
+    # XXX save_int is merged into save_long
+    # dispatch[IntType] = save_int
 
     def save_long(self, obj, pack=struct.pack):
+        if self.bin:
+            # If the int is small enough to fit in a signed 4-byte 2's-comp
+            # format, we can store it more efficiently than the general
+            # case.
+            # First one- and two-byte unsigned ints:
+            if obj >= 0:
+                if obj <= 0xff:
+                    self.write(BININT1 + chr(obj))
+                    return
+                if obj <= 0xffff:
+                    self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
+                    return
+            # Next check for 4-byte signed ints:
+            high_bits = obj >> 31  # note that Python shift sign-extends
+            if high_bits == 0 or high_bits == -1:
+                # All high bits are copies of bit 2**31, so the value
+                # fits in a 4-byte signed int.
+                self.write(BININT + pack("<i", obj))
+                return
         if self.proto >= 2:
             bytes = encode_long(obj)
             n = len(bytes)

File Lib/test/output/test_class

 __pos__: ()
 __abs__: ()
 __int__: ()
-__long__: ()
+__int__: ()
 __float__: ()
 __oct__: ()
 __hex__: ()

File Lib/test/test_builtin.py

 
         self.assertEqual(long(Foo0()), 42L)
         self.assertEqual(long(Foo1()), 42L)
-        self.assertEqual(long(Foo2()), 42L)
+	# XXX invokes __int__ now
+        # self.assertEqual(long(Foo2()), 42L)
         self.assertEqual(long(Foo3()), 0)
-        self.assertEqual(long(Foo4()), 42)
-        self.assertRaises(TypeError, long, Foo5())
+	# XXX likewise
+        # self.assertEqual(long(Foo4()), 42)
+        # self.assertRaises(TypeError, long, Foo5())
 
     def test_map(self):
         self.assertEqual(

File Lib/test/test_descr.py

         pass
     else:
         raise TestFailed, "NotImplemented should have caused TypeError"
-    import sys
-    try:
-        C(sys.maxint+1)
-    except OverflowError:
-        pass
-    else:
-        raise TestFailed, "should have raised OverflowError"
 
 def longs():
     if verbose: print "Testing long operations..."

File Lib/test/test_marshal.py

     def test_patch_873224(self):
         self.assertRaises(Exception, marshal.loads, '0')
         self.assertRaises(Exception, marshal.loads, 'f')
-        self.assertRaises(Exception, marshal.loads, marshal.dumps(5L)[:-1])
+        self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65L)[:-1])
 
     def test_version_argument(self):
         # Python 2.4.0 crashes for any call to marshal.dumps(x, y)

File Lib/test/test_optparse.py

         self.assertRaises(
             _parse_num, ("0xOoops", long), {},
             ValueError,
-            re.compile(r"invalid literal for long().*: '?0xOoops'?"))
+            re.compile(r"invalid literal for int().*: '?0xOoops'?"))
 
     def test_parse_num_ok(self):
         self.assertEqual(_parse_num("0", int), 0)
         self.assertParseFail(["-n008"],
                              "option -n: invalid integer value: '008'")
         self.assertParseFail(["-l0b0123"],
-                             "option -l: invalid long integer value: '0b0123'")
+                             "option -l: invalid integer value: '0b0123'")
         self.assertParseFail(["-l", "0x12x"],
-                             "option -l: invalid long integer value: '0x12x'")
+                             "option -l: invalid integer value: '0x12x'")
 
 
 def _testclasses():

File Modules/_csv.c

 	if (src == NULL)
 		*target = dflt;
 	else {
-		if (!PyInt_Check(src)) {
+		if (!PyInt_CheckExact(src)) {
 			PyErr_Format(PyExc_TypeError, 
 				     "\"%s\" must be an integer", name);
 			return -1;
 	if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit))
 		return NULL;
 	if (new_limit != NULL) {
-		if (!PyInt_Check(new_limit)) {
+		if (!PyInt_CheckExact(new_limit)) {
 			PyErr_Format(PyExc_TypeError, 
 				     "limit must be an integer");
 			return NULL;

File Modules/_ctypes/_ctypes.c

 		return NULL;
 
 	proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */
-	if (!proto || !PyInt_Check(proto)) {
+	if (!proto || !PyInt_CheckExact(proto)) {
 		PyErr_SetString(PyExc_AttributeError,
 				"class must define a '_length_' attribute, "
 				"which must be a positive integer");

File Modules/_ctypes/callproc.c

 		return 0;
 	}
 
-	if (PyInt_Check(obj)) {
-		pa->ffi_type = &ffi_type_sint;
-		pa->value.i = PyInt_AS_LONG(obj);
-		return 0;
-	}
-
 	if (PyLong_Check(obj)) {
 		pa->ffi_type = &ffi_type_sint;
 		pa->value.i = (long)PyLong_AsUnsignedLong(obj);

File Modules/_cursesmodule.c

 static int 
 PyCurses_ConvertToChtype(PyObject *obj, chtype *ch)
 {
-  if (PyInt_Check(obj)) {
+  if (PyInt_CheckExact(obj)) {
     *ch = (chtype) PyInt_AsLong(obj);
   } else if(PyString_Check(obj) 
 	    && (PyString_Size(obj) == 1)) {
 
   if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL;
 
-  if (PyInt_Check(temp))
+  if (PyInt_CheckExact(temp))
     ch = (chtype) PyInt_AsLong(temp);
   else if (PyString_Check(temp))
     ch = (chtype) *PyString_AsString(temp);
 
   if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL;
 
-  if (PyInt_Check(temp))
+  if (PyInt_CheckExact(temp))
     ch = (int) PyInt_AsLong(temp);
   else if (PyString_Check(temp))
     ch = (int) *PyString_AsString(temp);

File Modules/_sre.c

 
     for (i = 0; i < n; i++) {
         PyObject *o = PyList_GET_ITEM(code, i);
-        unsigned long value = PyInt_Check(o) ? (unsigned long)PyInt_AsLong(o)
-                                              : PyLong_AsUnsignedLong(o);
+        unsigned long value = PyLong_AsUnsignedLong(o);
         self->code[i] = (SRE_CODE) value;
         if ((unsigned long) self->code[i] != value) {
             PyErr_SetString(PyExc_OverflowError,
 {
     Py_ssize_t i;
 
+    if (index == NULL)
+	/* Default value */
+	return 0;
+
     if (PyInt_Check(index))
         return PyInt_AsSsize_t(index);
 
 {
     Py_ssize_t index;
 
-    PyObject* index_ = Py_False; /* zero */
+    PyObject* index_ = NULL;
     if (!PyArg_UnpackTuple(args, "start", 0, 1, &index_))
         return NULL;
 
 {
     Py_ssize_t index;
 
-    PyObject* index_ = Py_False; /* zero */
+    PyObject* index_ = NULL;
     if (!PyArg_UnpackTuple(args, "end", 0, 1, &index_))
         return NULL;
 
 {
     Py_ssize_t index;
 
-    PyObject* index_ = Py_False; /* zero */
+    PyObject* index_ = NULL;
     if (!PyArg_UnpackTuple(args, "span", 0, 1, &index_))
         return NULL;
 

File Modules/_struct.c

 	PyNumberMethods *m;
 
 	assert(v != NULL);
-	if (PyInt_Check(v))
-		return PyLong_FromLong(PyInt_AS_LONG(v));
 	if (PyLong_Check(v)) {
 		Py_INCREF(v);
 		return v;

File Modules/_testcapimodule.c

 	Py_RETURN_NONE;
 }
 
+#ifdef HAVE_GETTIMEOFDAY
+/* Profiling of integer performance */
+void print_delta(int test, struct timeval *s, struct timeval *e)
+{
+	e->tv_sec -= s->tv_sec;
+	e->tv_usec -= s->tv_usec;
+	if (e->tv_usec < 0) {
+		e->tv_sec -=1;
+		e->tv_usec += 1000000;
+	}
+	printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, e->tv_usec);
+}
+
+static PyObject *
+profile_int(PyObject *self, PyObject* args)
+{
+	int i, k;
+	struct timeval start, stop;
+	PyObject *single, **multiple, *op1, *result;
+
+	/* Test 1: Allocate and immediately deallocate
+	   many small integers */
+	gettimeofday(&start, NULL);
+	for(k=0; k < 20000; k++)
+		for(i=0; i < 1000; i++) {
+			single = PyInt_FromLong(i);
+			Py_DECREF(single);
+		}
+	gettimeofday(&stop, NULL);
+	print_delta(1, &start, &stop);
+
+	/* Test 2: Allocate and immediately deallocate
+	   many large integers */
+	gettimeofday(&start, NULL);
+	for(k=0; k < 20000; k++)
+		for(i=0; i < 1000; i++) {
+			single = PyInt_FromLong(i+1000000);
+			Py_DECREF(single);
+		}
+	gettimeofday(&stop, NULL);
+	print_delta(2, &start, &stop);
+
+	/* Test 3: Allocate a few integers, then release
+	   them all simultaneously. */
+	multiple = malloc(sizeof(PyObject*) * 1000);
+	gettimeofday(&start, NULL);
+	for(k=0; k < 20000; k++) {
+		for(i=0; i < 1000; i++) {
+			multiple[i] = PyInt_FromLong(i+1000000);
+		}
+		for(i=0; i < 1000; i++) {
+			Py_DECREF(multiple[i]);
+		}
+	}
+	gettimeofday(&stop, NULL);
+	print_delta(3, &start, &stop);
+
+	/* Test 4: Allocate many integers, then release
+	   them all simultaneously. */
+	multiple = malloc(sizeof(PyObject*) * 1000000);
+	gettimeofday(&start, NULL);
+	for(k=0; k < 20; k++) {
+		for(i=0; i < 1000000; i++) {
+			multiple[i] = PyInt_FromLong(i+1000000);
+		}
+		for(i=0; i < 1000000; i++) {
+			Py_DECREF(multiple[i]);
+		}
+	}
+	gettimeofday(&stop, NULL);
+	print_delta(4, &start, &stop);
+
+	/* Test 5: Allocate many integers < 32000 */
+	multiple = malloc(sizeof(PyObject*) * 1000000);
+	gettimeofday(&start, NULL);
+	for(k=0; k < 10; k++) {
+		for(i=0; i < 1000000; i++) {
+			multiple[i] = PyInt_FromLong(i+1000);
+		}
+		for(i=0; i < 1000000; i++) {
+			Py_DECREF(multiple[i]);
+		}
+	}
+	gettimeofday(&stop, NULL);
+	print_delta(5, &start, &stop);
+
+	/* Test 6: Perform small int addition */
+	op1 = PyInt_FromLong(1);
+	gettimeofday(&start, NULL);
+	for(i=0; i < 10000000; i++) {
+		result = PyNumber_Add(op1, op1);
+		Py_DECREF(result);
+	}
+	gettimeofday(&stop, NULL);
+	Py_DECREF(op1);
+	print_delta(6, &start, &stop);
+
+	/* Test 7: Perform medium int addition */
+	op1 = PyInt_FromLong(1000);
+	gettimeofday(&start, NULL);
+	for(i=0; i < 10000000; i++) {
+		result = PyNumber_Add(op1, op1);
+		Py_DECREF(result);
+	}
+	gettimeofday(&stop, NULL);
+	Py_DECREF(op1);
+	print_delta(7, &start, &stop);
+
+	Py_INCREF(Py_None);
+	return Py_None;
+}
+#endif
+
 static PyMethodDef TestMethods[] = {
 	{"raise_exception",	raise_exception,		 METH_VARARGS},
 	{"test_config",		(PyCFunction)test_config,	 METH_NOARGS},
 #ifdef WITH_THREAD
 	{"_test_thread_state",  test_thread_state, 		 METH_VARARGS},
 #endif
+#ifdef HAVE_GETTIMEOFDAY
+	{"profile_int",		profile_int,			METH_NOARGS},
+#endif
 	{NULL, NULL} /* sentinel */
 };
 

File Modules/_tkinter.c

 					PyString_GET_SIZE(value));
 	else if (PyBool_Check(value))
 		return Tcl_NewBooleanObj(PyObject_IsTrue(value));
-	else if (PyInt_Check(value))
+	else if (PyInt_CheckExact(value))
 		return Tcl_NewLongObj(PyInt_AS_LONG(value));
 	else if (PyFloat_Check(value))
 		return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value));

File Modules/cPickle.c

 		PyErr_SetString(PicklingError, "no int where int expected in memo");
 		return -1;
 	}
-	c_value = PyInt_AS_LONG((PyIntObject*)value);
+	c_value = PyInt_AsLong(value);
+	if (c_value == -1 && PyErr_Occurred())
+		return -1;
 
 	if (!self->bin) {
 		s[0] = GET;
 {
 	static const char *buf[2] = {FALSE, TRUE};
 	static char len[2] = {sizeof(FALSE)-1, sizeof(TRUE)-1};
-	long l = PyInt_AS_LONG((PyIntObject *)args);
+	long l = args == Py_True;
 
 	if (self->proto >= 2) {
 		char opcode = l ? NEWTRUE : NEWFALSE;
 }
 
 static int
-save_int(Picklerobject *self, PyObject *args)
+save_int(Picklerobject *self, long l)
 {
 	char c_str[32];
-	long l = PyInt_AS_LONG((PyIntObject *)args);
 	int len = 0;
 
 	if (!self->bin
 	Py_ssize_t size;
 	int res = -1;
 	PyObject *repr = NULL;
-
+	int val = PyInt_AsLong(args);
 	static char l = LONG;
 
+	if (val == -1 && PyErr_Occurred()) {
+		/* out of range for int pickling */
+		PyErr_Clear();
+	}
+	else
+		return save_int(self, val);
+
 	if (self->proto >= 2) {
 		/* Linear-time pickling. */
 		size_t nbits;
 			goto finally;
 		}
 		break;
-        case 'i':
-		if (type == &PyInt_Type) {
-			res = save_int(self, args);
-			goto finally;
-		}
-		break;
-
         case 'l':
 		if (type == &PyLong_Type) {
 			res = save_long(self, args);
 			rsize += PyString_GET_SIZE(k);
 
 		else if (PyInt_Check(k)) { /* put */
-			ik = PyInt_AS_LONG((PyIntObject*)k);
+			ik = PyInt_AsLong(k);
+			if (ik == -1 && PyErr_Occurred())
+				goto err;
 			if (ik >= lm || ik == 0) {
 				PyErr_SetString(PicklingError,
 						"Invalid get data");
 		}
 
 		else { /* put */
-			ik = PyInt_AS_LONG((PyIntObject *)k);
+			ik = PyInt_AsLong(k);
+			if (ik == -1 && PyErr_Occurred())
+				goto err;
 			if (ik >= lm || ik == 0) {
 				PyErr_SetString(PicklingError,
 						"Invalid get data");
 		}
 
 		else if (PyTuple_Check(k)) { /* get */
-			ik = PyInt_AS_LONG((PyIntObject *)
-					    PyTuple_GET_ITEM(k, 0));
+			ik = PyLong_AsLong(PyTuple_GET_ITEM(k, 0));
+			if (ik == -1 && PyErr_Occurred())
+				goto err;
 			if (ik < 256) {
 				*s++ = BINGET;
 				*s++ = (int)(ik & 0xff);
 		}
 
 		else { /* put */
-			ik = PyInt_AS_LONG((PyIntObject*)k);
+			ik = PyLong_AsLong(k);
+			if (ik == -1 && PyErr_Occurred())
+				goto err;
 
 			if (have_get[ik]) { /* with matching get */
 				if (ik < 256) {

File Modules/cjkcodecs/multibytecodec.c

 		return NULL;
 	}
 
+	if (size == -1 && PyErr_Occurred())
+		return NULL;
+
 	return mbstreamreader_iread(self, "read", size);
 }
 
 		return NULL;
 	}
 
+	if (size == -1 && PyErr_Occurred())
+		return NULL;
+
 	return mbstreamreader_iread(self, "readline", size);
 }
 
 		return NULL;
 	}
 
+	if (sizehint == -1 && PyErr_Occurred())
+		return NULL;
+
 	r = mbstreamreader_iread(self, "read", sizehint);
 	if (r == NULL)
 		return NULL;

File Modules/datetimemodule.c

 		 * lose a little info.
 		 */
 		assert(PyInt_Check(factor) || PyLong_Check(factor));
-		if (PyInt_Check(factor))
-			dnum = (double)PyInt_AsLong(factor);
-		else
-			dnum = PyLong_AsDouble(factor);
+		dnum = PyLong_AsDouble(factor);
 
 		dnum *= fracpart;
 		fracpart = modf(dnum, &intpart);
 					Py_DECREF(obj);
 					return NULL;
 				}
-				if (PyInt_Check(p))
+				if (PyInt_CheckExact(p))
 					ia[i] = PyInt_AsLong(p);
 				else
 					good_timetuple = 0;

File Modules/dlmodule.c

 	}
 	for (i = 1; i < n; i++) {
 		PyObject *v = PyTuple_GetItem(args, i);
-		if (PyInt_Check(v))
+		if (PyInt_Check(v)) {
 			alist[i-1] = PyInt_AsLong(v);
-		else if (PyString_Check(v))
+			if (alist[i-1] == -1 && PyErr_Occurred())
+				return NULL;
+		} else if (PyString_Check(v))
 			alist[i-1] = (long)PyString_AsString(v);
 		else if (v == Py_None)
 			alist[i-1] = (long) ((char *)NULL);

File Modules/posixmodule.c

 		elem = PySequence_GetItem(groups, i);
 		if (!elem)
 			return NULL;
-		if (!PyInt_Check(elem)) {
-			if (!PyLong_Check(elem)) {
-				PyErr_SetString(PyExc_TypeError,
-						"groups must be integers");
+		if (!PyLong_Check(elem)) {
+			PyErr_SetString(PyExc_TypeError,
+					"groups must be integers");
+			Py_DECREF(elem);
+			return NULL;
+		} else {
+			unsigned long x = PyLong_AsUnsignedLong(elem);
+			if (PyErr_Occurred()) {
+				PyErr_SetString(PyExc_TypeError, 
+						"group id too big");
 				Py_DECREF(elem);
 				return NULL;
-			} else {
-				unsigned long x = PyLong_AsUnsignedLong(elem);
-				if (PyErr_Occurred()) {
-					PyErr_SetString(PyExc_TypeError, 
-							"group id too big");
-					Py_DECREF(elem);
-					return NULL;
-				}
-				grouplist[i] = x;
-				/* read back the value to see if it fitted in gid_t */
-				if (grouplist[i] != x) {
-					PyErr_SetString(PyExc_TypeError,
-							"group id too big");
-					Py_DECREF(elem);
-					return NULL;
-				}
 			}
-		} else {
-			long x  = PyInt_AsLong(elem);
 			grouplist[i] = x;
+			/* read back the value to see if it fitted in gid_t */
 			if (grouplist[i] != x) {
 				PyErr_SetString(PyExc_TypeError,
 						"group id too big");

File Modules/socketmodule.c

 {
 	unsigned long x;
 
-	if (PyInt_Check(arg)) {
-		x = PyInt_AS_LONG(arg);
-		if (x == (unsigned long) -1 && PyErr_Occurred())
-			return NULL;
-	}
-	else if (PyLong_Check(arg)) {
+	if (PyLong_Check(arg)) {
 		x = PyLong_AsUnsignedLong(arg);
 		if (x == (unsigned long) -1 && PyErr_Occurred())
 			return NULL;
 {
 	unsigned long x;
 
-	if (PyInt_Check(arg)) {
-		x = PyInt_AS_LONG(arg);
-		if (x == (unsigned long) -1 && PyErr_Occurred())
-			return NULL;
-	}
-	else if (PyLong_Check(arg)) {
+	if (PyLong_Check(arg)) {
 		x = PyLong_AsUnsignedLong(arg);
 		if (x == (unsigned long) -1 && PyErr_Occurred())
 			return NULL;
 				"getaddrinfo() argument 1 must be string or None");
 		return NULL;
 	}
-	if (PyInt_Check(pobj)) {
+	if (PyInt_CheckExact(pobj)) {
 		PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
 		pptr = pbuf;
 	} else if (PyString_Check(pobj)) {

File Modules/timemodule.c

 	if (y < 1900) {
 		PyObject *accept = PyDict_GetItemString(moddict,
 							"accept2dyear");
-		if (accept == NULL || !PyInt_Check(accept) ||
+		if (accept == NULL || !PyInt_CheckExact(accept) ||
 		    PyInt_AsLong(accept) == 0) {
 			PyErr_SetString(PyExc_ValueError,
 					"year >= 1900 required");

File Objects/abstract.c

 	return type_error("bad operand type for abs(): '%.200s'", o);
 }
 
-/* Add a check for embedded NULL-bytes in the argument. */
-static PyObject *
-int_from_string(const char *s, Py_ssize_t len)
-{
-	char *end;
-	PyObject *x;
-
-	x = PyInt_FromString((char*)s, &end, 10);
-	if (x == NULL)
-		return NULL;
-	if (end != s + len) {
-		PyErr_SetString(PyExc_ValueError,
-				"null byte in argument for int()");
-		Py_DECREF(x);
-		return NULL;
-	}
-	return x;
-}
-
 /* Return a Python Int or Long from the object item 
    Raise TypeError if the result is not an int-or-long
    or if the object cannot be interpreted as an index. 
 		if (result &&
 		    !PyInt_Check(result) && !PyLong_Check(result)) {
 			PyErr_Format(PyExc_TypeError,
-				     "__index__ returned non-(int,long) " \
+				     "__index__ returned non-int " \
 				     "(type %.200s)",
 				     result->ob_type->tp_name);
 			Py_DECREF(result);
 }
 
 
-PyObject *
-PyNumber_Int(PyObject *o)
-{
-	PyNumberMethods *m;
-	const char *buffer;
-	Py_ssize_t buffer_len;
-
-	if (o == NULL)
-		return null_error();
-	if (PyInt_CheckExact(o)) {
-		Py_INCREF(o);
-		return o;
-	}
-	m = o->ob_type->tp_as_number;
-	if (m && m->nb_int) { /* This should include subclasses of int */
-		PyObject *res = m->nb_int(o);
-		if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
-			PyErr_Format(PyExc_TypeError,
-				     "__int__ returned non-int (type %.200s)",
-				     res->ob_type->tp_name);
-			Py_DECREF(res);
-			return NULL;
-		}
-		return res;
-	}
-	if (PyInt_Check(o)) { /* A int subclass without nb_int */
-		PyIntObject *io = (PyIntObject*)o;
-		return PyInt_FromLong(io->ob_ival);
-	}
-	if (PyString_Check(o))
-		return int_from_string(PyString_AS_STRING(o),
-				       PyString_GET_SIZE(o));
-#ifdef Py_USING_UNICODE
-	if (PyUnicode_Check(o))
-		return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
-					 PyUnicode_GET_SIZE(o),
-					 10);
-#endif
-	if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
-		return int_from_string((char*)buffer, buffer_len);
-
-	return type_error("int() argument must be a string or a "
-			  "number, not '%.200s'", o);
-}
-
 /* Add a check for embedded NULL-bytes in the argument. */
 static PyObject *
 long_from_string(const char *s, Py_ssize_t len)
 		return NULL;
 	if (end != s + len) {
 		PyErr_SetString(PyExc_ValueError,
-				"null byte in argument for long()");
+				"null byte in argument for int()");
 		Py_DECREF(x);
 		return NULL;
 	}
 
 	if (o == NULL)
 		return null_error();
+	if (PyLong_CheckExact(o)) {
+		Py_INCREF(o);
+		return o;
+	}
 	m = o->ob_type->tp_as_number;
+	if (m && m->nb_int) { /* This should include subclasses of int */
+		PyObject *res = m->nb_int(o);
+		if (res && !PyLong_Check(res)) {
+			PyErr_Format(PyExc_TypeError,
+				     "__int__ returned non-int (type %.200s)",
+				     res->ob_type->tp_name);
+			Py_DECREF(res);
+			return NULL;
+		}
+		return res;
+	}
 	if (m && m->nb_long) { /* This should include subclasses of long */
 		PyObject *res = m->nb_long(o);
 		if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
 	if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
 		return long_from_string(buffer, buffer_len);
 
-	return type_error("long() argument must be a string or a "
+	return type_error("int() argument must be a string or a "
 			  "number, not '%.200s'", o);
 }
 

File Objects/boolobject.c

 /* Boolean type, a subtype of int */
 
 #include "Python.h"
+#include "longintrepr.h"
 
 /* We need to define bool_print to override int_print */
 
 static int
-bool_print(PyBoolObject *self, FILE *fp, int flags)
+bool_print(PyObject *self, FILE *fp, int flags)
 {
-	fputs(self->ob_ival == 0 ? "False" : "True", fp);
+	fputs(self == Py_False ? "False" : "True", fp);
 	return 0;
 }
 
 static PyObject *true_str = NULL;
 
 static PyObject *
-bool_repr(PyBoolObject *self)
+bool_repr(PyObject *self)
 {
 	PyObject *s;
 
-	if (self->ob_ival)
+	if (self == Py_True)
 		s = true_str ? true_str :
 			(true_str = PyString_InternFromString("True"));
 	else
 bool_and(PyObject *a, PyObject *b)
 {
 	if (!PyBool_Check(a) || !PyBool_Check(b))
-		return PyInt_Type.tp_as_number->nb_and(a, b);
-	return PyBool_FromLong(
-		((PyBoolObject *)a)->ob_ival & ((PyBoolObject *)b)->ob_ival);
+		return PyLong_Type.tp_as_number->nb_and(a, b);
+	return PyBool_FromLong((a == Py_True) & (b == Py_True));
 }
 
 static PyObject *
 bool_or(PyObject *a, PyObject *b)
 {
 	if (!PyBool_Check(a) || !PyBool_Check(b))
-		return PyInt_Type.tp_as_number->nb_or(a, b);
-	return PyBool_FromLong(
-		((PyBoolObject *)a)->ob_ival | ((PyBoolObject *)b)->ob_ival);
+		return PyLong_Type.tp_as_number->nb_or(a, b);
+	return PyBool_FromLong((a == Py_True) | (b == Py_True));
 }
 
 static PyObject *
 bool_xor(PyObject *a, PyObject *b)
 {
 	if (!PyBool_Check(a) || !PyBool_Check(b))
-		return PyInt_Type.tp_as_number->nb_xor(a, b);
-	return PyBool_FromLong(
-		((PyBoolObject *)a)->ob_ival ^ ((PyBoolObject *)b)->ob_ival);
+		return PyLong_Type.tp_as_number->nb_xor(a, b);
+	return PyBool_FromLong((a == Py_True) ^ (b == Py_True));
 }
 
 /* Doc string */
 	0,			/* nb_true_divide */
 	0,			/* nb_inplace_floor_divide */
 	0,			/* nb_inplace_true_divide */
+	0,			/* nb_index */
 };
 
 /* The type object for bool.  Note that this cannot be subclassed! */
 	PyObject_HEAD_INIT(&PyType_Type)
 	0,
 	"bool",
-	sizeof(PyIntObject),
+	sizeof(struct _longobject),
 	0,
 	0,					/* tp_dealloc */
-	(printfunc)bool_print,			/* tp_print */
+	bool_print,				/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
 	0,					/* tp_compare */
-	(reprfunc)bool_repr,			/* tp_repr */
+	bool_repr,				/* tp_repr */
 	&bool_as_number,			/* tp_as_number */
 	0,					/* tp_as_sequence */
 	0,					/* tp_as_mapping */
 	0,					/* tp_hash */
         0,					/* tp_call */
-        (reprfunc)bool_repr,			/* tp_str */
+        bool_repr,				/* tp_str */
 	0,					/* tp_getattro */
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
 	0,					/* tp_methods */
 	0,					/* tp_members */
 	0,					/* tp_getset */
-	&PyInt_Type,				/* tp_base */
+	&PyLong_Type,				/* tp_base */
 	0,					/* tp_dict */
 	0,					/* tp_descr_get */
 	0,					/* tp_descr_set */
 /* The objects representing bool values False and True */
 
 /* Named Zero for link-level compatibility */
-PyIntObject _Py_ZeroStruct = {
+struct _longobject _Py_FalseStruct = {
 	PyObject_HEAD_INIT(&PyBool_Type)
-	0
+	0, { 0 }
 };
 
-PyIntObject _Py_TrueStruct = {
+struct _longobject _Py_TrueStruct = {
 	PyObject_HEAD_INIT(&PyBool_Type)
-	1
+	1, { 1 }
 };

File Objects/complexobject.c

     PyObject *obj = *pobj;
 
     pc->real = pc->imag = 0.0;
-    if (PyInt_Check(obj)) {
-        pc->real = PyInt_AS_LONG(obj);
-        return 0;
-    }
     if (PyLong_Check(obj)) {
         pc->real = PyLong_AsDouble(obj);
         if (pc->real == -1.0 && PyErr_Occurred()) {

File Objects/exceptions.c

 
     have_filename = (self->filename != NULL) &&
         PyString_Check(self->filename);
-    have_lineno = (self->lineno != NULL) && PyInt_Check(self->lineno);
+    have_lineno = (self->lineno != NULL) && PyInt_CheckExact(self->lineno);
 
     if (!have_filename && !have_lineno)
         return str;
         return -1;
     }
 
-    if (PyInt_Check(attr)) {
-        *value = PyInt_AS_LONG(attr);
-    } else if (PyLong_Check(attr)) {
-        *value = _PyLong_AsSsize_t(attr);
+    if (PyLong_Check(attr)) {
+        *value = PyLong_AsSsize_t(attr);
         if (*value == -1 && PyErr_Occurred())
             return -1;
     } else {
     if (!PyArg_ParseTuple(args, "O!O!O!O!O!",
         &PyString_Type, &self->encoding,
         objecttype, &self->object,
-        &PyInt_Type, &self->start,
-        &PyInt_Type, &self->end,
+        &PyLong_Type, &self->start,
+        &PyLong_Type, &self->end,
         &PyString_Type, &self->reason)) {
         self->encoding = self->object = self->start = self->end =
             self->reason = NULL;
 
     if (!PyArg_ParseTuple(args, "O!O!O!O!",
         &PyUnicode_Type, &self->object,
-        &PyInt_Type, &self->start,
-        &PyInt_Type, &self->end,
+        &PyLong_Type, &self->start,
+        &PyLong_Type, &self->end,
         &PyString_Type, &self->reason)) {
         self->object = self->start = self->end = self->reason = NULL;
         return -1;

File Objects/fileobject.c

 		if (v == NULL)
 			PyErr_Clear();
 		else {
-			if (PyInt_Check(v))
+			if (PyInt_CheckExact(v))
 				oldflag = PyInt_AsLong(v);
 			assert(oldflag < INT_MAX);
 			Py_DECREF(v);
 		return -1;
 	}
 
+	if (fd == -1 && PyErr_Occurred())
+		return -1;
 	if (fd < 0) {
 		PyErr_Format(PyExc_ValueError,
 			     "file descriptor cannot be a negative integer (%i)",

File Objects/floatobject.c

 {
 	register PyObject *obj = *v;
 
-	if (PyInt_Check(obj)) {
-		*dbl = (double)PyInt_AS_LONG(obj);
-	}
-	else if (PyLong_Check(obj)) {
+	if (PyLong_Check(obj)) {
 		*dbl = PyLong_AsDouble(obj);
 		if (*dbl == -1.0 && PyErr_Occurred()) {
 			*v = NULL;
 			goto Unimplemented;
 	}
 
-	else if (PyInt_Check(w)) {
-		long jj = PyInt_AS_LONG(w);
-		/* In the worst realistic case I can imagine, C double is a
-		 * Cray single with 48 bits of precision, and long has 64
-		 * bits.
-		 */
-#if SIZEOF_LONG > 6
-		unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
-		if (abs >> 48) {
-			/* Needs more than 48 bits.  Make it take the
-			 * PyLong path.
-			 */
-			PyObject *result;
-			PyObject *ww = PyLong_FromLong(jj);
-
-			if (ww == NULL)
-				return NULL;
-			result = float_richcompare(v, ww, op);
-			Py_DECREF(ww);
-			return result;
-		}
-#endif
-		j = (double)jj;
-		assert((long)j == jj);
-	}
-
 	else if (PyLong_Check(w)) {
 		int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
 		int wsign = _PyLong_Sign(w);

File Objects/frameobject.c

 	int setup_op = 0;               /* (ditto) */
 
 	/* f_lineno must be an integer. */
-	if (!PyInt_Check(p_new_lineno)) {
+	if (!PyInt_CheckExact(p_new_lineno)) {
 		PyErr_SetString(PyExc_ValueError,
 				"lineno must be an integer");
 		return -1;

File Objects/intobject.c

 	return LONG_MAX;	/* To initialize sys.maxint */
 }
 
+#if 0
 /* Integers are quite normal objects, to make object handling uniform.
    (Using odd pointers to represent integers would save much space
    but require extra checks for this special case throughout the code.)
 		}
 	}
 }
+#endif /* if 0 */

File Objects/listobject.c

 	Py_DECREF(args);
 	if (res == NULL)
 		return -1;
-	if (!PyInt_Check(res)) {
+	if (!PyInt_CheckExact(res)) {
 		PyErr_Format(PyExc_TypeError,
 			     "comparison function must return int, not %.200s",
 			     res->ob_type->tp_name);

File Objects/longobject.c

 
 #include <ctype.h>
 
+#ifndef NSMALLPOSINTS
+#define NSMALLPOSINTS		257
+#endif
+#ifndef NSMALLNEGINTS
+#define NSMALLNEGINTS		5
+#endif
+#if NSMALLNEGINTS + NSMALLPOSINTS > 0
+/* Small integers are preallocated in this array so that they
+   can be shared.
+   The integers that are preallocated are those in the range
+   -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
+*/
+static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
+#ifdef COUNT_ALLOCS
+int quick_int_allocs, quick_neg_int_allocs;
+#endif
+
+static inline PyObject *
+get_small_int(int ival)
+{
+	PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
+	Py_INCREF(v);
+#ifdef COUNT_ALLOCS
+	if (ival >= 0)
+		quick_int_allocs++;
+	else
+		quick_neg_int_allocs++;
+#endif
+	return v;
+}
+#define CHECK_SMALL_INT(ival) \
+	do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
+		return get_small_int(ival); \
+	} while(0)
+
+#else
+#define CHECK_SMALL_INT(ival)
+#endif
+
+#define MEDIUM_VALUE(x) ((x)->ob_size < 0 ? -(x)->ob_digit[0] : ((x)->ob_size == 0 ? 0 : (x)->ob_digit[0]))
+/* If a freshly-allocated long is already shared, it must
+   be a small integer, so negating it must go to PyLong_FromLong */
+#define NEGATE(x) \
+	do if ((x)->ob_refcnt == 1) (x)->ob_size = -(x)->ob_size;  \
+	   else { PyObject* tmp=PyInt_FromLong(-MEDIUM_VALUE(x));  \
+		   Py_DECREF(x); (x) = (PyLongObject*)tmp; }	   \
+        while(0)
 /* For long multiplication, use the O(N**2) school algorithm unless
  * both operands contain more than KARATSUBA_CUTOFF digits (this
  * being an internal Python long digit, in base BASE).
 PyLongObject *
 _PyLong_New(Py_ssize_t size)
 {
-	if (size > PY_SSIZE_T_MAX) {
+	PyLongObject *result;
+	/* Can't use sizeof(PyLongObject) here, since the
+	   compiler takes padding at the end into account.
+	   As the consequence, this would waste 2 bytes on
+	   a 32-bit system, and 6 bytes on a 64-bit system.
+	   This computation would be incorrect on systems
+	   which have padding before the digits; with 16-bit
+	   digits this should not happen. */
+	result = PyObject_MALLOC(sizeof(PyVarObject) + 
+				 size*sizeof(digit));
+	if (!result) {
 		PyErr_NoMemory();
 		return NULL;
 	}
-	return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
+	return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
 }
 
 PyObject *
 	i = src->ob_size;
 	if (i < 0)
 		i = -(i);
+	if (i < 2) {
+		int ival = src->ob_digit[0];
+		if (src->ob_size < 0)
+			ival = -ival;
+		CHECK_SMALL_INT(ival);
+	}
 	result = _PyLong_New(i);
 	if (result != NULL) {
 		result->ob_size = src->ob_size;
 	PyLongObject *v;
 	unsigned long t;  /* unsigned so >> doesn't propagate sign bit */
 	int ndigits = 0;
-	int negative = 0;
+	int sign = 1;
+
+	CHECK_SMALL_INT(ival);
 
 	if (ival < 0) {
 		ival = -ival;
-		negative = 1;
+		sign = -1;
 	}
 
-	/* Count the number of Python digits.
-	   We used to pick 5 ("big enough for anything"), but that's a
-	   waste of time and space given that 5*15 = 75 bits are rarely
-	   needed. */
+	/* Fast path for single-digits ints */
+	if (!(ival>>SHIFT)) {
+		v = _PyLong_New(1);
+		if (v) {
+			v->ob_size = sign;
+			v->ob_digit[0] = ival;
+		}
+		return (PyObject*)v;
+	}
+
+	/* 2 digits */
+	if (!(ival >> 2*SHIFT)) {
+		v = _PyLong_New(2);
+		if (v) {
+			v->ob_size = 2*sign;
+			v->ob_digit[0] = (digit)ival & MASK;
+			v->ob_digit[1] = ival >> SHIFT;
+		}
+		return (PyObject*)v;
+	}
+
+	/* Larger numbers: loop to determine number of digits */
 	t = (unsigned long)ival;
 	while (t) {
 		++ndigits;
 	v = _PyLong_New(ndigits);
 	if (v != NULL) {
 		digit *p = v->ob_digit;
-		v->ob_size = negative ? -ndigits : ndigits;
+		v->ob_size = ndigits*sign;
 		t = (unsigned long)ival;
 		while (t) {
 			*p++ = (digit)(t & MASK);
 	unsigned long t;
 	int ndigits = 0;
 
+	if (ival < BASE)
+		return PyLong_FromLong(ival);
 	/* Count the number of Python digits. */
 	t = (unsigned long)ival;
 	while (t) {
 	neg = 0;
 	if (Py_IS_INFINITY(dval)) {
 		PyErr_SetString(PyExc_OverflowError,
-			"cannot convert float infinity to long");
+			"cannot convert float infinity to int");
 		return NULL;
 	}
+	CHECK_SMALL_INT((int)dval);
 	if (dval < 0.0) {
 		neg = 1;
 		dval = -dval;
 	unsigned long x, prev;
 	Py_ssize_t i;
 	int sign;
-
-	if (vv == NULL || !PyLong_Check(vv)) {
-		if (vv != NULL && PyInt_Check(vv))
-			return PyInt_AsLong(vv);
+	int do_decref = 0; /* if nb_int was called */
+
+	if (vv == NULL) {
 		PyErr_BadInternalCall();
 		return -1;
 	}
+
+	if (!PyLong_Check(vv)) {
+		PyNumberMethods *nb;
+		if ((nb = vv->ob_type->tp_as_number) == NULL ||
+		    nb->nb_int == NULL) {
+			PyErr_SetString(PyExc_TypeError, "an integer is required");
+			return -1;
+		}
+		vv = (*nb->nb_int) (vv);
+		if (vv == NULL)
+			return -1;
+		do_decref = 1;
+		if (!PyLong_Check(vv)) {
+			Py_DECREF(vv);
+			PyErr_SetString(PyExc_TypeError,
+					"nb_int should return int object");
+			return -1;
+		}
+	}
+
 	v = (PyLongObject *)vv;
 	i = v->ob_size;
+	switch (i) {
+	case -1: return -v->ob_digit[0];
+	case 0: return 0;
+	case 1: return v->ob_digit[0];
+	}
 	sign = 1;
 	x = 0;
 	if (i < 0) {
 		if ((x >> SHIFT) != prev)
 			goto overflow;
 	}
+	if (do_decref) {
+		Py_DECREF(vv);
+	}
 	/* Haven't lost any bits, but casting to long requires extra care
 	 * (see comment above).
          */
 	/* else overflow */
 
  overflow:
+	if (do_decref) {
+		Py_DECREF(vv);
+	}
 	PyErr_SetString(PyExc_OverflowError,
-			"long int too large to convert to int");
+			"int too large to convert to int");
 	return -1;
 }
 
+int
+_PyLong_FitsInLong(PyObject *vv)
+{
+	int size;
+	if (!PyLong_CheckExact(vv)) {
+		PyErr_BadInternalCall();
+		return 0;
+	}
+	/* conservative estimate */
+	size = ((PyLongObject*)vv)->ob_size;
+	return -2 <= size && size <= 2;
+}
+
 /* Get a Py_ssize_t from a long int object.
    Returns -1 and sets an error condition if overflow occurs. */
 
 Py_ssize_t
-_PyLong_AsSsize_t(PyObject *vv) {
+PyLong_AsSsize_t(PyObject *vv) {
 	register PyLongObject *v;
 	size_t x, prev;
 	Py_ssize_t i;
 	}
 	v = (PyLongObject *)vv;
 	i = v->ob_size;
+	switch (i) {
+	case -1: return -v->ob_digit[0];
+	case 0: return 0;
+	case 1: return v->ob_digit[0];
+	}
 	sign = 1;
 	x = 0;
 	if (i < 0) {
 
  overflow:
 	PyErr_SetString(PyExc_OverflowError,
-			"long int too large to convert to int");
+			"int too large to convert to ");
 	return -1;
 }
 
 	Py_ssize_t i;
 
 	if (vv == NULL || !PyLong_Check(vv)) {
-		if (vv != NULL && PyInt_Check(vv)) {
-			long val = PyInt_AsLong(vv);
-			if (val < 0) {
-				PyErr_SetString(PyExc_OverflowError,
-				"can't convert negative value to unsigned long");
-				return (unsigned long) -1;
-			}
-			return val;
-		}
 		PyErr_BadInternalCall();
 		return (unsigned long) -1;
 	}
 	x = 0;
 	if (i < 0) {
 		PyErr_SetString(PyExc_OverflowError,
-			   "can't convert negative value to unsigned long");
+			   "can't convert negative value to unsigned int");
 		return (unsigned long) -1;
 	}
+	switch (i) {
+	case 0: return 0;
+	case 1: return v->ob_digit[0];
+	}
 	while (--i >= 0) {
 		prev = x;
 		x = (x << SHIFT) + v->ob_digit[i];
 		if ((x >> SHIFT) != prev) {
 			PyErr_SetString(PyExc_OverflowError,
-				"long int too large to convert");
+				"int too large to convert");
 			return (unsigned long) -1;
 		}
 	}
 	return x;
 }
 
+/* Get a C unsigned long int from a long int object.
+   Returns -1 and sets an error condition if overflow occurs. */
+
+size_t
+PyLong_AsSize_t(PyObject *vv)
+{
+	register PyLongObject *v;
+	size_t x, prev;
+	Py_ssize_t i;
+
+	if (vv == NULL || !PyLong_Check(vv)) {
+		PyErr_BadInternalCall();
+		return (unsigned long) -1;
+	}
+	v = (PyLongObject *)vv;
+	i = v->ob_size;
+	x = 0;
+	if (i < 0) {
+		PyErr_SetString(PyExc_OverflowError,
+			   "can't convert negative value to size_t");
+		return (size_t) -1;
+	}
+	switch (i) {
+	case 0: return 0;
+	case 1: return v->ob_digit[0];
+	}
+	while (--i >= 0) {
+		prev = x;
+		x = (x << SHIFT) + v->ob_digit[i];
+		if ((x >> SHIFT) != prev) {
+			PyErr_SetString(PyExc_OverflowError,
+				"int too large to convert");
+			return (unsigned long) -1;
+		}
+	}
+	return x;
+}
+
 /* Get a C unsigned long int from a long int object, ignoring the high bits.
    Returns -1 and sets an error condition if an error occurs. */
 
-unsigned long
-PyLong_AsUnsignedLongMask(PyObject *vv)
+static unsigned long
+_PyLong_AsUnsignedLongMask(PyObject *vv)
 {
 	register PyLongObject *v;
 	unsigned long x;
 	int sign;
 
 	if (vv == NULL || !PyLong_Check(vv)) {
-		if (vv != NULL && PyInt_Check(vv))
-			return PyInt_AsUnsignedLongMask(vv);
 		PyErr_BadInternalCall();
 		return (unsigned long) -1;
 	}
 	v = (PyLongObject *)vv;
 	i = v->ob_size;
+	switch (i) {
+	case 0: return 0;
+	case 1: return v->ob_digit[0];
+	}
 	sign = 1;
 	x = 0;
 	if (i < 0) {
 	return x * sign;
 }
 
+unsigned long
+PyLong_AsUnsignedLongMask(register PyObject *op)
+{
+	PyNumberMethods *nb;
+	PyLongObject *lo;
+	unsigned long val;
+
+	if (op && PyLong_Check(op))
+		return _PyLong_AsUnsignedLongMask(op);
+
+	if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
+	    nb->nb_int == NULL) {
+		PyErr_SetString(PyExc_TypeError, "an integer is required");
+		return (unsigned long)-1;
+	}
+
+	lo = (PyLongObject*) (*nb->nb_int) (op);
+	if (lo == NULL)
+		return (unsigned long)-1;
+	if (PyLong_Check(lo)) {
+		val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
+		Py_DECREF(lo);
+		if (PyErr_Occurred())
+			return (unsigned long)-1;
+		return val;
+	}
+	else
+	{
+		Py_DECREF(lo);
+		PyErr_SetString(PyExc_TypeError,
+				"nb_int should return int object");
+		return (unsigned long)-1;
+	}
+}
+
 int
 _PyLong_Sign(PyObject *vv)
 {
 	return result;
 
 Overflow:
-	PyErr_SetString(PyExc_OverflowError, "long has too many bits "
+	PyErr_SetString(PyExc_OverflowError, "int has too many bits "
 			"to express in a platform size_t");
 	return (size_t)-1;
 }
 		ndigits = -(v->ob_size);
 		if (!is_signed) {
 			PyErr_SetString(PyExc_TypeError,
-				"can't convert negative long to unsigned");
+				"can't convert negative int to unsigned");
 			return -1;
 		}
 		do_twos_comp = 1;
 	return 0;
 
 Overflow:
-	PyErr_SetString(PyExc_OverflowError, "long too big to convert");
+	PyErr_SetString(PyExc_OverflowError, "int too big to convert");
 	return -1;
 
 }
 
 overflow:
 	PyErr_SetString(PyExc_OverflowError,
-		"long int too large to convert to float");
+		"int too large to convert to float");
 	return -1.0;
 }
 
 PyObject *
 PyLong_FromVoidPtr(void *p)
 {
-#if SIZEOF_VOID_P <= SIZEOF_LONG
-	if ((long)p < 0)
-		return PyLong_FromUnsignedLong((unsigned long)p);
-	return PyInt_FromLong((long)p);
-#else
-
 #ifndef HAVE_LONG_LONG
 #   error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
 #endif
 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
 #   error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
 #endif
-	/* optimize null pointers */
-	if (p == NULL)
+	/* special-case null pointer */
+	if (!p)
 		return PyInt_FromLong(0);
-	return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
-
-#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
+	return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
+
 }
 
 /* Get a C pointer from a long object (or an int object in some cases) */
 #if SIZEOF_VOID_P <= SIZEOF_LONG
 	long x;
 
-	if (PyInt_Check(vv))
-		x = PyInt_AS_LONG(vv);
-	else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
+	if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
 		x = PyLong_AsLong(vv);
 	else
 		x = PyLong_AsUnsignedLong(vv);
 #endif
 	PY_LONG_LONG x;
 
-	if (PyInt_Check(vv))
-		x = PyInt_AS_LONG(vv);
-	else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
+	if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
 		x = PyLong_AsLongLong(vv);
 	else
 		x = PyLong_AsUnsignedLongLong(vv);
 	int ndigits = 0;
 	int negative = 0;
 
+	CHECK_SMALL_INT(ival);
 	if (ival < 0) {
 		ival = -ival;
 		negative = 1;
 	unsigned PY_LONG_LONG t;
 	int ndigits = 0;
 
+	if (ival < BASE)
+		return PyLong_FromLong(ival);
 	/* Count the number of Python digits. */
 	t = (unsigned PY_LONG_LONG)ival;
 	while (t) {
 /* Create a new long int object from a C Py_ssize_t. */
 
 PyObject *
-_PyLong_FromSsize_t(Py_ssize_t ival)
+PyLong_FromSsize_t(Py_ssize_t ival)
 {
 	Py_ssize_t bytes = ival;
 	int one = 1;
+	if (ival < BASE)
+		return PyLong_FromLong(ival);
+	return _PyLong_FromByteArray(
+			(unsigned char *)&bytes,
+			SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
+}
+
+/* Create a new long int object from a C size_t. */
+
+PyObject *
+PyLong_FromSize_t(size_t ival)
+{
+	size_t bytes = ival;
+	int one = 1;
+	if (ival < BASE)
+		return PyLong_FromLong(ival);
 	return _PyLong_FromByteArray(
 			(unsigned char *)&bytes,
 			SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
 }
 
-/* Create a new long int object from a C size_t. */
-
-PyObject *
-_PyLong_FromSize_t(size_t ival)
-{
-	size_t bytes = ival;
-	int one = 1;
-	return _PyLong_FromByteArray(
-			(unsigned char *)&bytes,
-			SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
-}
-
 /* Get a C PY_LONG_LONG int from a long int object.
    Return -1 and set an error if overflow occurs. */
 
 PY_LONG_LONG
 PyLong_AsLongLong(PyObject *vv)
 {
+	PyLongObject *v;
 	PY_LONG_LONG bytes;
 	int one = 1;
 	int res;
 	if (!PyLong_Check(vv)) {
 		PyNumberMethods *nb;
 		PyObject *io;
-		if (PyInt_Check(vv))
-			return (PY_LONG_LONG)PyInt_AsLong(vv);
 		if ((nb = vv->ob_type->tp_as_number) == NULL ||
 		    nb->nb_int == NULL) {
 			PyErr_SetString(PyExc_TypeError, "an integer is required");
 		io = (*nb->nb_int) (vv);
 		if (io == NULL)
 			return -1;
-		if (PyInt_Check(io)) {
-			bytes = PyInt_AsLong(io);
-			Py_DECREF(io);
-			return bytes;
-		}
 		if (PyLong_Check(io)) {
 			bytes = PyLong_AsLongLong(io);
 			Py_DECREF(io);
 		return -1;
 	}
 
+	v = (PyLongObject*)vv;
+	switch(v->ob_size) {
+	case -1: return -v->ob_digit[0];
+	case 0: return 0;
+	case 1: return v->ob_digit[0];
+	}
 	res = _PyLong_AsByteArray(
 			(PyLongObject *)vv, (unsigned char *)&bytes,
 			SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
 unsigned PY_LONG_LONG
 PyLong_AsUnsignedLongLong(PyObject *vv)
 {
+	PyLongObject *v;
 	unsigned PY_LONG_LONG bytes;
 	int one = 1;
 	int res;
 		return (unsigned PY_LONG_LONG)-1;
 	}
 
+	v = (PyLongObject*)vv;
+	switch(v->ob_size) {
+	case 0: return 0;
+	case 1: return v->ob_digit[0];
+	}
+
 	res = _PyLong_AsByteArray(
 			(PyLongObject *)vv, (unsigned char *)&bytes,
 			SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
 /* Get a C unsigned long int from a long int object, ignoring the high bits.
    Returns -1 and sets an error condition if an error occurs. */
 
-unsigned PY_LONG_LONG
-PyLong_AsUnsignedLongLongMask(PyObject *vv)
+static unsigned PY_LONG_LONG
+_PyLong_AsUnsignedLongLongMask(PyObject *vv)
 {
 	register PyLongObject *v;
 	unsigned PY_LONG_LONG x;
 		return (unsigned long) -1;
 	}
 	v = (PyLongObject *)vv;
+	switch(v->ob_size) {
+	case 0: return 0;
+	case 1: return v->ob_digit[0];
+	}
 	i = v->ob_size;
 	sign = 1;
 	x = 0;
 	}
 	return x * sign;
 }
+
+unsigned PY_LONG_LONG
+PyLong_AsUnsignedLongLongMask(register PyObject *op)
+{
+	PyNumberMethods *nb;
+	PyLongObject *lo;
+	unsigned PY_LONG_LONG val;
+
+	if (op && PyLong_Check(op))
+		return _PyLong_AsUnsignedLongLongMask(op);
+
+	if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
+	    nb->nb_int == NULL) {
+		PyErr_SetString(PyExc_TypeError, "an integer is required");
+		return (unsigned PY_LONG_LONG)-1;
+	}
+
+	lo = (PyLongObject*) (*nb->nb_int) (op);
+	if (lo == NULL)
+		return (unsigned PY_LONG_LONG)-1;
+	if (PyLong_Check(lo)) {
+		val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
+		Py_DECREF(lo);
+		if (PyErr_Occurred())
+			return (unsigned PY_LONG_LONG)-1;
+		return val;
+	}
+	else
+	{
+		Py_DECREF(lo);
+		PyErr_SetString(PyExc_TypeError,
+				"nb_int should return int object");
+		return (unsigned PY_LONG_LONG)-1;
+	}
+}
 #undef IS_LITTLE_ENDIAN
 
 #endif /* HAVE_LONG_LONG */
 		*a = (PyLongObject *) v;
 		Py_INCREF(v);
 	}
-	else if (PyInt_Check(v)) {
-		*a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
-	}
 	else {
 		return 0;
 	}
 		*b = (PyLongObject *) w;
 		Py_INCREF(w);
 	}
-	else if (PyInt_Check(w)) {
-		*b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
-	}
 	else {
 		Py_DECREF(*a);
 		return 0;
 	sz = i + j / bits;
 	if (j / SHIFT < size_a || sz < i) {
 		PyErr_SetString(PyExc_OverflowError,
-				"long is too large to format");
+				"int is too large to format");
 		return NULL;
 	}
 	str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
 	n = (p - start) * bits_per_char + SHIFT - 1;
 	if (n / bits_per_char < p - start) {
 		PyErr_SetString(PyExc_ValueError,
-				"long string too large to convert");
+				"int string too large to convert");
 		return NULL;
 	}
 	n = n / SHIFT;
 
 	if ((base != 0 && base < 2) || base > 36) {
 		PyErr_SetString(PyExc_ValueError,
-				"long() arg 2 must be >= 2 and <= 36");
+				"int() arg 2 must be >= 2 and <= 36");
 		return NULL;
 	}
 	while (*str != '\0' && isspace(Py_CHARMASK(*str)))
 	if (strrepr == NULL)
 		return NULL;
 	PyErr_Format(PyExc_ValueError,
-		     "invalid literal for long() with base %d: %s",
+		     "invalid literal for int() with base %d: %s",
 		     base, PyString_AS_STRING(strrepr));
 	Py_DECREF(strrepr);
 	return NULL;
 
 	if (size_b == 0) {
 		PyErr_SetString(PyExc_ZeroDivisionError,
-				"long division or modulo by zero");
+				"integer division or modulo by zero");
 		return -1;
 	}
 	if (size_a < size_b ||
 	    (size_a == size_b &&
 	     a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
 		/* |a| < |b|. */
-		*pdiv = _PyLong_New(0);
+		*pdiv = (PyLongObject*)PyLong_FromLong(0);
 		Py_INCREF(a);
 		*prem = (PyLongObject *) a;
 		return 0;
 	   the remainder r has the sign of a,
 	   so a = b*z + r. */
 	if ((a->ob_size < 0) != (b->ob_size < 0))
-		z->ob_size = -(z->ob_size);
+		NEGATE(z);
 	if (a->ob_size < 0 && (*prem)->ob_size != 0)