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 / dictobject.c < prev    next >
C/C++ Source or Header  |  2000-12-21  |  24KB  |  1,109 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. /* Dictionary object implementation using a hash table */
  33.  
  34. #include "Python.h"
  35.  
  36.  
  37. /*
  38.  * MINSIZE is the minimum size of a dictionary.
  39.  */
  40.  
  41. #define MINSIZE 4
  42.  
  43. /*
  44. Table of irreducible polynomials to efficiently cycle through
  45. GF(2^n)-{0}, 2<=n<=30.
  46. */
  47. const static long polys[] = {
  48.     4 + 3,
  49.     8 + 3,
  50.     16 + 3,
  51.     32 + 5,
  52.     64 + 3,
  53.     128 + 3,
  54.     256 + 29,
  55.     512 + 17,
  56.     1024 + 9,
  57.     2048 + 5,
  58.     4096 + 83,
  59.     8192 + 27,
  60.     16384 + 43,
  61.     32768 + 3,
  62.     65536 + 45,
  63.     131072 + 9,
  64.     262144 + 39,
  65.     524288 + 39,
  66.     1048576 + 9,
  67.     2097152 + 5,
  68.     4194304 + 3,
  69.     8388608 + 33,
  70.     16777216 + 27,
  71.     33554432 + 9,
  72.     67108864 + 71,
  73.     134217728 + 39,
  74.     268435456 + 9,
  75.     536870912 + 5,
  76.     1073741824 + 83,
  77.     0
  78. };
  79.  
  80. /* Object used as dummy key to fill deleted entries */
  81. static PyObject *dummy; /* Initialized by first call to newdictobject() */
  82.  
  83. /*
  84. Invariant for entries: when in use, me_value is not NULL and me_key is
  85. not NULL and not dummy; when not in use, me_value is NULL and me_key
  86. is either NULL or dummy.  A dummy key value cannot be replaced by
  87. NULL, since otherwise other keys may be lost.
  88. */
  89. typedef struct {
  90.     long me_hash;
  91.     PyObject *me_key;
  92.     PyObject *me_value;
  93. #ifdef USE_CACHE_ALIGNED
  94.     long    aligner;
  95. #endif
  96. } dictentry;
  97.  
  98. /*
  99. To ensure the lookup algorithm terminates, the table size must be a
  100. prime number and there must be at least one NULL key in the table.
  101. The value ma_fill is the number of non-NULL keys; ma_used is the number
  102. of non-NULL, non-dummy keys.
  103. To avoid slowing down lookups on a near-full table, we resize the table
  104. when it is more than half filled.
  105. */
  106. typedef struct {
  107.     PyObject_HEAD
  108.     int ma_fill;
  109.     int ma_used;
  110.     int ma_size;
  111.     int ma_poly;
  112.     dictentry *ma_table;
  113. } dictobject;
  114.  
  115. #include "other/dictobject_c.h"
  116.  
  117. PyObject *
  118. PyDict_New()
  119. {
  120.     register dictobject *mp;
  121.     if (dummy == NULL) { /* Auto-initialize dummy */
  122.         dummy = PyString_FromString("<dummy key>");
  123.         if (dummy == NULL)
  124.             return NULL;
  125.     }
  126.     mp = PyObject_NEW(dictobject, &PyDict_Type);
  127.     if (mp == NULL)
  128.         return NULL;
  129.     mp->ma_size = 0;
  130.     mp->ma_poly = 0;
  131.     mp->ma_table = NULL;
  132.     mp->ma_fill = 0;
  133.     mp->ma_used = 0;
  134.     return (PyObject *)mp;
  135. }
  136.  
  137. /*
  138. The basic lookup function used by all operations.
  139. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
  140. Open addressing is preferred over chaining since the link overhead for
  141. chaining would be substantial (100% with typical malloc overhead).
  142. However, instead of going through the table at constant steps, we cycle
  143. through the values of GF(2^n)-{0}. This avoids modulo computations, being
  144. much cheaper on RISC machines, without leading to clustering.
  145.  
  146. The initial probe index is computed as hash mod the table size.
  147. Subsequent probe indices use the values of x^i in GF(2^n) as an offset,
  148. where x is a root. The initial value is derived from hash, too.
  149.  
  150. All arithmetic on hash should ignore overflow.
  151.  
  152. (This version is due to Reimer Behrends, some ideas are also due to
  153. Jyrki Alakuijala and Vladimir Marangozov.)
  154. */
  155. /* static dictentry *lookdict Py_PROTO((dictobject *, PyObject *, long)); */
  156. static dictentry *
  157. lookdict(mp, key, hash)
  158.     dictobject *mp;
  159.     PyObject *key;
  160.     register long hash;
  161. {
  162.     register int i;
  163.     register unsigned incr;
  164.     register dictentry *freeslot;
  165.     register unsigned int mask = mp->ma_size-1;
  166.     dictentry *ep0 = mp->ma_table;
  167.     register dictentry *ep;
  168.     /* We must come up with (i, incr) such that 0 <= i < ma_size
  169.        and 0 < incr < ma_size and both are a function of hash */
  170.     i = (~hash) & mask;
  171.     /* We use ~hash instead of hash, as degenerate hash functions, such
  172.        as for ints <sigh>, can have lots of leading zeros. It's not
  173.        really a performance risk, but better safe than sorry. */
  174.     ep = &ep0[i];
  175.     if (ep->me_key == NULL || ep->me_key == key)
  176.         return ep;
  177.     if (ep->me_key == dummy)
  178.         freeslot = ep;
  179.     else {
  180.         if (ep->me_hash == hash &&
  181.             PyObject_Compare(ep->me_key, key) == 0)
  182.         {
  183.             return ep;
  184.         }
  185.         freeslot = NULL;
  186.     }
  187.     /* XXX What if PyObject_Compare returned an exception? */
  188.     /* Derive incr from hash, just to make it more arbitrary. Note that
  189.        incr must not be 0, or we will get into an infinite loop.*/
  190.     incr = (hash ^ ((unsigned long)hash >> 3)) & mask;
  191.     if (!incr)
  192.         incr = mask;
  193.     for (;;) {
  194.         ep = &ep0[(i+incr)&mask];
  195.         if (ep->me_key == NULL) {
  196.             if (freeslot != NULL)
  197.                 return freeslot;
  198.             else
  199.                 return ep;
  200.         }
  201.         if (ep->me_key == dummy) {
  202.             if (freeslot == NULL)
  203.                 freeslot = ep;
  204.         }
  205.         else if (ep->me_key == key ||
  206.              (ep->me_hash == hash &&
  207.               PyObject_Compare(ep->me_key, key) == 0)) {
  208.             return ep;
  209.         }
  210.         /* XXX What if PyObject_Compare returned an exception? */
  211.         /* Cycle through GF(2^n)-{0} */
  212.         incr = incr << 1;
  213.         if (incr > mask)
  214.             incr ^= mp->ma_poly; /* This will implicitely clear
  215.                         the highest bit */
  216.     }
  217. }
  218.  
  219. /*
  220. Internal routine to insert a new item into the table.
  221. Used both by the internal resize routine and by the public insert routine.
  222. Eats a reference to key and one to value.
  223. */
  224. /* static void insertdict */
  225. /*     Py_PROTO((dictobject *, PyObject *, long, PyObject *)); */
  226. static void
  227. insertdict(mp, key, hash, value)
  228.     register dictobject *mp;
  229.     PyObject *key;
  230.     long hash;
  231.     PyObject *value;
  232. {
  233.     PyObject *old_value;
  234.     register dictentry *ep;
  235.     ep = lookdict(mp, key, hash);
  236.     if (ep->me_value != NULL) {
  237.         old_value = ep->me_value;
  238.         ep->me_value = value;
  239.         Py_DECREF(old_value); /* which **CAN** re-enter */
  240.         Py_DECREF(key);
  241.     }
  242.     else {
  243.         if (ep->me_key == NULL)
  244.             mp->ma_fill++;
  245.         else
  246.             Py_DECREF(ep->me_key);
  247.         ep->me_key = key;
  248.         ep->me_hash = hash;
  249.         ep->me_value = value;
  250.         mp->ma_used++;
  251.     }
  252. }
  253.  
  254. /*
  255. Restructure the table by allocating a new table and reinserting all
  256. items again.  When entries have been deleted, the new table may
  257. actually be smaller than the old one.
  258. */
  259. /* static int dictresize Py_PROTO((dictobject *, int)); */
  260. static int
  261. dictresize(mp, minused)
  262.     dictobject *mp;
  263.     int minused;
  264. {
  265.     register int oldsize = mp->ma_size;
  266.     register int newsize, newpoly;
  267.     register dictentry *oldtable = mp->ma_table;
  268.     register dictentry *newtable;
  269.     register dictentry *ep;
  270.     register int i;
  271.     for (i = 0, newsize = MINSIZE; ; i++, newsize <<= 1) {
  272.         if (i > sizeof(polys)/sizeof(polys[0])) {
  273.             /* Ran out of polynomials */
  274.             PyErr_NoMemory();
  275.             return -1;
  276.         }
  277.         if (newsize > minused) {
  278.             newpoly = polys[i];
  279.             break;
  280.         }
  281.     }
  282.     newtable = (dictentry *) malloc(sizeof(dictentry) * newsize);
  283.     if (newtable == NULL) {
  284.         PyErr_NoMemory();
  285.         return -1;
  286.     }
  287.     memset(newtable, '\0', sizeof(dictentry) * newsize);
  288.     mp->ma_size = newsize;
  289.     mp->ma_poly = newpoly;
  290.     mp->ma_table = newtable;
  291.     mp->ma_fill = 0;
  292.     mp->ma_used = 0;
  293.  
  294.     /* Make two passes, so we can avoid decrefs
  295.        (and possible side effects) till the table is copied */
  296.     for (i = 0, ep = oldtable; i < oldsize; i++, ep++) {
  297.         if (ep->me_value != NULL)
  298.             insertdict(mp,ep->me_key,ep->me_hash,ep->me_value);
  299.     }
  300.     for (i = 0, ep = oldtable; i < oldsize; i++, ep++) {
  301.         if (ep->me_value == NULL) {
  302.             Py_XDECREF(ep->me_key);
  303.         }
  304.     }
  305.  
  306.     PyMem_XDEL(oldtable);
  307.     return 0;
  308. }
  309.  
  310. PyObject *
  311. PyDict_GetItem(op, key)
  312.     PyObject *op;
  313.     PyObject *key;
  314. {
  315.     long hash;
  316.     if (!PyDict_Check(op)) {
  317.         return NULL;
  318.     }
  319.     if (((dictobject *)op)->ma_table == NULL)
  320.         return NULL;
  321. #ifdef CACHE_HASH
  322.     if (!PyString_Check(key) ||
  323.         (hash = ((PyStringObject *) key)->ob_shash) == -1)
  324. #endif
  325.     {
  326.         hash = PyObject_Hash(key);
  327.         if (hash == -1) {
  328.             PyErr_Clear();
  329.             return NULL;
  330.         }
  331.     }
  332.     return lookdict((dictobject *)op, key, hash) -> me_value;
  333. }
  334.  
  335. int
  336. PyDict_SetItem(op, key, value)
  337.     register PyObject *op;
  338.     PyObject *key;
  339.     PyObject *value;
  340. {
  341.     register dictobject *mp;
  342.     register long hash;
  343.     if (!PyDict_Check(op)) {
  344.         PyErr_BadInternalCall();
  345.         return -1;
  346.     }
  347.     mp = (dictobject *)op;
  348. #ifdef CACHE_HASH
  349.     if (PyString_Check(key)) {
  350. #ifdef INTERN_STRINGS
  351.         if (((PyStringObject *)key)->ob_sinterned != NULL) {
  352.             key = ((PyStringObject *)key)->ob_sinterned;
  353.             hash = ((PyStringObject *)key)->ob_shash;
  354.         }
  355.         else
  356. #endif
  357.         {
  358.             hash = ((PyStringObject *)key)->ob_shash;
  359.             if (hash == -1)
  360.                 hash = PyObject_Hash(key);
  361.         }
  362.     }
  363.     else
  364. #endif
  365.     {
  366.         hash = PyObject_Hash(key);
  367.         if (hash == -1)
  368.             return -1;
  369.     }
  370.     /* if fill >= 2/3 size, double in size */
  371.     if (mp->ma_fill*3 >= mp->ma_size*2) {
  372.         if (dictresize(mp, mp->ma_used*2) != 0) {
  373.             if (mp->ma_fill+1 > mp->ma_size)
  374.                 return -1;
  375.         }
  376.     }
  377.     Py_INCREF(value);
  378.     Py_INCREF(key);
  379.     insertdict(mp, key, hash, value);
  380.     return 0;
  381. }
  382.  
  383. int
  384. PyDict_DelItem(op, key)
  385.     PyObject *op;
  386.     PyObject *key;
  387. {
  388.     register dictobject *mp;
  389.     register long hash;
  390.     register dictentry *ep;
  391.     PyObject *old_value, *old_key;
  392.  
  393.     if (!PyDict_Check(op)) {
  394.         PyErr_BadInternalCall();
  395.         return -1;
  396.     }
  397. #ifdef CACHE_HASH
  398.     if (!PyString_Check(key) ||
  399.         (hash = ((PyStringObject *) key)->ob_shash) == -1)
  400. #endif
  401.     {
  402.         hash = PyObject_Hash(key);
  403.         if (hash == -1)
  404.             return -1;
  405.     }
  406.     mp = (dictobject *)op;
  407.     if (((dictobject *)op)->ma_table == NULL)
  408.         goto empty;
  409.     ep = lookdict(mp, key, hash);
  410.     if (ep->me_value == NULL) {
  411.     empty:
  412.         PyErr_SetObject(PyExc_KeyError, key);
  413.         return -1;
  414.     }
  415.     old_key = ep->me_key;
  416.     Py_INCREF(dummy);
  417.     ep->me_key = dummy;
  418.     old_value = ep->me_value;
  419.     ep->me_value = NULL;
  420.     mp->ma_used--;
  421.     Py_DECREF(old_value); 
  422.     Py_DECREF(old_key); 
  423.     return 0;
  424. }
  425.  
  426. void
  427. PyDict_Clear(op)
  428.     PyObject *op;
  429. {
  430.     int i, n;
  431.     register dictentry *table;
  432.     dictobject *mp;
  433.     if (!PyDict_Check(op))
  434.         return;
  435.     mp = (dictobject *)op;
  436.     table = mp->ma_table;
  437.     if (table == NULL)
  438.         return;
  439.     n = mp->ma_size;
  440.     mp->ma_size = mp->ma_used = mp->ma_fill = 0;
  441.     mp->ma_table = NULL;
  442.     for (i = 0; i < n; i++) {
  443.         Py_XDECREF(table[i].me_key);
  444.         Py_XDECREF(table[i].me_value);
  445.     }
  446.     PyMem_DEL(table);
  447. }
  448.  
  449. int
  450. PyDict_Next(op, ppos, pkey, pvalue)
  451.     PyObject *op;
  452.     int *ppos;
  453.     PyObject **pkey;
  454.     PyObject **pvalue;
  455. {
  456.     int i;
  457.     register dictobject *mp;
  458.     if (!PyDict_Check(op))
  459.         return 0;
  460.     mp = (dictobject *)op;
  461.     i = *ppos;
  462.     if (i < 0)
  463.         return 0;
  464.     while (i < mp->ma_size && mp->ma_table[i].me_value == NULL)
  465.         i++;
  466.     *ppos = i+1;
  467.     if (i >= mp->ma_size)
  468.         return 0;
  469.     if (pkey)
  470.         *pkey = mp->ma_table[i].me_key;
  471.     if (pvalue)
  472.         *pvalue = mp->ma_table[i].me_value;
  473.     return 1;
  474. }
  475.  
  476. /* Methods */
  477.  
  478. static void
  479. dict_dealloc(mp)
  480.     register dictobject *mp;
  481. {
  482.     register int i;
  483.     register dictentry *ep;
  484.     for (i = 0, ep = mp->ma_table; i < mp->ma_size; i++, ep++) {
  485.         if (ep->me_key != NULL) {
  486.             Py_DECREF(ep->me_key);
  487.         }
  488.         if (ep->me_value != NULL) {
  489.             Py_DECREF(ep->me_value);
  490.         }
  491.     }
  492.     PyMem_XDEL(mp->ma_table);
  493.     PyMem_DEL(mp);
  494. }
  495.  
  496. static int
  497. dict_print(mp, fp, flags)
  498.     register dictobject *mp;
  499.     register FILE *fp;
  500.     register int flags;
  501. {
  502.     register int i;
  503.     register int any;
  504.     register dictentry *ep;
  505.  
  506.     i = Py_ReprEnter((PyObject*)mp);
  507.     if (i != 0) {
  508.         if (i < 0)
  509.             return i;
  510.         fprintf(fp, "{...}");
  511.         return 0;
  512.     }
  513.  
  514.     fprintf(fp, "{");
  515.     any = 0;
  516.     for (i = 0, ep = mp->ma_table; i < mp->ma_size; i++, ep++) {
  517.         if (ep->me_value != NULL) {
  518.             if (any++ > 0)
  519.                 fprintf(fp, ", ");
  520.             if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
  521.                 Py_ReprLeave((PyObject*)mp);
  522.                 return -1;
  523.             }
  524.             fprintf(fp, ": ");
  525.             if (PyObject_Print(ep->me_value, fp, 0) != 0) {
  526.                 Py_ReprLeave((PyObject*)mp);
  527.                 return -1;
  528.             }
  529.         }
  530.     }
  531.     fprintf(fp, "}");
  532.     Py_ReprLeave((PyObject*)mp);
  533.     return 0;
  534. }
  535.  
  536. static PyObject *
  537. dict_repr(mp)
  538.     dictobject *mp;
  539. {
  540.     auto PyObject *v;
  541.     PyObject *sepa, *colon;
  542.     register int i;
  543.     register int any;
  544.     register dictentry *ep;
  545.  
  546.     i = Py_ReprEnter((PyObject*)mp);
  547.     if (i != 0) {
  548.         if (i > 0)
  549.             return PyString_FromString("{...}");
  550.         return NULL;
  551.     }
  552.  
  553.     v = PyString_FromString("{");
  554.     sepa = PyString_FromString(", ");
  555.     colon = PyString_FromString(": ");
  556.     any = 0;
  557.     for (i = 0, ep = mp->ma_table; i < mp->ma_size && v; i++, ep++) {
  558.         if (ep->me_value != NULL) {
  559.             if (any++)
  560.                 PyString_Concat(&v, sepa);
  561.             PyString_ConcatAndDel(&v, PyObject_Repr(ep->me_key));
  562.             PyString_Concat(&v, colon);
  563.             PyString_ConcatAndDel(&v, PyObject_Repr(ep->me_value));
  564.         }
  565.     }
  566.     PyString_ConcatAndDel(&v, PyString_FromString("}"));
  567.     Py_ReprLeave((PyObject*)mp);
  568.     Py_XDECREF(sepa);
  569.     Py_XDECREF(colon);
  570.     return v;
  571. }
  572.  
  573. static int
  574. dict_length(mp)
  575.     dictobject *mp;
  576. {
  577.     return mp->ma_used;
  578. }
  579.  
  580. static PyObject *
  581. dict_subscript(mp, key)
  582.     dictobject *mp;
  583.     register PyObject *key;
  584. {
  585.     PyObject *v;
  586.     long hash;
  587.     if (mp->ma_table == NULL) {
  588.         PyErr_SetObject(PyExc_KeyError, key);
  589.         return NULL;
  590.     }
  591. #ifdef CACHE_HASH
  592.     if (!PyString_Check(key) ||
  593.         (hash = ((PyStringObject *) key)->ob_shash) == -1)
  594. #endif
  595.     {
  596.         hash = PyObject_Hash(key);
  597.         if (hash == -1)
  598.             return NULL;
  599.     }
  600.     v = lookdict(mp, key, hash) -> me_value;
  601.     if (v == NULL)
  602.         PyErr_SetObject(PyExc_KeyError, key);
  603.     else
  604.         Py_INCREF(v);
  605.     return v;
  606. }
  607.  
  608. static int
  609. dict_ass_sub(mp, v, w)
  610.     dictobject *mp;
  611.     PyObject *v, *w;
  612. {
  613.     if (w == NULL)
  614.         return PyDict_DelItem((PyObject *)mp, v);
  615.     else
  616.         return PyDict_SetItem((PyObject *)mp, v, w);
  617. }
  618.  
  619. static PyMappingMethods dict_as_mapping = {
  620.     (inquiry)dict_length, /*mp_length*/
  621.     (binaryfunc)dict_subscript, /*mp_subscript*/
  622.     (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
  623. };
  624.  
  625. static PyObject *
  626. dict_keys(mp, args)
  627.     register dictobject *mp;
  628.     PyObject *args;
  629. {
  630.     register PyObject *v;
  631.     register int i, j;
  632.     if (!PyArg_NoArgs(args))
  633.         return NULL;
  634.     v = PyList_New(mp->ma_used);
  635.     if (v == NULL)
  636.         return NULL;
  637.     for (i = 0, j = 0; i < mp->ma_size; i++) {
  638.         if (mp->ma_table[i].me_value != NULL) {
  639.             PyObject *key = mp->ma_table[i].me_key;
  640.             Py_INCREF(key);
  641.             PyList_SetItem(v, j, key);
  642.             j++;
  643.         }
  644.     }
  645.     return v;
  646. }
  647.  
  648. static PyObject *
  649. dict_values(mp, args)
  650.     register dictobject *mp;
  651.     PyObject *args;
  652. {
  653.     register PyObject *v;
  654.     register int i, j;
  655.     if (!PyArg_NoArgs(args))
  656.         return NULL;
  657.     v = PyList_New(mp->ma_used);
  658.     if (v == NULL)
  659.         return NULL;
  660.     for (i = 0, j = 0; i < mp->ma_size; i++) {
  661.         if (mp->ma_table[i].me_value != NULL) {
  662.             PyObject *value = mp->ma_table[i].me_value;
  663.             Py_INCREF(value);
  664.             PyList_SetItem(v, j, value);
  665.             j++;
  666.         }
  667.     }
  668.     return v;
  669. }
  670.  
  671. static PyObject *
  672. dict_items(mp, args)
  673.     register dictobject *mp;
  674.     PyObject *args;
  675. {
  676.     register PyObject *v;
  677.     register int i, j;
  678.     if (!PyArg_NoArgs(args))
  679.         return NULL;
  680.     v = PyList_New(mp->ma_used);
  681.     if (v == NULL)
  682.         return NULL;
  683.     for (i = 0, j = 0; i < mp->ma_size; i++) {
  684.         if (mp->ma_table[i].me_value != NULL) {
  685.             PyObject *key = mp->ma_table[i].me_key;
  686.             PyObject *value = mp->ma_table[i].me_value;
  687.             PyObject *item = PyTuple_New(2);
  688.             if (item == NULL) {
  689.                 Py_DECREF(v);
  690.                 return NULL;
  691.             }
  692.             Py_INCREF(key);
  693.             PyTuple_SetItem(item, 0, key);
  694.             Py_INCREF(value);
  695.             PyTuple_SetItem(item, 1, value);
  696.             PyList_SetItem(v, j, item);
  697.             j++;
  698.         }
  699.     }
  700.     return v;
  701. }
  702.  
  703. static PyObject *
  704. dict_update(mp, args)
  705.       register dictobject *mp;
  706.       PyObject *args;
  707. {
  708.     register int i;
  709.     dictobject *other;
  710.         dictentry *entry;
  711.     if (!PyArg_Parse(args, "O!", &PyDict_Type, &other))
  712.         return NULL;
  713.     if (other == mp)
  714.         goto done; /* a.update(a); nothing to do */
  715.     /* Do one big resize at the start, rather than incrementally
  716.        resizing as we insert new items.  Expect that there will be
  717.        no (or few) overlapping keys. */
  718.     if ((mp->ma_fill + other->ma_used)*3 >= mp->ma_size*2) {
  719.         if (dictresize(mp, (mp->ma_used + other->ma_used)*3/2) != 0)
  720.             return NULL;
  721.     }
  722.     for (i = 0; i < other->ma_size; i++) {
  723.         entry = &other->ma_table[i];
  724.         if (entry->me_value != NULL) {
  725.             Py_INCREF(entry->me_key);
  726.             Py_INCREF(entry->me_value);
  727.             insertdict(mp, entry->me_key, entry->me_hash,
  728.                    entry->me_value);
  729.         }
  730.     }
  731.   done:
  732.     Py_INCREF(Py_None);
  733.     return Py_None;
  734. }
  735.  
  736. static PyObject *
  737. dict_copy(mp, args)
  738.       register dictobject *mp;
  739.       PyObject *args;
  740. {
  741.     register int i;
  742.     dictobject *copy;
  743.         dictentry *entry;
  744.     if (!PyArg_Parse(args, ""))
  745.         return NULL;
  746.     copy = (dictobject *)PyDict_New();
  747.     if (copy == NULL)
  748.         return NULL;
  749.     if (mp->ma_used > 0) {
  750.         if (dictresize(copy, mp->ma_used*3/2) != 0)
  751.             return NULL;
  752.         for (i = 0; i < mp->ma_size; i++) {
  753.             entry = &mp->ma_table[i];
  754.             if (entry->me_value != NULL) {
  755.                 Py_INCREF(entry->me_key);
  756.                 Py_INCREF(entry->me_value);
  757.                 insertdict(copy, entry->me_key, entry->me_hash,
  758.                        entry->me_value);
  759.             }
  760.         }
  761.     }
  762.     return (PyObject *)copy;
  763. }
  764.  
  765. int
  766. PyDict_Size(mp)
  767.     PyObject *mp;
  768. {
  769.     if (mp == NULL || !PyDict_Check(mp)) {
  770.         PyErr_BadInternalCall();
  771.         return 0;
  772.     }
  773.     return ((dictobject *)mp)->ma_used;
  774. }
  775.  
  776. PyObject *
  777. PyDict_Keys(mp)
  778.     PyObject *mp;
  779. {
  780.     if (mp == NULL || !PyDict_Check(mp)) {
  781.         PyErr_BadInternalCall();
  782.         return NULL;
  783.     }
  784.     return dict_keys((dictobject *)mp, (PyObject *)NULL);
  785. }
  786.  
  787. PyObject *
  788. PyDict_Values(mp)
  789.     PyObject *mp;
  790. {
  791.     if (mp == NULL || !PyDict_Check(mp)) {
  792.         PyErr_BadInternalCall();
  793.         return NULL;
  794.     }
  795.     return dict_values((dictobject *)mp, (PyObject *)NULL);
  796. }
  797.  
  798. PyObject *
  799. PyDict_Items(mp)
  800.     PyObject *mp;
  801. {
  802.     if (mp == NULL || !PyDict_Check(mp)) {
  803.         PyErr_BadInternalCall();
  804.         return NULL;
  805.     }
  806.     return dict_items((dictobject *)mp, (PyObject *)NULL);
  807. }
  808.  
  809. #define NEWCMP
  810.  
  811. #ifdef NEWCMP
  812.  
  813. /* Subroutine which returns the smallest key in a for which b's value
  814.    is different or absent.  The value is returned too, through the
  815.    pval argument.  No reference counts are incremented. */
  816.  
  817. static PyObject *
  818. characterize(a, b, pval)
  819.     dictobject *a;
  820.     dictobject *b;
  821.     PyObject **pval;
  822. {
  823.     PyObject *diff = NULL;
  824.     int i;
  825.  
  826.     *pval = NULL;
  827.     for (i = 0; i < a->ma_size; i++) {
  828.         if (a->ma_table[i].me_value != NULL) {
  829.             PyObject *key = a->ma_table[i].me_key;
  830.             PyObject *aval, *bval;
  831.             /* XXX What if PyObject_Compare raises an exception? */
  832.             if (diff != NULL && PyObject_Compare(key, diff) > 0)
  833.                 continue;
  834.             aval = a->ma_table[i].me_value;
  835.             bval = PyDict_GetItem((PyObject *)b, key);
  836.             /* XXX What if PyObject_Compare raises an exception? */
  837.             if (bval == NULL || PyObject_Compare(aval, bval) != 0)
  838.             {
  839.                 diff = key;
  840.                 *pval = aval;
  841.             }
  842.         }
  843.     }
  844.     return diff;
  845. }
  846.  
  847. static int
  848. dict_compare(a, b)
  849.     dictobject *a, *b;
  850. {
  851.     PyObject *adiff, *bdiff, *aval, *bval;
  852.     int res;
  853.  
  854.     /* Compare lengths first */
  855.     if (a->ma_used < b->ma_used)
  856.         return -1;    /* a is shorter */
  857.     else if (a->ma_used > b->ma_used)
  858.         return 1;    /* b is shorter */
  859.     /* Same length -- check all keys */
  860.     adiff = characterize(a, b, &aval);
  861.     if (PyErr_Occurred())
  862.         return -1;
  863.     if (adiff == NULL)
  864.         return 0;    /* a is a subset with the same length */
  865.     bdiff = characterize(b, a, &bval);
  866.     if (PyErr_Occurred())
  867.         return -1;
  868.     /* bdiff == NULL would be impossible now */
  869.     res = PyObject_Compare(adiff, bdiff);
  870.     if (res == 0)
  871.         res = PyObject_Compare(aval, bval);
  872.     return res;
  873. }
  874.  
  875. #else /* !NEWCMP */
  876.  
  877. static int
  878. dict_compare(a, b)
  879.     dictobject *a, *b;
  880. {
  881.     PyObject *akeys, *bkeys;
  882.     int i, n, res;
  883.     if (a == b)
  884.         return 0;
  885.     if (a->ma_used == 0) {
  886.         if (b->ma_used != 0)
  887.             return -1;
  888.         else
  889.             return 0;
  890.     }
  891.     else {
  892.         if (b->ma_used == 0)
  893.             return 1;
  894.     }
  895.     akeys = dict_keys(a, (PyObject *)NULL);
  896.     bkeys = dict_keys(b, (PyObject *)NULL);
  897.     if (akeys == NULL || bkeys == NULL) {
  898.         /* Oops, out of memory -- what to do? */
  899.         /* For now, sort on address! */
  900.         Py_XDECREF(akeys);
  901.         Py_XDECREF(bkeys);
  902.         if (a < b)
  903.             return -1;
  904.         else
  905.             return 1;
  906.     }
  907.     PyList_Sort(akeys);
  908.     PyList_Sort(bkeys);
  909.     n = a->ma_used < b->ma_used ? a->ma_used : b->ma_used; /* smallest */
  910.     res = 0;
  911.     for (i = 0; i < n; i++) {
  912.         PyObject *akey, *bkey, *aval, *bval;
  913.         long ahash, bhash;
  914.         akey = PyList_GetItem(akeys, i);
  915.         bkey = PyList_GetItem(bkeys, i);
  916.         res = PyObject_Compare(akey, bkey);
  917.         if (res != 0)
  918.             break;
  919. #ifdef CACHE_HASH
  920.         if (!PyString_Check(akey) ||
  921.             (ahash = ((PyStringObject *) akey)->ob_shash) == -1)
  922. #endif
  923.         {
  924.             ahash = PyObject_Hash(akey);
  925.             if (ahash == -1)
  926.                 PyErr_Clear(); /* Don't want errors here */
  927.         }
  928. #ifdef CACHE_HASH
  929.         if (!PyString_Check(bkey) ||
  930.             (bhash = ((PyStringObject *) bkey)->ob_shash) == -1)
  931. #endif
  932.         {
  933.             bhash = PyObject_Hash(bkey);
  934.             if (bhash == -1)
  935.                 PyErr_Clear(); /* Don't want errors here */
  936.         }
  937.         aval = lookdict(a, akey, ahash) -> me_value;
  938.         bval = lookdict(b, bkey, bhash) -> me_value;
  939.         res = PyObject_Compare(aval, bval);
  940.         if (res != 0)
  941.             break;
  942.     }
  943.     if (res == 0) {
  944.         if (a->ma_used < b->ma_used)
  945.             res = -1;
  946.         else if (a->ma_used > b->ma_used)
  947.             res = 1;
  948.     }
  949.     Py_DECREF(akeys);
  950.     Py_DECREF(bkeys);
  951.     return res;
  952. }
  953.  
  954. #endif /* !NEWCMP */
  955.  
  956. static PyObject *
  957. dict_has_key(mp, args)
  958.     register dictobject *mp;
  959.     PyObject *args;
  960. {
  961.     PyObject *key;
  962.     long hash;
  963.     register long ok;
  964.     if (!PyArg_ParseTuple(args, "O:has_key", &key))
  965.         return NULL;
  966. #ifdef CACHE_HASH
  967.     if (!PyString_Check(key) ||
  968.         (hash = ((PyStringObject *) key)->ob_shash) == -1)
  969. #endif
  970.     {
  971.         hash = PyObject_Hash(key);
  972.         if (hash == -1)
  973.             return NULL;
  974.     }
  975.     ok = mp->ma_size != 0 && lookdict(mp, key, hash)->me_value != NULL;
  976.     return PyInt_FromLong(ok);
  977. }
  978.  
  979. static PyObject *
  980. dict_get(mp, args)
  981.     register dictobject *mp;
  982.     PyObject *args;
  983. {
  984.     PyObject *key;
  985.     PyObject *failobj = Py_None;
  986.     PyObject *val = NULL;
  987.     long hash;
  988.  
  989.     if (!PyArg_ParseTuple(args, "O|O:get", &key, &failobj))
  990.         return NULL;
  991.     if (mp->ma_table == NULL)
  992.         goto finally;
  993.  
  994. #ifdef CACHE_HASH
  995.     if (!PyString_Check(key) ||
  996.         (hash = ((PyStringObject *) key)->ob_shash) == -1)
  997. #endif
  998.     {
  999.         hash = PyObject_Hash(key);
  1000.         if (hash == -1)
  1001.             return NULL;
  1002.     }
  1003.     val = lookdict(mp, key, hash)->me_value;
  1004.  
  1005.   finally:
  1006.     if (val == NULL)
  1007.         val = failobj;
  1008.     Py_INCREF(val);
  1009.     return val;
  1010. }
  1011.  
  1012.  
  1013. static PyObject *
  1014. dict_clear(mp, args)
  1015.     register dictobject *mp;
  1016.     PyObject *args;
  1017. {
  1018.     if (!PyArg_NoArgs(args))
  1019.         return NULL;
  1020.     PyDict_Clear((PyObject *)mp);
  1021.     Py_INCREF(Py_None);
  1022.     return Py_None;
  1023. }
  1024.  
  1025. static PyMethodDef mapp_methods[] = {
  1026.     {"has_key",    (PyCFunction)dict_has_key,      METH_VARARGS},
  1027.     {"keys",    (PyCFunction)dict_keys},
  1028.     {"items",    (PyCFunction)dict_items},
  1029.     {"values",    (PyCFunction)dict_values},
  1030.     {"update",    (PyCFunction)dict_update},
  1031.     {"clear",    (PyCFunction)dict_clear},
  1032.     {"copy",    (PyCFunction)dict_copy},
  1033.     {"get",         (PyCFunction)dict_get,          METH_VARARGS},
  1034.     {NULL,        NULL}        /* sentinel */
  1035. };
  1036.  
  1037. static PyObject *
  1038. dict_getattr(mp, name)
  1039.     dictobject *mp;
  1040.     char *name;
  1041. {
  1042.     return Py_FindMethod(mapp_methods, (PyObject *)mp, name);
  1043. }
  1044.  
  1045. PyTypeObject PyDict_Type = {
  1046.     PyObject_HEAD_INIT(&PyType_Type)
  1047.     0,
  1048.     "dictionary",
  1049.     sizeof(dictobject),
  1050.     0,
  1051.     (destructor)dict_dealloc, /*tp_dealloc*/
  1052.     (printfunc)dict_print, /*tp_print*/
  1053.     (getattrfunc)dict_getattr, /*tp_getattr*/
  1054.     0,            /*tp_setattr*/
  1055.     (cmpfunc)dict_compare, /*tp_compare*/
  1056.     (reprfunc)dict_repr, /*tp_repr*/
  1057.     0,            /*tp_as_number*/
  1058.     0,            /*tp_as_sequence*/
  1059.     &dict_as_mapping,    /*tp_as_mapping*/
  1060. };
  1061.  
  1062. /* For backward compatibility with old dictionary interface */
  1063.  
  1064. PyObject *
  1065. PyDict_GetItemString(v, key)
  1066.     PyObject *v;
  1067.     char *key;
  1068. {
  1069.     PyObject *kv, *rv;
  1070.     kv = PyString_FromString(key);
  1071.     if (kv == NULL)
  1072.         return NULL;
  1073.     rv = PyDict_GetItem(v, kv);
  1074.     Py_DECREF(kv);
  1075.     return rv;
  1076. }
  1077.  
  1078. int
  1079. PyDict_SetItemString(v, key, item)
  1080.     PyObject *v;
  1081.     char *key;
  1082.     PyObject *item;
  1083. {
  1084.     PyObject *kv;
  1085.     int err;
  1086.     kv = PyString_FromString(key);
  1087.     if (kv == NULL)
  1088.         return -1;
  1089.     PyString_InternInPlace(&kv); /* XXX Should we really? */
  1090.     err = PyDict_SetItem(v, kv, item);
  1091.     Py_DECREF(kv);
  1092.     return err;
  1093. }
  1094.  
  1095. int
  1096. PyDict_DelItemString(v, key)
  1097.     PyObject *v;
  1098.     char *key;
  1099. {
  1100.     PyObject *kv;
  1101.     int err;
  1102.     kv = PyString_FromString(key);
  1103.     if (kv == NULL)
  1104.         return -1;
  1105.     err = PyDict_DelItem(v, kv);
  1106.     Py_DECREF(kv);
  1107.     return err;
  1108. }
  1109.