Coverage Report

Created: 2025-08-25 06:57

/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
92.6k
#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
86.1k
#define haslastfree(t)     ((t)->lsizenode >= LIMFORLAST)
63
222k
#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
254k
#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
15.6k
#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
15.6k
    (((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
13.0k
#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
6.54k
#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
49.9M
#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
76.2k
#define hashmod(t,n)  (gnode(t, ((n) % ((sizenode(t)-1u)|1u))))
113
114
115
49.8M
#define hashstr(t,str)    hashpow2(t, (str)->hash)
116
555
#define hashboolean(t,p)  hashpow2(t, p)
117
118
119
431
#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
107k
static Node *hashint (const Table *t, lua_Integer i) {
146
107k
  lua_Unsigned ui = l_castS2U(i);
147
107k
  if (ui <= cast_uint(INT_MAX))
148
80.5k
    return gnode(t, cast_int(ui) % cast_int((sizenode(t)-1) | 1));
149
27.0k
  else
150
27.0k
    return hashmod(t, ui);
151
107k
}
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
48.7k
static unsigned l_hashfloat (lua_Number n) {
169
48.7k
  int i;
170
48.7k
  lua_Integer ni;
171
48.7k
  n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
172
48.7k
  if (!lua_numbertointeger(n, &ni)) {  /* is 'n' inf/-inf/NaN? */
173
2.40k
    lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
174
2.40k
    return 0;
175
2.40k
  }
176
46.3k
  else {  /* normal case */
177
46.3k
    unsigned int u = cast_uint(i) + cast_uint(ni);
178
46.3k
    return (u <= cast_uint(INT_MAX) ? u : ~u);
179
46.3k
  }
180
48.7k
}
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
395k
static Node *mainpositionTV (const Table *t, const TValue *key) {
189
395k
  switch (ttypetag(key)) {
190
29.8k
    case LUA_VNUMINT: {
191
29.8k
      lua_Integer i = ivalue(key);
192
0
      return hashint(t, i);
193
29.8k
    }
194
48.7k
    case LUA_VNUMFLT: {
195
48.7k
      lua_Number n = fltvalue(key);
196
48.7k
      return hashmod(t, l_hashfloat(n));
197
48.7k
    }
198
287k
    case LUA_VSHRSTR: {
199
574k
      TString *ts = tsvalue(key);
200
574k
      return hashstr(t, ts);
201
574k
    }
202
28.4k
    case LUA_VLNGSTR: {
203
56.8k
      TString *ts = tsvalue(key);
204
56.8k
      return hashpow2(t, luaS_hashlongstr(ts));
205
56.8k
    }
206
31
    case LUA_VFALSE:
207
31
      return hashboolean(t, 0);
208
524
    case LUA_VTRUE:
209
524
      return hashboolean(t, 1);
210
431
    case LUA_VLIGHTUSERDATA: {
211
431
      void *p = pvalue(key);
212
431
      return hashpointer(t, p);
213
431
    }
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
395k
  }
223
395k
}
224
225
226
57.9k
l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {
227
57.9k
  TValue key;
228
57.9k
  getnodekey(cast(lua_State *, NULL), &key, nd);
229
57.9k
  return mainpositionTV(t, &key);
230
57.9k
}
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,
238
** so that short strings are handled in the default case.  The flag
239
** 'deadok' means to accept dead keys as equal to their original values.
240
** (Only collectable objects can produce dead keys.) Note that dead
241
** long strings are also compared by identity.  Once a key is dead,
242
** its corresponding value may be collected, and then another value
243
** can be created with the same address. If this other value is given
244
** to 'next', 'equalkey' will signal a false positive. In a regular
245
** traversal, this situation should never happen, as all keys given to
246
** 'next' came from the table itself, and therefore could not have been
247
** collected. Outside a regular traversal, we have garbage in, garbage
248
** out. What is relevant is that this false positive does not break
249
** anything.  (In particular, 'next' will return some other valid item
250
** on the table or nil.)
251
*/
252
229k
static int equalkey (const TValue *k1, const Node *n2, int deadok) {
253
229k
  if (rawtt(k1) != keytt(n2)) {  /* not the same variants? */
254
124k
    if (keyisshrstr(n2) && ttislngstring(k1)) {
255
      /* an external string can be equal to a short-string key */
256
15.1k
      return luaS_eqstr(tsvalue(k1), keystrval(n2));
257
15.1k
    }
258
116k
    else if (deadok && keyisdead(n2) && iscollectable(k1)) {
259
      /* a collectable value can be equal to a dead key */
260
0
      return gcvalue(k1) == gcvalueraw(keyval(n2));
261
0
   }
262
116k
   else
263
116k
     return 0;  /* otherwise, different variants cannot be equal */
264
124k
  }
265
104k
  else {  /* equal variants */
266
104k
    switch (keytt(n2)) {
267
86
      case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
268
86
        return 1;
269
1.26k
      case LUA_VNUMINT:
270
1.26k
        return (ivalue(k1) == keyival(n2));
271
32.3k
      case LUA_VNUMFLT:
272
32.3k
        return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
273
84
      case LUA_VLIGHTUSERDATA:
274
84
        return pvalue(k1) == pvalueraw(keyval(n2));
275
0
      case LUA_VLCF:
276
0
        return fvalue(k1) == fvalueraw(keyval(n2));
277
11.2k
      case ctb(LUA_VLNGSTR):
278
22.4k
        return luaS_eqstr(tsvalue(k1), keystrval(n2));
279
59.6k
      default:
280
59.6k
        return gcvalue(k1) == gcvalueraw(keyval(n2));
281
104k
    }
282
104k
  }
283
229k
}
284
285
286
/*
287
** "Generic" get version. (Not that generic: not valid for integers,
288
** which may be in array part, nor for floats with integral values.)
289
** See explanation about 'deadok' in function 'equalkey'.
290
*/
291
191k
static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
292
191k
  Node *n = mainpositionTV(t, key);
293
229k
  for (;;) {  /* check whether 'key' is somewhere in the chain */
294
229k
    if (equalkey(key, n, deadok))
295
34.8k
      return gval(n);  /* that's it */
296
194k
    else {
297
194k
      int nx = gnext(n);
298
194k
      if (nx == 0)
299
156k
        return &absentkey;  /* not found */
300
38.0k
      n += nx;
301
38.0k
    }
302
229k
  }
303
191k
}
304
305
306
/*
307
** Return the index 'k' (converted to an unsigned) if it is inside
308
** the range [1, limit].
309
*/
310
229k
static unsigned checkrange (lua_Integer k, unsigned limit) {
311
229k
  return (l_castS2U(k) - 1u < limit) ? cast_uint(k) : 0;
312
229k
}
313
314
315
/*
316
** Return the index 'k' if 'k' is an appropriate key to live in the
317
** array part of a table, 0 otherwise.
318
*/
319
8.62k
#define arrayindex(k) checkrange(k, MAXASIZE)
320
321
322
/*
323
** Check whether an integer key is in the array part of a table and
324
** return its index there, or zero.
325
*/
326
138k
#define ikeyinarray(t,k)  checkrange(k, t->asize)
327
328
329
/*
330
** Check whether a key is in the array part of a table and return its
331
** index there, or zero.
332
*/
333
93.7k
static unsigned keyinarray (Table *t, const TValue *key) {
334
93.7k
  return (ttisinteger(key)) ? ikeyinarray(t, ivalue(key)) : 0;
335
93.7k
}
336
337
338
/*
339
** returns the index of a 'key' for table traversals. First goes all
340
** elements in the array part, then elements in the hash part. The
341
** beginning of a traversal is signaled by 0.
342
*/
343
static unsigned findindex (lua_State *L, Table *t, TValue *key,
344
0
                               unsigned asize) {
345
0
  unsigned int i;
346
0
  if (ttisnil(key)) return 0;  /* first iteration */
347
0
  i = keyinarray(t, key);
348
0
  if (i != 0)  /* is 'key' inside array part? */
349
0
    return i;  /* yes; that's the index */
350
0
  else {
351
0
    const TValue *n = getgeneric(t, key, 1);
352
0
    if (l_unlikely(isabstkey(n)))
353
0
      luaG_runerror(L, "invalid key to 'next'");  /* key not found */
354
0
    i = cast_uint(nodefromval(n) - gnode(t, 0));  /* key index in hash table */
355
    /* hash elements are numbered after array ones */
356
0
    return (i + 1) + asize;
357
0
  }
358
0
}
359
360
361
0
int luaH_next (lua_State *L, Table *t, StkId key) {
362
0
  unsigned int asize = t->asize;
363
0
  unsigned int i = findindex(L, t, s2v(key), asize);  /* find original key */
364
0
  for (; i < asize; i++) {  /* try first array part */
365
0
    lu_byte tag = *getArrTag(t, i);
366
0
    if (!tagisempty(tag)) {  /* a non-empty entry? */
367
0
      setivalue(s2v(key), cast_int(i) + 1);
368
0
      farr2val(t, i, tag, s2v(key + 1));
369
0
      return 1;
370
0
    }
371
0
  }
372
0
  for (i -= asize; i < sizenode(t); i++) {  /* hash part */
373
0
    if (!isempty(gval(gnode(t, i)))) {  /* a non-empty entry? */
374
0
      Node *n = gnode(t, i);
375
0
      getnodekey(L, s2v(key), n);
376
0
      setobj2s(L, key + 1, gval(n));
377
0
      return 1;
378
0
    }
379
0
  }
380
0
  return 0;  /* no more elements */
381
0
}
382
383
384
/* Extra space in Node array if it has a lastfree entry */
385
16.8k
#define extraLastfree(t)  (haslastfree(t) ? sizeof(Limbox) : 0)
386
387
/* 'node' size in bytes */
388
10.3k
static size_t sizehash (Table *t) {
389
10.3k
  return cast_sizet(sizenode(t)) * sizeof(Node) + extraLastfree(t);
390
10.3k
}
391
392
393
9.52k
static void freehash (lua_State *L, Table *t) {
394
9.52k
  if (!isdummy(t)) {
395
    /* get pointer to the beginning of Node array */
396
6.54k
    char *arr = cast_charp(t->node) - extraLastfree(t);
397
6.54k
    luaM_freearray(L, arr, sizehash(t));
398
6.54k
  }
399
9.52k
}
400
401
402
/*
403
** {=============================================================
404
** Rehash
405
** ==============================================================
406
*/
407
408
static int insertkey (Table *t, const TValue *key, TValue *value);
409
static void newcheckedkey (Table *t, const TValue *key, TValue *value);
410
411
412
/*
413
** Structure to count the keys in a table.
414
** 'total' is the total number of keys in the table.
415
** 'na' is the number of *array indices* in the table (see 'arrayindex').
416
** 'deleted' is true if there are deleted nodes in the hash part.
417
** 'nums' is a "count array" where 'nums[i]' is the number of integer
418
** keys between 2^(i - 1) + 1 and 2^i. Note that 'na' is the summation
419
** of 'nums'.
420
*/
421
typedef struct {
422
  unsigned total;
423
  unsigned na;
424
  int deleted;
425
  unsigned nums[MAXABITS + 1];
426
} Counters;
427
428
429
/*
430
** Check whether it is worth to use 'na' array entries instead of 'nh'
431
** hash nodes. (A hash node uses ~3 times more memory than an array
432
** entry: Two values plus 'next' versus one value.) Evaluate with size_t
433
** to avoid overflows.
434
*/
435
8.05k
#define arrayXhash(na,nh) (cast_sizet(na) <= cast_sizet(nh) * 3)
436
437
/*
438
** Compute the optimal size for the array part of table 't'.
439
** This size maximizes the number of elements going to the array part
440
** while satisfying the condition 'arrayXhash' with the use of memory if
441
** all those elements went to the hash part.
442
** 'ct->na' enters with the total number of array indices in the table
443
** and leaves with the number of keys that will go to the array part;
444
** return the optimal size for the array part.
445
*/
446
1.13k
static unsigned computesizes (Counters *ct) {
447
1.13k
  int i;
448
1.13k
  unsigned int twotoi;  /* 2^i (candidate for optimal size) */
449
1.13k
  unsigned int a = 0;  /* number of elements smaller than 2^i */
450
1.13k
  unsigned int na = 0;  /* number of elements to go to array part */
451
1.13k
  unsigned int optimal = 0;  /* optimal size for array part */
452
  /* traverse slices while 'twotoi' does not overflow and total of array
453
     indices still can satisfy 'arrayXhash' against the array size */
454
1.13k
  for (i = 0, twotoi = 1;
455
5.69k
       twotoi > 0 && arrayXhash(twotoi, ct->na);
456
4.56k
       i++, twotoi *= 2) {
457
4.56k
    unsigned nums = ct->nums[i];
458
4.56k
    a += nums;
459
4.56k
    if (nums > 0 &&  /* grows array only if it gets more elements... */
460
4.56k
        arrayXhash(twotoi, a)) {  /* ...while using "less memory" */
461
2.02k
      optimal = twotoi;  /* optimal size (till now) */
462
2.02k
      na = a;  /* all elements up to 'optimal' will go to array part */
463
2.02k
    }
464
4.56k
  }
465
1.13k
  ct->na = na;
466
1.13k
  return optimal;
467
1.13k
}
468
469
470
8.62k
static void countint (lua_Integer key, Counters *ct) {
471
8.62k
  unsigned int k = arrayindex(key);
472
8.62k
  if (k != 0) {  /* is 'key' an array index? */
473
5.84k
    ct->nums[luaO_ceillog2(k)]++;  /* count as such */
474
5.84k
    ct->na++;
475
5.84k
  }
476
8.62k
}
477
478
479
3.07k
l_sinline int arraykeyisempty (const Table *t, unsigned key) {
480
3.07k
  int tag = *getArrTag(t, key - 1);
481
3.07k
  return tagisempty(tag);
482
3.07k
}
483
484
485
/*
486
** Count keys in array part of table 't'.
487
*/
488
1.13k
static void numusearray (const Table *t, Counters *ct) {
489
1.13k
  int lg;
490
1.13k
  unsigned int ttlg;  /* 2^lg */
491
1.13k
  unsigned int ause = 0;  /* summation of 'nums' */
492
1.13k
  unsigned int i = 1;  /* index to traverse all array keys */
493
1.13k
  unsigned int asize = t->asize;
494
  /* traverse each slice */
495
2.77k
  for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
496
2.77k
    unsigned int lc = 0;  /* counter */
497
2.77k
    unsigned int lim = ttlg;
498
2.77k
    if (lim > asize) {
499
1.13k
      lim = asize;  /* adjust upper limit */
500
1.13k
      if (i > lim)
501
1.13k
        break;  /* no more elements to count */
502
1.13k
    }
503
    /* count elements in range (2^(lg - 1), 2^lg] */
504
4.71k
    for (; i <= lim; i++) {
505
3.07k
      if (!arraykeyisempty(t, i))
506
1.62k
        lc++;
507
3.07k
    }
508
1.64k
    ct->nums[lg] += lc;
509
1.64k
    ause += lc;
510
1.64k
  }
511
1.13k
  ct->total += ause;
512
1.13k
  ct->na += ause;
513
1.13k
}
514
515
516
/*
517
** Count keys in hash part of table 't'. As this only happens during
518
** a rehash, all nodes have been used. A node can have a nil value only
519
** if it was deleted after being created.
520
*/
521
6.49k
static void numusehash (const Table *t, Counters *ct) {
522
6.49k
  unsigned i = sizenode(t);
523
6.49k
  unsigned total = 0;
524
95.0k
  while (i--) {
525
88.5k
    Node *n = &t->node[i];
526
88.5k
    if (isempty(gval(n))) {
527
1.28k
      lua_assert(!keyisnil(n));  /* entry was deleted; key cannot be nil */
528
1.28k
      ct->deleted = 1;
529
1.28k
    }
530
87.2k
    else {
531
87.2k
      total++;
532
87.2k
      if (keyisinteger(n))
533
8.28k
        countint(keyival(n), ct);
534
87.2k
    }
535
88.5k
  }
536
6.49k
  ct->total += total;
537
6.49k
}
538
539
540
/*
541
** Convert an "abstract size" (number of slots in an array) to
542
** "concrete size" (number of bytes in the array).
543
*/
544
9.74k
static size_t concretesize (unsigned int size) {
545
9.74k
  if (size == 0)
546
5.50k
    return 0;
547
4.24k
  else  /* space for the two arrays plus an unsigned in between */
548
4.24k
    return size * (sizeof(Value) + 1) + sizeof(unsigned);
549
9.74k
}
550
551
552
/*
553
** Resize the array part of a table. If new size is equal to the old,
554
** do nothing. Else, if new size is zero, free the old array. (It must
555
** be present, as the sizes are different.) Otherwise, allocate a new
556
** array, move the common elements to new proper position, and then
557
** frees the old array.
558
** We could reallocate the array, but we still would need to move the
559
** elements to their new position, so the copy implicit in realloc is a
560
** waste. Moreover, most allocators will move the array anyway when the
561
** new size is double the old one (the most common case).
562
*/
563
static Value *resizearray (lua_State *L , Table *t,
564
                               unsigned oldasize,
565
9.52k
                               unsigned newasize) {
566
9.52k
  if (oldasize == newasize)
567
8.02k
    return t->array;  /* nothing to be done */
568
1.50k
  else if (newasize == 0) {  /* erasing array? */
569
705
    Value *op = t->array - oldasize;  /* original array's real address */
570
705
    luaM_freemem(L, op, concretesize(oldasize));  /* free it */
571
705
    return NULL;
572
705
  }
573
795
  else {
574
795
    size_t newasizeb = concretesize(newasize);
575
795
    Value *np = cast(Value *,
576
795
                  luaM_reallocvector(L, NULL, 0, newasizeb, lu_byte));
577
795
    if (np == NULL)  /* allocation error? */
578
0
      return NULL;
579
795
    np += newasize;  /* shift pointer to the end of value segment */
580
795
    if (oldasize > 0) {
581
      /* move common elements to new position */
582
90
      size_t oldasizeb = concretesize(oldasize);
583
90
      Value *op = t->array;  /* original array */
584
90
      unsigned tomove = (oldasize < newasize) ? oldasize : newasize;
585
90
      size_t tomoveb = (oldasize < newasize) ? oldasizeb : newasizeb;
586
90
      lua_assert(tomoveb > 0);
587
90
      memcpy(np - tomove, op - tomove, tomoveb);
588
90
      luaM_freemem(L, op - oldasize, oldasizeb);  /* free old block */
589
90
    }
590
795
    return np;
591
795
  }
592
9.52k
}
593
594
595
/*
596
** Creates an array for the hash part of a table with the given
597
** size, or reuses the dummy node if size is zero.
598
** The computation for size overflow is in two steps: the first
599
** comparison ensures that the shift in the second one does not
600
** overflow.
601
*/
602
9.52k
static void setnodevector (lua_State *L, Table *t, unsigned size) {
603
9.52k
  if (size == 0) {  /* no elements to hash part? */
604
2.98k
    t->node = cast(Node *, dummynode);  /* use common 'dummynode' */
605
2.98k
    t->lsizenode = 0;
606
2.98k
    setdummy(t);  /* signal that it is using dummy node */
607
2.98k
  }
608
6.54k
  else {
609
6.54k
    int i;
610
6.54k
    int lsize = luaO_ceillog2(size);
611
6.54k
    if (lsize > MAXHBITS || (1 << lsize) > MAXHSIZE)
612
0
      luaG_runerror(L, "table overflow");
613
6.54k
    size = twoto(lsize);
614
6.54k
    if (lsize < LIMFORLAST)  /* no 'lastfree' field? */
615
3.29k
      t->node = luaM_newvector(L, size, Node);
616
3.25k
    else {
617
3.25k
      size_t bsize = size * sizeof(Node) + sizeof(Limbox);
618
3.25k
      char *node = luaM_newblock(L, bsize);
619
3.25k
      t->node = cast(Node *, node + sizeof(Limbox));
620
3.25k
      getlastfree(t) = gnode(t, size);  /* all positions are free */
621
3.25k
    }
622
6.54k
    t->lsizenode = cast_byte(lsize);
623
6.54k
    setnodummy(t);
624
165k
    for (i = 0; i < cast_int(size); i++) {
625
158k
      Node *n = gnode(t, i);
626
158k
      gnext(n) = 0;
627
158k
      setnilkey(n);
628
158k
      setempty(gval(n));
629
158k
    }
630
6.54k
  }
631
9.52k
}
632
633
634
/*
635
** (Re)insert all elements from the hash part of 'ot' into table 't'.
636
*/
637
7.01k
static void reinserthash (lua_State *L, Table *ot, Table *t) {
638
7.01k
  unsigned j;
639
7.01k
  unsigned size = sizenode(ot);
640
96.0k
  for (j = 0; j < size; j++) {
641
89.0k
    Node *old = gnode(ot, j);
642
89.0k
    if (!isempty(gval(old))) {
643
      /* doesn't need barrier/invalidate cache, as entry was
644
         already present in the table */
645
87.2k
      TValue k;
646
87.2k
      getnodekey(L, &k, old);
647
87.2k
      newcheckedkey(t, &k, gval(old));
648
87.2k
    }
649
89.0k
  }
650
7.01k
}
651
652
653
/*
654
** Exchange the hash part of 't1' and 't2'. (In 'flags', only the
655
** dummy bit must be exchanged: The 'isrealasize' is not related
656
** to the hash part, and the metamethod bits do not change during
657
** a resize, so the "real" table can keep their values.)
658
*/
659
7.03k
static void exchangehashpart (Table *t1, Table *t2) {
660
7.03k
  lu_byte lsizenode = t1->lsizenode;
661
7.03k
  Node *node = t1->node;
662
7.03k
  int bitdummy1 = t1->flags & BITDUMMY;
663
7.03k
  t1->lsizenode = t2->lsizenode;
664
7.03k
  t1->node = t2->node;
665
7.03k
  t1->flags = cast_byte((t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY));
666
7.03k
  t2->lsizenode = lsizenode;
667
7.03k
  t2->node = node;
668
7.03k
  t2->flags = cast_byte((t2->flags & NOTBITDUMMY) | bitdummy1);
669
7.03k
}
670
671
672
/*
673
** Re-insert into the new hash part of a table the elements from the
674
** vanishing slice of the array part.
675
*/
676
static void reinsertOldSlice (Table *t, unsigned oldasize,
677
10
                                        unsigned newasize) {
678
10
  unsigned i;
679
20
  for (i = newasize; i < oldasize; i++) {  /* traverse vanishing slice */
680
10
    lu_byte tag = *getArrTag(t, i);
681
10
    if (!tagisempty(tag)) {  /* a non-empty entry? */
682
0
      TValue key, aux;
683
0
      setivalue(&key, l_castU2S(i) + 1);  /* make the key */
684
0
      farr2val(t, i, tag, &aux);  /* copy value into 'aux' */
685
0
      insertkey(t, &key, &aux);  /* insert entry into the hash part */
686
0
    }
687
10
  }
688
10
}
689
690
691
/*
692
** Clear new slice of the array.
693
*/
694
7.01k
static void clearNewSlice (Table *t, unsigned oldasize, unsigned newasize) {
695
907k
  for (; oldasize < newasize; oldasize++)
696
900k
    *getArrTag(t, oldasize) = LUA_VEMPTY;
697
7.01k
}
698
699
700
/*
701
** Resize table 't' for the new given sizes. Both allocations (for
702
** the hash part and for the array part) can fail, which creates some
703
** subtleties. If the first allocation, for the hash part, fails, an
704
** error is raised and that is it. Otherwise, it copies the elements from
705
** the shrinking part of the array (if it is shrinking) into the new
706
** hash. Then it reallocates the array part.  If that fails, the table
707
** is in its original state; the function frees the new hash part and then
708
** raises the allocation error. Otherwise, it sets the new hash part
709
** into the table, initializes the new part of the array (if any) with
710
** nils and reinserts the elements of the old hash back into the new
711
** parts of the table.
712
** Note that if the new size for the array part ('newasize') is equal to
713
** the old one ('oldasize'), this function will do nothing with that
714
** part.
715
*/
716
void luaH_resize (lua_State *L, Table *t, unsigned newasize,
717
7.01k
                                          unsigned nhsize) {
718
7.01k
  Table newt;  /* to keep the new hash part */
719
7.01k
  unsigned oldasize = t->asize;
720
7.01k
  Value *newarray;
721
7.01k
  if (newasize > MAXASIZE)
722
0
    luaG_runerror(L, "table overflow");
723
  /* create new hash part with appropriate size into 'newt' */
724
7.01k
  newt.flags = 0;
725
7.01k
  setnodevector(L, &newt, nhsize);
726
7.01k
  if (newasize < oldasize) {  /* will array shrink? */
727
    /* re-insert into the new hash the elements from vanishing slice */
728
10
    exchangehashpart(t, &newt);  /* pretend table has new hash */
729
10
    reinsertOldSlice(t, oldasize, newasize);
730
10
    exchangehashpart(t, &newt);  /* restore old hash (in case of errors) */
731
10
  }
732
  /* allocate new array */
733
7.01k
  newarray = resizearray(L, t, oldasize, newasize);
734
7.01k
  if (l_unlikely(newarray == NULL && newasize > 0)) {  /* allocation failed? */
735
0
    freehash(L, &newt);  /* release new hash part */
736
0
    luaM_error(L);  /* raise error (with array unchanged) */
737
0
  }
738
  /* allocation ok; initialize new part of the array */
739
7.01k
  exchangehashpart(t, &newt);  /* 't' has the new hash ('newt' has the old) */
740
7.01k
  t->array = newarray;  /* set new array part */
741
7.01k
  t->asize = newasize;
742
7.01k
  if (newarray != NULL)
743
1.33k
    *lenhint(t) = newasize / 2u;  /* set an initial hint */
744
7.01k
  clearNewSlice(t, oldasize, newasize);
745
  /* re-insert elements from old hash part into new parts */
746
7.01k
  reinserthash(L, &newt, t);  /* 'newt' now has the old hash */
747
7.01k
  freehash(L, &newt);  /* free old hash part */
748
7.01k
}
749
750
751
0
void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
752
0
  unsigned nsize = allocsizenode(t);
753
0
  luaH_resize(L, t, nasize, nsize);
754
0
}
755
756
757
/*
758
** Rehash a table. First, count its keys. If there are array indices
759
** outside the array part, compute the new best size for that part.
760
** Then, resize the table.
761
*/
762
6.49k
static void rehash (lua_State *L, Table *t, const TValue *ek) {
763
6.49k
  unsigned asize;  /* optimal size for array part */
764
6.49k
  Counters ct;
765
6.49k
  unsigned i;
766
6.49k
  unsigned nsize;  /* size for the hash part */
767
  /* reset counts */
768
214k
  for (i = 0; i <= MAXABITS; i++) ct.nums[i] = 0;
769
6.49k
  ct.na = 0;
770
6.49k
  ct.deleted = 0;
771
6.49k
  ct.total = 1;  /* count extra key */
772
6.49k
  if (ttisinteger(ek))
773
342
    countint(ivalue(ek), &ct);  /* extra key may go to array */
774
6.49k
  numusehash(t, &ct);  /* count keys in hash part */
775
6.49k
  if (ct.na == 0) {
776
    /* no new keys to enter array part; keep it with the same size */
777
5.36k
    asize = t->asize;
778
5.36k
  }
779
1.13k
  else {  /* compute best size for array part */
780
1.13k
    numusearray(t, &ct);  /* count keys in array part */
781
1.13k
    asize = computesizes(&ct);  /* compute new size for array part */
782
1.13k
  }
783
  /* all keys not in the array part go to the hash part */
784
6.49k
  nsize = ct.total - ct.na;
785
6.49k
  if (ct.deleted) {  /* table has deleted entries? */
786
    /* insertion-deletion-insertion: give hash some extra size to
787
       avoid repeated resizings */
788
1.28k
    nsize += nsize >> 2;
789
1.28k
  }
790
  /* resize the table to new computed sizes */
791
6.49k
  luaH_resize(L, t, asize, nsize);
792
6.49k
}
793
794
/*
795
** }=============================================================
796
*/
797
798
799
2.51k
Table *luaH_new (lua_State *L) {
800
2.51k
  GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
801
2.51k
  Table *t = gco2t(o);
802
0
  t->metatable = NULL;
803
2.51k
  t->flags = maskflags;  /* table has no metamethod fields */
804
2.51k
  t->array = NULL;
805
2.51k
  t->asize = 0;
806
2.51k
  setnodevector(L, t, 0);
807
2.51k
  return t;
808
2.51k
}
809
810
811
8.15k
lu_mem luaH_size (Table *t) {
812
8.15k
  lu_mem sz = cast(lu_mem, sizeof(Table)) + concretesize(t->asize);
813
8.15k
  if (!isdummy(t))
814
3.80k
    sz += sizehash(t);
815
8.15k
  return sz;
816
8.15k
}
817
818
819
/*
820
** Frees a table.
821
*/
822
2.51k
void luaH_free (lua_State *L, Table *t) {
823
2.51k
  freehash(L, t);
824
2.51k
  resizearray(L, t, t->asize, 0);
825
2.51k
  luaM_free(L, t);
826
2.51k
}
827
828
829
69.2k
static Node *getfreepos (Table *t) {
830
69.2k
  if (haslastfree(t)) {  /* does it have 'lastfree' information? */
831
    /* look for a spot before 'lastfree', updating 'lastfree' */
832
111k
    while (getlastfree(t) > t->node) {
833
107k
      Node *free = --getlastfree(t);
834
107k
      if (keyisnil(free))
835
55.8k
        return free;
836
107k
    }
837
60.1k
  }
838
9.08k
  else {  /* no 'lastfree' information */
839
9.08k
    unsigned i = sizenode(t);
840
24.8k
    while (i--) {  /* do a linear search */
841
17.7k
      Node *free = gnode(t, i);
842
17.7k
      if (keyisnil(free))
843
2.03k
        return free;
844
17.7k
    }
845
9.08k
  }
846
11.3k
  return NULL;  /* could not find a free place */
847
69.2k
}
848
849
850
851
/*
852
** Inserts a new key into a hash table; first, check whether key's main
853
** position is free. If not, check whether colliding node is in its main
854
** position or not: if it is not, move colliding node to an empty place
855
** and put new key in its main position; otherwise (colliding node is in
856
** its main position), new key goes to an empty position. Return 0 if
857
** could not insert key (could not find a free space).
858
*/
859
146k
static int insertkey (Table *t, const TValue *key, TValue *value) {
860
146k
  Node *mp = mainpositionTV(t, key);
861
  /* table cannot already contain the key */
862
146k
  lua_assert(isabstkey(getgeneric(t, key, 0)));
863
146k
  if (!isempty(gval(mp)) || isdummy(t)) {  /* main position is taken? */
864
69.2k
    Node *othern;
865
69.2k
    Node *f = getfreepos(t);  /* get a free place */
866
69.2k
    if (f == NULL)  /* cannot find a free place? */
867
11.3k
      return 0;
868
57.9k
    lua_assert(!isdummy(t));
869
57.9k
    othern = mainpositionfromnode(t, mp);
870
57.9k
    if (othern != mp) {  /* is colliding node out of its main position? */
871
      /* yes; move colliding node into free position */
872
18.0k
      while (othern + gnext(othern) != mp)  /* find previous */
873
3.54k
        othern += gnext(othern);
874
14.4k
      gnext(othern) = cast_int(f - othern);  /* rechain to point to 'f' */
875
14.4k
      *f = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
876
14.4k
      if (gnext(mp) != 0) {
877
2.60k
        gnext(f) += cast_int(mp - f);  /* correct 'next' */
878
2.60k
        gnext(mp) = 0;  /* now 'mp' is free */
879
2.60k
      }
880
14.4k
      setempty(gval(mp));
881
14.4k
    }
882
43.4k
    else {  /* colliding node is in its own main position */
883
      /* new node will go into free position */
884
43.4k
      if (gnext(mp) != 0)
885
10.6k
        gnext(f) = cast_int((mp + gnext(mp)) - f);  /* chain new position */
886
43.4k
      else lua_assert(gnext(f) == 0);
887
43.4k
      gnext(mp) = cast_int(f - mp);
888
43.4k
      mp = f;
889
43.4k
    }
890
57.9k
  }
891
135k
  setnodekey(mp, key);
892
135k
  lua_assert(isempty(gval(mp)));
893
270k
  setobj2t(cast(lua_State *, 0), gval(mp), value);
894
135k
  return 1;
895
270k
}
896
897
898
/*
899
** Insert a key in a table where there is space for that key, the
900
** key is valid, and the value is not nil.
901
*/
902
93.7k
static void newcheckedkey (Table *t, const TValue *key, TValue *value) {
903
93.7k
  unsigned i = keyinarray(t, key);
904
93.7k
  if (i > 0)  /* is key in the array part? */
905
737
    obj2arr(t, i - 1, value);  /* set value in the array */
906
93.0k
  else {
907
93.0k
    int done = insertkey(t, key, value);  /* insert key in the hash part */
908
93.0k
    lua_assert(done);  /* it cannot fail */
909
93.0k
    cast(void, done);  /* to avoid warnings */
910
93.0k
  }
911
93.7k
}
912
913
914
static void luaH_newkey (lua_State *L, Table *t, const TValue *key,
915
16.6k
                                                 TValue *value) {
916
16.6k
  if (!ttisnil(value)) {  /* do not insert nil values */
917
16.6k
    int done = insertkey(t, key, value);
918
16.6k
    if (!done) {  /* could not find a free place? */
919
6.49k
      rehash(L, t, key);  /* grow table */
920
6.49k
      newcheckedkey(t, key, value);  /* insert key in grown table */
921
6.49k
    }
922
16.6k
    luaC_barrierback(L, obj2gco(t), key);
923
    /* for debugging only: any new key may force an emergency collection */
924
16.6k
    condchangemem(L, (void)0, (void)0, 1);
925
16.6k
  }
926
16.6k
}
927
928
929
77.6k
static const TValue *getintfromhash (Table *t, lua_Integer key) {
930
77.6k
  Node *n = hashint(t, key);
931
77.6k
  lua_assert(!ikeyinarray(t, key));
932
106k
  for (;;) {  /* check whether 'key' is somewhere in the chain */
933
106k
    if (keyisinteger(n) && keyival(n) == key)
934
68.5k
      return gval(n);  /* that's it */
935
38.3k
    else {
936
38.3k
      int nx = gnext(n);
937
38.3k
      if (nx == 0) break;
938
29.1k
      n += nx;
939
29.1k
    }
940
106k
  }
941
9.19k
  return &absentkey;
942
77.6k
}
943
944
945
81
static int hashkeyisempty (Table *t, lua_Unsigned key) {
946
81
  const TValue *val = getintfromhash(t, l_castU2S(key));
947
81
  return isempty(val);
948
81
}
949
950
951
49.6M
static lu_byte finishnodeget (const TValue *val, TValue *res) {
952
49.6M
  if (!ttisnil(val)) {
953
49.0M
    setobj(((lua_State*)NULL), res, val);
954
49.0M
  }
955
49.6M
  return ttypetag(val);
956
49.6M
}
957
958
959
128k
lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res) {
960
128k
  unsigned k = ikeyinarray(t, key);
961
128k
  if (k > 0) {
962
55.2k
    lu_byte tag = *getArrTag(t, k - 1);
963
55.2k
    if (!tagisempty(tag))
964
55.0k
      farr2val(t, k - 1, tag, res);
965
55.2k
    return tag;
966
55.2k
  }
967
72.8k
  else
968
72.8k
    return finishnodeget(getintfromhash(t, key), res);
969
128k
}
970
971
972
/*
973
** search function for short strings
974
*/
975
49.5M
const TValue *luaH_Hgetshortstr (Table *t, TString *key) {
976
49.5M
  Node *n = hashstr(t, key);
977
49.5M
  lua_assert(strisshr(key));
978
68.3M
  for (;;) {  /* check whether 'key' is somewhere in the chain */
979
68.3M
    if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
980
48.9M
      return gval(n);  /* that's it */
981
19.3M
    else {
982
19.3M
      int nx = gnext(n);
983
19.3M
      if (nx == 0)
984
616k
        return &absentkey;  /* not found */
985
18.7M
      n += nx;
986
18.7M
    }
987
68.3M
  }
988
49.5M
}
989
990
991
537k
lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res) {
992
537k
  return finishnodeget(luaH_Hgetshortstr(t, key), res);
993
537k
}
994
995
996
5.54k
static const TValue *Hgetlongstr (Table *t, TString *key) {
997
5.54k
  TValue ko;
998
5.54k
  lua_assert(!strisshr(key));
999
11.0k
  setsvalue(cast(lua_State *, NULL), &ko, key);
1000
5.54k
  return getgeneric(t, &ko, 0);  /* for long strings, use generic case */
1001
11.0k
}
1002
1003
1004
24.6M
static const TValue *Hgetstr (Table *t, TString *key) {
1005
24.6M
  if (strisshr(key))
1006
24.6M
    return luaH_Hgetshortstr(t, key);
1007
5.54k
  else
1008
5.54k
    return Hgetlongstr(t, key);
1009
24.6M
}
1010
1011
1012
24.6M
lu_byte luaH_getstr (Table *t, TString *key, TValue *res) {
1013
24.6M
  return finishnodeget(Hgetstr(t, key), res);
1014
24.6M
}
1015
1016
1017
/*
1018
** main search function
1019
*/
1020
24.5M
lu_byte luaH_get (Table *t, const TValue *key, TValue *res) {
1021
24.5M
  const TValue *slot;
1022
24.5M
  switch (ttypetag(key)) {
1023
24.3M
    case LUA_VSHRSTR:
1024
24.3M
      slot = luaH_Hgetshortstr(t, tsvalue(key));
1025
0
      break;
1026
127k
    case LUA_VNUMINT:
1027
127k
      return luaH_getint(t, ivalue(key), res);
1028
0
    case LUA_VNIL:
1029
0
      slot = &absentkey;
1030
0
      break;
1031
28.3k
    case LUA_VNUMFLT: {
1032
28.3k
      lua_Integer k;
1033
28.3k
      if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
1034
0
        return luaH_getint(t, k, res);  /* use specialized version */
1035
      /* else... */
1036
28.3k
    }  /* FALLTHROUGH */
1037
34.1k
    default:
1038
34.1k
      slot = getgeneric(t, key, 0);
1039
34.1k
      break;
1040
24.5M
  }
1041
24.4M
  return finishnodeget(slot, res);
1042
24.5M
}
1043
1044
1045
/*
1046
** When a 'pset' cannot be completed, this function returns an encoding
1047
** of its result, to be used by 'luaH_finishset'.
1048
*/
1049
16.6k
static int retpsetcode (Table *t, const TValue *slot) {
1050
16.6k
  if (isabstkey(slot))
1051
16.6k
    return HNOTFOUND;  /* no slot with that key */
1052
0
  else  /* return node encoded */
1053
0
    return cast_int((cast(Node*, slot) - t->node)) + HFIRSTNODE;
1054
16.6k
}
1055
1056
1057
9.58k
static int finishnodeset (Table *t, const TValue *slot, TValue *val) {
1058
9.58k
  if (!ttisnil(slot)) {
1059
148
    setobj(((lua_State*)NULL), cast(TValue*, slot), val);
1060
148
    return HOK;  /* success */
1061
148
  }
1062
9.43k
  else
1063
9.43k
    return retpsetcode(t, slot);
1064
9.58k
}
1065
1066
1067
0
static int rawfinishnodeset (const TValue *slot, TValue *val) {
1068
0
  if (isabstkey(slot))
1069
0
    return 0;  /* no slot with that key */
1070
0
  else {
1071
0
    setobj(((lua_State*)NULL), cast(TValue*, slot), val);
1072
0
    return 1;  /* success */
1073
0
  }
1074
0
}
1075
1076
1077
4.71k
int luaH_psetint (Table *t, lua_Integer key, TValue *val) {
1078
4.71k
  lua_assert(!ikeyinarray(t, key));
1079
4.71k
  return finishnodeset(t, getintfromhash(t, key), val);
1080
4.71k
}
1081
1082
1083
4.75k
static int psetint (Table *t, lua_Integer key, TValue *val) {
1084
4.75k
  int hres;
1085
4.75k
  luaH_fastseti(t, key, val, hres);
1086
4.75k
  return hres;
1087
4.75k
}
1088
1089
1090
/*
1091
** This function could be just this:
1092
**    return finishnodeset(t, luaH_Hgetshortstr(t, key), val);
1093
** However, it optimizes the common case created by constructors (e.g.,
1094
** {x=1, y=2}), which creates a key in a table that has no metatable,
1095
** it is not old/black, and it already has space for the key.
1096
*/
1097
1098
40.3k
int luaH_psetshortstr (Table *t, TString *key, TValue *val) {
1099
40.3k
  const TValue *slot = luaH_Hgetshortstr(t, key);
1100
40.3k
  if (!ttisnil(slot)) {  /* key already has a value? (all too common) */
1101
481
    setobj(((lua_State*)NULL), cast(TValue*, slot), val);  /* update it */
1102
481
    return HOK;  /* done */
1103
481
  }
1104
39.9k
  else if (checknoTM(t->metatable, TM_NEWINDEX)) {  /* no metamethod? */
1105
39.9k
    if (ttisnil(val))  /* new value is nil? */
1106
716
      return HOK;  /* done (value is already nil/absent) */
1107
39.2k
    if (isabstkey(slot) &&  /* key is absent? */
1108
39.2k
       !(isblack(t) && iswhite(key))) {  /* and don't need barrier? */
1109
36.8k
      TValue tk;  /* key as a TValue */
1110
36.8k
      setsvalue(cast(lua_State *, NULL), &tk, key);
1111
36.8k
      if (insertkey(t, &tk, val)) {  /* insert key, if there is space */
1112
32.0k
        invalidateTMcache(t);
1113
32.0k
        return HOK;
1114
32.0k
      }
1115
36.8k
    }
1116
39.2k
  }
1117
  /* Else, either table has new-index metamethod, or it needs barrier,
1118
     or it needs to rehash for the new key. In any of these cases, the
1119
     operation cannot be completed here. Return a code for the caller. */
1120
7.19k
  return retpsetcode(t, slot);
1121
40.3k
}
1122
1123
1124
200
int luaH_psetstr (Table *t, TString *key, TValue *val) {
1125
200
  if (strisshr(key))
1126
200
    return luaH_psetshortstr(t, key, val);
1127
0
  else
1128
0
    return finishnodeset(t, Hgetlongstr(t, key), val);
1129
200
}
1130
1131
1132
48.6k
int luaH_pset (Table *t, const TValue *key, TValue *val) {
1133
48.6k
  switch (ttypetag(key)) {
1134
38.9k
    case LUA_VSHRSTR: return luaH_psetshortstr(t, tsvalue(key), val);
1135
4.75k
    case LUA_VNUMINT: return psetint(t, ivalue(key), val);
1136
0
    case LUA_VNIL: return HNOTFOUND;
1137
2.35k
    case LUA_VNUMFLT: {
1138
2.35k
      lua_Integer k;
1139
2.35k
      if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
1140
0
        return psetint(t, k, val);  /* use specialized version */
1141
      /* else... */
1142
2.35k
    }  /* FALLTHROUGH */
1143
4.86k
    default:
1144
4.86k
      return finishnodeset(t, getgeneric(t, key, 0), val);
1145
48.6k
  }
1146
48.6k
}
1147
1148
/*
1149
** Finish a raw "set table" operation, where 'hres' encodes where the
1150
** value should have been (the result of a previous 'pset' operation).
1151
** Beware: when using this function the caller probably need to check a
1152
** GC barrier and invalidate the TM cache.
1153
*/
1154
void luaH_finishset (lua_State *L, Table *t, const TValue *key,
1155
16.6k
                                    TValue *value, int hres) {
1156
16.6k
  lua_assert(hres != HOK);
1157
16.6k
  if (hres == HNOTFOUND) {
1158
16.6k
    TValue aux;
1159
16.6k
    if (l_unlikely(ttisnil(key)))
1160
0
      luaG_runerror(L, "table index is nil");
1161
16.6k
    else if (ttisfloat(key)) {
1162
2.35k
      lua_Number f = fltvalue(key);
1163
0
      lua_Integer k;
1164
2.35k
      if (luaV_flttointeger(f, &k, F2Ieq)) {
1165
0
        setivalue(&aux, k);  /* key is equal to an integer */
1166
0
        key = &aux;  /* insert it as an integer */
1167
0
      }
1168
2.35k
      else if (l_unlikely(luai_numisnan(f)))
1169
0
        luaG_runerror(L, "table index is NaN");
1170
2.35k
    }
1171
14.2k
    else if (isextstr(key)) {  /* external string? */
1172
      /* If string is short, must internalize it to be used as table key */
1173
0
      TString *ts = luaS_normstr(L, tsvalue(key));
1174
0
      setsvalue2s(L, L->top.p++, ts);  /* anchor 'ts' (EXTRA_STACK) */
1175
0
      luaH_newkey(L, t, s2v(L->top.p - 1), value);
1176
0
      L->top.p--;
1177
0
      return;
1178
0
    }
1179
16.6k
    luaH_newkey(L, t, key, value);
1180
16.6k
  }
1181
0
  else if (hres > 0) {  /* regular Node? */
1182
0
    setobj2t(L, gval(gnode(t, hres - HFIRSTNODE)), value);
1183
0
  }
1184
0
  else {  /* array entry */
1185
0
    hres = ~hres;  /* real index */
1186
0
    obj2arr(t, cast_uint(hres), value);
1187
0
  }
1188
16.6k
}
1189
1190
1191
/*
1192
** beware: when using this function you probably need to check a GC
1193
** barrier and invalidate the TM cache.
1194
*/
1195
48.6k
void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
1196
48.6k
  int hres = luaH_pset(t, key, value);
1197
48.6k
  if (hres != HOK)
1198
16.4k
    luaH_finishset(L, t, key, value, hres);
1199
48.6k
}
1200
1201
1202
/*
1203
** Ditto for a GC barrier. (No need to invalidate the TM cache, as
1204
** integers cannot be keys to metamethods.)
1205
*/
1206
1.32k
void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
1207
1.32k
  unsigned ik = ikeyinarray(t, key);
1208
1.32k
  if (ik > 0)
1209
1.32k
    obj2arr(t, ik - 1, value);
1210
0
  else {
1211
0
    int ok = rawfinishnodeset(getintfromhash(t, key), value);
1212
0
    if (!ok) {
1213
0
      TValue k;
1214
0
      setivalue(&k, key);
1215
0
      luaH_newkey(L, t, &k, value);
1216
0
    }
1217
0
  }
1218
1.32k
}
1219
1220
1221
/*
1222
** Try to find a boundary in the hash part of table 't'. From the
1223
** caller, we know that 'asize + 1' is present. We want to find a larger
1224
** key that is absent from the table, so that we can do a binary search
1225
** between the two keys to find a boundary. We keep doubling 'j' until
1226
** we get an absent index.  If the doubling would overflow, we try
1227
** LUA_MAXINTEGER. If it is absent, we are ready for the binary search.
1228
** ('j', being max integer, is larger or equal to 'i', but it cannot be
1229
** equal because it is absent while 'i' is present.) Otherwise, 'j' is a
1230
** boundary. ('j + 1' cannot be a present integer key because it is not
1231
** a valid integer in Lua.)
1232
** About 'rnd': If we used a fixed algorithm, a bad actor could fill
1233
** a table with only the keys that would be probed, in such a way that
1234
** a small table could result in a huge length. To avoid that, we use
1235
** the state's seed as a source of randomness. For the first probe,
1236
** we "randomly double" 'i' by adding to it a random number roughly its
1237
** width.
1238
*/
1239
0
static lua_Unsigned hash_search (lua_State *L, Table *t, unsigned asize) {
1240
0
  lua_Unsigned i = asize + 1;  /* caller ensures t[i] is present */
1241
0
  unsigned rnd = G(L)->seed;
1242
0
  int n = (asize > 0) ? luaO_ceillog2(asize) : 0;  /* width of 'asize' */
1243
0
  unsigned mask = (1u << n) - 1;  /* 11...111 with the width of 'asize' */
1244
0
  unsigned incr = (rnd & mask) + 1;  /* first increment (at least 1) */
1245
0
  lua_Unsigned j = (incr <= l_castS2U(LUA_MAXINTEGER) - i) ? i + incr : i + 1;
1246
0
  rnd >>= n;  /* used 'n' bits from 'rnd' */
1247
0
  while (!hashkeyisempty(t, j)) {  /* repeat until an absent t[j] */
1248
0
    i = j;  /* 'i' is a present index */
1249
0
    if (j <= l_castS2U(LUA_MAXINTEGER)/2 - 1) {
1250
0
      j = j*2 + (rnd & 1);  /* try again with 2j or 2j+1 */
1251
0
      rnd >>= 1;
1252
0
    }
1253
0
    else {
1254
0
      j = LUA_MAXINTEGER;
1255
0
      if (hashkeyisempty(t, j))  /* t[j] not present? */
1256
0
        break;  /* 'j' now is an absent index */
1257
0
      else  /* weird case */
1258
0
        return j;  /* well, max integer is a boundary... */
1259
0
    }
1260
0
  }
1261
  /* i < j  &&  t[i] present  &&  t[j] absent */
1262
0
  while (j - i > 1u) {  /* do a binary search between them */
1263
0
    lua_Unsigned m = (i + j) / 2;
1264
0
    if (hashkeyisempty(t, m)) j = m;
1265
0
    else i = m;
1266
0
  }
1267
0
  return i;
1268
0
}
1269
1270
1271
0
static unsigned int binsearch (Table *array, unsigned int i, unsigned int j) {
1272
0
  lua_assert(i <= j);
1273
0
  while (j - i > 1u) {  /* binary search */
1274
0
    unsigned int m = (i + j) / 2;
1275
0
    if (arraykeyisempty(array, m)) j = m;
1276
0
    else i = m;
1277
0
  }
1278
0
  return i;
1279
0
}
1280
1281
1282
/* return a border, saving it as a hint for next call */
1283
0
static lua_Unsigned newhint (Table *t, unsigned hint) {
1284
0
  lua_assert(hint <= t->asize);
1285
0
  *lenhint(t) = hint;
1286
0
  return hint;
1287
0
}
1288
1289
1290
/*
1291
** Try to find a border in table 't'. (A 'border' is an integer index
1292
** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent,
1293
** or 'maxinteger' if t[maxinteger] is present.)
1294
** If there is an array part, try to find a border there. First try
1295
** to find it in the vicinity of the previous result (hint), to handle
1296
** cases like 't[#t + 1] = val' or 't[#t] = nil', that move the border
1297
** by one entry. Otherwise, do a binary search to find the border.
1298
** If there is no array part, or its last element is non empty, the
1299
** border may be in the hash part.
1300
*/
1301
81
lua_Unsigned luaH_getn (lua_State *L, Table *t) {
1302
81
  unsigned asize = t->asize;
1303
81
  if (asize > 0) {  /* is there an array part? */
1304
0
    const unsigned maxvicinity = 4;
1305
0
    unsigned limit = *lenhint(t);  /* start with the hint */
1306
0
    if (limit == 0)
1307
0
      limit = 1;  /* make limit a valid index in the array */
1308
0
    if (arraykeyisempty(t, limit)) {  /* t[limit] empty? */
1309
      /* there must be a border before 'limit' */
1310
0
      unsigned i;
1311
      /* look for a border in the vicinity of the hint */
1312
0
      for (i = 0; i < maxvicinity && limit > 1; i++) {
1313
0
        limit--;
1314
0
        if (!arraykeyisempty(t, limit))
1315
0
          return newhint(t, limit);  /* 'limit' is a border */
1316
0
      }
1317
      /* t[limit] still empty; search for a border in [0, limit) */
1318
0
      return newhint(t, binsearch(t, 0, limit));
1319
0
    }
1320
0
    else {  /* 'limit' is present in table; look for a border after it */
1321
0
      unsigned i;
1322
      /* look for a border in the vicinity of the hint */
1323
0
      for (i = 0; i < maxvicinity && limit < asize; i++) {
1324
0
        limit++;
1325
0
        if (arraykeyisempty(t, limit))
1326
0
          return newhint(t, limit - 1);  /* 'limit - 1' is a border */
1327
0
      }
1328
0
      if (arraykeyisempty(t, asize)) {  /* last element empty? */
1329
        /* t[limit] not empty; search for a border in [limit, asize) */
1330
0
        return newhint(t, binsearch(t, limit, asize));
1331
0
      }
1332
0
    }
1333
    /* last element non empty; set a hint to speed up finding that again */
1334
    /* (keys in the hash part cannot be hints) */
1335
0
    *lenhint(t) = asize;
1336
0
  }
1337
  /* no array part or t[asize] is not empty; check the hash part */
1338
81
  lua_assert(asize == 0 || !arraykeyisempty(t, asize));
1339
81
  if (isdummy(t) || hashkeyisempty(t, asize + 1))
1340
81
    return asize;  /* 'asize + 1' is empty */
1341
0
  else  /* 'asize + 1' is also non empty */
1342
0
    return hash_search(L, t, asize);
1343
81
}
1344
1345
1346
1347
#if defined(LUA_DEBUG)
1348
1349
/* export this function for the test library */
1350
1351
Node *luaH_mainposition (const Table *t, const TValue *key) {
1352
  return mainpositionTV(t, key);
1353
}
1354
1355
#endif