1/*
2** $Id: ltable.c,v 2.72.1.1 2013/04/12 18:48:47 roberto Exp $
3** Lua tables (hash)
4** See Copyright Notice in lua.h
5*/
6
7
8/*
9** Implementation of tables (aka arrays, objects, or hash tables).
10** Tables keep its elements in two parts: an array part and a hash part.
11** Non-negative integer keys are all candidates to be kept in the array
12** part. The actual size of the array is the largest `n' such that at
13** least half the slots between 0 and n are in use.
14** Hash uses a mix of chained scatter table with Brent's variation.
15** A main invariant of these tables is that, if an element is not
16** in its main position (i.e. the `original' position that its hash gives
17** to it), then the colliding element is in its own main position.
18** Hence even when the load factor reaches 100%, performance remains good.
19*/
20
21#include <string.h>
22
23#define ltable_c
24#define LUA_CORE
25
26#include "lua.h"
27
28#include "ldebug.h"
29#include "ldo.h"
30#include "lgc.h"
31#include "lmem.h"
32#include "lobject.h"
33#include "lstate.h"
34#include "lstring.h"
35#include "ltable.h"
36#include "lvm.h"
37
38
39/*
40** max size of array part is 2^MAXBITS
41*/
42#if LUAI_BITSINT >= 32
43#define MAXBITS		30
44#else
45#define MAXBITS		(LUAI_BITSINT-2)
46#endif
47
48#define MAXASIZE	(1 << MAXBITS)
49
50
51#define hashpow2(t,n)		(gnode(t, lmod((n), sizenode(t))))
52
53#define hashstr(t,str)		hashpow2(t, (str)->tsv.hash)
54#define hashboolean(t,p)	hashpow2(t, p)
55
56
57/*
58** for some types, it is better to avoid modulus by power of 2, as
59** they tend to have many 2 factors.
60*/
61#define hashmod(t,n)	(gnode(t, ((n) % ((sizenode(t)-1)|1))))
62
63
64#define hashpointer(t,p)	hashmod(t, IntPoint(p))
65
66
67#define dummynode		(&dummynode_)
68
69#define isdummy(n)		((n) == dummynode)
70
71static const Node dummynode_ = {
72  {NILCONSTANT},  /* value */
73  {{NILCONSTANT, NULL}}  /* key */
74};
75
76
77/*
78** hash for lua_Numbers
79*/
80/* Taken from Lua 5.1 to avoid frexp() */
81#define numints	cast_int(sizeof(lua_Number)/sizeof(int))
82static Node *hashnum (const Table *t, lua_Number n) {
83  unsigned int a[numints];
84  int i;
85  if (luai_numeq(n, 0))  /* avoid problems with -0 */
86    return gnode(t, 0);
87  memcpy(a, &n, sizeof(a));
88  for (i = 1; i < numints; i++) a[0] += a[i];
89  return hashmod(t, a[0]);
90}
91
92
93
94/*
95** returns the `main' position of an element in a table (that is, the index
96** of its hash value)
97*/
98static Node *mainposition (const Table *t, const TValue *key) {
99  switch (ttype(key)) {
100    case LUA_TNUMBER:
101      return hashnum(t, nvalue(key));
102    case LUA_TLNGSTR: {
103      TString *s = rawtsvalue(key);
104      if (s->tsv.extra == 0) {  /* no hash? */
105        s->tsv.hash = luaS_hash(getstr(s), s->tsv.len, s->tsv.hash);
106        s->tsv.extra = 1;  /* now it has its hash */
107      }
108      return hashstr(t, rawtsvalue(key));
109    }
110    case LUA_TSHRSTR:
111      return hashstr(t, rawtsvalue(key));
112    case LUA_TBOOLEAN:
113      return hashboolean(t, bvalue(key));
114    case LUA_TLIGHTUSERDATA:
115      return hashpointer(t, pvalue(key));
116    case LUA_TLCF:
117      return hashpointer(t, fvalue(key));
118    default:
119      return hashpointer(t, gcvalue(key));
120  }
121}
122
123
124/*
125** returns the index for `key' if `key' is an appropriate key to live in
126** the array part of the table, -1 otherwise.
127*/
128static int arrayindex (const TValue *key) {
129  if (ttisnumber(key)) {
130    lua_Number n = nvalue(key);
131    int k;
132    lua_number2int(k, n);
133    if (luai_numeq(cast_num(k), n))
134      return k;
135  }
136  return -1;  /* `key' did not match some condition */
137}
138
139
140/*
141** returns the index of a `key' for table traversals. First goes all
142** elements in the array part, then elements in the hash part. The
143** beginning of a traversal is signaled by -1.
144*/
145static int findindex (lua_State *L, Table *t, StkId key) {
146  int i;
147  if (ttisnil(key)) return -1;  /* first iteration */
148  i = arrayindex(key);
149  if (0 < i && i <= t->sizearray)  /* is `key' inside array part? */
150    return i-1;  /* yes; that's the index (corrected to C) */
151  else {
152    Node *n = mainposition(t, key);
153    for (;;) {  /* check whether `key' is somewhere in the chain */
154      /* key may be dead already, but it is ok to use it in `next' */
155      if (luaV_rawequalobj(gkey(n), key) ||
156            (ttisdeadkey(gkey(n)) && iscollectable(key) &&
157             deadvalue(gkey(n)) == gcvalue(key))) {
158        i = cast_int(n - gnode(t, 0));  /* key index in hash table */
159        /* hash elements are numbered after array ones */
160        return i + t->sizearray;
161      }
162      else n = gnext(n);
163      if (n == NULL)
164        luaG_runerror(L, "invalid key to " LUA_QL("next"));  /* key not found */
165    }
166  }
167}
168
169
170int luaH_next (lua_State *L, Table *t, StkId key) {
171  int i = findindex(L, t, key);  /* find original element */
172  for (i++; i < t->sizearray; i++) {  /* try first array part */
173    if (!ttisnil(&t->array[i])) {  /* a non-nil value? */
174      setnvalue(key, cast_num(i+1));
175      setobj2s(L, key+1, &t->array[i]);
176      return 1;
177    }
178  }
179  for (i -= t->sizearray; i < sizenode(t); i++) {  /* then hash part */
180    if (!ttisnil(gval(gnode(t, i)))) {  /* a non-nil value? */
181      setobj2s(L, key, gkey(gnode(t, i)));
182      setobj2s(L, key+1, gval(gnode(t, i)));
183      return 1;
184    }
185  }
186  return 0;  /* no more elements */
187}
188
189
190/*
191** {=============================================================
192** Rehash
193** ==============================================================
194*/
195
196
197static int computesizes (int nums[], int *narray) {
198  int i;
199  int twotoi;  /* 2^i */
200  int a = 0;  /* number of elements smaller than 2^i */
201  int na = 0;  /* number of elements to go to array part */
202  int n = 0;  /* optimal size for array part */
203  for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
204    if (nums[i] > 0) {
205      a += nums[i];
206      if (a > twotoi/2) {  /* more than half elements present? */
207        n = twotoi;  /* optimal size (till now) */
208        na = a;  /* all elements smaller than n will go to array part */
209      }
210    }
211    if (a == *narray) break;  /* all elements already counted */
212  }
213  *narray = n;
214  lua_assert(*narray/2 <= na && na <= *narray);
215  return na;
216}
217
218
219static int countint (const TValue *key, int *nums) {
220  int k = arrayindex(key);
221  if (0 < k && k <= MAXASIZE) {  /* is `key' an appropriate array index? */
222    nums[luaO_ceillog2(k)]++;  /* count as such */
223    return 1;
224  }
225  else
226    return 0;
227}
228
229
230static int numusearray (const Table *t, int *nums) {
231  int lg;
232  int ttlg;  /* 2^lg */
233  int ause = 0;  /* summation of `nums' */
234  int i = 1;  /* count to traverse all array keys */
235  for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) {  /* for each slice */
236    int lc = 0;  /* counter */
237    int lim = ttlg;
238    if (lim > t->sizearray) {
239      lim = t->sizearray;  /* adjust upper limit */
240      if (i > lim)
241        break;  /* no more elements to count */
242    }
243    /* count elements in range (2^(lg-1), 2^lg] */
244    for (; i <= lim; i++) {
245      if (!ttisnil(&t->array[i-1]))
246        lc++;
247    }
248    nums[lg] += lc;
249    ause += lc;
250  }
251  return ause;
252}
253
254
255static int numusehash (const Table *t, int *nums, int *pnasize) {
256  int totaluse = 0;  /* total number of elements */
257  int ause = 0;  /* summation of `nums' */
258  int i = sizenode(t);
259  while (i--) {
260    Node *n = &t->node[i];
261    if (!ttisnil(gval(n))) {
262      ause += countint(gkey(n), nums);
263      totaluse++;
264    }
265  }
266  *pnasize += ause;
267  return totaluse;
268}
269
270
271static void setarrayvector (lua_State *L, Table *t, int size) {
272  int i;
273  luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
274  for (i=t->sizearray; i<size; i++)
275     setnilvalue(&t->array[i]);
276  t->sizearray = size;
277}
278
279
280static void setnodevector (lua_State *L, Table *t, int size) {
281  int lsize;
282  if (size == 0) {  /* no elements to hash part? */
283    t->node = cast(Node *, dummynode);  /* use common `dummynode' */
284    lsize = 0;
285  }
286  else {
287    int i;
288    lsize = luaO_ceillog2(size);
289    if (lsize > MAXBITS)
290      luaG_runerror(L, "table overflow");
291    size = twoto(lsize);
292    t->node = luaM_newvector(L, size, Node);
293    for (i=0; i<size; i++) {
294      Node *n = gnode(t, i);
295      gnext(n) = NULL;
296      setnilvalue(gkey(n));
297      setnilvalue(gval(n));
298    }
299  }
300  t->lsizenode = cast_byte(lsize);
301  t->lastfree = gnode(t, size);  /* all positions are free */
302}
303
304
305void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {
306  int i;
307  int oldasize = t->sizearray;
308  int oldhsize = t->lsizenode;
309  Node *nold = t->node;  /* save old hash ... */
310  if (nasize > oldasize)  /* array part must grow? */
311    setarrayvector(L, t, nasize);
312  /* create new hash part with appropriate size */
313  setnodevector(L, t, nhsize);
314  if (nasize < oldasize) {  /* array part must shrink? */
315    t->sizearray = nasize;
316    /* re-insert elements from vanishing slice */
317    for (i=nasize; i<oldasize; i++) {
318      if (!ttisnil(&t->array[i]))
319        luaH_setint(L, t, i + 1, &t->array[i]);
320    }
321    /* shrink array */
322    luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
323  }
324  /* re-insert elements from hash part */
325  for (i = twoto(oldhsize) - 1; i >= 0; i--) {
326    Node *old = nold+i;
327    if (!ttisnil(gval(old))) {
328      /* doesn't need barrier/invalidate cache, as entry was
329         already present in the table */
330      setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old));
331    }
332  }
333  if (!isdummy(nold))
334    luaM_freearray(L, nold, cast(size_t, twoto(oldhsize))); /* free old array */
335}
336
337
338void luaH_resizearray (lua_State *L, Table *t, int nasize) {
339  int nsize = isdummy(t->node) ? 0 : sizenode(t);
340  luaH_resize(L, t, nasize, nsize);
341}
342
343
344static void rehash (lua_State *L, Table *t, const TValue *ek) {
345  int nasize, na;
346  int nums[MAXBITS+1];  /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */
347  int i;
348  int totaluse;
349  for (i=0; i<=MAXBITS; i++) nums[i] = 0;  /* reset counts */
350  nasize = numusearray(t, nums);  /* count keys in array part */
351  totaluse = nasize;  /* all those keys are integer keys */
352  totaluse += numusehash(t, nums, &nasize);  /* count keys in hash part */
353  /* count extra key */
354  nasize += countint(ek, nums);
355  totaluse++;
356  /* compute new size for array part */
357  na = computesizes(nums, &nasize);
358  /* resize the table to new computed sizes */
359  luaH_resize(L, t, nasize, totaluse - na);
360}
361
362
363
364/*
365** }=============================================================
366*/
367
368
369Table *luaH_new (lua_State *L) {
370  Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h;
371  t->metatable = NULL;
372  t->flags = cast_byte(~0);
373  t->array = NULL;
374  t->sizearray = 0;
375  setnodevector(L, t, 0);
376  return t;
377}
378
379
380void luaH_free (lua_State *L, Table *t) {
381  if (!isdummy(t->node))
382    luaM_freearray(L, t->node, cast(size_t, sizenode(t)));
383  luaM_freearray(L, t->array, t->sizearray);
384  luaM_free(L, t);
385}
386
387
388static Node *getfreepos (Table *t) {
389  while (t->lastfree > t->node) {
390    t->lastfree--;
391    if (ttisnil(gkey(t->lastfree)))
392      return t->lastfree;
393  }
394  return NULL;  /* could not find a free place */
395}
396
397
398
399/*
400** inserts a new key into a hash table; first, check whether key's main
401** position is free. If not, check whether colliding node is in its main
402** position or not: if it is not, move colliding node to an empty place and
403** put new key in its main position; otherwise (colliding node is in its main
404** position), new key goes to an empty position.
405*/
406TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
407  Node *mp;
408  if (ttisnil(key)) luaG_runerror(L, "table index is nil");
409  else if (ttisnumber(key) && luai_numisnan(L, nvalue(key)))
410    luaG_runerror(L, "table index is NaN");
411  mp = mainposition(t, key);
412  if (!ttisnil(gval(mp)) || isdummy(mp)) {  /* main position is taken? */
413    Node *othern;
414    Node *n = getfreepos(t);  /* get a free place */
415    if (n == NULL) {  /* cannot find a free place? */
416      rehash(L, t, key);  /* grow table */
417      /* whatever called 'newkey' take care of TM cache and GC barrier */
418      return luaH_set(L, t, key);  /* insert key into grown table */
419    }
420    lua_assert(!isdummy(n));
421    othern = mainposition(t, gkey(mp));
422    if (othern != mp) {  /* is colliding node out of its main position? */
423      /* yes; move colliding node into free position */
424      while (gnext(othern) != mp) othern = gnext(othern);  /* find previous */
425      gnext(othern) = n;  /* redo the chain with `n' in place of `mp' */
426      *n = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
427      gnext(mp) = NULL;  /* now `mp' is free */
428      setnilvalue(gval(mp));
429    }
430    else {  /* colliding node is in its own main position */
431      /* new node will go into free position */
432      gnext(n) = gnext(mp);  /* chain new position */
433      gnext(mp) = n;
434      mp = n;
435    }
436  }
437  setobj2t(L, gkey(mp), key);
438  luaC_barrierback(L, obj2gco(t), key);
439  lua_assert(ttisnil(gval(mp)));
440  return gval(mp);
441}
442
443
444/*
445** search function for integers
446*/
447const TValue *luaH_getint (Table *t, int key) {
448  /* (1 <= key && key <= t->sizearray) */
449  if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
450    return &t->array[key-1];
451  else {
452    lua_Number nk = cast_num(key);
453    Node *n = hashnum(t, nk);
454    do {  /* check whether `key' is somewhere in the chain */
455      if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
456        return gval(n);  /* that's it */
457      else n = gnext(n);
458    } while (n);
459    return luaO_nilobject;
460  }
461}
462
463
464/*
465** search function for short strings
466*/
467const TValue *luaH_getstr (Table *t, TString *key) {
468  Node *n = hashstr(t, key);
469  lua_assert(key->tsv.tt == LUA_TSHRSTR);
470  do {  /* check whether `key' is somewhere in the chain */
471    if (ttisshrstring(gkey(n)) && eqshrstr(rawtsvalue(gkey(n)), key))
472      return gval(n);  /* that's it */
473    else n = gnext(n);
474  } while (n);
475  return luaO_nilobject;
476}
477
478
479/*
480** main search function
481*/
482const TValue *luaH_get (Table *t, const TValue *key) {
483  switch (ttype(key)) {
484    case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key));
485    case LUA_TNIL: return luaO_nilobject;
486    case LUA_TNUMBER: {
487      int k;
488      lua_Number n = nvalue(key);
489      lua_number2int(k, n);
490      if (luai_numeq(cast_num(k), n)) /* index is int? */
491        return luaH_getint(t, k);  /* use specialized version */
492      /* else go through */
493    }
494    default: {
495      Node *n = mainposition(t, key);
496      do {  /* check whether `key' is somewhere in the chain */
497        if (luaV_rawequalobj(gkey(n), key))
498          return gval(n);  /* that's it */
499        else n = gnext(n);
500      } while (n);
501      return luaO_nilobject;
502    }
503  }
504}
505
506
507/*
508** beware: when using this function you probably need to check a GC
509** barrier and invalidate the TM cache.
510*/
511TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
512  const TValue *p = luaH_get(t, key);
513  if (p != luaO_nilobject)
514    return cast(TValue *, p);
515  else return luaH_newkey(L, t, key);
516}
517
518
519void luaH_setint (lua_State *L, Table *t, int key, TValue *value) {
520  const TValue *p = luaH_getint(t, key);
521  TValue *cell;
522  if (p != luaO_nilobject)
523    cell = cast(TValue *, p);
524  else {
525    TValue k;
526    setnvalue(&k, cast_num(key));
527    cell = luaH_newkey(L, t, &k);
528  }
529  setobj2t(L, cell, value);
530}
531
532
533static int unbound_search (Table *t, unsigned int j) {
534  unsigned int i = j;  /* i is zero or a present index */
535  j++;
536  /* find `i' and `j' such that i is present and j is not */
537  while (!ttisnil(luaH_getint(t, j))) {
538    i = j;
539    j *= 2;
540    if (j > cast(unsigned int, MAX_INT)) {  /* overflow? */
541      /* table was built with bad purposes: resort to linear search */
542      i = 1;
543      while (!ttisnil(luaH_getint(t, i))) i++;
544      return i - 1;
545    }
546  }
547  /* now do a binary search between them */
548  while (j - i > 1) {
549    unsigned int m = (i+j)/2;
550    if (ttisnil(luaH_getint(t, m))) j = m;
551    else i = m;
552  }
553  return i;
554}
555
556
557/*
558** Try to find a boundary in table `t'. A `boundary' is an integer index
559** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
560*/
561int luaH_getn (Table *t) {
562  unsigned int j = t->sizearray;
563  if (j > 0 && ttisnil(&t->array[j - 1])) {
564    /* there is a boundary in the array part: (binary) search for it */
565    unsigned int i = 0;
566    while (j - i > 1) {
567      unsigned int m = (i+j)/2;
568      if (ttisnil(&t->array[m - 1])) j = m;
569      else i = m;
570    }
571    return i;
572  }
573  /* else must find a boundary in hash part */
574  else if (isdummy(t->node))  /* hash part is empty? */
575    return j;  /* that is easy... */
576  else return unbound_search(t, j);
577}
578
579
580
581#if defined(LUA_DEBUG)
582
583Node *luaH_mainposition (const Table *t, const TValue *key) {
584  return mainposition(t, key);
585}
586
587int luaH_isdummy (Node *n) { return isdummy(n); }
588
589#endif
590