rpm  4.5
ltable.c
Go to the documentation of this file.
1 /*
2 ** $Id: ltable.c,v 1.1 2004/03/16 21:58:30 niemeyer 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 ** In other words, there are collisions only when two elements have the
19 ** same main position (i.e. the same hash values for that table size).
20 ** Because of that, the load factor of these tables can be 100% without
21 ** performance penalties.
22 */
23 
24 #include <string.h>
25 
26 #define ltable_c
27 
28 #include "lua.h"
29 
30 #include "ldebug.h"
31 #include "ldo.h"
32 #include "lgc.h"
33 #include "lmem.h"
34 #include "lobject.h"
35 #include "lstate.h"
36 #include "ltable.h"
37 
38 
39 /*
40 ** max size of array part is 2^MAXBITS
41 */
42 #if BITS_INT > 26
43 #define MAXBITS 24
44 #else
45 #define MAXBITS (BITS_INT-2)
46 #endif
47 
48 /* check whether `x' < 2^MAXBITS */
49 #define toobig(x) ((((x)-1) >> MAXBITS) != 0)
50 
51 
52 /* function to convert a lua_Number to int (with any rounding method) */
53 #ifndef lua_number2int
54 #define lua_number2int(i,n) ((i)=(int)(n))
55 #endif
56 
57 
58 #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
59 
60 #define hashstr(t,str) hashpow2(t, (str)->tsv.hash)
61 #define hashboolean(t,p) hashpow2(t, p)
62 
63 
64 /*
65 ** for some types, it is better to avoid modulus by power of 2, as
66 ** they tend to have many 2 factors.
67 */
68 #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
69 
70 
71 #define hashpointer(t,p) hashmod(t, IntPoint(p))
72 
73 
74 /*
75 ** number of ints inside a lua_Number
76 */
77 #define numints cast(int, sizeof(lua_Number)/sizeof(int))
78 
79 
80 /*
81 ** hash for lua_Numbers
82 */
83 static Node *hashnum (const Table *t, lua_Number n)
84  /*@*/
85 {
86  unsigned int a[numints];
87  int i;
88  n += 1; /* normalize number (avoid -0) */
89  lua_assert(sizeof(a) <= sizeof(n));
90  memcpy(a, &n, sizeof(a));
91  for (i = 1; i < numints; i++) a[0] += a[i];
92  return hashmod(t, cast(lu_hash, a[0]));
93 }
94 
95 
96 
97 /*
98 ** returns the `main' position of an element in a table (that is, the index
99 ** of its hash value)
100 */
101 Node *luaH_mainposition (const Table *t, const TObject *key) {
102  switch (ttype(key)) {
103  case LUA_TNUMBER:
104  return hashnum(t, nvalue(key));
105  case LUA_TSTRING:
106  return hashstr(t, tsvalue(key));
107  case LUA_TBOOLEAN:
108  return hashboolean(t, bvalue(key));
109  case LUA_TLIGHTUSERDATA:
110  return hashpointer(t, pvalue(key));
111  default:
112  return hashpointer(t, gcvalue(key));
113  }
114 }
115 
116 
117 /*
118 ** returns the index for `key' if `key' is an appropriate key to live in
119 ** the array part of the table, -1 otherwise.
120 */
121 static int arrayindex (const TObject *key)
122  /*@*/
123 {
124  if (ttisnumber(key)) {
125  int k;
126  lua_number2int(k, (nvalue(key)));
127  if (cast(lua_Number, k) == nvalue(key) && k >= 1 && !toobig(k))
128  return k;
129  }
130  return -1; /* `key' did not match some condition */
131 }
132 
133 
134 /*
135 ** returns the index of a `key' for table traversals. First goes all
136 ** elements in the array part, then elements in the hash part. The
137 ** beginning and end of a traversal are signalled by -1.
138 */
139 static int luaH_index (lua_State *L, Table *t, StkId key)
140  /*@modifies L @*/
141 {
142  int i;
143  if (ttisnil(key)) return -1; /* first iteration */
144  i = arrayindex(key);
145  if (0 <= i && i <= t->sizearray) { /* is `key' inside array part? */
146  return i-1; /* yes; that's the index (corrected to C) */
147  }
148  else {
149  const TObject *v = luaH_get(t, key);
150  if (v == &luaO_nilobject)
151  luaG_runerror(L, "invalid key for `next'");
152  i = cast(int, (cast(const lu_byte *, v) -
153  cast(const lu_byte *, gval(gnode(t, 0)))) / sizeof(Node));
154  return i + t->sizearray; /* hash elements are numbered after array ones */
155  }
156 }
157 
158 
159 int luaH_next (lua_State *L, Table *t, StkId key) {
160  int i = luaH_index(L, t, key); /* find original element */
161  for (i++; i < t->sizearray; i++) { /* try first array part */
162  if (!ttisnil(&t->array[i])) { /* a non-nil value? */
163  setnvalue(key, cast(lua_Number, i+1));
164  setobj2s(key+1, &t->array[i]);
165  return 1;
166  }
167  }
168  for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */
169  if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */
170  setobj2s(key, gkey(gnode(t, i)));
171  setobj2s(key+1, gval(gnode(t, i)));
172  return 1;
173  }
174  }
175  return 0; /* no more elements */
176 }
177 
178 
179 /*
180 ** {=============================================================
181 ** Rehash
182 ** ==============================================================
183 */
184 
185 
186 static void computesizes (int nums[], int ntotal, int *narray, int *nhash)
187  /*@modifies *narray, *nhash @*/
188 {
189  int i;
190  int a = nums[0]; /* number of elements smaller than 2^i */
191  int na = a; /* number of elements to go to array part */
192  int n = (na == 0) ? -1 : 0; /* (log of) optimal size for array part */
193  for (i = 1; a < *narray && *narray >= twoto(i-1); i++) {
194  if (nums[i] > 0) {
195  a += nums[i];
196  if (a >= twoto(i-1)) { /* more than half elements in use? */
197  n = i;
198  na = a;
199  }
200  }
201  }
202  lua_assert(na <= *narray && *narray <= ntotal);
203  *nhash = ntotal - na;
204  *narray = (n == -1) ? 0 : twoto(n);
205  lua_assert(na <= *narray && na >= *narray/2);
206 }
207 
208 
209 static void numuse (const Table *t, int *narray, int *nhash)
210  /*@modifies *narray, *nhash @*/
211 {
212  int nums[MAXBITS+1];
213  int i, lg;
214  int totaluse = 0;
215  /* count elements in array part */
216  for (i=0, lg=0; lg<=MAXBITS; lg++) { /* for each slice [2^(lg-1) to 2^lg) */
217  int ttlg = twoto(lg); /* 2^lg */
218  if (ttlg > t->sizearray) {
219  ttlg = t->sizearray;
220  if (i >= ttlg) break;
221  }
222  nums[lg] = 0;
223  for (; i<ttlg; i++) {
224  if (!ttisnil(&t->array[i])) {
225  nums[lg]++;
226  totaluse++;
227  }
228  }
229  }
230  for (; lg<=MAXBITS; lg++) nums[lg] = 0; /* reset other counts */
231  *narray = totaluse; /* all previous uses were in array part */
232  /* count elements in hash part */
233  i = sizenode(t);
234  while (i--) {
235  Node *n = &t->node[i];
236  if (!ttisnil(gval(n))) {
237  int k = arrayindex(gkey(n));
238  if (k >= 0) { /* is `key' an appropriate array index? */
239  nums[luaO_log2(k-1)+1]++; /* count as such */
240  (*narray)++;
241  }
242  totaluse++;
243  }
244  }
245  computesizes(nums, totaluse, narray, nhash);
246 }
247 
248 
249 static void setarrayvector (lua_State *L, Table *t, int size)
250  /*@modifies L, t @*/
251 {
252  int i;
253  luaM_reallocvector(L, t->array, t->sizearray, size, TObject);
254  for (i=t->sizearray; i<size; i++)
255  setnilvalue(&t->array[i]);
256  t->sizearray = size;
257 }
258 
259 
260 static void setnodevector (lua_State *L, Table *t, int lsize)
261  /*@modifies L, t @*/
262 {
263  int i;
264  int size = twoto(lsize);
265  if (lsize > MAXBITS)
266  luaG_runerror(L, "table overflow");
267  if (lsize == 0) { /* no elements to hash part? */
268  t->node = G(L)->dummynode; /* use common `dummynode' */
269  lua_assert(ttisnil(gkey(t->node))); /* assert invariants: */
270  lua_assert(ttisnil(gval(t->node)));
271  lua_assert(t->node->next == NULL); /* (`dummynode' must be empty) */
272  }
273  else {
274  t->node = luaM_newvector(L, size, Node);
275  for (i=0; i<size; i++) {
276  t->node[i].next = NULL;
277  setnilvalue(gkey(gnode(t, i)));
278  setnilvalue(gval(gnode(t, i)));
279  }
280  }
281  t->lsizenode = cast(lu_byte, lsize);
282  t->firstfree = gnode(t, size-1); /* first free position to be used */
283 }
284 
285 
286 static void resize (lua_State *L, Table *t, int nasize, int nhsize)
287  /*@modifies L, t @*/
288 {
289  int i;
290  int oldasize = t->sizearray;
291  int oldhsize = t->lsizenode;
292  Node *nold;
293  Node temp[1];
294  if (oldhsize)
295  nold = t->node; /* save old hash ... */
296  else { /* old hash is `dummynode' */
297  lua_assert(t->node == G(L)->dummynode);
298  temp[0] = t->node[0]; /* copy it to `temp' */
299  nold = temp;
300  setnilvalue(gkey(G(L)->dummynode)); /* restate invariant */
301  setnilvalue(gval(G(L)->dummynode));
302  lua_assert(G(L)->dummynode->next == NULL);
303  }
304  if (nasize > oldasize) /* array part must grow? */
305  setarrayvector(L, t, nasize);
306  /* create new hash part with appropriate size */
307  setnodevector(L, t, nhsize);
308  /* re-insert elements */
309  if (nasize < oldasize) { /* array part must shrink? */
310  t->sizearray = nasize;
311  /* re-insert elements from vanishing slice */
312  for (i=nasize; i<oldasize; i++) {
313  if (!ttisnil(&t->array[i]))
314  setobjt2t(luaH_setnum(L, t, i+1), &t->array[i]);
315  }
316  /* shrink array */
317  luaM_reallocvector(L, t->array, oldasize, nasize, TObject);
318  }
319  /* re-insert elements in hash part */
320  for (i = twoto(oldhsize) - 1; i >= 0; i--) {
321  Node *old = nold+i;
322  if (!ttisnil(gval(old)))
323  setobjt2t(luaH_set(L, t, gkey(old)), gval(old));
324  }
325  if (oldhsize)
326  luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */
327 }
328 
329 
330 static void rehash (lua_State *L, Table *t)
331  /*@modifies L, t @*/
332 {
333  int nasize, nhsize;
334  numuse(t, &nasize, &nhsize); /* compute new sizes for array and hash parts */
335  resize(L, t, nasize, luaO_log2(nhsize)+1);
336 }
337 
338 
339 
340 /*
341 ** }=============================================================
342 */
343 
344 
345 Table *luaH_new (lua_State *L, int narray, int lnhash) {
346  Table *t = luaM_new(L, Table);
347  luaC_link(L, valtogco(t), LUA_TTABLE);
348  t->metatable = hvalue(defaultmeta(L));
349  t->flags = cast(lu_byte, ~0);
350  /* temporary values (kept only if some malloc fails) */
351  t->array = NULL;
352  t->sizearray = 0;
353  t->lsizenode = 0;
354  t->node = NULL;
355  setarrayvector(L, t, narray);
356  setnodevector(L, t, lnhash);
357  return t;
358 }
359 
360 
361 void luaH_free (lua_State *L, Table *t) {
362  if (t->lsizenode)
363  luaM_freearray(L, t->node, sizenode(t), Node);
365  luaM_freelem(L, t);
366 }
367 
368 
369 #if 0
370 /*
371 ** try to remove an element from a hash table; cannot move any element
372 ** (because gc can call `remove' during a table traversal)
373 */
374 void luaH_remove (Table *t, Node *e) {
375  Node *mp = luaH_mainposition(t, gkey(e));
376  if (e != mp) { /* element not in its main position? */
377  while (mp->next != e) mp = mp->next; /* find previous */
378  mp->next = e->next; /* remove `e' from its list */
379  }
380  else {
381  if (e->next != NULL) ??
382  }
383  lua_assert(ttisnil(gval(node)));
384  setnilvalue(gkey(e)); /* clear node `e' */
385  e->next = NULL;
386 }
387 #endif
388 
389 
390 /*
391 ** inserts a new key into a hash table; first, check whether key's main
392 ** position is free. If not, check whether colliding node is in its main
393 ** position or not: if it is not, move colliding node to an empty place and
394 ** put new key in its main position; otherwise (colliding node is in its main
395 ** position), new key goes to an empty position.
396 */
397 static TObject *newkey (lua_State *L, Table *t, const TObject *key)
398  /*@modifies L, t @*/
399 {
400  TObject *val;
401  Node *mp = luaH_mainposition(t, key);
402  if (!ttisnil(gval(mp))) { /* main position is not free? */
403  Node *othern = luaH_mainposition(t, gkey(mp)); /* `mp' of colliding node */
404  Node *n = t->firstfree; /* get a free place */
405  if (othern != mp) { /* is colliding node out of its main position? */
406  /* yes; move colliding node into free position */
407  while (othern->next != mp) othern = othern->next; /* find previous */
408  othern->next = n; /* redo the chain with `n' in place of `mp' */
409  *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
410  mp->next = NULL; /* now `mp' is free */
411  setnilvalue(gval(mp));
412  }
413  else { /* colliding node is in its own main position */
414  /* new node will go into free position */
415  n->next = mp->next; /* chain new position */
416  mp->next = n;
417  mp = n;
418  }
419  }
420  setobj2t(gkey(mp), key); /* write barrier */
421  lua_assert(ttisnil(gval(mp)));
422  for (;;) { /* correct `firstfree' */
423  if (ttisnil(gkey(t->firstfree)))
424  return gval(mp); /* OK; table still has a free place */
425  else if (t->firstfree == t->node) break; /* cannot decrement from here */
426  else (t->firstfree)--;
427  }
428  /* no more free places; must create one */
429  setbvalue(gval(mp), 0); /* avoid new key being removed */
430  rehash(L, t); /* grow table */
431  val = cast(TObject *, luaH_get(t, key)); /* get new position */
432  lua_assert(ttisboolean(val));
433  setnilvalue(val);
434 /*@-observertrans -dependenttrans @*/
435  return val;
436 /*@=observertrans =dependenttrans @*/
437 }
438 
439 
440 /*
441 ** generic search function
442 */
443 /*@observer@*/
444 static const TObject *luaH_getany (Table *t, const TObject *key)
445  /*@*/
446 {
447  if (ttisnil(key)) return &luaO_nilobject;
448  else {
449  Node *n = luaH_mainposition(t, key);
450  do { /* check whether `key' is somewhere in the chain */
451  if (luaO_rawequalObj(gkey(n), key)) return gval(n); /* that's it */
452  else n = n->next;
453  } while (n);
454  return &luaO_nilobject;
455  }
456 }
457 
458 
459 /*
460 ** search function for integers
461 */
462 const TObject *luaH_getnum (Table *t, int key) {
463  if (1 <= key && key <= t->sizearray)
464  return &t->array[key-1];
465  else {
466  lua_Number nk = cast(lua_Number, key);
467  Node *n = hashnum(t, nk);
468  do { /* check whether `key' is somewhere in the chain */
469  if (ttisnumber(gkey(n)) && nvalue(gkey(n)) == nk)
470  return gval(n); /* that's it */
471  else n = n->next;
472  } while (n);
473  return &luaO_nilobject;
474  }
475 }
476 
477 
478 /*
479 ** search function for strings
480 */
481 const TObject *luaH_getstr (Table *t, TString *key) {
482  Node *n = hashstr(t, key);
483  do { /* check whether `key' is somewhere in the chain */
484  if (ttisstring(gkey(n)) && tsvalue(gkey(n)) == key)
485  return gval(n); /* that's it */
486  else n = n->next;
487  } while (n);
488  return &luaO_nilobject;
489 }
490 
491 
492 /*
493 ** main search function
494 */
495 const TObject *luaH_get (Table *t, const TObject *key) {
496  switch (ttype(key)) {
497  case LUA_TSTRING: return luaH_getstr(t, tsvalue(key));
498  case LUA_TNUMBER: {
499  int k;
500  lua_number2int(k, (nvalue(key)));
501  if (cast(lua_Number, k) == nvalue(key)) /* is an integer index? */
502  return luaH_getnum(t, k); /* use specialized version */
503  /* else go through */
504  }
505  default: return luaH_getany(t, key);
506  }
507 }
508 
509 
510 TObject *luaH_set (lua_State *L, Table *t, const TObject *key) {
511  const TObject *p = luaH_get(t, key);
512  t->flags = 0;
513  if (p != &luaO_nilobject)
514 /*@-observertrans -dependenttrans @*/
515  return cast(TObject *, p);
516 /*@=observertrans =dependenttrans @*/
517  else {
518  if (ttisnil(key)) luaG_runerror(L, "table index is nil");
519  else if (ttisnumber(key) && nvalue(key) != nvalue(key))
520  luaG_runerror(L, "table index is NaN");
521  return newkey(L, t, key);
522  }
523 }
524 
525 
526 TObject *luaH_setnum (lua_State *L, Table *t, int key) {
527  const TObject *p = luaH_getnum(t, key);
528  if (p != &luaO_nilobject)
529 /*@-observertrans -dependenttrans @*/
530  return cast(TObject *, p);
531 /*@=observertrans =dependenttrans @*/
532  else {
533  TObject k;
534  setnvalue(&k, cast(lua_Number, key));
535  return newkey(L, t, &k);
536  }
537 }
538