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