[Python-checkins] CVS: python/dist/src/Objects abstract.c,2.66,2.67

Tim Peters tim_one@users.sourceforge.net
Sat, 05 May 2001 04:33:45 -0700


Update of /cvsroot/python/python/dist/src/Objects
In directory usw-pr-cvs1:/tmp/cvs-serv7467/python/dist/src/Objects

Modified Files:
	abstract.c 
Log Message:
Generalize PySequence_Count() (operator.countOf) to work with iterators.


Index: abstract.c
===================================================================
RCS file: /cvsroot/python/python/dist/src/Objects/abstract.c,v
retrieving revision 2.66
retrieving revision 2.67
diff -C2 -r2.66 -r2.67
*** abstract.c	2001/05/05 10:06:16	2.66
--- abstract.c	2001/05/05 11:33:43	2.67
***************
*** 1334,1342 ****
  }
  
  int
  PySequence_Count(PyObject *s, PyObject *o)
  {
! 	int l, i, n, cmp, err;
! 	PyObject *item;
  
  	if (s == NULL || o == NULL) {
--- 1334,1343 ----
  }
  
+ /* Return # of times o appears in s. */
  int
  PySequence_Count(PyObject *s, PyObject *o)
  {
! 	int n;  /* running count of o hits */
! 	PyObject *it;  /* iter(s) */
  
  	if (s == NULL || o == NULL) {
***************
*** 1344,1365 ****
  		return -1;
  	}
! 	
! 	l = PySequence_Size(s);
! 	if (l < 0)
  		return -1;
  
  	n = 0;
! 	for (i = 0; i < l; i++) {
! 		item = PySequence_GetItem(s, i);
! 		if (item == NULL)
! 			return -1;
! 		err = PyObject_Cmp(item, o, &cmp);
  		Py_DECREF(item);
! 		if (err < 0)
! 			return err;
! 		if (cmp == 0)
  			n++;
  	}
  	return n;
  }
  
--- 1345,1383 ----
  		return -1;
  	}
! 
! 	it = PyObject_GetIter(s);
! 	if (it == NULL) {
! 		type_error(".count() requires iterable argument");
  		return -1;
+ 	}
  
  	n = 0;
! 	for (;;) {
! 		int cmp;
! 		PyObject *item = PyIter_Next(it);
! 		if (item == NULL) {
! 			if (PyErr_Occurred())
! 				goto Fail;
! 			break;
! 		}
! 		cmp = PyObject_RichCompareBool(o, item, Py_EQ);
  		Py_DECREF(item);
! 		if (cmp < 0)
! 			goto Fail;
! 		if (cmp > 0) {
! 			if (n == INT_MAX) {
! 				PyErr_SetString(PyExc_OverflowError,
! 				                "count exceeds C int size");
! 				goto Fail;
! 			}
  			n++;
+ 		}
  	}
+ 	Py_DECREF(it);
  	return n;
+ 
+ Fail:
+ 	Py_DECREF(it);
+ 	return -1;
  }