Coverage Report

Created: 2025-07-18 06:59

/src/testdir/build/lua-master/source/ltable.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
** $Id: ltable.c $
3
** Lua tables (hash)
4
** See Copyright Notice in lua.h
5
*/
6
7
#define ltable_c
8
#define LUA_CORE
9
10
#include "lprefix.h"
11
12
13
/*
14
** Implementation of tables (aka arrays, objects, or hash tables).
15
** Tables keep its elements in two parts: an array part and a hash part.
16
** Non-negative integer keys are all candidates to be kept in the array
17
** part. The actual size of the array is the largest 'n' such that
18
** more than half the slots between 1 and n are in use.
19
** Hash uses a mix of chained scatter table with Brent's variation.
20
** A main invariant of these tables is that, if an element is not
21
** in its main position (i.e. the 'original' position that its hash gives
22
** to it), then the colliding element is in its own main position.
23
** Hence even when the load factor reaches 100%, performance remains good.
24
*/
25
26
#include <math.h>
27
#include <limits.h>
28
#include <string.h>
29
30
#include "lua.h"
31
32
#include "ldebug.h"
33
#include "ldo.h"
34
#include "lgc.h"
35
#include "lmem.h"
36
#include "lobject.h"
37
#include "lstate.h"
38
#include "lstring.h"
39
#include "ltable.h"
40
#include "lvm.h"
41
42
43
/*
44
** Only hash parts with at least 2^LIMFORLAST have a 'lastfree' field
45
** that optimizes finding a free slot. That field is stored just before
46
** the array of nodes, in the same block. Smaller tables do a complete
47
** search when looking for a free slot.
48
*/
49
81.2k
#define LIMFORLAST    3  /* log2 of real limit (8) */
50
51
/*
52
** The union 'Limbox' stores 'lastfree' and ensures that what follows it
53
** is properly aligned to store a Node.
54
*/
55
typedef struct { Node *dummy; Node follows_pNode; } Limbox_aux;
56
57
typedef union {
58
  Node *lastfree;
59
  char padding[offsetof(Limbox_aux, follows_pNode)];
60
} Limbox;
61
62
75.2k
#define haslastfree(t)     ((t)->lsizenode >= LIMFORLAST)
63
190k
#define getlastfree(t)     ((cast(Limbox *, (t)->node) - 1)->lastfree)
64
65
66
/*
67
** MAXABITS is the largest integer such that 2^MAXABITS fits in an
68
** unsigned int.
69
*/
70
230k
#define MAXABITS  (l_numbits(int) - 1)
71
72
73
/*
74
** MAXASIZEB is the maximum number of elements in the array part such
75
** that the size of the array fits in 'size_t'.
76
*/
77
13.5k
#define MAXASIZEB (MAX_SIZET/(sizeof(Value) + 1))
78
79
80
/*
81
** MAXASIZE is the maximum size of the array part. It is the minimum
82
** between 2^MAXABITS and MAXASIZEB.
83
*/
84
#define MAXASIZE  \
85
13.5k
    (((1u << MAXABITS) < MAXASIZEB) ? (1u << MAXABITS) : cast_uint(MAXASIZEB))
86
87
/*
88
** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a
89
** signed int.
90
*/
91
11.8k
#define MAXHBITS  (MAXABITS - 1)
92
93
94
/*
95
** MAXHSIZE is the maximum size of the hash part. It is the minimum
96
** between 2^MAXHBITS and the maximum size such that, measured in bytes,
97
** it fits in a 'size_t'.
98
*/
99
5.94k
#define MAXHSIZE  luaM_limitN(1 << MAXHBITS, Node)
100
101
102
/*
103
** When the original hash value is good, hashing by a power of 2
104
** avoids the cost of '%'.
105
*/
106
37.0M
#define hashpow2(t,n)   (gnode(t, lmod((n), sizenode(t))))
107
108
/*
109
** for other types, it is better to avoid modulo by power of 2, as
110
** they can have many 2 factors.
111
*/
112
62.3k
#define hashmod(t,n)  (gnode(t, ((n) % ((sizenode(t)-1u)|1u))))
113
114
115
37.0M
#define hashstr(t,str)    hashpow2(t, (str)->hash)
116
522
#define hashboolean(t,p)  hashpow2(t, p)
117
118
119
573
#define hashpointer(t,p)  hashmod(t, point2uint(p))
120
121
122
#define dummynode   (&dummynode_)
123
124
/*
125
** Common hash part for tables with empty hash parts. That allows all
126
** tables to have a hash part, avoiding an extra check ("is there a hash
127
** part?") when indexing. Its sole node has an empty value and a key
128
** (DEADKEY, NULL) that is different from any valid TValue.
129
*/
130
static const Node dummynode_ = {
131
  {{NULL}, LUA_VEMPTY,  /* value's value and type */
132
   LUA_TDEADKEY, 0, {NULL}}  /* key type, next, and key value */
133
};
134
135
136
static const TValue absentkey = {ABSTKEYCONSTANT};
137
138
139
/*
140
** Hash for integers. To allow a good hash, use the remainder operator
141
** ('%'). If integer fits as a non-negative int, compute an int
142
** remainder, which is faster. Otherwise, use an unsigned-integer
143
** remainder, which uses all bits and ensures a non-negative result.
144
*/
145
86.9k
static Node *hashint (const Table *t, lua_Integer i) {
146
86.9k
  lua_Unsigned ui = l_castS2U(i);
147
86.9k
  if (ui <= cast_uint(INT_MAX))
148
64.7k
    return gnode(t, cast_int(ui) % cast_int((sizenode(t)-1) | 1));
149
22.1k
  else
150
22.1k
    return hashmod(t, ui);
151
86.9k
}
152
153
154
/*
155
** Hash for floating-point numbers.
156
** The main computation should be just
157
**     n = frexp(n, &i); return (n * INT_MAX) + i
158
** but there are some numerical subtleties.
159
** In a two-complement representation, INT_MAX does not has an exact
160
** representation as a float, but INT_MIN does; because the absolute
161
** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the
162
** absolute value of the product 'frexp * -INT_MIN' is smaller or equal
163
** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when
164
** adding 'i'; the use of '~u' (instead of '-u') avoids problems with
165
** INT_MIN.
166
*/
167
#if !defined(l_hashfloat)
168
39.6k
static unsigned l_hashfloat (lua_Number n) {
169
39.6k
  int i;
170
39.6k
  lua_Integer ni;
171
39.6k
  n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
172
39.6k
  if (!lua_numbertointeger(n, &ni)) {  /* is 'n' inf/-inf/NaN? */
173
2.00k
    lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
174
2.00k
    return 0;
175
2.00k
  }
176
37.6k
  else {  /* normal case */
177
37.6k
    unsigned int u = cast_uint(i) + cast_uint(ni);
178
37.6k
    return (u <= cast_uint(INT_MAX) ? u : ~u);
179
37.6k
  }
180
39.6k
}
181
#endif
182
183
184
/*
185
** returns the 'main' position of an element in a table (that is,
186
** the index of its hash value).
187
*/
188
338k
static Node *mainpositionTV (const Table *t, const TValue *key) {
189
338k
  switch (ttypetag(key)) {
190
24.9k
    case LUA_VNUMINT: {
191
24.9k
      lua_Integer i = ivalue(key);
192
0
      return hashint(t, i);
193
24.9k
    }
194
39.6k
    case LUA_VNUMFLT: {
195
39.6k
      lua_Number n = fltvalue(key);
196
39.6k
      return hashmod(t, l_hashfloat(n));
197
39.6k
    }
198
250k
    case LUA_VSHRSTR: {
199
500k
      TString *ts = tsvalue(key);
200
500k
      return hashstr(t, ts);
201
500k
    }
202
23.0k
    case LUA_VLNGSTR: {
203
46.1k
      TString *ts = tsvalue(key);
204
46.1k
      return hashpow2(t, luaS_hashlongstr(ts));
205
46.1k
    }
206
31
    case LUA_VFALSE:
207
31
      return hashboolean(t, 0);
208
491
    case LUA_VTRUE:
209
491
      return hashboolean(t, 1);
210
573
    case LUA_VLIGHTUSERDATA: {
211
573
      void *p = pvalue(key);
212
573
      return hashpointer(t, p);
213
573
    }
214
0
    case LUA_VLCF: {
215
0
      lua_CFunction f = fvalue(key);
216
0
      return hashpointer(t, f);
217
0
    }
218
0
    default: {
219
0
      GCObject *o = gcvalue(key);
220
0
      return hashpointer(t, o);
221
0
    }
222
338k
  }
223
338k
}
224
225
226
49.7k
l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {
227
49.7k
  TValue key;
228
49.7k
  getnodekey(cast(lua_State *, NULL), &key, nd);
229
49.7k
  return mainpositionTV(t, &key);
230
49.7k
}
231
232
233
/*
234
** Check whether key 'k1' is equal to the key in node 'n2'. This
235
** equality is raw, so there are no metamethods. Floats with integer
236
** values have been normalized, so integers cannot be equal to
237
** floats. It is assumed that 'eqshrstr' is simply pointer equality, so
238
** that short strings are handled in the default case.
239
** A true 'deadok' means to accept dead keys as equal to their original
240
** values. All dead keys are compared in the default case, by pointer
241
** identity. (Only collectable objects can produce dead keys.) Note that
242
** dead long strings are also compared by identity.
243
** Once a key is dead, its corresponding value may be collected, and
244
** then another value can be created with the same address. If this
245
** other value is given to 'next', 'equalkey' will signal a false
246
** positive. In a regular traversal, this situation should never happen,
247
** as all keys given to 'next' came from the table itself, and therefore
248
** could not have been collected. Outside a regular traversal, we
249
** have garbage in, garbage out. What is relevant is that this false
250
** positive does not break anything.  (In particular, 'next' will return
251
** some other valid item on the table or nil.)
252
*/
253
198k
static int equalkey (const TValue *k1, const Node *n2, int deadok) {
254
198k
  if ((rawtt(k1) != keytt(n2)) &&  /* not the same variants? */
255
198k
       !(deadok && keyisdead(n2) && iscollectable(k1)))
256
107k
   return 0;  /* cannot be same key */
257
90.7k
  switch (keytt(n2)) {
258
88
    case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
259
88
      return 1;
260
1.06k
    case LUA_VNUMINT:
261
1.06k
      return (ivalue(k1) == keyival(n2));
262
27.0k
    case LUA_VNUMFLT:
263
27.0k
      return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
264
193
    case LUA_VLIGHTUSERDATA:
265
193
      return pvalue(k1) == pvalueraw(keyval(n2));
266
0
    case LUA_VLCF:
267
0
      return fvalue(k1) == fvalueraw(keyval(n2));
268
10.2k
    case ctb(LUA_VLNGSTR):
269
20.5k
      return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
270
52.0k
    default:
271
52.0k
      return gcvalue(k1) == gcvalueraw(keyval(n2));
272
90.7k
  }
273
90.7k
}
274
275
276
/*
277
** "Generic" get version. (Not that generic: not valid for integers,
278
** which may be in array part, nor for floats with integral values.)
279
** See explanation about 'deadok' in function 'equalkey'.
280
*/
281
163k
static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
282
163k
  Node *n = mainpositionTV(t, key);
283
198k
  for (;;) {  /* check whether 'key' is somewhere in the chain */
284
198k
    if (equalkey(key, n, deadok))
285
29.3k
      return gval(n);  /* that's it */
286
168k
    else {
287
168k
      int nx = gnext(n);
288
168k
      if (nx == 0)
289
133k
        return &absentkey;  /* not found */
290
35.0k
      n += nx;
291
35.0k
    }
292
198k
  }
293
163k
}
294
295
296
/*
297
** Return the index 'k' (converted to an unsigned) if it is inside
298
** the range [1, limit].
299
*/
300
185k
static unsigned checkrange (lua_Integer k, unsigned limit) {
301
185k
  return (l_castS2U(k) - 1u < limit) ? cast_uint(k) : 0;
302
185k
}
303
304
305
/*
306
** Return the index 'k' if 'k' is an appropriate key to live in the
307
** array part of a table, 0 otherwise.
308
*/
309
7.14k
#define arrayindex(k) checkrange(k, MAXASIZE)
310
311
312
/*
313
** Check whether an integer key is in the array part of a table and
314
** return its index there, or zero.
315
*/
316
112k
#define ikeyinarray(t,k)  checkrange(k, t->asize)
317
318
319
/*
320
** Check whether a key is in the array part of a table and return its
321
** index there, or zero.
322
*/
323
80.2k
static unsigned keyinarray (Table *t, const TValue *key) {
324
80.2k
  return (ttisinteger(key)) ? ikeyinarray(t, ivalue(key)) : 0;
325
80.2k
}
326
327
328
/*
329
** returns the index of a 'key' for table traversals. First goes all
330
** elements in the array part, then elements in the hash part. The
331
** beginning of a traversal is signaled by 0.
332
*/
333
static unsigned findindex (lua_State *L, Table *t, TValue *key,
334
0
                               unsigned asize) {
335
0
  unsigned int i;
336
0
  if (ttisnil(key)) return 0;  /* first iteration */
337
0
  i = keyinarray(t, key);
338
0
  if (i != 0)  /* is 'key' inside array part? */
339
0
    return i;  /* yes; that's the index */
340
0
  else {
341
0
    const TValue *n = getgeneric(t, key, 1);
342
0
    if (l_unlikely(isabstkey(n)))
343
0
      luaG_runerror(L, "invalid key to 'next'");  /* key not found */
344
0
    i = cast_uint(nodefromval(n) - gnode(t, 0));  /* key index in hash table */
345
    /* hash elements are numbered after array ones */
346
0
    return (i + 1) + asize;
347
0
  }
348
0
}
349
350
351
0
int luaH_next (lua_State *L, Table *t, StkId key) {
352
0
  unsigned int asize = t->asize;
353
0
  unsigned int i = findindex(L, t, s2v(key), asize);  /* find original key */
354
0
  for (; i < asize; i++) {  /* try first array part */
355
0
    lu_byte tag = *getArrTag(t, i);
356
0
    if (!tagisempty(tag)) {  /* a non-empty entry? */
357
0
      setivalue(s2v(key), cast_int(i) + 1);
358
0
      farr2val(t, i, tag, s2v(key + 1));
359
0
      return 1;
360
0
    }
361
0
  }
362
0
  for (i -= asize; i < sizenode(t); i++) {  /* hash part */
363
0
    if (!isempty(gval(gnode(t, i)))) {  /* a non-empty entry? */
364
0
      Node *n = gnode(t, i);
365
0
      getnodekey(L, s2v(key), n);
366
0
      setobj2s(L, key + 1, gval(n));
367
0
      return 1;
368
0
    }
369
0
  }
370
0
  return 0;  /* no more elements */
371
0
}
372
373
374
/* Extra space in Node array if it has a lastfree entry */
375
15.3k
#define extraLastfree(t)  (haslastfree(t) ? sizeof(Limbox) : 0)
376
377
/* 'node' size in bytes */
378
9.40k
static size_t sizehash (Table *t) {
379
9.40k
  return cast_sizet(sizenode(t)) * sizeof(Node) + extraLastfree(t);
380
9.40k
}
381
382
383
8.83k
static void freehash (lua_State *L, Table *t) {
384
8.83k
  if (!isdummy(t)) {
385
    /* get pointer to the beginning of Node array */
386
5.94k
    char *arr = cast_charp(t->node) - extraLastfree(t);
387
5.94k
    luaM_freearray(L, arr, sizehash(t));
388
5.94k
  }
389
8.83k
}
390
391
392
/*
393
** {=============================================================
394
** Rehash
395
** ==============================================================
396
*/
397
398
static int insertkey (Table *t, const TValue *key, TValue *value);
399
static void newcheckedkey (Table *t, const TValue *key, TValue *value);
400
401
402
/*
403
** Structure to count the keys in a table.
404
** 'total' is the total number of keys in the table.
405
** 'na' is the number of *array indices* in the table (see 'arrayindex').
406
** 'deleted' is true if there are deleted nodes in the hash part.
407
** 'nums' is a "count array" where 'nums[i]' is the number of integer
408
** keys between 2^(i - 1) + 1 and 2^i. Note that 'na' is the summation
409
** of 'nums'.
410
*/
411
typedef struct {
412
  unsigned total;
413
  unsigned na;
414
  int deleted;
415
  unsigned nums[MAXABITS + 1];
416
} Counters;
417
418
419
/*
420
** Check whether it is worth to use 'na' array entries instead of 'nh'
421
** hash nodes. (A hash node uses ~3 times more memory than an array
422
** entry: Two values plus 'next' versus one value.) Evaluate with size_t
423
** to avoid overflows.
424
*/
425
7.58k
#define arrayXhash(na,nh) (cast_sizet(na) <= cast_sizet(nh) * 3)
426
427
/*
428
** Compute the optimal size for the array part of table 't'.
429
** This size maximizes the number of elements going to the array part
430
** while satisfying the condition 'arrayXhash' with the use of memory if
431
** all those elements went to the hash part.
432
** 'ct->na' enters with the total number of array indices in the table
433
** and leaves with the number of keys that will go to the array part;
434
** return the optimal size for the array part.
435
*/
436
1.11k
static unsigned computesizes (Counters *ct) {
437
1.11k
  int i;
438
1.11k
  unsigned int twotoi;  /* 2^i (candidate for optimal size) */
439
1.11k
  unsigned int a = 0;  /* number of elements smaller than 2^i */
440
1.11k
  unsigned int na = 0;  /* number of elements to go to array part */
441
1.11k
  unsigned int optimal = 0;  /* optimal size for array part */
442
  /* traverse slices while 'twotoi' does not overflow and total of array
443
     indices still can satisfy 'arrayXhash' against the array size */
444
1.11k
  for (i = 0, twotoi = 1;
445
5.42k
       twotoi > 0 && arrayXhash(twotoi, ct->na);
446
4.31k
       i++, twotoi *= 2) {
447
4.31k
    unsigned nums = ct->nums[i];
448
4.31k
    a += nums;
449
4.31k
    if (nums > 0 &&  /* grows array only if it gets more elements... */
450
4.31k
        arrayXhash(twotoi, a)) {  /* ...while using "less memory" */
451
1.88k
      optimal = twotoi;  /* optimal size (till now) */
452
1.88k
      na = a;  /* all elements up to 'optimal' will go to array part */
453
1.88k
    }
454
4.31k
  }
455
1.11k
  ct->na = na;
456
1.11k
  return optimal;
457
1.11k
}
458
459
460
7.14k
static void countint (lua_Integer key, Counters *ct) {
461
7.14k
  unsigned int k = arrayindex(key);
462
7.14k
  if (k != 0) {  /* is 'key' an array index? */
463
4.77k
    ct->nums[luaO_ceillog2(k)]++;  /* count as such */
464
4.77k
    ct->na++;
465
4.77k
  }
466
7.14k
}
467
468
469
2.86k
l_sinline int arraykeyisempty (const Table *t, unsigned key) {
470
2.86k
  int tag = *getArrTag(t, key - 1);
471
2.86k
  return tagisempty(tag);
472
2.86k
}
473
474
475
/*
476
** Count keys in array part of table 't'.
477
*/
478
1.11k
static void numusearray (const Table *t, Counters *ct) {
479
1.11k
  int lg;
480
1.11k
  unsigned int ttlg;  /* 2^lg */
481
1.11k
  unsigned int ause = 0;  /* summation of 'nums' */
482
1.11k
  unsigned int i = 1;  /* index to traverse all array keys */
483
1.11k
  unsigned int asize = t->asize;
484
  /* traverse each slice */
485
2.73k
  for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
486
2.73k
    unsigned int lc = 0;  /* counter */
487
2.73k
    unsigned int lim = ttlg;
488
2.73k
    if (lim > asize) {
489
1.11k
      lim = asize;  /* adjust upper limit */
490
1.11k
      if (i > lim)
491
1.11k
        break;  /* no more elements to count */
492
1.11k
    }
493
    /* count elements in range (2^(lg - 1), 2^lg] */
494
4.48k
    for (; i <= lim; i++) {
495
2.86k
      if (!arraykeyisempty(t, i))
496
1.51k
        lc++;
497
2.86k
    }
498
1.62k
    ct->nums[lg] += lc;
499
1.62k
    ause += lc;
500
1.62k
  }
501
1.11k
  ct->total += ause;
502
1.11k
  ct->na += ause;
503
1.11k
}
504
505
506
/*
507
** Count keys in hash part of table 't'. As this only happens during
508
** a rehash, all nodes have been used. A node can have a nil value only
509
** if it was deleted after being created.
510
*/
511
5.88k
static void numusehash (const Table *t, Counters *ct) {
512
5.88k
  unsigned i = sizenode(t);
513
5.88k
  unsigned total = 0;
514
81.4k
  while (i--) {
515
75.5k
    Node *n = &t->node[i];
516
75.5k
    if (isempty(gval(n))) {
517
1.23k
      lua_assert(!keyisnil(n));  /* entry was deleted; key cannot be nil */
518
1.23k
      ct->deleted = 1;
519
1.23k
    }
520
74.3k
    else {
521
74.3k
      total++;
522
74.3k
      if (keyisinteger(n))
523
6.76k
        countint(keyival(n), ct);
524
74.3k
    }
525
75.5k
  }
526
5.88k
  ct->total += total;
527
5.88k
}
528
529
530
/*
531
** Convert an "abstract size" (number of slots in an array) to
532
** "concrete size" (number of bytes in the array).
533
*/
534
9.04k
static size_t concretesize (unsigned int size) {
535
9.04k
  if (size == 0)
536
4.97k
    return 0;
537
4.06k
  else  /* space for the two arrays plus an unsigned in between */
538
4.06k
    return size * (sizeof(Value) + 1) + sizeof(unsigned);
539
9.04k
}
540
541
542
/*
543
** Resize the array part of a table. If new size is equal to the old,
544
** do nothing. Else, if new size is zero, free the old array. (It must
545
** be present, as the sizes are different.) Otherwise, allocate a new
546
** array, move the common elements to new proper position, and then
547
** frees the old array.
548
** We could reallocate the array, but we still would need to move the
549
** elements to their new position, so the copy implicit in realloc is a
550
** waste. Moreover, most allocators will move the array anyway when the
551
** new size is double the old one (the most common case).
552
*/
553
static Value *resizearray (lua_State *L , Table *t,
554
                               unsigned oldasize,
555
8.83k
                               unsigned newasize) {
556
8.83k
  if (oldasize == newasize)
557
7.32k
    return t->array;  /* nothing to be done */
558
1.51k
  else if (newasize == 0) {  /* erasing array? */
559
707
    Value *op = t->array - oldasize;  /* original array's real address */
560
707
    luaM_freemem(L, op, concretesize(oldasize));  /* free it */
561
707
    return NULL;
562
707
  }
563
803
  else {
564
803
    size_t newasizeb = concretesize(newasize);
565
803
    Value *np = cast(Value *,
566
803
                  luaM_reallocvector(L, NULL, 0, newasizeb, lu_byte));
567
803
    if (np == NULL)  /* allocation error? */
568
0
      return NULL;
569
803
    np += newasize;  /* shift pointer to the end of value segment */
570
803
    if (oldasize > 0) {
571
      /* move common elements to new position */
572
96
      size_t oldasizeb = concretesize(oldasize);
573
96
      Value *op = t->array;  /* original array */
574
96
      unsigned tomove = (oldasize < newasize) ? oldasize : newasize;
575
96
      size_t tomoveb = (oldasize < newasize) ? oldasizeb : newasizeb;
576
96
      lua_assert(tomoveb > 0);
577
96
      memcpy(np - tomove, op - tomove, tomoveb);
578
96
      luaM_freemem(L, op - oldasize, oldasizeb);  /* free old block */
579
96
    }
580
803
    return np;
581
803
  }
582
8.83k
}
583
584
585
/*
586
** Creates an array for the hash part of a table with the given
587
** size, or reuses the dummy node if size is zero.
588
** The computation for size overflow is in two steps: the first
589
** comparison ensures that the shift in the second one does not
590
** overflow.
591
*/
592
8.83k
static void setnodevector (lua_State *L, Table *t, unsigned size) {
593
8.83k
  if (size == 0) {  /* no elements to hash part? */
594
2.89k
    t->node = cast(Node *, dummynode);  /* use common 'dummynode' */
595
2.89k
    t->lsizenode = 0;
596
2.89k
    setdummy(t);  /* signal that it is using dummy node */
597
2.89k
  }
598
5.94k
  else {
599
5.94k
    int i;
600
5.94k
    int lsize = luaO_ceillog2(size);
601
5.94k
    if (lsize > MAXHBITS || (1 << lsize) > MAXHSIZE)
602
0
      luaG_runerror(L, "table overflow");
603
5.94k
    size = twoto(lsize);
604
5.94k
    if (lsize < LIMFORLAST)  /* no 'lastfree' field? */
605
3.05k
      t->node = luaM_newvector(L, size, Node);
606
2.88k
    else {
607
2.88k
      size_t bsize = size * sizeof(Node) + sizeof(Limbox);
608
2.88k
      char *node = luaM_newblock(L, bsize);
609
2.88k
      t->node = cast(Node *, node + sizeof(Limbox));
610
2.88k
      getlastfree(t) = gnode(t, size);  /* all positions are free */
611
2.88k
    }
612
5.94k
    t->lsizenode = cast_byte(lsize);
613
5.94k
    setnodummy(t);
614
141k
    for (i = 0; i < cast_int(size); i++) {
615
135k
      Node *n = gnode(t, i);
616
135k
      gnext(n) = 0;
617
135k
      setnilkey(n);
618
135k
      setempty(gval(n));
619
135k
    }
620
5.94k
  }
621
8.83k
}
622
623
624
/*
625
** (Re)insert all elements from the hash part of 'ot' into table 't'.
626
*/
627
6.43k
static void reinserthash (lua_State *L, Table *ot, Table *t) {
628
6.43k
  unsigned j;
629
6.43k
  unsigned size = sizenode(ot);
630
82.5k
  for (j = 0; j < size; j++) {
631
76.1k
    Node *old = gnode(ot, j);
632
76.1k
    if (!isempty(gval(old))) {
633
      /* doesn't need barrier/invalidate cache, as entry was
634
         already present in the table */
635
74.3k
      TValue k;
636
74.3k
      getnodekey(L, &k, old);
637
74.3k
      newcheckedkey(t, &k, gval(old));
638
74.3k
    }
639
76.1k
  }
640
6.43k
}
641
642
643
/*
644
** Exchange the hash part of 't1' and 't2'. (In 'flags', only the
645
** dummy bit must be exchanged: The 'isrealasize' is not related
646
** to the hash part, and the metamethod bits do not change during
647
** a resize, so the "real" table can keep their values.)
648
*/
649
6.48k
static void exchangehashpart (Table *t1, Table *t2) {
650
6.48k
  lu_byte lsizenode = t1->lsizenode;
651
6.48k
  Node *node = t1->node;
652
6.48k
  int bitdummy1 = t1->flags & BITDUMMY;
653
6.48k
  t1->lsizenode = t2->lsizenode;
654
6.48k
  t1->node = t2->node;
655
6.48k
  t1->flags = cast_byte((t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY));
656
6.48k
  t2->lsizenode = lsizenode;
657
6.48k
  t2->node = node;
658
6.48k
  t2->flags = cast_byte((t2->flags & NOTBITDUMMY) | bitdummy1);
659
6.48k
}
660
661
662
/*
663
** Re-insert into the new hash part of a table the elements from the
664
** vanishing slice of the array part.
665
*/
666
static void reinsertOldSlice (Table *t, unsigned oldasize,
667
28
                                        unsigned newasize) {
668
28
  unsigned i;
669
56
  for (i = newasize; i < oldasize; i++) {  /* traverse vanishing slice */
670
28
    lu_byte tag = *getArrTag(t, i);
671
28
    if (!tagisempty(tag)) {  /* a non-empty entry? */
672
0
      TValue key, aux;
673
0
      setivalue(&key, l_castU2S(i) + 1);  /* make the key */
674
0
      farr2val(t, i, tag, &aux);  /* copy value into 'aux' */
675
0
      insertkey(t, &key, &aux);  /* insert entry into the hash part */
676
0
    }
677
28
  }
678
28
}
679
680
681
/*
682
** Clear new slice of the array.
683
*/
684
6.43k
static void clearNewSlice (Table *t, unsigned oldasize, unsigned newasize) {
685
688k
  for (; oldasize < newasize; oldasize++)
686
681k
    *getArrTag(t, oldasize) = LUA_VEMPTY;
687
6.43k
}
688
689
690
/*
691
** Resize table 't' for the new given sizes. Both allocations (for
692
** the hash part and for the array part) can fail, which creates some
693
** subtleties. If the first allocation, for the hash part, fails, an
694
** error is raised and that is it. Otherwise, it copies the elements from
695
** the shrinking part of the array (if it is shrinking) into the new
696
** hash. Then it reallocates the array part.  If that fails, the table
697
** is in its original state; the function frees the new hash part and then
698
** raises the allocation error. Otherwise, it sets the new hash part
699
** into the table, initializes the new part of the array (if any) with
700
** nils and reinserts the elements of the old hash back into the new
701
** parts of the table.
702
** Note that if the new size for the array part ('newasize') is equal to
703
** the old one ('oldasize'), this function will do nothing with that
704
** part.
705
*/
706
void luaH_resize (lua_State *L, Table *t, unsigned newasize,
707
6.43k
                                          unsigned nhsize) {
708
6.43k
  Table newt;  /* to keep the new hash part */
709
6.43k
  unsigned oldasize = t->asize;
710
6.43k
  Value *newarray;
711
6.43k
  if (newasize > MAXASIZE)
712
0
    luaG_runerror(L, "table overflow");
713
  /* create new hash part with appropriate size into 'newt' */
714
6.43k
  newt.flags = 0;
715
6.43k
  setnodevector(L, &newt, nhsize);
716
6.43k
  if (newasize < oldasize) {  /* will array shrink? */
717
    /* re-insert into the new hash the elements from vanishing slice */
718
28
    exchangehashpart(t, &newt);  /* pretend table has new hash */
719
28
    reinsertOldSlice(t, oldasize, newasize);
720
28
    exchangehashpart(t, &newt);  /* restore old hash (in case of errors) */
721
28
  }
722
  /* allocate new array */
723
6.43k
  newarray = resizearray(L, t, oldasize, newasize);
724
6.43k
  if (l_unlikely(newarray == NULL && newasize > 0)) {  /* allocation failed? */
725
0
    freehash(L, &newt);  /* release new hash part */
726
0
    luaM_error(L);  /* raise error (with array unchanged) */
727
0
  }
728
  /* allocation ok; initialize new part of the array */
729
6.43k
  exchangehashpart(t, &newt);  /* 't' has the new hash ('newt' has the old) */
730
6.43k
  t->array = newarray;  /* set new array part */
731
6.43k
  t->asize = newasize;
732
6.43k
  if (newarray != NULL)
733
1.37k
    *lenhint(t) = newasize / 2u;  /* set an initial hint */
734
6.43k
  clearNewSlice(t, oldasize, newasize);
735
  /* re-insert elements from old hash part into new parts */
736
6.43k
  reinserthash(L, &newt, t);  /* 'newt' now has the old hash */
737
6.43k
  freehash(L, &newt);  /* free old hash part */
738
6.43k
}
739
740
741
0
void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
742
0
  unsigned nsize = allocsizenode(t);
743
0
  luaH_resize(L, t, nasize, nsize);
744
0
}
745
746
747
/*
748
** Rehash a table. First, count its keys. If there are array indices
749
** outside the array part, compute the new best size for that part.
750
** Then, resize the table.
751
*/
752
5.88k
static void rehash (lua_State *L, Table *t, const TValue *ek) {
753
5.88k
  unsigned asize;  /* optimal size for array part */
754
5.88k
  Counters ct;
755
5.88k
  unsigned i;
756
5.88k
  unsigned nsize;  /* size for the hash part */
757
  /* reset counts */
758
194k
  for (i = 0; i <= MAXABITS; i++) ct.nums[i] = 0;
759
5.88k
  ct.na = 0;
760
5.88k
  ct.deleted = 0;
761
5.88k
  ct.total = 1;  /* count extra key */
762
5.88k
  if (ttisinteger(ek))
763
376
    countint(ivalue(ek), &ct);  /* extra key may go to array */
764
5.88k
  numusehash(t, &ct);  /* count keys in hash part */
765
5.88k
  if (ct.na == 0) {
766
    /* no new keys to enter array part; keep it with the same size */
767
4.77k
    asize = t->asize;
768
4.77k
  }
769
1.11k
  else {  /* compute best size for array part */
770
1.11k
    numusearray(t, &ct);  /* count keys in array part */
771
1.11k
    asize = computesizes(&ct);  /* compute new size for array part */
772
1.11k
  }
773
  /* all keys not in the array part go to the hash part */
774
5.88k
  nsize = ct.total - ct.na;
775
5.88k
  if (ct.deleted) {  /* table has deleted entries? */
776
    /* insertion-deletion-insertion: give hash some extra size to
777
       avoid repeated resizings */
778
1.23k
    nsize += nsize >> 2;
779
1.23k
  }
780
  /* resize the table to new computed sizes */
781
5.88k
  luaH_resize(L, t, asize, nsize);
782
5.88k
}
783
784
/*
785
** }=============================================================
786
*/
787
788
789
2.40k
Table *luaH_new (lua_State *L) {
790
2.40k
  GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
791
2.40k
  Table *t = gco2t(o);
792
0
  t->metatable = NULL;
793
2.40k
  t->flags = maskflags;  /* table has no metamethod fields */
794
2.40k
  t->array = NULL;
795
2.40k
  t->asize = 0;
796
2.40k
  setnodevector(L, t, 0);
797
2.40k
  return t;
798
2.40k
}
799
800
801
7.43k
lu_mem luaH_size (Table *t) {
802
7.43k
  lu_mem sz = cast(lu_mem, sizeof(Table)) + concretesize(t->asize);
803
7.43k
  if (!isdummy(t))
804
3.46k
    sz += sizehash(t);
805
7.43k
  return sz;
806
7.43k
}
807
808
809
/*
810
** Frees a table.
811
*/
812
2.40k
void luaH_free (lua_State *L, Table *t) {
813
2.40k
  freehash(L, t);
814
2.40k
  resizearray(L, t, t->asize, 0);
815
2.40k
  luaM_free(L, t);
816
2.40k
}
817
818
819
59.9k
static Node *getfreepos (Table *t) {
820
59.9k
  if (haslastfree(t)) {  /* does it have 'lastfree' information? */
821
    /* look for a spot before 'lastfree', updating 'lastfree' */
822
95.5k
    while (getlastfree(t) > t->node) {
823
91.7k
      Node *free = --getlastfree(t);
824
91.7k
      if (keyisnil(free))
825
48.0k
        return free;
826
91.7k
    }
827
51.8k
  }
828
8.05k
  else {  /* no 'lastfree' information */
829
8.05k
    unsigned i = sizenode(t);
830
22.0k
    while (i--) {  /* do a linear search */
831
15.6k
      Node *free = gnode(t, i);
832
15.6k
      if (keyisnil(free))
833
1.67k
        return free;
834
15.6k
    }
835
8.05k
  }
836
10.1k
  return NULL;  /* could not find a free place */
837
59.9k
}
838
839
840
841
/*
842
** Inserts a new key into a hash table; first, check whether key's main
843
** position is free. If not, check whether colliding node is in its main
844
** position or not: if it is not, move colliding node to an empty place
845
** and put new key in its main position; otherwise (colliding node is in
846
** its main position), new key goes to an empty position. Return 0 if
847
** could not insert key (could not find a free space).
848
*/
849
126k
static int insertkey (Table *t, const TValue *key, TValue *value) {
850
126k
  Node *mp = mainpositionTV(t, key);
851
  /* table cannot already contain the key */
852
126k
  lua_assert(isabstkey(getgeneric(t, key, 0)));
853
126k
  if (!isempty(gval(mp)) || isdummy(t)) {  /* main position is taken? */
854
59.9k
    Node *othern;
855
59.9k
    Node *f = getfreepos(t);  /* get a free place */
856
59.9k
    if (f == NULL)  /* cannot find a free place? */
857
10.1k
      return 0;
858
49.7k
    lua_assert(!isdummy(t));
859
49.7k
    othern = mainpositionfromnode(t, mp);
860
49.7k
    if (othern != mp) {  /* is colliding node out of its main position? */
861
      /* yes; move colliding node into free position */
862
15.1k
      while (othern + gnext(othern) != mp)  /* find previous */
863
2.79k
        othern += gnext(othern);
864
12.3k
      gnext(othern) = cast_int(f - othern);  /* rechain to point to 'f' */
865
12.3k
      *f = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
866
12.3k
      if (gnext(mp) != 0) {
867
2.18k
        gnext(f) += cast_int(mp - f);  /* correct 'next' */
868
2.18k
        gnext(mp) = 0;  /* now 'mp' is free */
869
2.18k
      }
870
12.3k
      setempty(gval(mp));
871
12.3k
    }
872
37.3k
    else {  /* colliding node is in its own main position */
873
      /* new node will go into free position */
874
37.3k
      if (gnext(mp) != 0)
875
8.92k
        gnext(f) = cast_int((mp + gnext(mp)) - f);  /* chain new position */
876
37.3k
      else lua_assert(gnext(f) == 0);
877
37.3k
      gnext(mp) = cast_int(f - mp);
878
37.3k
      mp = f;
879
37.3k
    }
880
49.7k
  }
881
115k
  setnodekey(mp, key);
882
115k
  lua_assert(isempty(gval(mp)));
883
231k
  setobj2t(cast(lua_State *, 0), gval(mp), value);
884
115k
  return 1;
885
231k
}
886
887
888
/*
889
** Insert a key in a table where there is space for that key, the
890
** key is valid, and the value is not nil.
891
*/
892
80.2k
static void newcheckedkey (Table *t, const TValue *key, TValue *value) {
893
80.2k
  unsigned i = keyinarray(t, key);
894
80.2k
  if (i > 0)  /* is key in the array part? */
895
602
    obj2arr(t, i - 1, value);  /* set value in the array */
896
79.6k
  else {
897
79.6k
    int done = insertkey(t, key, value);  /* insert key in the hash part */
898
79.6k
    lua_assert(done);  /* it cannot fail */
899
79.6k
    cast(void, done);  /* to avoid warnings */
900
79.6k
  }
901
80.2k
}
902
903
904
static void luaH_newkey (lua_State *L, Table *t, const TValue *key,
905
14.0k
                                                 TValue *value) {
906
14.0k
  if (!ttisnil(value)) {  /* do not insert nil values */
907
14.0k
    int done = insertkey(t, key, value);
908
14.0k
    if (!done) {  /* could not find a free place? */
909
5.88k
      rehash(L, t, key);  /* grow table */
910
5.88k
      newcheckedkey(t, key, value);  /* insert key in grown table */
911
5.88k
    }
912
14.0k
    luaC_barrierback(L, obj2gco(t), key);
913
    /* for debugging only: any new key may force an emergency collection */
914
14.0k
    condchangemem(L, (void)0, (void)0, 1);
915
14.0k
  }
916
14.0k
}
917
918
919
61.9k
static const TValue *getintfromhash (Table *t, lua_Integer key) {
920
61.9k
  Node *n = hashint(t, key);
921
61.9k
  lua_assert(!ikeyinarray(t, key));
922
83.7k
  for (;;) {  /* check whether 'key' is somewhere in the chain */
923
83.7k
    if (keyisinteger(n) && keyival(n) == key)
924
54.4k
      return gval(n);  /* that's it */
925
29.2k
    else {
926
29.2k
      int nx = gnext(n);
927
29.2k
      if (nx == 0) break;
928
21.7k
      n += nx;
929
21.7k
    }
930
83.7k
  }
931
7.56k
  return &absentkey;
932
61.9k
}
933
934
935
0
static int hashkeyisempty (Table *t, lua_Unsigned key) {
936
0
  const TValue *val = getintfromhash(t, l_castU2S(key));
937
0
  return isempty(val);
938
0
}
939
940
941
36.8M
static lu_byte finishnodeget (const TValue *val, TValue *res) {
942
36.8M
  if (!ttisnil(val)) {
943
36.3M
    setobj(((lua_State*)NULL), res, val);
944
36.3M
  }
945
36.8M
  return ttypetag(val);
946
36.8M
}
947
948
949
103k
lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res) {
950
103k
  unsigned k = ikeyinarray(t, key);
951
103k
  if (k > 0) {
952
45.5k
    lu_byte tag = *getArrTag(t, k - 1);
953
45.5k
    if (!tagisempty(tag))
954
45.3k
      farr2val(t, k - 1, tag, res);
955
45.5k
    return tag;
956
45.5k
  }
957
58.1k
  else
958
58.1k
    return finishnodeget(getintfromhash(t, key), res);
959
103k
}
960
961
962
/*
963
** search function for short strings
964
*/
965
36.7M
const TValue *luaH_Hgetshortstr (Table *t, TString *key) {
966
36.7M
  Node *n = hashstr(t, key);
967
36.7M
  lua_assert(strisshr(key));
968
46.2M
  for (;;) {  /* check whether 'key' is somewhere in the chain */
969
46.2M
    if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
970
36.2M
      return gval(n);  /* that's it */
971
9.97M
    else {
972
9.97M
      int nx = gnext(n);
973
9.97M
      if (nx == 0)
974
514k
        return &absentkey;  /* not found */
975
9.46M
      n += nx;
976
9.46M
    }
977
46.2M
  }
978
36.7M
}
979
980
981
445k
lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res) {
982
445k
  return finishnodeget(luaH_Hgetshortstr(t, key), res);
983
445k
}
984
985
986
4.71k
static const TValue *Hgetlongstr (Table *t, TString *key) {
987
4.71k
  TValue ko;
988
4.71k
  lua_assert(!strisshr(key));
989
9.42k
  setsvalue(cast(lua_State *, NULL), &ko, key);
990
4.71k
  return getgeneric(t, &ko, 0);  /* for long strings, use generic case */
991
9.42k
}
992
993
994
18.2M
static const TValue *Hgetstr (Table *t, TString *key) {
995
18.2M
  if (strisshr(key))
996
18.2M
    return luaH_Hgetshortstr(t, key);
997
4.71k
  else
998
4.71k
    return Hgetlongstr(t, key);
999
18.2M
}
1000
1001
1002
18.2M
lu_byte luaH_getstr (Table *t, TString *key, TValue *res) {
1003
18.2M
  return finishnodeget(Hgetstr(t, key), res);
1004
18.2M
}
1005
1006
1007
/*
1008
** main search function
1009
*/
1010
18.1M
lu_byte luaH_get (Table *t, const TValue *key, TValue *res) {
1011
18.1M
  const TValue *slot;
1012
18.1M
  switch (ttypetag(key)) {
1013
18.0M
    case LUA_VSHRSTR:
1014
18.0M
      slot = luaH_Hgetshortstr(t, tsvalue(key));
1015
0
      break;
1016
103k
    case LUA_VNUMINT:
1017
103k
      return luaH_getint(t, ivalue(key), res);
1018
0
    case LUA_VNIL:
1019
0
      slot = &absentkey;
1020
0
      break;
1021
23.4k
    case LUA_VNUMFLT: {
1022
23.4k
      lua_Integer k;
1023
23.4k
      if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
1024
0
        return luaH_getint(t, k, res);  /* use specialized version */
1025
      /* else... */
1026
23.4k
    }  /* FALLTHROUGH */
1027
28.4k
    default:
1028
28.4k
      slot = getgeneric(t, key, 0);
1029
28.4k
      break;
1030
18.1M
  }
1031
18.0M
  return finishnodeget(slot, res);
1032
18.1M
}
1033
1034
1035
/*
1036
** When a 'pset' cannot be completed, this function returns an encoding
1037
** of its result, to be used by 'luaH_finishset'.
1038
*/
1039
14.0k
static int retpsetcode (Table *t, const TValue *slot) {
1040
14.0k
  if (isabstkey(slot))
1041
14.0k
    return HNOTFOUND;  /* no slot with that key */
1042
0
  else  /* return node encoded */
1043
0
    return cast_int((cast(Node*, slot) - t->node)) + HFIRSTNODE;
1044
14.0k
}
1045
1046
1047
7.65k
static int finishnodeset (Table *t, const TValue *slot, TValue *val) {
1048
7.65k
  if (!ttisnil(slot)) {
1049
0
    setobj(((lua_State*)NULL), cast(TValue*, slot), val);
1050
0
    return HOK;  /* success */
1051
0
  }
1052
7.65k
  else
1053
7.65k
    return retpsetcode(t, slot);
1054
7.65k
}
1055
1056
1057
0
static int rawfinishnodeset (const TValue *slot, TValue *val) {
1058
0
  if (isabstkey(slot))
1059
0
    return 0;  /* no slot with that key */
1060
0
  else {
1061
0
    setobj(((lua_State*)NULL), cast(TValue*, slot), val);
1062
0
    return 1;  /* success */
1063
0
  }
1064
0
}
1065
1066
1067
3.81k
int luaH_psetint (Table *t, lua_Integer key, TValue *val) {
1068
3.81k
  lua_assert(!ikeyinarray(t, key));
1069
3.81k
  return finishnodeset(t, getintfromhash(t, key), val);
1070
3.81k
}
1071
1072
1073
3.97k
static int psetint (Table *t, lua_Integer key, TValue *val) {
1074
3.97k
  int hres;
1075
3.97k
  luaH_fastseti(t, key, val, hres);
1076
3.97k
  return hres;
1077
3.97k
}
1078
1079
1080
/*
1081
** This function could be just this:
1082
**    return finishnodeset(t, luaH_Hgetshortstr(t, key), val);
1083
** However, it optimizes the common case created by constructors (e.g.,
1084
** {x=1, y=2}), which creates a key in a table that has no metatable,
1085
** it is not old/black, and it already has space for the key.
1086
*/
1087
1088
34.6k
int luaH_psetshortstr (Table *t, TString *key, TValue *val) {
1089
34.6k
  const TValue *slot = luaH_Hgetshortstr(t, key);
1090
34.6k
  if (!ttisnil(slot)) {  /* key already has a value? (all too common) */
1091
120
    setobj(((lua_State*)NULL), cast(TValue*, slot), val);  /* update it */
1092
120
    return HOK;  /* done */
1093
120
  }
1094
34.5k
  else if (checknoTM(t->metatable, TM_NEWINDEX)) {  /* no metamethod? */
1095
34.5k
    if (ttisnil(val))  /* new value is nil? */
1096
0
      return HOK;  /* done (value is already nil/absent) */
1097
34.5k
    if (isabstkey(slot) &&  /* key is absent? */
1098
34.5k
       !(isblack(t) && iswhite(key))) {  /* and don't need barrier? */
1099
32.4k
      TValue tk;  /* key as a TValue */
1100
32.4k
      setsvalue(cast(lua_State *, NULL), &tk, key);
1101
32.4k
      if (insertkey(t, &tk, val)) {  /* insert key, if there is space */
1102
28.1k
        invalidateTMcache(t);
1103
28.1k
        return HOK;
1104
28.1k
      }
1105
32.4k
    }
1106
34.5k
  }
1107
  /* Else, either table has new-index metamethod, or it needs barrier,
1108
     or it needs to rehash for the new key. In any of these cases, the
1109
     operation cannot be completed here. Return a code for the caller. */
1110
6.39k
  return retpsetcode(t, slot);
1111
34.6k
}
1112
1113
1114
212
int luaH_psetstr (Table *t, TString *key, TValue *val) {
1115
212
  if (strisshr(key))
1116
212
    return luaH_psetshortstr(t, key, val);
1117
0
  else
1118
0
    return finishnodeset(t, Hgetlongstr(t, key), val);
1119
212
}
1120
1121
1122
42.1k
int luaH_pset (Table *t, const TValue *key, TValue *val) {
1123
42.1k
  switch (ttypetag(key)) {
1124
34.3k
    case LUA_VSHRSTR: return luaH_psetshortstr(t, tsvalue(key), val);
1125
3.97k
    case LUA_VNUMINT: return psetint(t, ivalue(key), val);
1126
0
    case LUA_VNIL: return HNOTFOUND;
1127
1.81k
    case LUA_VNUMFLT: {
1128
1.81k
      lua_Integer k;
1129
1.81k
      if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
1130
0
        return psetint(t, k, val);  /* use specialized version */
1131
      /* else... */
1132
1.81k
    }  /* FALLTHROUGH */
1133
3.84k
    default:
1134
3.84k
      return finishnodeset(t, getgeneric(t, key, 0), val);
1135
42.1k
  }
1136
42.1k
}
1137
1138
/*
1139
** Finish a raw "set table" operation, where 'hres' encodes where the
1140
** value should have been (the result of a previous 'pset' operation).
1141
** Beware: when using this function the caller probably need to check a
1142
** GC barrier and invalidate the TM cache.
1143
*/
1144
void luaH_finishset (lua_State *L, Table *t, const TValue *key,
1145
14.0k
                                    TValue *value, int hres) {
1146
14.0k
  lua_assert(hres != HOK);
1147
14.0k
  if (hres == HNOTFOUND) {
1148
14.0k
    TValue aux;
1149
14.0k
    if (l_unlikely(ttisnil(key)))
1150
0
      luaG_runerror(L, "table index is nil");
1151
14.0k
    else if (ttisfloat(key)) {
1152
1.81k
      lua_Number f = fltvalue(key);
1153
0
      lua_Integer k;
1154
1.81k
      if (luaV_flttointeger(f, &k, F2Ieq)) {
1155
0
        setivalue(&aux, k);  /* key is equal to an integer */
1156
0
        key = &aux;  /* insert it as an integer */
1157
0
      }
1158
1.81k
      else if (l_unlikely(luai_numisnan(f)))
1159
0
        luaG_runerror(L, "table index is NaN");
1160
1.81k
    }
1161
14.0k
    luaH_newkey(L, t, key, value);
1162
14.0k
  }
1163
0
  else if (hres > 0) {  /* regular Node? */
1164
0
    setobj2t(L, gval(gnode(t, hres - HFIRSTNODE)), value);
1165
0
  }
1166
0
  else {  /* array entry */
1167
0
    hres = ~hres;  /* real index */
1168
0
    obj2arr(t, cast_uint(hres), value);
1169
0
  }
1170
14.0k
}
1171
1172
1173
/*
1174
** beware: when using this function you probably need to check a GC
1175
** barrier and invalidate the TM cache.
1176
*/
1177
42.1k
void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
1178
42.1k
  int hres = luaH_pset(t, key, value);
1179
42.1k
  if (hres != HOK)
1180
13.8k
    luaH_finishset(L, t, key, value, hres);
1181
42.1k
}
1182
1183
1184
/*
1185
** Ditto for a GC barrier. (No need to invalidate the TM cache, as
1186
** integers cannot be keys to metamethods.)
1187
*/
1188
1.26k
void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
1189
1.26k
  unsigned ik = ikeyinarray(t, key);
1190
1.26k
  if (ik > 0)
1191
1.26k
    obj2arr(t, ik - 1, value);
1192
0
  else {
1193
0
    int ok = rawfinishnodeset(getintfromhash(t, key), value);
1194
0
    if (!ok) {
1195
0
      TValue k;
1196
0
      setivalue(&k, key);
1197
0
      luaH_newkey(L, t, &k, value);
1198
0
    }
1199
0
  }
1200
1.26k
}
1201
1202
1203
/*
1204
** Try to find a boundary in the hash part of table 't'. From the
1205
** caller, we know that 'j' is zero or present and that 'j + 1' is
1206
** present. We want to find a larger key that is absent from the
1207
** table, so that we can do a binary search between the two keys to
1208
** find a boundary. We keep doubling 'j' until we get an absent index.
1209
** If the doubling would overflow, we try LUA_MAXINTEGER. If it is
1210
** absent, we are ready for the binary search. ('j', being max integer,
1211
** is larger or equal to 'i', but it cannot be equal because it is
1212
** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a
1213
** boundary. ('j + 1' cannot be a present integer key because it is
1214
** not a valid integer in Lua.)
1215
*/
1216
0
static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
1217
0
  lua_Unsigned i;
1218
0
  if (j == 0) j++;  /* the caller ensures 'j + 1' is present */
1219
0
  do {
1220
0
    i = j;  /* 'i' is a present index */
1221
0
    if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
1222
0
      j *= 2;
1223
0
    else {
1224
0
      j = LUA_MAXINTEGER;
1225
0
      if (hashkeyisempty(t, j))  /* t[j] not present? */
1226
0
        break;  /* 'j' now is an absent index */
1227
0
      else  /* weird case */
1228
0
        return j;  /* well, max integer is a boundary... */
1229
0
    }
1230
0
  } while (!hashkeyisempty(t, j));  /* repeat until an absent t[j] */
1231
  /* i < j  &&  t[i] present  &&  t[j] absent */
1232
0
  while (j - i > 1u) {  /* do a binary search between them */
1233
0
    lua_Unsigned m = (i + j) / 2;
1234
0
    if (hashkeyisempty(t, m)) j = m;
1235
0
    else i = m;
1236
0
  }
1237
0
  return i;
1238
0
}
1239
1240
1241
0
static unsigned int binsearch (Table *array, unsigned int i, unsigned int j) {
1242
0
  lua_assert(i <= j);
1243
0
  while (j - i > 1u) {  /* binary search */
1244
0
    unsigned int m = (i + j) / 2;
1245
0
    if (arraykeyisempty(array, m)) j = m;
1246
0
    else i = m;
1247
0
  }
1248
0
  return i;
1249
0
}
1250
1251
1252
/* return a border, saving it as a hint for next call */
1253
0
static lua_Unsigned newhint (Table *t, unsigned hint) {
1254
0
  lua_assert(hint <= t->asize);
1255
0
  *lenhint(t) = hint;
1256
0
  return hint;
1257
0
}
1258
1259
1260
/*
1261
** Try to find a border in table 't'. (A 'border' is an integer index
1262
** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent,
1263
** or 'maxinteger' if t[maxinteger] is present.)
1264
** If there is an array part, try to find a border there. First try
1265
** to find it in the vicinity of the previous result (hint), to handle
1266
** cases like 't[#t + 1] = val' or 't[#t] = nil', that move the border
1267
** by one entry. Otherwise, do a binary search to find the border.
1268
** If there is no array part, or its last element is non empty, the
1269
** border may be in the hash part.
1270
*/
1271
0
lua_Unsigned luaH_getn (Table *t) {
1272
0
  unsigned asize = t->asize;
1273
0
  if (asize > 0) {  /* is there an array part? */
1274
0
    const unsigned maxvicinity = 4;
1275
0
    unsigned limit = *lenhint(t);  /* start with the hint */
1276
0
    if (limit == 0)
1277
0
      limit = 1;  /* make limit a valid index in the array */
1278
0
    if (arraykeyisempty(t, limit)) {  /* t[limit] empty? */
1279
      /* there must be a border before 'limit' */
1280
0
      unsigned i;
1281
      /* look for a border in the vicinity of the hint */
1282
0
      for (i = 0; i < maxvicinity && limit > 1; i++) {
1283
0
        limit--;
1284
0
        if (!arraykeyisempty(t, limit))
1285
0
          return newhint(t, limit);  /* 'limit' is a border */
1286
0
      }
1287
      /* t[limit] still empty; search for a border in [0, limit) */
1288
0
      return newhint(t, binsearch(t, 0, limit));
1289
0
    }
1290
0
    else {  /* 'limit' is present in table; look for a border after it */
1291
0
      unsigned i;
1292
      /* look for a border in the vicinity of the hint */
1293
0
      for (i = 0; i < maxvicinity && limit < asize; i++) {
1294
0
        limit++;
1295
0
        if (arraykeyisempty(t, limit))
1296
0
          return newhint(t, limit - 1);  /* 'limit - 1' is a border */
1297
0
      }
1298
0
      if (arraykeyisempty(t, asize)) {  /* last element empty? */
1299
        /* t[limit] not empty; search for a border in [limit, asize) */
1300
0
        return newhint(t, binsearch(t, limit, asize));
1301
0
      }
1302
0
    }
1303
    /* last element non empty; set a hint to speed up finding that again */
1304
    /* (keys in the hash part cannot be hints) */
1305
0
    *lenhint(t) = asize;
1306
0
  }
1307
  /* no array part or t[asize] is not empty; check the hash part */
1308
0
  lua_assert(asize == 0 || !arraykeyisempty(t, asize));
1309
0
  if (isdummy(t) || hashkeyisempty(t, asize + 1))
1310
0
    return asize;  /* 'asize + 1' is empty */
1311
0
  else  /* 'asize + 1' is also non empty */
1312
0
    return hash_search(t, asize);
1313
0
}
1314
1315
1316
1317
#if defined(LUA_DEBUG)
1318
1319
/* export this function for the test library */
1320
1321
Node *luaH_mainposition (const Table *t, const TValue *key) {
1322
  return mainpositionTV(t, key);
1323
}
1324
1325
#endif