home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 4 / AACD04.ISO / AACD / Programming / Python / Source / Objects / listobject.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-04-25  |  36.6 KB  |  1,518 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* List object implementation */
  33.  
  34. #include "Python.h"
  35.  
  36. #ifdef STDC_HEADERS
  37. #include <stddef.h>
  38. #else
  39. #include <sys/types.h>        /* For size_t */
  40. #endif
  41.  
  42. #include "protos/listobject.h"
  43.  
  44. #define ROUNDUP(n, PyTryBlock) \
  45.     ((((n)+(PyTryBlock)-1)/(PyTryBlock))*(PyTryBlock))
  46.  
  47. static int
  48. roundupsize(n)
  49.     int n;
  50. {
  51.     if (n < 500)
  52.         return ROUNDUP(n, 10);
  53.     else
  54.         return ROUNDUP(n, 100);
  55. }
  56.  
  57. #define NRESIZE(var, type, nitems) PyMem_RESIZE(var, type, roundupsize(nitems))
  58.  
  59. PyObject *
  60. PyList_New(size)
  61.     int size;
  62. {
  63.     int i;
  64.     PyListObject *op;
  65.     size_t nbytes;
  66.     if (size < 0) {
  67.         PyErr_BadInternalCall();
  68.         return NULL;
  69.     }
  70.     nbytes = size * sizeof(PyObject *);
  71.     /* Check for overflow */
  72.     if (nbytes / sizeof(PyObject *) != (size_t)size) {
  73.         return PyErr_NoMemory();
  74.     }
  75.     op = (PyListObject *) malloc(sizeof(PyListObject));
  76.     if (op == NULL) {
  77.         return PyErr_NoMemory();
  78.     }
  79.     if (size <= 0) {
  80.         op->ob_item = NULL;
  81.     }
  82.     else {
  83.         op->ob_item = (PyObject **) malloc(nbytes);
  84.         if (op->ob_item == NULL) {
  85.             free((ANY *)op);
  86.             return PyErr_NoMemory();
  87.         }
  88.     }
  89.     op->ob_type = &PyList_Type;
  90.     op->ob_size = size;
  91.     for (i = 0; i < size; i++)
  92.         op->ob_item[i] = NULL;
  93.     _Py_NewReference(op);
  94.     return (PyObject *) op;
  95. }
  96.  
  97. int
  98. PyList_Size(op)
  99.     PyObject *op;
  100. {
  101.     if (!PyList_Check(op)) {
  102.         PyErr_BadInternalCall();
  103.         return -1;
  104.     }
  105.     else
  106.         return ((PyListObject *)op) -> ob_size;
  107. }
  108.  
  109. static PyObject *indexerr;
  110.  
  111. PyObject *
  112. PyList_GetItem(op, i)
  113.     PyObject *op;
  114.     int i;
  115. {
  116.     if (!PyList_Check(op)) {
  117.         PyErr_BadInternalCall();
  118.         return NULL;
  119.     }
  120.     if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
  121.         if (indexerr == NULL)
  122.             indexerr = PyString_FromString(
  123.                 "list index out of range");
  124.         PyErr_SetObject(PyExc_IndexError, indexerr);
  125.         return NULL;
  126.     }
  127.     return ((PyListObject *)op) -> ob_item[i];
  128. }
  129.  
  130. int
  131. PyList_SetItem(op, i, newitem)
  132.     register PyObject *op;
  133.     register int i;
  134.     register PyObject *newitem;
  135. {
  136.     register PyObject *olditem;
  137.     register PyObject **p;
  138.     if (!PyList_Check(op)) {
  139.         Py_XDECREF(newitem);
  140.         PyErr_BadInternalCall();
  141.         return -1;
  142.     }
  143.     if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
  144.         Py_XDECREF(newitem);
  145.         PyErr_SetString(PyExc_IndexError,
  146.                 "list assignment index out of range");
  147.         return -1;
  148.     }
  149.     p = ((PyListObject *)op) -> ob_item + i;
  150.     olditem = *p;
  151.     *p = newitem;
  152.     Py_XDECREF(olditem);
  153.     return 0;
  154. }
  155.  
  156. static int
  157. ins1(self, where, v)
  158.     PyListObject *self;
  159.     int where;
  160.     PyObject *v;
  161. {
  162.     int i;
  163.     PyObject **items;
  164.     if (v == NULL) {
  165.         PyErr_BadInternalCall();
  166.         return -1;
  167.     }
  168.     items = self->ob_item;
  169.     NRESIZE(items, PyObject *, self->ob_size+1);
  170.     if (items == NULL) {
  171.         PyErr_NoMemory();
  172.         return -1;
  173.     }
  174.     if (where < 0)
  175.         where = 0;
  176.     if (where > self->ob_size)
  177.         where = self->ob_size;
  178.     for (i = self->ob_size; --i >= where; )
  179.         items[i+1] = items[i];
  180.     Py_INCREF(v);
  181.     items[where] = v;
  182.     self->ob_item = items;
  183.     self->ob_size++;
  184.     return 0;
  185. }
  186.  
  187. int
  188. PyList_Insert(op, where, newitem)
  189.     PyObject *op;
  190.     int where;
  191.     PyObject *newitem;
  192. {
  193.     if (!PyList_Check(op)) {
  194.         PyErr_BadInternalCall();
  195.         return -1;
  196.     }
  197.     return ins1((PyListObject *)op, where, newitem);
  198. }
  199.  
  200. int
  201. PyList_Append(op, newitem)
  202.     PyObject *op;
  203.     PyObject *newitem;
  204. {
  205.     if (!PyList_Check(op)) {
  206.         PyErr_BadInternalCall();
  207.         return -1;
  208.     }
  209.     return ins1((PyListObject *)op,
  210.         (int) ((PyListObject *)op)->ob_size, newitem);
  211. }
  212.  
  213. /* Methods */
  214.  
  215. static void
  216. list_dealloc(op)
  217.     PyListObject *op;
  218. {
  219.     int i;
  220.     if (op->ob_item != NULL) {
  221.         for (i = 0; i < op->ob_size; i++) {
  222.             Py_XDECREF(op->ob_item[i]);
  223.         }
  224.         free((ANY *)op->ob_item);
  225.     }
  226.     free((ANY *)op);
  227. }
  228.  
  229. static int
  230. list_print(op, fp, flags)
  231.     PyListObject *op;
  232.     FILE *fp;
  233.     int flags;
  234. {
  235.     int i;
  236.  
  237.     i = Py_ReprEnter((PyObject*)op);
  238.     if (i != 0) {
  239.         if (i < 0)
  240.             return i;
  241.         fprintf(fp, "[...]");
  242.         return 0;
  243.     }
  244.     fprintf(fp, "[");
  245.     for (i = 0; i < op->ob_size; i++) {
  246.         if (i > 0)
  247.             fprintf(fp, ", ");
  248.         if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
  249.             Py_ReprLeave((PyObject *)op);
  250.             return -1;
  251.         }
  252.     }
  253.     fprintf(fp, "]");
  254.     Py_ReprLeave((PyObject *)op);
  255.     return 0;
  256. }
  257.  
  258. static PyObject *
  259. list_repr(v)
  260.     PyListObject *v;
  261. {
  262.     PyObject *s, *comma;
  263.     int i;
  264.  
  265.     i = Py_ReprEnter((PyObject*)v);
  266.     if (i != 0) {
  267.         if (i > 0)
  268.             return PyString_FromString("[...]");
  269.         return NULL;
  270.     }
  271.     s = PyString_FromString("[");
  272.     comma = PyString_FromString(", ");
  273.     for (i = 0; i < v->ob_size && s != NULL; i++) {
  274.         if (i > 0)
  275.             PyString_Concat(&s, comma);
  276.         PyString_ConcatAndDel(&s, PyObject_Repr(v->ob_item[i]));
  277.     }
  278.     Py_XDECREF(comma);
  279.     PyString_ConcatAndDel(&s, PyString_FromString("]"));
  280.     Py_ReprLeave((PyObject *)v);
  281.     return s;
  282. }
  283.  
  284. static int
  285. list_compare(v, w)
  286.     PyListObject *v, *w;
  287. {
  288.     int i;
  289.     for (i = 0; i < v->ob_size && i < w->ob_size; i++) {
  290.         int cmp = PyObject_Compare(v->ob_item[i], w->ob_item[i]);
  291.         if (cmp != 0)
  292.             return cmp;
  293.     }
  294.     return v->ob_size - w->ob_size;
  295. }
  296.  
  297. static int
  298. list_length(a)
  299.     PyListObject *a;
  300. {
  301.     return a->ob_size;
  302. }
  303.  
  304. static PyObject *
  305. list_item(a, i)
  306.     PyListObject *a;
  307.     int i;
  308. {
  309.     if (i < 0 || i >= a->ob_size) {
  310.         if (indexerr == NULL)
  311.             indexerr = PyString_FromString(
  312.                 "list index out of range");
  313.         PyErr_SetObject(PyExc_IndexError, indexerr);
  314.         return NULL;
  315.     }
  316.     Py_INCREF(a->ob_item[i]);
  317.     return a->ob_item[i];
  318. }
  319.  
  320. static PyObject *
  321. list_slice(a, ilow, ihigh)
  322.     PyListObject *a;
  323.     int ilow, ihigh;
  324. {
  325.     PyListObject *np;
  326.     int i;
  327.     if (ilow < 0)
  328.         ilow = 0;
  329.     else if (ilow > a->ob_size)
  330.         ilow = a->ob_size;
  331.     if (ihigh < ilow)
  332.         ihigh = ilow;
  333.     else if (ihigh > a->ob_size)
  334.         ihigh = a->ob_size;
  335.     np = (PyListObject *) PyList_New(ihigh - ilow);
  336.     if (np == NULL)
  337.         return NULL;
  338.     for (i = ilow; i < ihigh; i++) {
  339.         PyObject *v = a->ob_item[i];
  340.         Py_INCREF(v);
  341.         np->ob_item[i - ilow] = v;
  342.     }
  343.     return (PyObject *)np;
  344. }
  345.  
  346. PyObject *
  347. PyList_GetSlice(a, ilow, ihigh)
  348.     PyObject *a;
  349.     int ilow, ihigh;
  350. {
  351.     if (!PyList_Check(a)) {
  352.         PyErr_BadInternalCall();
  353.         return NULL;
  354.     }
  355.     return list_slice((PyListObject *)a, ilow, ihigh);
  356. }
  357.  
  358. static PyObject *
  359. list_concat(a, bb)
  360.     PyListObject *a;
  361.     PyObject *bb;
  362. {
  363.     int size;
  364.     int i;
  365.     PyListObject *np;
  366.     if (!PyList_Check(bb)) {
  367.         PyErr_BadArgument();
  368.         return NULL;
  369.     }
  370. #define b ((PyListObject *)bb)
  371.     size = a->ob_size + b->ob_size;
  372.     np = (PyListObject *) PyList_New(size);
  373.     if (np == NULL) {
  374.         return NULL;
  375.     }
  376.     for (i = 0; i < a->ob_size; i++) {
  377.         PyObject *v = a->ob_item[i];
  378.         Py_INCREF(v);
  379.         np->ob_item[i] = v;
  380.     }
  381.     for (i = 0; i < b->ob_size; i++) {
  382.         PyObject *v = b->ob_item[i];
  383.         Py_INCREF(v);
  384.         np->ob_item[i + a->ob_size] = v;
  385.     }
  386.     return (PyObject *)np;
  387. #undef b
  388. }
  389.  
  390. static PyObject *
  391. list_repeat(a, n)
  392.     PyListObject *a;
  393.     int n;
  394. {
  395.     int i, j;
  396.     int size;
  397.     PyListObject *np;
  398.     PyObject **p;
  399.     if (n < 0)
  400.         n = 0;
  401.     size = a->ob_size * n;
  402.     np = (PyListObject *) PyList_New(size);
  403.     if (np == NULL)
  404.         return NULL;
  405.     p = np->ob_item;
  406.     for (i = 0; i < n; i++) {
  407.         for (j = 0; j < a->ob_size; j++) {
  408.             *p = a->ob_item[j];
  409.             Py_INCREF(*p);
  410.             p++;
  411.         }
  412.     }
  413.     return (PyObject *) np;
  414. }
  415.  
  416. static int
  417. list_ass_slice(a, ilow, ihigh, v)
  418.     PyListObject *a;
  419.     int ilow, ihigh;
  420.     PyObject *v;
  421. {
  422.     /* Because [X]DECREF can recursively invoke list operations on
  423.        this list, we must postpone all [X]DECREF activity until
  424.        after the list is back in its canonical shape.  Therefore
  425.        we must allocate an additional array, 'recycle', into which
  426.        we temporarily copy the items that are deleted from the
  427.        list. :-( */
  428.     PyObject **recycle, **p;
  429.     PyObject **item;
  430.     int n; /* Size of replacement list */
  431.     int d; /* Change in size */
  432.     int k; /* Loop index */
  433. #define b ((PyListObject *)v)
  434.     if (v == NULL)
  435.         n = 0;
  436.     else if (PyList_Check(v)) {
  437.         n = b->ob_size;
  438.         if (a == b) {
  439.             /* Special case "a[i:j] = a" -- copy b first */
  440.             int ret;
  441.             v = list_slice(b, 0, n);
  442.             ret = list_ass_slice(a, ilow, ihigh, v);
  443.             Py_DECREF(v);
  444.             return ret;
  445.         }
  446.     }
  447.     else {
  448.         PyErr_BadArgument();
  449.         return -1;
  450.     }
  451.     if (ilow < 0)
  452.         ilow = 0;
  453.     else if (ilow > a->ob_size)
  454.         ilow = a->ob_size;
  455.     if (ihigh < ilow)
  456.         ihigh = ilow;
  457.     else if (ihigh > a->ob_size)
  458.         ihigh = a->ob_size;
  459.     item = a->ob_item;
  460.     d = n - (ihigh-ilow);
  461.     if (ihigh > ilow)
  462.         p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
  463.     else
  464.         p = recycle = NULL;
  465.     if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
  466.         for (k = ilow; k < ihigh; k++)
  467.             *p++ = item[k];
  468.         if (d < 0) {
  469.             for (/*k = ihigh*/; k < a->ob_size; k++)
  470.                 item[k+d] = item[k];
  471.             a->ob_size += d;
  472.             NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
  473.             a->ob_item = item;
  474.         }
  475.     }
  476.     else { /* Insert d items; recycle ihigh-ilow items */
  477.         NRESIZE(item, PyObject *, a->ob_size + d);
  478.         if (item == NULL) {
  479.             PyMem_XDEL(recycle);
  480.             PyErr_NoMemory();
  481.             return -1;
  482.         }
  483.         for (k = a->ob_size; --k >= ihigh; )
  484.             item[k+d] = item[k];
  485.         for (/*k = ihigh-1*/; k >= ilow; --k)
  486.             *p++ = item[k];
  487.         a->ob_item = item;
  488.         a->ob_size += d;
  489.     }
  490.     for (k = 0; k < n; k++, ilow++) {
  491.         PyObject *w = b->ob_item[k];
  492.         Py_XINCREF(w);
  493.         item[ilow] = w;
  494.     }
  495.     if (recycle) {
  496.         while (--p >= recycle)
  497.             Py_XDECREF(*p);
  498.         PyMem_DEL(recycle);
  499.     }
  500.     return 0;
  501. #undef b
  502. }
  503.  
  504. int
  505. PyList_SetSlice(a, ilow, ihigh, v)
  506.     PyObject *a;
  507.     int ilow, ihigh;
  508.     PyObject *v;
  509. {
  510.     if (!PyList_Check(a)) {
  511.         PyErr_BadInternalCall();
  512.         return -1;
  513.     }
  514.     return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
  515. }
  516.  
  517. static int
  518. list_ass_item(a, i, v)
  519.     PyListObject *a;
  520.     int i;
  521.     PyObject *v;
  522. {
  523.     PyObject *old_value;
  524.     if (i < 0 || i >= a->ob_size) {
  525.         PyErr_SetString(PyExc_IndexError,
  526.                 "list assignment index out of range");
  527.         return -1;
  528.     }
  529.     if (v == NULL)
  530.         return list_ass_slice(a, i, i+1, v);
  531.     Py_INCREF(v);
  532.     old_value = a->ob_item[i];
  533.     a->ob_item[i] = v;
  534.     Py_DECREF(old_value); 
  535.     return 0;
  536. }
  537.  
  538. static PyObject *
  539. ins(self, where, v)
  540.     PyListObject *self;
  541.     int where;
  542.     PyObject *v;
  543. {
  544.     if (ins1(self, where, v) != 0)
  545.         return NULL;
  546.     Py_INCREF(Py_None);
  547.     return Py_None;
  548. }
  549.  
  550. static PyObject *
  551. listinsert(self, args)
  552.     PyListObject *self;
  553.     PyObject *args;
  554. {
  555.     int i;
  556.     PyObject *v;
  557.     if (!PyArg_Parse(args, "(iO)", &i, &v))
  558.         return NULL;
  559.     return ins(self, i, v);
  560. }
  561.  
  562. static PyObject *
  563. listappend(self, args)
  564.     PyListObject *self;
  565.     PyObject *args;
  566. {
  567.     PyObject *v;
  568.     if (!PyArg_Parse(args, "O", &v))
  569.         return NULL;
  570.     return ins(self, (int) self->ob_size, v);
  571. }
  572.  
  573. static PyObject *
  574. listextend(self, args)
  575.     PyListObject *self;
  576.     PyObject *args;
  577. {
  578.     PyObject *b = NULL, *res = NULL;
  579.     PyObject **items;
  580.     int selflen = PyList_GET_SIZE(self);
  581.     int blen;
  582.     register int i;
  583.  
  584.     if (!PyArg_ParseTuple(args, "O", &b))
  585.         return NULL;
  586.  
  587.     if (!PyList_Check(b)) {
  588.         PyErr_SetString(PyExc_TypeError,
  589.                 "list.extend() argument must be a list");
  590.         return NULL;
  591.     }
  592.     if (PyList_GET_SIZE(b) == 0) {
  593.         /* short circuit when b is empty */
  594.         Py_INCREF(Py_None);
  595.         return Py_None;
  596.     }
  597.     if (self == (PyListObject*)b) {
  598.         /* as in list_ass_slice() we must special case the
  599.          * situation: a.extend(a)
  600.          *
  601.          * XXX: I think this way ought to be faster than using
  602.          * list_slice() the way list_ass_slice() does.
  603.          */
  604.         b = PyList_New(selflen);
  605.         if (!b)
  606.             return NULL;
  607.         for (i = 0; i < selflen; i++) {
  608.             PyObject *o = PyList_GET_ITEM(self, i);
  609.             Py_INCREF(o);
  610.             PyList_SET_ITEM(b, i, o);
  611.         }
  612.     }
  613.     else
  614.         /* we want b to have the same refcount semantics for the
  615.          * Py_XDECREF() in the finally clause regardless of which
  616.          * branch in the above conditional we took.
  617.          */
  618.         Py_INCREF(b);
  619.  
  620.     blen = PyList_GET_SIZE(b);
  621.     /* resize a using idiom */
  622.     items = self->ob_item;
  623.     NRESIZE(items, PyObject*, selflen + blen);
  624.     if (items == NULL ) {
  625.         PyErr_NoMemory();
  626.         goto finally;
  627.     }
  628.     self->ob_item = items;
  629.  
  630.     /* populate the end self with b's items */
  631.     for (i = 0; i < blen; i++) {
  632.         PyObject *o = PyList_GET_ITEM(b, i);
  633.         Py_INCREF(o);
  634.         PyList_SET_ITEM(self, self->ob_size++, o);
  635.     }
  636.     res = Py_None;
  637.     Py_INCREF(res);
  638.   finally:
  639.     Py_XDECREF(b);
  640.     return res;
  641. }
  642.  
  643.  
  644. static PyObject *
  645. listpop(self, args)
  646.     PyListObject *self;
  647.     PyObject *args;
  648. {
  649.     int i = -1;
  650.     PyObject *v;
  651.     if (!PyArg_ParseTuple(args, "|i", &i))
  652.         return NULL;
  653.     if (self->ob_size == 0) {
  654.         /* Special-case most common failure cause */
  655.         PyErr_SetString(PyExc_IndexError, "pop from empty list");
  656.         return NULL;
  657.     }
  658.     if (i < 0)
  659.         i += self->ob_size;
  660.     if (i < 0 || i >= self->ob_size) {
  661.         PyErr_SetString(PyExc_IndexError, "pop index out of range");
  662.         return NULL;
  663.     }
  664.     v = self->ob_item[i];
  665.     Py_INCREF(v);
  666.     if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
  667.         Py_DECREF(v);
  668.         return NULL;
  669.     }
  670.     return v;
  671. }
  672.  
  673. /* New quicksort implementation for arrays of object pointers.
  674.    Thanks to discussions with Tim Peters. */
  675.  
  676. /* CMPERROR is returned by our comparison function when an error
  677.    occurred.  This is the largest negative integer (0x80000000 on a
  678.    32-bit system). */
  679. #define CMPERROR ( (int) ((unsigned int)1 << (8*sizeof(int) - 1)) )
  680.  
  681. /* Comparison function.  Takes care of calling a user-supplied
  682.    comparison function (any callable Python object).  Calls the
  683.    standard comparison function, PyObject_Compare(), if the user-
  684.    supplied function is NULL. */
  685.  
  686. static int
  687. docompare(x, y, compare)
  688.     PyObject *x;
  689.     PyObject *y;
  690.     PyObject *compare;
  691. {
  692.     PyObject *args, *res;
  693.     int i;
  694.  
  695.     if (compare == NULL) {
  696.         i = PyObject_Compare(x, y);
  697.         if (i && PyErr_Occurred())
  698.             i = CMPERROR;
  699.         return i;
  700.     }
  701.  
  702.     args = Py_BuildValue("(OO)", x, y);
  703.     if (args == NULL)
  704.         return CMPERROR;
  705.     res = PyEval_CallObject(compare, args);
  706.     Py_DECREF(args);
  707.     if (res == NULL)
  708.         return CMPERROR;
  709.     if (!PyInt_Check(res)) {
  710.         Py_DECREF(res);
  711.         PyErr_SetString(PyExc_TypeError,
  712.                 "comparison function should return int");
  713.         return CMPERROR;
  714.     }
  715.     i = PyInt_AsLong(res);
  716.     Py_DECREF(res);
  717.     if (i < 0)
  718.         return -1;
  719.     if (i > 0)
  720.         return 1;
  721.     return 0;
  722. }
  723.  
  724. /* MINSIZE is the smallest array that will get a full-blown samplesort
  725.    treatment; smaller arrays are sorted using binary insertion.  It must
  726.    be at least 7 for the samplesort implementation to work.  Binary
  727.    insertion does fewer compares, but can suffer O(N**2) data movement.
  728.    The more expensive compares, the larger MINSIZE should be. */
  729. #define MINSIZE 100
  730.  
  731. /* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
  732.    partition; smaller slices are passed to binarysort.  It must be at
  733.    least 2, and no larger than MINSIZE.  Setting it higher reduces the #
  734.    of compares slowly, but increases the amount of data movement quickly.
  735.    The value here was chosen assuming a compare costs ~25x more than
  736.    swapping a pair of memory-resident pointers -- but under that assumption,
  737.    changing the value by a few dozen more or less has aggregate effect
  738.    under 1%.  So the value is crucial, but not touchy <wink>. */
  739. #define MINPARTITIONSIZE 40
  740.  
  741. /* MAXMERGE is the largest number of elements we'll always merge into
  742.    a known-to-be sorted chunk via binary insertion, regardless of the
  743.    size of that chunk.  Given a chunk of N sorted elements, and a group
  744.    of K unknowns, the largest K for which it's better to do insertion
  745.    (than a full-blown sort) is a complicated function of N and K mostly
  746.    involving the expected number of compares and data moves under each
  747.    approach, and the relative cost of those operations on a specific
  748.    architecure.  The fixed value here is conservative, and should be a
  749.    clear win regardless of architecture or N. */
  750. #define MAXMERGE 15
  751.  
  752. /* STACKSIZE is the size of our work stack.  A rough estimate is that
  753.    this allows us to sort arrays of size N where
  754.    N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
  755.    for arrays of size 2**64.  Because we push the biggest partition
  756.    first, the worst case occurs when all subarrays are always partitioned
  757.    exactly in two. */
  758. #define STACKSIZE 60
  759.  
  760.  
  761. #define SETK(X,Y) if ((k = docompare(X,Y,compare))==CMPERROR) goto fail
  762.  
  763. /* binarysort is the best method for sorting small arrays: it does
  764.    few compares, but can do data movement quadratic in the number of
  765.    elements.
  766.    [lo, hi) is a contiguous slice of a list, and is sorted via
  767.    binary insertion.
  768.    On entry, must have lo <= start <= hi, and that [lo, start) is already
  769.    sorted (pass start == lo if you don't know!).
  770.    If docompare complains (returns CMPERROR) return -1, else 0.
  771.    Even in case of error, the output slice will be some permutation of
  772.    the input (nothing is lost or duplicated).
  773. */
  774.  
  775. static int
  776. binarysort(lo, hi, start, compare)
  777.     PyObject **lo;
  778.     PyObject **hi;
  779.     PyObject **start;
  780.     PyObject *compare;/* Comparison function object, or NULL for default */
  781. {
  782.     /* assert lo <= start <= hi
  783.        assert [lo, start) is sorted */
  784.     register int k;
  785.     register PyObject **l, **p, **r;
  786.     register PyObject *pivot;
  787.  
  788.     if (lo == start)
  789.         ++start;
  790.     for (; start < hi; ++start) {
  791.         /* set l to where *start belongs */
  792.         l = lo;
  793.         r = start;
  794.         pivot = *r;
  795.         do {
  796.             p = l + ((r - l) >> 1);
  797.             SETK(pivot, *p);
  798.             if (k < 0)
  799.                 r = p;
  800.             else
  801.                 l = p + 1;
  802.         } while (l < r);
  803.         /* Pivot should go at l -- slide over to make room.
  804.            Caution: using memmove is much slower under MSVC 5;
  805.            we're not usually moving many slots. */
  806.         for (p = start; p > l; --p)
  807.             *p = *(p-1);
  808.         *l = pivot;
  809.     }
  810.     return 0;
  811.  
  812.  fail:
  813.     return -1;
  814. }
  815.  
  816. /* samplesortslice is the sorting workhorse.
  817.    [lo, hi) is a contiguous slice of a list, to be sorted in place.
  818.    On entry, must have lo <= hi,
  819.    If docompare complains (returns CMPERROR) return -1, else 0.
  820.    Even in case of error, the output slice will be some permutation of
  821.    the input (nothing is lost or duplicated).
  822.  
  823.    samplesort is basically quicksort on steroids:  a power of 2 close
  824.    to n/ln(n) is computed, and that many elements (less 1) are picked at
  825.    random from the array and sorted.  These 2**k - 1 elements are then
  826.    used as preselected pivots for an equal number of quicksort
  827.    partitioning steps, partitioning the slice into 2**k chunks each of
  828.    size about ln(n).  These small final chunks are then usually handled
  829.    by binarysort.  Note that when k=1, this is roughly the same as an
  830.    ordinary quicksort using a random pivot, and when k=2 this is roughly
  831.    a median-of-3 quicksort.  From that view, using k ~= lg(n/ln(n)) makes
  832.    this a "median of n/ln(n)" quicksort.  You can also view it as a kind
  833.    of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
  834.  
  835.    The large number of samples makes a quadratic-time case almost
  836.    impossible, and asymptotically drives the average-case number of
  837.    compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
  838.    3 variant) down to N lg N.
  839.  
  840.    We also play lots of low-level tricks to cut the number of compares.
  841.    
  842.    Very obscure:  To avoid using extra memory, the PPs are stored in the
  843.    array and shuffled around as partitioning proceeds.  At the start of a
  844.    partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
  845.    adjacent (either on the left or the right!) to a chunk of X elements
  846.    that are to be partitioned: P X or X P.  In either case we need to
  847.    shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
  848.    left, followed by the PP to be used for this step (that's the middle
  849.    of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
  850.        P X or X P -> Psmall pivot X Plarge
  851.    and the order of the PPs must not be altered.  It can take a while
  852.    to realize this isn't trivial!  It can take even longer <wink> to
  853.    understand why the simple code below works, using only 2**(m-1) swaps.
  854.    The key is that the order of the X elements isn't necessarily
  855.    preserved:  X can end up as some cyclic permutation of its original
  856.    order.  That's OK, because X is unsorted anyway.  If the order of X
  857.    had to be preserved too, the simplest method I know of using O(1)
  858.    scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
  859.    Since len(X) is typically several times larger than 2**(m-1), that
  860.    would slow things down.
  861. */
  862.  
  863. struct SamplesortStackNode {
  864.     /* Represents a slice of the array, from (& including) lo up
  865.        to (but excluding) hi.  "extra" additional & adjacent elements
  866.        are pre-selected pivots (PPs), spanning [lo-extra, lo) if
  867.        extra > 0, or [hi, hi-extra) if extra < 0.  The PPs are
  868.        already sorted, but nothing is known about the other elements
  869.        in [lo, hi). |extra| is always one less than a power of 2.
  870.        When extra is 0, we're out of PPs, and the slice must be
  871.        sorted by some other means. */
  872.     PyObject **lo;
  873.     PyObject **hi;
  874.     int extra;
  875. };
  876.  
  877. /* The number of PPs we want is 2**k - 1, where 2**k is as close to
  878.    N / ln(N) as possible.  So k ~= lg(N / ln(N)).  Calling libm routines
  879.    is undesirable, so cutoff values are canned in the "cutoff" table
  880.    below:  cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
  881. #define CUTOFFBASE 4
  882. static long cutoff[] = {
  883.     43,        /* smallest N such that k == 4 */
  884.     106,       /* etc */
  885.     250,
  886.     576,
  887.     1298,
  888.     2885,
  889.     6339,
  890.     13805,
  891.     29843,
  892.     64116,
  893.     137030,
  894.     291554,
  895.     617916,
  896.     1305130,
  897.     2748295,
  898.     5771662,
  899.     12091672,
  900.     25276798,
  901.     52734615,
  902.     109820537,
  903.     228324027,
  904.     473977813,
  905.     982548444,   /* smallest N such that k == 26 */
  906.     2034159050   /* largest N that fits in signed 32-bit; k == 27 */
  907. };
  908.  
  909. static int
  910. samplesortslice(lo, hi, compare)
  911.     PyObject **lo;
  912.     PyObject **hi;
  913.     PyObject *compare;/* Comparison function object, or NULL for default */
  914. {
  915.     register PyObject **l, **r;
  916.     register PyObject *tmp, *pivot;
  917.     register int k;
  918.     int n, extra, top, extraOnRight;
  919.     struct SamplesortStackNode stack[STACKSIZE];
  920.  
  921.     /* assert lo <= hi */
  922.     n = hi - lo;
  923.  
  924.     /* ----------------------------------------------------------
  925.      * Special cases
  926.      * --------------------------------------------------------*/
  927.     if (n < 2)
  928.         return 0;
  929.  
  930.     /* Set r to the largest value such that [lo,r) is sorted.
  931.        This catches the already-sorted case, the all-the-same
  932.        case, and the appended-a-few-elements-to-a-sorted-list case.
  933.        If the array is unsorted, we're very likely to get out of
  934.        the loop fast, so the test is cheap if it doesn't pay off.
  935.     */
  936.     /* assert lo < hi */
  937.     for (r = lo+1; r < hi; ++r) {
  938.         SETK(*r, *(r-1));
  939.         if (k < 0)
  940.             break;
  941.     }
  942.     /* [lo,r) is sorted, [r,hi) unknown.  Get out cheap if there are
  943.        few unknowns, or few elements in total. */
  944.     if (hi - r <= MAXMERGE || n < MINSIZE)
  945.         return binarysort(lo, hi, r, compare);
  946.  
  947.     /* Check for the array already being reverse-sorted.  Typical
  948.        benchmark-driven silliness <wink>. */
  949.     /* assert lo < hi */
  950.     for (r = lo+1; r < hi; ++r) {
  951.         SETK(*(r-1), *r);
  952.         if (k < 0)
  953.             break;
  954.     }
  955.     if (hi - r <= MAXMERGE) {
  956.         /* Reverse the reversed prefix, then insert the tail */
  957.         PyObject **originalr = r;
  958.         l = lo;
  959.         do {
  960.             --r;
  961.             tmp = *l; *l = *r; *r = tmp;
  962.             ++l;
  963.         } while (l < r);
  964.         return binarysort(lo, hi, originalr, compare);
  965.     }
  966.  
  967.     /* ----------------------------------------------------------
  968.      * Normal case setup: a large array without obvious pattern.
  969.      * --------------------------------------------------------*/
  970.  
  971.     /* extra := a power of 2 ~= n/ln(n), less 1.
  972.        First find the smallest extra s.t. n < cutoff[extra] */
  973.     for (extra = 0;
  974.          extra < sizeof(cutoff) / sizeof(cutoff[0]);
  975.          ++extra) {
  976.         if (n < cutoff[extra])
  977.             break;
  978.         /* note that if we fall out of the loop, the value of
  979.            extra still makes *sense*, but may be smaller than
  980.            we would like (but the array has more than ~= 2**31
  981.            elements in this case!) */ 
  982.     }
  983.     /* Now k == extra - 1 + CUTOFFBASE.  The smallest value k can
  984.        have is CUTOFFBASE-1, so
  985.        assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
  986.     extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
  987.     /* assert extra > 0 and n >= extra */
  988.  
  989.     /* Swap that many values to the start of the array.  The
  990.        selection of elements is pseudo-random, but the same on
  991.        every run (this is intentional! timing algorithm changes is
  992.        a pain if timing varies across runs).  */
  993.     {
  994.         unsigned int seed = n / extra;  /* arbitrary */
  995.         unsigned int i;
  996.         for (i = 0; i < (unsigned)extra; ++i) {
  997.             /* j := random int in [i, n) */
  998.             unsigned int j;
  999.             seed = seed * 69069 + 7;
  1000.             j = i + seed % (n - i);
  1001.             tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
  1002.         }
  1003.     }
  1004.  
  1005.     /* Recursively sort the preselected pivots. */
  1006.     if (samplesortslice(lo, lo + extra, compare) < 0)
  1007.         goto fail;
  1008.  
  1009.     top = 0;          /* index of available stack slot */
  1010.     lo += extra;      /* point to first unknown */
  1011.     extraOnRight = 0; /* the PPs are at the left end */
  1012.  
  1013.     /* ----------------------------------------------------------
  1014.      * Partition [lo, hi), and repeat until out of work.
  1015.      * --------------------------------------------------------*/
  1016.     for (;;) {
  1017.         /* assert lo <= hi, so n >= 0 */
  1018.         n = hi - lo;
  1019.  
  1020.         /* We may not want, or may not be able, to partition:
  1021.            If n is small, it's quicker to insert.
  1022.            If extra is 0, we're out of pivots, and *must* use
  1023.            another method.
  1024.         */
  1025.         if (n < MINPARTITIONSIZE || extra == 0) {
  1026.             if (n >= MINSIZE) {
  1027.                 /* assert extra == 0
  1028.                    This is rare, since the average size
  1029.                    of a final block is only about
  1030.                    ln(original n). */
  1031.                 if (samplesortslice(lo, hi, compare) < 0)
  1032.                     goto fail;
  1033.             }
  1034.             else {
  1035.                 /* Binary insertion should be quicker,
  1036.                    and we can take advantage of the PPs
  1037.                    already being sorted. */
  1038.                 if (extraOnRight && extra) {
  1039.                     /* swap the PPs to the left end */
  1040.                     k = extra;
  1041.                     do {
  1042.                         tmp = *lo;
  1043.                         *lo = *hi;
  1044.                         *hi = tmp;
  1045.                         ++lo; ++hi;
  1046.                     } while (--k);
  1047.                 }
  1048.                 if (binarysort(lo - extra, hi, lo,
  1049.                            compare) < 0)
  1050.                     goto fail;
  1051.             }
  1052.  
  1053.             /* Find another slice to work on. */
  1054.             if (--top < 0)
  1055.                 break;   /* no more -- done! */
  1056.             lo = stack[top].lo;
  1057.             hi = stack[top].hi;
  1058.             extra = stack[top].extra;
  1059.             extraOnRight = 0;
  1060.             if (extra < 0) {
  1061.                 extraOnRight = 1;
  1062.                 extra = -extra;
  1063.             }
  1064.             continue;
  1065.         }
  1066.  
  1067.         /* Pretend the PPs are indexed 0, 1, ..., extra-1.
  1068.            Then our preselected pivot is at (extra-1)/2, and we
  1069.            want to move the PPs before that to the left end of
  1070.            the slice, and the PPs after that to the right end.
  1071.            The following section changes extra, lo, hi, and the
  1072.            slice such that:
  1073.            [lo-extra, lo) contains the smaller PPs.
  1074.            *lo == our PP.
  1075.            (lo, hi) contains the unknown elements.
  1076.            [hi, hi+extra) contains the larger PPs.
  1077.         */
  1078.         k = extra >>= 1;  /* num PPs to move */ 
  1079.         if (extraOnRight) {
  1080.             /* Swap the smaller PPs to the left end.
  1081.                Note that this loop actually moves k+1 items:
  1082.                the last is our PP */
  1083.             do {
  1084.                 tmp = *lo; *lo = *hi; *hi = tmp;
  1085.                 ++lo; ++hi;
  1086.             } while (k--);
  1087.         }
  1088.         else {
  1089.             /* Swap the larger PPs to the right end. */
  1090.             while (k--) {
  1091.                 --lo; --hi;
  1092.                 tmp = *lo; *lo = *hi; *hi = tmp;
  1093.             }
  1094.         }
  1095.         --lo;   /* *lo is now our PP */
  1096.         pivot = *lo;
  1097.  
  1098.         /* Now an almost-ordinary quicksort partition step.
  1099.            Note that most of the time is spent here!
  1100.            Only odd thing is that we partition into < and >=,
  1101.            instead of the usual <= and >=.  This helps when
  1102.            there are lots of duplicates of different values,
  1103.            because it eventually tends to make subfiles
  1104.            "pure" (all duplicates), and we special-case for
  1105.            duplicates later. */
  1106.         l = lo + 1;
  1107.         r = hi - 1;
  1108.         /* assert lo < l < r < hi (small n weeded out above) */
  1109.  
  1110.         do {
  1111.             /* slide l right, looking for key >= pivot */
  1112.             do {
  1113.                 SETK(*l, pivot);
  1114.                 if (k < 0)
  1115.                     ++l;
  1116.                 else
  1117.                     break;
  1118.             } while (l < r);
  1119.  
  1120.             /* slide r left, looking for key < pivot */
  1121.             while (l < r) {
  1122.                 register PyObject *rval = *r--;
  1123.                 SETK(rval, pivot);
  1124.                 if (k < 0) {
  1125.                     /* swap and advance */
  1126.                     r[1] = *l;
  1127.                     *l++ = rval;
  1128.                     break;
  1129.                 }
  1130.             }
  1131.  
  1132.         } while (l < r);
  1133.  
  1134.         /* assert lo < r <= l < hi
  1135.            assert r == l or r+1 == l
  1136.            everything to the left of l is < pivot, and
  1137.            everything to the right of r is >= pivot */
  1138.  
  1139.         if (l == r) {
  1140.             SETK(*r, pivot);
  1141.             if (k < 0)
  1142.                 ++l;
  1143.             else
  1144.                 --r;
  1145.         }
  1146.         /* assert lo <= r and r+1 == l and l <= hi
  1147.            assert r == lo or a[r] < pivot
  1148.            assert a[lo] is pivot
  1149.            assert l == hi or a[l] >= pivot
  1150.            Swap the pivot into "the middle", so we can henceforth
  1151.            ignore it.
  1152.         */
  1153.         *lo = *r;
  1154.         *r = pivot;
  1155.  
  1156.         /* The following is true now, & will be preserved:
  1157.            All in [lo,r) are < pivot
  1158.            All in [r,l) == pivot (& so can be ignored)
  1159.            All in [l,hi) are >= pivot */
  1160.  
  1161.         /* Check for duplicates of the pivot.  One compare is
  1162.            wasted if there are no duplicates, but can win big
  1163.            when there are.
  1164.            Tricky: we're sticking to "<" compares, so deduce
  1165.            equality indirectly.  We know pivot <= *l, so they're
  1166.            equal iff not pivot < *l.
  1167.         */
  1168.         while (l < hi) {
  1169.             /* pivot <= *l known */
  1170.             SETK(pivot, *l);
  1171.             if (k < 0)
  1172.                 break;
  1173.             else
  1174.                 /* <= and not < implies == */
  1175.                 ++l;
  1176.         }
  1177.  
  1178.         /* assert lo <= r < l <= hi
  1179.            Partitions are [lo, r) and [l, hi) */
  1180.  
  1181.         /* push fattest first; remember we still have extra PPs
  1182.            to the left of the left chunk and to the right of
  1183.            the right chunk! */
  1184.         /* assert top < STACKSIZE */
  1185.         if (r - lo <= hi - l) {
  1186.             /* second is bigger */
  1187.             stack[top].lo = l;
  1188.             stack[top].hi = hi;
  1189.             stack[top].extra = -extra;
  1190.             hi = r;
  1191.             extraOnRight = 0;
  1192.         }
  1193.         else {
  1194.             /* first is bigger */
  1195.             stack[top].lo = lo;
  1196.             stack[top].hi = r;
  1197.             stack[top].extra = extra;
  1198.             lo = l;
  1199.             extraOnRight = 1;
  1200.         }
  1201.         ++top;
  1202.  
  1203.     }   /* end of partitioning loop */
  1204.  
  1205.     return 0;
  1206.  
  1207.  fail:
  1208.     return -1;
  1209. }
  1210.  
  1211. #undef SETK
  1212.  
  1213. staticforward PyTypeObject immutable_list_type;
  1214.  
  1215. static PyObject *
  1216. listsort(self, compare)
  1217.     PyListObject *self;
  1218.     PyObject *compare;
  1219. {
  1220.     int err;
  1221.  
  1222.     self->ob_type = &immutable_list_type;
  1223.     err = samplesortslice(self->ob_item,
  1224.                   self->ob_item + self->ob_size,
  1225.                   compare);
  1226.     self->ob_type = &PyList_Type;
  1227.     if (err < 0)
  1228.         return NULL;
  1229.     Py_INCREF(Py_None);
  1230.     return Py_None;
  1231. }
  1232.  
  1233. int
  1234. PyList_Sort(v)
  1235.     PyObject *v;
  1236. {
  1237.     if (v == NULL || !PyList_Check(v)) {
  1238.         PyErr_BadInternalCall();
  1239.         return -1;
  1240.     }
  1241.     v = listsort((PyListObject *)v, (PyObject *)NULL);
  1242.     if (v == NULL)
  1243.         return -1;
  1244.     Py_DECREF(v);
  1245.     return 0;
  1246. }
  1247.  
  1248. static PyObject *
  1249. listreverse(self, args)
  1250.     PyListObject *self;
  1251.     PyObject *args;
  1252. {
  1253.     register PyObject **p, **q;
  1254.     register PyObject *tmp;
  1255.     
  1256.     if (args != NULL) {
  1257.         PyErr_BadArgument();
  1258.         return NULL;
  1259.     }
  1260.  
  1261.     if (self->ob_size > 1) {
  1262.         for (p = self->ob_item, q = self->ob_item + self->ob_size - 1;
  1263.                         p < q; p++, q--) {
  1264.             tmp = *p;
  1265.             *p = *q;
  1266.             *q = tmp;
  1267.         }
  1268.     }
  1269.     
  1270.     Py_INCREF(Py_None);
  1271.     return Py_None;
  1272. }
  1273.  
  1274. int
  1275. PyList_Reverse(v)
  1276.     PyObject *v;
  1277. {
  1278.     if (v == NULL || !PyList_Check(v)) {
  1279.         PyErr_BadInternalCall();
  1280.         return -1;
  1281.     }
  1282.     v = listreverse((PyListObject *)v, (PyObject *)NULL);
  1283.     if (v == NULL)
  1284.         return -1;
  1285.     Py_DECREF(v);
  1286.     return 0;
  1287. }
  1288.  
  1289. PyObject *
  1290. PyList_AsTuple(v)
  1291.     PyObject *v;
  1292. {
  1293.     PyObject *w;
  1294.     PyObject **p;
  1295.     int n;
  1296.     if (v == NULL || !PyList_Check(v)) {
  1297.         PyErr_BadInternalCall();
  1298.         return NULL;
  1299.     }
  1300.     n = ((PyListObject *)v)->ob_size;
  1301.     w = PyTuple_New(n);
  1302.     if (w == NULL)
  1303.         return NULL;
  1304.     p = ((PyTupleObject *)w)->ob_item;
  1305.     memcpy((ANY *)p,
  1306.            (ANY *)((PyListObject *)v)->ob_item,
  1307.            n*sizeof(PyObject *));
  1308.     while (--n >= 0) {
  1309.         Py_INCREF(*p);
  1310.         p++;
  1311.     }
  1312.     return w;
  1313. }
  1314.  
  1315. static PyObject *
  1316. listindex(self, args)
  1317.     PyListObject *self;
  1318.     PyObject *args;
  1319. {
  1320.     int i;
  1321.     
  1322.     if (args == NULL) {
  1323.         PyErr_BadArgument();
  1324.         return NULL;
  1325.     }
  1326.     for (i = 0; i < self->ob_size; i++) {
  1327.         if (PyObject_Compare(self->ob_item[i], args) == 0)
  1328.             return PyInt_FromLong((long)i);
  1329.         if (PyErr_Occurred())
  1330.             return NULL;
  1331.     }
  1332.     PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
  1333.     return NULL;
  1334. }
  1335.  
  1336. static PyObject *
  1337. listcount(self, args)
  1338.     PyListObject *self;
  1339.     PyObject *args;
  1340. {
  1341.     int count = 0;
  1342.     int i;
  1343.     
  1344.     if (args == NULL) {
  1345.         PyErr_BadArgument();
  1346.         return NULL;
  1347.     }
  1348.     for (i = 0; i < self->ob_size; i++) {
  1349.         if (PyObject_Compare(self->ob_item[i], args) == 0)
  1350.             count++;
  1351.         if (PyErr_Occurred())
  1352.             return NULL;
  1353.     }
  1354.     return PyInt_FromLong((long)count);
  1355. }
  1356.  
  1357. static PyObject *
  1358. listremove(self, args)
  1359.     PyListObject *self;
  1360.     PyObject *args;
  1361. {
  1362.     int i;
  1363.     
  1364.     if (args == NULL) {
  1365.         PyErr_BadArgument();
  1366.         return NULL;
  1367.     }
  1368.     for (i = 0; i < self->ob_size; i++) {
  1369.         if (PyObject_Compare(self->ob_item[i], args) == 0) {
  1370.             if (list_ass_slice(self, i, i+1,
  1371.                        (PyObject *)NULL) != 0)
  1372.                 return NULL;
  1373.             Py_INCREF(Py_None);
  1374.             return Py_None;
  1375.         }
  1376.         if (PyErr_Occurred())
  1377.             return NULL;
  1378.     }
  1379.     PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
  1380.     return NULL;
  1381. }
  1382.  
  1383. static char append_doc[] =
  1384. "L.append(object) -- append object to end";
  1385. static char extend_doc[] =
  1386. "L.extend(list) -- extend list by appending list elements";
  1387. static char insert_doc[] =
  1388. "L.insert(index, object) -- insert object before index";
  1389. static char pop_doc[] =
  1390. "L.pop([index]) -> item -- remove and return item at index (default last)";
  1391. static char remove_doc[] =
  1392. "L.remove(value) -- remove first occurrence of value";
  1393. static char index_doc[] =
  1394. "L.index(value) -> integer -- return index of first occurrence of value";
  1395. static char count_doc[] =
  1396. "L.count(value) -> integer -- return number of occurrences of value";
  1397. static char reverse_doc[] =
  1398. "L.reverse() -- reverse *IN PLACE*";
  1399. static char sort_doc[] =
  1400. "L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1";
  1401.  
  1402. static PyMethodDef list_methods[] = {
  1403.     {"append",    (PyCFunction)listappend, 0, append_doc},
  1404.     {"insert",    (PyCFunction)listinsert, 0, insert_doc},
  1405.     {"extend",      (PyCFunction)listextend, 1, extend_doc},
  1406.     {"pop",        (PyCFunction)listpop, 1, pop_doc},
  1407.     {"remove",    (PyCFunction)listremove, 0, remove_doc},
  1408.     {"index",    (PyCFunction)listindex, 0, index_doc},
  1409.     {"count",    (PyCFunction)listcount, 0, count_doc},
  1410.     {"reverse",    (PyCFunction)listreverse, 0, reverse_doc},
  1411.     {"sort",    (PyCFunction)listsort, 0, sort_doc},
  1412.     {NULL,        NULL}        /* sentinel */
  1413. };
  1414.  
  1415. static PyObject *
  1416. list_getattr(f, name)
  1417.     PyListObject *f;
  1418.     char *name;
  1419. {
  1420.     return Py_FindMethod(list_methods, (PyObject *)f, name);
  1421. }
  1422.  
  1423. static PySequenceMethods list_as_sequence = {
  1424.     (inquiry)list_length, /*sq_length*/
  1425.     (binaryfunc)list_concat, /*sq_concat*/
  1426.     (intargfunc)list_repeat, /*sq_repeat*/
  1427.     (intargfunc)list_item, /*sq_item*/
  1428.     (intintargfunc)list_slice, /*sq_slice*/
  1429.     (intobjargproc)list_ass_item, /*sq_ass_item*/
  1430.     (intintobjargproc)list_ass_slice, /*sq_ass_slice*/
  1431. };
  1432.  
  1433. PyTypeObject PyList_Type = {
  1434.     PyObject_HEAD_INIT(&PyType_Type)
  1435.     0,
  1436.     "list",
  1437.     sizeof(PyListObject),
  1438.     0,
  1439.     (destructor)list_dealloc, /*tp_dealloc*/
  1440.     (printfunc)list_print, /*tp_print*/
  1441.     (getattrfunc)list_getattr, /*tp_getattr*/
  1442.     0,        /*tp_setattr*/
  1443.     (cmpfunc)list_compare, /*tp_compare*/
  1444.     (reprfunc)list_repr, /*tp_repr*/
  1445.     0,        /*tp_as_number*/
  1446.     &list_as_sequence,    /*tp_as_sequence*/
  1447.     0,        /*tp_as_mapping*/
  1448. };
  1449.  
  1450.  
  1451. /* During a sort, we really can't have anyone modifying the list; it could
  1452.    cause core dumps.  Thus, we substitute a dummy type that raises an
  1453.    explanatory exception when a modifying operation is used.  Caveat:
  1454.    comparisons may behave differently; but I guess it's a bad idea anyway to
  1455.    compare a list that's being sorted... */
  1456.  
  1457. static PyObject *
  1458. immutable_list_op(/*No args!*/)
  1459. {
  1460.     PyErr_SetString(PyExc_TypeError,
  1461.             "a list cannot be modified while it is being sorted");
  1462.     return NULL;
  1463. }
  1464.  
  1465. static PyMethodDef immutable_list_methods[] = {
  1466.     {"append",    (PyCFunction)immutable_list_op},
  1467.     {"insert",    (PyCFunction)immutable_list_op},
  1468.     {"remove",    (PyCFunction)immutable_list_op},
  1469.     {"index",    (PyCFunction)listindex},
  1470.     {"count",    (PyCFunction)listcount},
  1471.     {"reverse",    (PyCFunction)immutable_list_op},
  1472.     {"sort",    (PyCFunction)immutable_list_op},
  1473.     {NULL,        NULL}        /* sentinel */
  1474. };
  1475.  
  1476. static PyObject *
  1477. immutable_list_getattr(f, name)
  1478.     PyListObject *f;
  1479.     char *name;
  1480. {
  1481.     return Py_FindMethod(immutable_list_methods, (PyObject *)f, name);
  1482. }
  1483.  
  1484. static int
  1485. immutable_list_ass(/*No args!*/)
  1486. {
  1487.     immutable_list_op();
  1488.     return -1;
  1489. }
  1490.  
  1491. static PySequenceMethods immutable_list_as_sequence = {
  1492.     (inquiry)list_length, /*sq_length*/
  1493.     (binaryfunc)list_concat, /*sq_concat*/
  1494.     (intargfunc)list_repeat, /*sq_repeat*/
  1495.     (intargfunc)list_item, /*sq_item*/
  1496.     (intintargfunc)list_slice, /*sq_slice*/
  1497.     (intobjargproc)immutable_list_ass, /*sq_ass_item*/
  1498.     (intintobjargproc)immutable_list_ass, /*sq_ass_slice*/
  1499. };
  1500.  
  1501. static PyTypeObject immutable_list_type = {
  1502.     PyObject_HEAD_INIT(&PyType_Type)
  1503.     0,
  1504.     "list (immutable, during sort)",
  1505.     sizeof(PyListObject),
  1506.     0,
  1507.     0,        /*tp_dealloc*/ /* Cannot happen */
  1508.     (printfunc)list_print, /*tp_print*/
  1509.     (getattrfunc)immutable_list_getattr, /*tp_getattr*/
  1510.     0,        /*tp_setattr*/
  1511.     0,        /*tp_compare*/ /* Won't be called */
  1512.     (reprfunc)list_repr, /*tp_repr*/
  1513.     0,        /*tp_as_number*/
  1514.     &immutable_list_as_sequence,    /*tp_as_sequence*/
  1515.     0,        /*tp_as_mapping*/
  1516. };
  1517.  
  1518.