Lua 5.1.4: ltable.c


L0001    /*
L0002    ** $Id: ltable.c,v 2.32.1.2 2007/12/28 15:32:23 roberto Exp $
L0003    ** Lua tables (hash)
L0004    ** See Copyright Notice in lua.h
L0005    */
L0006    
L0007    
L0008    /*
L0009    ** Implementation of tables (aka arrays, objects, or hash tables).
L0010    ** Tables keep its elements in two parts: an array part and a hash part.
L0011    ** Non-negative integer keys are all candidates to be kept in the array
L0012    ** part. The actual size of the array is the largest `n' such that at
L0013    ** least half the slots between 0 and n are in use.
L0014    ** Hash uses a mix of chained scatter table with Brent's variation.
L0015    ** A main invariant of these tables is that, if an element is not
L0016    ** in its main position (i.e. the `original' position that its hash gives
L0017    ** to it), then the colliding element is in its own main position.
L0018    ** Hence even when the load factor reaches 100%, performance remains good.
L0019    */
L0020    
L0021    #include <math.h>
L0022    #include <string.h>
L0023    
L0024    #define ltable_c
L0025    #define LUA_CORE
L0026    
L0027    #include "lua.h"
L0028    
L0029    #include "ldebug.h"
L0030    #include "ldo.h"
L0031    #include "lgc.h"
L0032    #include "lmem.h"
L0033    #include "lobject.h"
L0034    #include "lstate.h"
L0035    #include "ltable.h"
L0036    
L0037    
L0038    /*
L0039    ** max size of array part is 2^MAXBITS
L0040    */
L0041    #if LUAI_BITSINT > 26
L0042    #define MAXBITS		26
L0043    #else
L0044    #define MAXBITS		(LUAI_BITSINT-2)
L0045    #endif
L0046    
L0047    #define MAXASIZE	(1 << MAXBITS)
L0048    
L0049    
L0050    #define hashpow2(t,n)      (gnode(t, lmod((n), sizenode(t))))
L0051      
L0052    #define hashstr(t,str)  hashpow2(t, (str)->tsv.hash)
L0053    #define hashboolean(t,p)        hashpow2(t, p)
L0054    
L0055    
L0056    /*
L0057    ** for some types, it is better to avoid modulus by power of 2, as
L0058    ** they tend to have many 2 factors.
L0059    */
L0060    #define hashmod(t,n)	(gnode(t, ((n) % ((sizenode(t)-1)|1))))
L0061    
L0062    
L0063    #define hashpointer(t,p)	hashmod(t, IntPoint(p))
L0064    
L0065    
L0066    /*
L0067    ** number of ints inside a lua_Number
L0068    */
L0069    #define numints		cast_int(sizeof(lua_Number)/sizeof(int))
L0070    
L0071    
L0072    
L0073    #define dummynode		(&dummynode_)
L0074    
L0075    static const Node dummynode_ = {
L0076      {{NULL}, LUA_TNIL},  /* value */
L0077      {{{NULL}, LUA_TNIL, NULL}}  /* key */
L0078    };
L0079    
L0080    
L0081    /*
L0082    ** hash for lua_Numbers
L0083    */
L0084    static Node *hashnum (const Table *t, lua_Number n) {
L0085      unsigned int a[numints];
L0086      int i;
L0087      if (luai_numeq(n, 0))  /* avoid problems with -0 */
L0088        return gnode(t, 0);
L0089      memcpy(a, &n, sizeof(a));
L0090      for (i = 1; i < numints; i++) a[0] += a[i];
L0091      return hashmod(t, a[0]);
L0092    }
L0093    
L0094    
L0095    
L0096    /*
L0097    ** returns the `main' position of an element in a table (that is, the index
L0098    ** of its hash value)
L0099    */
L0100    static Node *mainposition (const Table *t, const TValue *key) {
L0101      switch (ttype(key)) {
L0102        case LUA_TNUMBER:
L0103          return hashnum(t, nvalue(key));
L0104        case LUA_TSTRING:
L0105          return hashstr(t, rawtsvalue(key));
L0106        case LUA_TBOOLEAN:
L0107          return hashboolean(t, bvalue(key));
L0108        case LUA_TLIGHTUSERDATA:
L0109          return hashpointer(t, pvalue(key));
L0110        default:
L0111          return hashpointer(t, gcvalue(key));
L0112      }
L0113    }
L0114    
L0115    
L0116    /*
L0117    ** returns the index for `key' if `key' is an appropriate key to live in
L0118    ** the array part of the table, -1 otherwise.
L0119    */
L0120    static int arrayindex (const TValue *key) {
L0121      if (ttisnumber(key)) {
L0122        lua_Number n = nvalue(key);
L0123        int k;
L0124        lua_number2int(k, n);
L0125        if (luai_numeq(cast_num(k), n))
L0126          return k;
L0127      }
L0128      return -1;  /* `key' did not match some condition */
L0129    }
L0130    
L0131    
L0132    /*
L0133    ** returns the index of a `key' for table traversals. First goes all
L0134    ** elements in the array part, then elements in the hash part. The
L0135    ** beginning of a traversal is signalled by -1.
L0136    */
L0137    static int findindex (lua_State *L, Table *t, StkId key) {
L0138      int i;
L0139      if (ttisnil(key)) return -1;  /* first iteration */
L0140      i = arrayindex(key);
L0141      if (0 < i && i <= t->sizearray)  /* is `key' inside array part? */
L0142        return i-1;  /* yes; that's the index (corrected to C) */
L0143      else {
L0144        Node *n = mainposition(t, key);
L0145        do {  /* check whether `key' is somewhere in the chain */
L0146          /* key may be dead already, but it is ok to use it in `next' */
L0147          if (luaO_rawequalObj(key2tval(n), key) ||
L0148                (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) &&
L0149                 gcvalue(gkey(n)) == gcvalue(key))) {
L0150            i = cast_int(n - gnode(t, 0));  /* key index in hash table */
L0151            /* hash elements are numbered after array ones */
L0152            return i + t->sizearray;
L0153          }
L0154          else n = gnext(n);
L0155        } while (n);
L0156        luaG_runerror(L, "invalid key to " LUA_QL("next"));  /* key not found */
L0157        return 0;  /* to avoid warnings */
L0158      }
L0159    }
L0160    
L0161    
L0162    int luaH_next (lua_State *L, Table *t, StkId key) {
L0163      int i = findindex(L, t, key);  /* find original element */
L0164      for (i++; i < t->sizearray; i++) {  /* try first array part */
L0165        if (!ttisnil(&t->array[i])) {  /* a non-nil value? */
L0166          setnvalue(key, cast_num(i+1));
L0167          setobj2s(L, key+1, &t->array[i]);
L0168          return 1;
L0169        }
L0170      }
L0171      for (i -= t->sizearray; i < sizenode(t); i++) {  /* then hash part */
L0172        if (!ttisnil(gval(gnode(t, i)))) {  /* a non-nil value? */
L0173          setobj2s(L, key, key2tval(gnode(t, i)));
L0174          setobj2s(L, key+1, gval(gnode(t, i)));
L0175          return 1;
L0176        }
L0177      }
L0178      return 0;  /* no more elements */
L0179    }
L0180    
L0181    
L0182    /*
L0183    ** {=============================================================
L0184    ** Rehash
L0185    ** ==============================================================
L0186    */
L0187    
L0188    
L0189    static int computesizes (int nums[], int *narray) {
L0190      int i;
L0191      int twotoi;  /* 2^i */
L0192      int a = 0;  /* number of elements smaller than 2^i */
L0193      int na = 0;  /* number of elements to go to array part */
L0194      int n = 0;  /* optimal size for array part */
L0195      for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
L0196        if (nums[i] > 0) {
L0197          a += nums[i];
L0198          if (a > twotoi/2) {  /* more than half elements present? */
L0199            n = twotoi;  /* optimal size (till now) */
L0200            na = a;  /* all elements smaller than n will go to array part */
L0201          }
L0202        }
L0203        if (a == *narray) break;  /* all elements already counted */
L0204      }
L0205      *narray = n;
L0206      lua_assert(*narray/2 <= na && na <= *narray);
L0207      return na;
L0208    }
L0209    
L0210    
L0211    static int countint (const TValue *key, int *nums) {
L0212      int k = arrayindex(key);
L0213      if (0 < k && k <= MAXASIZE) {  /* is `key' an appropriate array index? */
L0214        nums[ceillog2(k)]++;  /* count as such */
L0215        return 1;
L0216      }
L0217      else
L0218        return 0;
L0219    }
L0220    
L0221    
L0222    static int numusearray (const Table *t, int *nums) {
L0223      int lg;
L0224      int ttlg;  /* 2^lg */
L0225      int ause = 0;  /* summation of `nums' */
L0226      int i = 1;  /* count to traverse all array keys */
L0227      for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) {  /* for each slice */
L0228        int lc = 0;  /* counter */
L0229        int lim = ttlg;
L0230        if (lim > t->sizearray) {
L0231          lim = t->sizearray;  /* adjust upper limit */
L0232          if (i > lim)
L0233            break;  /* no more elements to count */
L0234        }
L0235        /* count elements in range (2^(lg-1), 2^lg] */
L0236        for (; i <= lim; i++) {
L0237          if (!ttisnil(&t->array[i-1]))
L0238            lc++;
L0239        }
L0240        nums[lg] += lc;
L0241        ause += lc;
L0242      }
L0243      return ause;
L0244    }
L0245    
L0246    
L0247    static int numusehash (const Table *t, int *nums, int *pnasize) {
L0248      int totaluse = 0;  /* total number of elements */
L0249      int ause = 0;  /* summation of `nums' */
L0250      int i = sizenode(t);
L0251      while (i--) {
L0252        Node *n = &t->node[i];
L0253        if (!ttisnil(gval(n))) {
L0254          ause += countint(key2tval(n), nums);
L0255          totaluse++;
L0256        }
L0257      }
L0258      *pnasize += ause;
L0259      return totaluse;
L0260    }
L0261    
L0262    
L0263    static void setarrayvector (lua_State *L, Table *t, int size) {
L0264      int i;
L0265      luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
L0266      for (i=t->sizearray; i<size; i++)
L0267         setnilvalue(&t->array[i]);
L0268      t->sizearray = size;
L0269    }
L0270    
L0271    
L0272    static void setnodevector (lua_State *L, Table *t, int size) {
L0273      int lsize;
L0274      if (size == 0) {  /* no elements to hash part? */
L0275        t->node = cast(Node *, dummynode);  /* use common `dummynode' */
L0276        lsize = 0;
L0277      }
L0278      else {
L0279        int i;
L0280        lsize = ceillog2(size);
L0281        if (lsize > MAXBITS)
L0282          luaG_runerror(L, "table overflow");
L0283        size = twoto(lsize);
L0284        t->node = luaM_newvector(L, size, Node);
L0285        for (i=0; i<size; i++) {
L0286          Node *n = gnode(t, i);
L0287          gnext(n) = NULL;
L0288          setnilvalue(gkey(n));
L0289          setnilvalue(gval(n));
L0290        }
L0291      }
L0292      t->lsizenode = cast_byte(lsize);
L0293      t->lastfree = gnode(t, size);  /* all positions are free */
L0294    }
L0295    
L0296    
L0297    static void resize (lua_State *L, Table *t, int nasize, int nhsize) {
L0298      int i;
L0299      int oldasize = t->sizearray;
L0300      int oldhsize = t->lsizenode;
L0301      Node *nold = t->node;  /* save old hash ... */
L0302      if (nasize > oldasize)  /* array part must grow? */
L0303        setarrayvector(L, t, nasize);
L0304      /* create new hash part with appropriate size */
L0305      setnodevector(L, t, nhsize);  
L0306      if (nasize < oldasize) {  /* array part must shrink? */
L0307        t->sizearray = nasize;
L0308        /* re-insert elements from vanishing slice */
L0309        for (i=nasize; i<oldasize; i++) {
L0310          if (!ttisnil(&t->array[i]))
L0311            setobjt2t(L, luaH_setnum(L, t, i+1), &t->array[i]);
L0312        }
L0313        /* shrink array */
L0314        luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
L0315      }
L0316      /* re-insert elements from hash part */
L0317      for (i = twoto(oldhsize) - 1; i >= 0; i--) {
L0318        Node *old = nold+i;
L0319        if (!ttisnil(gval(old)))
L0320          setobjt2t(L, luaH_set(L, t, key2tval(old)), gval(old));
L0321      }
L0322      if (nold != dummynode)
L0323        luaM_freearray(L, nold, twoto(oldhsize), Node);  /* free old array */
L0324    }
L0325    
L0326    
L0327    void luaH_resizearray (lua_State *L, Table *t, int nasize) {
L0328      int nsize = (t->node == dummynode) ? 0 : sizenode(t);
L0329      resize(L, t, nasize, nsize);
L0330    }
L0331    
L0332    
L0333    static void rehash (lua_State *L, Table *t, const TValue *ek) {
L0334      int nasize, na;
L0335      int nums[MAXBITS+1];  /* nums[i] = number of keys between 2^(i-1) and 2^i */
L0336      int i;
L0337      int totaluse;
L0338      for (i=0; i<=MAXBITS; i++) nums[i] = 0;  /* reset counts */
L0339      nasize = numusearray(t, nums);  /* count keys in array part */
L0340      totaluse = nasize;  /* all those keys are integer keys */
L0341      totaluse += numusehash(t, nums, &nasize);  /* count keys in hash part */
L0342      /* count extra key */
L0343      nasize += countint(ek, nums);
L0344      totaluse++;
L0345      /* compute new size for array part */
L0346      na = computesizes(nums, &nasize);
L0347      /* resize the table to new computed sizes */
L0348      resize(L, t, nasize, totaluse - na);
L0349    }
L0350    
L0351    
L0352    
L0353    /*
L0354    ** }=============================================================
L0355    */
L0356    
L0357    
L0358    Table *luaH_new (lua_State *L, int narray, int nhash) {
L0359      Table *t = luaM_new(L, Table);
L0360      luaC_link(L, obj2gco(t), LUA_TTABLE);
L0361      t->metatable = NULL;
L0362      t->flags = cast_byte(~0);
L0363      /* temporary values (kept only if some malloc fails) */
L0364      t->array = NULL;
L0365      t->sizearray = 0;
L0366      t->lsizenode = 0;
L0367      t->node = cast(Node *, dummynode);
L0368      setarrayvector(L, t, narray);
L0369      setnodevector(L, t, nhash);
L0370      return t;
L0371    }
L0372    
L0373    
L0374    void luaH_free (lua_State *L, Table *t) {
L0375      if (t->node != dummynode)
L0376        luaM_freearray(L, t->node, sizenode(t), Node);
L0377      luaM_freearray(L, t->array, t->sizearray, TValue);
L0378      luaM_free(L, t);
L0379    }
L0380    
L0381    
L0382    static Node *getfreepos (Table *t) {
L0383      while (t->lastfree-- > t->node) {
L0384        if (ttisnil(gkey(t->lastfree)))
L0385          return t->lastfree;
L0386      }
L0387      return NULL;  /* could not find a free place */
L0388    }
L0389    
L0390    
L0391    
L0392    /*
L0393    ** inserts a new key into a hash table; first, check whether key's main 
L0394    ** position is free. If not, check whether colliding node is in its main 
L0395    ** position or not: if it is not, move colliding node to an empty place and 
L0396    ** put new key in its main position; otherwise (colliding node is in its main 
L0397    ** position), new key goes to an empty position. 
L0398    */
L0399    static TValue *newkey (lua_State *L, Table *t, const TValue *key) {
L0400      Node *mp = mainposition(t, key);
L0401      if (!ttisnil(gval(mp)) || mp == dummynode) {
L0402        Node *othern;
L0403        Node *n = getfreepos(t);  /* get a free place */
L0404        if (n == NULL) {  /* cannot find a free place? */
L0405          rehash(L, t, key);  /* grow table */
L0406          return luaH_set(L, t, key);  /* re-insert key into grown table */
L0407        }
L0408        lua_assert(n != dummynode);
L0409        othern = mainposition(t, key2tval(mp));
L0410        if (othern != mp) {  /* is colliding node out of its main position? */
L0411          /* yes; move colliding node into free position */
L0412          while (gnext(othern) != mp) othern = gnext(othern);  /* find previous */
L0413          gnext(othern) = n;  /* redo the chain with `n' in place of `mp' */
L0414          *n = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
L0415          gnext(mp) = NULL;  /* now `mp' is free */
L0416          setnilvalue(gval(mp));
L0417        }
L0418        else {  /* colliding node is in its own main position */
L0419          /* new node will go into free position */
L0420          gnext(n) = gnext(mp);  /* chain new position */
L0421          gnext(mp) = n;
L0422          mp = n;
L0423        }
L0424      }
L0425      gkey(mp)->value = key->value; gkey(mp)->tt = key->tt;
L0426      luaC_barriert(L, t, key);
L0427      lua_assert(ttisnil(gval(mp)));
L0428      return gval(mp);
L0429    }
L0430    
L0431    
L0432    /*
L0433    ** search function for integers
L0434    */
L0435    const TValue *luaH_getnum (Table *t, int key) {
L0436      /* (1 <= key && key <= t->sizearray) */
L0437      if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
L0438        return &t->array[key-1];
L0439      else {
L0440        lua_Number nk = cast_num(key);
L0441        Node *n = hashnum(t, nk);
L0442        do {  /* check whether `key' is somewhere in the chain */
L0443          if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
L0444            return gval(n);  /* that's it */
L0445          else n = gnext(n);
L0446        } while (n);
L0447        return luaO_nilobject;
L0448      }
L0449    }
L0450    
L0451    
L0452    /*
L0453    ** search function for strings
L0454    */
L0455    const TValue *luaH_getstr (Table *t, TString *key) {
L0456      Node *n = hashstr(t, key);
L0457      do {  /* check whether `key' is somewhere in the chain */
L0458        if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key)
L0459          return gval(n);  /* that's it */
L0460        else n = gnext(n);
L0461      } while (n);
L0462      return luaO_nilobject;
L0463    }
L0464    
L0465    
L0466    /*
L0467    ** main search function
L0468    */
L0469    const TValue *luaH_get (Table *t, const TValue *key) {
L0470      switch (ttype(key)) {
L0471        case LUA_TNIL: return luaO_nilobject;
L0472        case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));
L0473        case LUA_TNUMBER: {
L0474          int k;
L0475          lua_Number n = nvalue(key);
L0476          lua_number2int(k, n);
L0477          if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */
L0478            return luaH_getnum(t, k);  /* use specialized version */
L0479          /* else go through */
L0480        }
L0481        default: {
L0482          Node *n = mainposition(t, key);
L0483          do {  /* check whether `key' is somewhere in the chain */
L0484            if (luaO_rawequalObj(key2tval(n), key))
L0485              return gval(n);  /* that's it */
L0486            else n = gnext(n);
L0487          } while (n);
L0488          return luaO_nilobject;
L0489        }
L0490      }
L0491    }
L0492    
L0493    
L0494    TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
L0495      const TValue *p = luaH_get(t, key);
L0496      t->flags = 0;
L0497      if (p != luaO_nilobject)
L0498        return cast(TValue *, p);
L0499      else {
L0500        if (ttisnil(key)) luaG_runerror(L, "table index is nil");
L0501        else if (ttisnumber(key) && luai_numisnan(nvalue(key)))
L0502          luaG_runerror(L, "table index is NaN");
L0503        return newkey(L, t, key);
L0504      }
L0505    }
L0506    
L0507    
L0508    TValue *luaH_setnum (lua_State *L, Table *t, int key) {
L0509      const TValue *p = luaH_getnum(t, key);
L0510      if (p != luaO_nilobject)
L0511        return cast(TValue *, p);
L0512      else {
L0513        TValue k;
L0514        setnvalue(&k, cast_num(key));
L0515        return newkey(L, t, &k);
L0516      }
L0517    }
L0518    
L0519    
L0520    TValue *luaH_setstr (lua_State *L, Table *t, TString *key) {
L0521      const TValue *p = luaH_getstr(t, key);
L0522      if (p != luaO_nilobject)
L0523        return cast(TValue *, p);
L0524      else {
L0525        TValue k;
L0526        setsvalue(L, &k, key);
L0527        return newkey(L, t, &k);
L0528      }
L0529    }
L0530    
L0531    
L0532    static int unbound_search (Table *t, unsigned int j) {
L0533      unsigned int i = j;  /* i is zero or a present index */
L0534      j++;
L0535      /* find `i' and `j' such that i is present and j is not */
L0536      while (!ttisnil(luaH_getnum(t, j))) {
L0537        i = j;
L0538        j *= 2;
L0539        if (j > cast(unsigned int, MAX_INT)) {  /* overflow? */
L0540          /* table was built with bad purposes: resort to linear search */
L0541          i = 1;
L0542          while (!ttisnil(luaH_getnum(t, i))) i++;
L0543          return i - 1;
L0544        }
L0545      }
L0546      /* now do a binary search between them */
L0547      while (j - i > 1) {
L0548        unsigned int m = (i+j)/2;
L0549        if (ttisnil(luaH_getnum(t, m))) j = m;
L0550        else i = m;
L0551      }
L0552      return i;
L0553    }
L0554    
L0555    
L0556    /*
L0557    ** Try to find a boundary in table `t'. A `boundary' is an integer index
L0558    ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
L0559    */
L0560    int luaH_getn (Table *t) {
L0561      unsigned int j = t->sizearray;
L0562      if (j > 0 && ttisnil(&t->array[j - 1])) {
L0563        /* there is a boundary in the array part: (binary) search for it */
L0564        unsigned int i = 0;
L0565        while (j - i > 1) {
L0566          unsigned int m = (i+j)/2;
L0567          if (ttisnil(&t->array[m - 1])) j = m;
L0568          else i = m;
L0569        }
L0570        return i;
L0571      }
L0572      /* else must find a boundary in hash part */
L0573      else if (t->node == dummynode)  /* hash part is empty? */
L0574        return j;  /* that is easy... */
L0575      else return unbound_search(t, j);
L0576    }
L0577    
L0578    
L0579    
L0580    #if defined(LUA_DEBUG)
L0581    
L0582    Node *luaH_mainposition (const Table *t, const TValue *key) {
L0583      return mainposition(t, key);
L0584    }
L0585    
L0586    int luaH_isdummy (Node *n) { return n == dummynode; }
L0587    
L0588    #endif

Generated by pretty.lua