Coverage Report

Created: 2025-07-11 06:33

/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
359M
#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
311M
#define haslastfree(t)     ((t)->lsizenode >= LIMFORLAST)
63
326M
#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
1.63G
#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
57.4M
#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
57.4M
    (((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
97.6M
#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
48.8M
#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
1.88G
#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
79.2M
#define hashmod(t,n)  (gnode(t, ((n) % ((sizenode(t)-1u)|1u))))
113
114
115
1.86G
#define hashstr(t,str)    hashpow2(t, (str)->hash)
116
1.04M
#define hashboolean(t,p)  hashpow2(t, p)
117
118
119
16.2M
#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
78.5M
static Node *hashint (const Table *t, lua_Integer i) {
146
78.5M
  lua_Unsigned ui = l_castS2U(i);
147
78.5M
  if (ui <= cast_uint(INT_MAX))
148
60.5M
    return gnode(t, cast_int(ui) % cast_int((sizenode(t)-1) | 1));
149
17.9M
  else
150
17.9M
    return hashmod(t, ui);
151
78.5M
}
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
45.0M
static unsigned l_hashfloat (lua_Number n) {
169
45.0M
  int i;
170
45.0M
  lua_Integer ni;
171
45.0M
  n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
172
45.0M
  if (!lua_numbertointeger(n, &ni)) {  /* is 'n' inf/-inf/NaN? */
173
1.16M
    lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
174
1.16M
    return 0;
175
1.16M
  }
176
43.8M
  else {  /* normal case */
177
43.8M
    unsigned int u = cast_uint(i) + cast_uint(ni);
178
43.8M
    return (u <= cast_uint(INT_MAX) ? u : ~u);
179
43.8M
  }
180
45.0M
}
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
1.05G
static Node *mainpositionTV (const Table *t, const TValue *key) {
189
1.05G
  switch (ttypetag(key)) {
190
49.9M
    case LUA_VNUMINT: {
191
49.9M
      lua_Integer i = ivalue(key);
192
0
      return hashint(t, i);
193
49.9M
    }
194
45.0M
    case LUA_VNUMFLT: {
195
45.0M
      lua_Number n = fltvalue(key);
196
45.0M
      return hashmod(t, l_hashfloat(n));
197
45.0M
    }
198
924M
    case LUA_VSHRSTR: {
199
1.84G
      TString *ts = tsvalue(key);
200
1.84G
      return hashstr(t, ts);
201
1.84G
    }
202
13.7M
    case LUA_VLNGSTR: {
203
27.5M
      TString *ts = tsvalue(key);
204
27.5M
      return hashpow2(t, luaS_hashlongstr(ts));
205
27.5M
    }
206
631k
    case LUA_VFALSE:
207
631k
      return hashboolean(t, 0);
208
409k
    case LUA_VTRUE:
209
409k
      return hashboolean(t, 1);
210
236k
    case LUA_VLIGHTUSERDATA: {
211
236k
      void *p = pvalue(key);
212
236k
      return hashpointer(t, p);
213
236k
    }
214
602k
    case LUA_VLCF: {
215
602k
      lua_CFunction f = fvalue(key);
216
602k
      return hashpointer(t, f);
217
602k
    }
218
15.4M
    default: {
219
15.4M
      GCObject *o = gcvalue(key);
220
15.4M
      return hashpointer(t, o);
221
15.4M
    }
222
1.05G
  }
223
1.05G
}
224
225
226
96.5M
l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {
227
96.5M
  TValue key;
228
96.5M
  getnodekey(cast(lua_State *, NULL), &key, nd);
229
96.5M
  return mainpositionTV(t, &key);
230
96.5M
}
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
732M
static int equalkey (const TValue *k1, const Node *n2, int deadok) {
254
732M
  if ((rawtt(k1) != keytt(n2)) &&  /* not the same variants? */
255
732M
       !(deadok && keyisdead(n2) && iscollectable(k1)))
256
210M
   return 0;  /* cannot be same key */
257
522M
  switch (keytt(n2)) {
258
120k
    case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
259
120k
      return 1;
260
40.3M
    case LUA_VNUMINT:
261
40.3M
      return (ivalue(k1) == keyival(n2));
262
31.6M
    case LUA_VNUMFLT:
263
31.6M
      return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
264
81.9k
    case LUA_VLIGHTUSERDATA:
265
81.9k
      return pvalue(k1) == pvalueraw(keyval(n2));
266
600k
    case LUA_VLCF:
267
600k
      return fvalue(k1) == fvalueraw(keyval(n2));
268
5.47M
    case ctb(LUA_VLNGSTR):
269
10.9M
      return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
270
443M
    default:
271
443M
      return gcvalue(k1) == gcvalueraw(keyval(n2));
272
522M
  }
273
522M
}
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
612M
static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
282
612M
  Node *n = mainpositionTV(t, key);
283
732M
  for (;;) {  /* check whether 'key' is somewhere in the chain */
284
732M
    if (equalkey(key, n, deadok))
285
260M
      return gval(n);  /* that's it */
286
472M
    else {
287
472M
      int nx = gnext(n);
288
472M
      if (nx == 0)
289
352M
        return &absentkey;  /* not found */
290
119M
      n += nx;
291
119M
    }
292
732M
  }
293
612M
}
294
295
296
/*
297
** Return the index 'k' (converted to an unsigned) if it is inside
298
** the range [1, limit].
299
*/
300
154M
static unsigned checkrange (lua_Integer k, unsigned limit) {
301
154M
  return (l_castS2U(k) - 1u < limit) ? cast_uint(k) : 0;
302
154M
}
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
4.37M
#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
380M
#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
473M
static unsigned keyinarray (Table *t, const TValue *key) {
324
473M
  return (ttisinteger(key)) ? ikeyinarray(t, ivalue(key)) : 0;
325
473M
}
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
318M
                               unsigned asize) {
335
318M
  unsigned int i;
336
318M
  if (ttisnil(key)) return 0;  /* first iteration */
337
303M
  i = keyinarray(t, key);
338
303M
  if (i != 0)  /* is 'key' inside array part? */
339
56.1M
    return i;  /* yes; that's the index */
340
247M
  else {
341
247M
    const TValue *n = getgeneric(t, key, 1);
342
247M
    if (l_unlikely(isabstkey(n)))
343
1.06k
      luaG_runerror(L, "invalid key to 'next'");  /* key not found */
344
247M
    i = cast_uint(nodefromval(n) - gnode(t, 0));  /* key index in hash table */
345
    /* hash elements are numbered after array ones */
346
247M
    return (i + 1) + asize;
347
247M
  }
348
303M
}
349
350
351
318M
int luaH_next (lua_State *L, Table *t, StkId key) {
352
318M
  unsigned int asize = t->asize;
353
318M
  unsigned int i = findindex(L, t, s2v(key), asize);  /* find original key */
354
345M
  for (; i < asize; i++) {  /* try first array part */
355
82.9M
    lu_byte tag = *getArrTag(t, i);
356
82.9M
    if (!tagisempty(tag)) {  /* a non-empty entry? */
357
56.2M
      setivalue(s2v(key), cast_int(i) + 1);
358
56.2M
      farr2val(t, i, tag, s2v(key + 1));
359
56.2M
      return 1;
360
56.2M
    }
361
82.9M
  }
362
375M
  for (i -= asize; i < sizenode(t); i++) {  /* hash part */
363
363M
    if (!isempty(gval(gnode(t, i)))) {  /* a non-empty entry? */
364
250M
      Node *n = gnode(t, i);
365
250M
      getnodekey(L, s2v(key), n);
366
250M
      setobj2s(L, key + 1, gval(n));
367
250M
      return 1;
368
250M
    }
369
363M
  }
370
11.2M
  return 0;  /* no more elements */
371
262M
}
372
373
374
/* Extra space in Node array if it has a lastfree entry */
375
127M
#define extraLastfree(t)  (haslastfree(t) ? sizeof(Limbox) : 0)
376
377
/* 'node' size in bytes */
378
79.0M
static size_t sizehash (Table *t) {
379
79.0M
  return cast_sizet(sizenode(t)) * sizeof(Node) + extraLastfree(t);
380
79.0M
}
381
382
383
94.6M
static void freehash (lua_State *L, Table *t) {
384
94.6M
  if (!isdummy(t)) {
385
    /* get pointer to the beginning of Node array */
386
48.8M
    char *arr = cast_charp(t->node) - extraLastfree(t);
387
48.8M
    luaM_freearray(L, arr, sizehash(t));
388
48.8M
  }
389
94.6M
}
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.56M
#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.64M
static unsigned computesizes (Counters *ct) {
437
1.64M
  int i;
438
1.64M
  unsigned int twotoi;  /* 2^i (candidate for optimal size) */
439
1.64M
  unsigned int a = 0;  /* number of elements smaller than 2^i */
440
1.64M
  unsigned int na = 0;  /* number of elements to go to array part */
441
1.64M
  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.64M
  for (i = 0, twotoi = 1;
445
6.05M
       twotoi > 0 && arrayXhash(twotoi, ct->na);
446
4.41M
       i++, twotoi *= 2) {
447
4.41M
    unsigned nums = ct->nums[i];
448
4.41M
    a += nums;
449
4.41M
    if (nums > 0 &&  /* grows array only if it gets more elements... */
450
4.41M
        arrayXhash(twotoi, a)) {  /* ...while using "less memory" */
451
1.20M
      optimal = twotoi;  /* optimal size (till now) */
452
1.20M
      na = a;  /* all elements up to 'optimal' will go to array part */
453
1.20M
    }
454
4.41M
  }
455
1.64M
  ct->na = na;
456
1.64M
  return optimal;
457
1.64M
}
458
459
460
4.37M
static void countint (lua_Integer key, Counters *ct) {
461
4.37M
  unsigned int k = arrayindex(key);
462
4.37M
  if (k != 0) {  /* is 'key' an array index? */
463
2.52M
    ct->nums[luaO_ceillog2(k)]++;  /* count as such */
464
2.52M
    ct->na++;
465
2.52M
  }
466
4.37M
}
467
468
469
30.9M
l_sinline int arraykeyisempty (const Table *t, unsigned key) {
470
30.9M
  int tag = *getArrTag(t, key - 1);
471
30.9M
  return tagisempty(tag);
472
30.9M
}
473
474
475
/*
476
** Count keys in array part of table 't'.
477
*/
478
1.64M
static void numusearray (const Table *t, Counters *ct) {
479
1.64M
  int lg;
480
1.64M
  unsigned int ttlg;  /* 2^lg */
481
1.64M
  unsigned int ause = 0;  /* summation of 'nums' */
482
1.64M
  unsigned int i = 1;  /* index to traverse all array keys */
483
1.64M
  unsigned int asize = t->asize;
484
  /* traverse each slice */
485
2.60M
  for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
486
2.60M
    unsigned int lc = 0;  /* counter */
487
2.60M
    unsigned int lim = ttlg;
488
2.60M
    if (lim > asize) {
489
1.65M
      lim = asize;  /* adjust upper limit */
490
1.65M
      if (i > lim)
491
1.64M
        break;  /* no more elements to count */
492
1.65M
    }
493
    /* count elements in range (2^(lg - 1), 2^lg] */
494
12.2M
    for (; i <= lim; i++) {
495
11.2M
      if (!arraykeyisempty(t, i))
496
10.6M
        lc++;
497
11.2M
    }
498
963k
    ct->nums[lg] += lc;
499
963k
    ause += lc;
500
963k
  }
501
1.64M
  ct->total += ause;
502
1.64M
  ct->na += ause;
503
1.64M
}
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
44.5M
static void numusehash (const Table *t, Counters *ct) {
512
44.5M
  unsigned i = sizenode(t);
513
44.5M
  unsigned total = 0;
514
183M
  while (i--) {
515
138M
    Node *n = &t->node[i];
516
138M
    if (isempty(gval(n))) {
517
13.1M
      lua_assert(!keyisnil(n));  /* entry was deleted; key cannot be nil */
518
13.1M
      ct->deleted = 1;
519
13.1M
    }
520
125M
    else {
521
125M
      total++;
522
125M
      if (keyisinteger(n))
523
3.04M
        countint(keyival(n), ct);
524
125M
    }
525
138M
  }
526
44.5M
  ct->total += total;
527
44.5M
}
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
72.3M
static size_t concretesize (unsigned int size) {
535
72.3M
  if (size == 0)
536
51.7M
    return 0;
537
20.5M
  else  /* space for the two arrays plus an unsigned in between */
538
20.5M
    return size * (sizeof(Value) + 1) + sizeof(unsigned);
539
72.3M
}
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
94.6M
                               unsigned newasize) {
556
94.6M
  if (oldasize == newasize)
557
84.1M
    return t->array;  /* nothing to be done */
558
10.4M
  else if (newasize == 0) {  /* erasing array? */
559
5.13M
    Value *op = t->array - oldasize;  /* original array's real address */
560
5.13M
    luaM_freemem(L, op, concretesize(oldasize));  /* free it */
561
5.13M
    return NULL;
562
5.13M
  }
563
5.33M
  else {
564
5.33M
    size_t newasizeb = concretesize(newasize);
565
5.33M
    Value *np = cast(Value *,
566
5.33M
                  luaM_reallocvector(L, NULL, 0, newasizeb, lu_byte));
567
5.33M
    if (np == NULL)  /* allocation error? */
568
0
      return NULL;
569
5.33M
    np += newasize;  /* shift pointer to the end of value segment */
570
5.33M
    if (oldasize > 0) {
571
      /* move common elements to new position */
572
197k
      size_t oldasizeb = concretesize(oldasize);
573
197k
      Value *op = t->array;  /* original array */
574
197k
      unsigned tomove = (oldasize < newasize) ? oldasize : newasize;
575
197k
      size_t tomoveb = (oldasize < newasize) ? oldasizeb : newasizeb;
576
197k
      lua_assert(tomoveb > 0);
577
197k
      memcpy(np - tomove, op - tomove, tomoveb);
578
197k
      luaM_freemem(L, op - oldasize, oldasizeb);  /* free old block */
579
197k
    }
580
5.33M
    return np;
581
5.33M
  }
582
94.6M
}
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
94.6M
static void setnodevector (lua_State *L, Table *t, unsigned size) {
593
94.6M
  if (size == 0) {  /* no elements to hash part? */
594
45.8M
    t->node = cast(Node *, dummynode);  /* use common 'dummynode' */
595
45.8M
    t->lsizenode = 0;
596
45.8M
    setdummy(t);  /* signal that it is using dummy node */
597
45.8M
  }
598
48.8M
  else {
599
48.8M
    int i;
600
48.8M
    int lsize = luaO_ceillog2(size);
601
48.8M
    if (lsize > MAXHBITS || (1 << lsize) > MAXHSIZE)
602
0
      luaG_runerror(L, "table overflow");
603
48.8M
    size = twoto(lsize);
604
48.8M
    if (lsize < LIMFORLAST)  /* no 'lastfree' field? */
605
35.7M
      t->node = luaM_newvector(L, size, Node);
606
13.0M
    else {
607
13.0M
      size_t bsize = size * sizeof(Node) + sizeof(Limbox);
608
13.0M
      char *node = luaM_newblock(L, bsize);
609
13.0M
      t->node = cast(Node *, node + sizeof(Limbox));
610
13.0M
      getlastfree(t) = gnode(t, size);  /* all positions are free */
611
13.0M
    }
612
48.8M
    t->lsizenode = cast_byte(lsize);
613
48.8M
    setnodummy(t);
614
329M
    for (i = 0; i < cast_int(size); i++) {
615
280M
      Node *n = gnode(t, i);
616
280M
      gnext(n) = 0;
617
280M
      setnilkey(n);
618
280M
      setempty(gval(n));
619
280M
    }
620
48.8M
  }
621
94.6M
}
622
623
624
/*
625
** (Re)insert all elements from the hash part of 'ot' into table 't'.
626
*/
627
53.0M
static void reinserthash (lua_State *L, Table *ot, Table *t) {
628
53.0M
  unsigned j;
629
53.0M
  unsigned size = sizenode(ot);
630
200M
  for (j = 0; j < size; j++) {
631
147M
    Node *old = gnode(ot, j);
632
147M
    if (!isempty(gval(old))) {
633
      /* doesn't need barrier/invalidate cache, as entry was
634
         already present in the table */
635
125M
      TValue k;
636
125M
      getnodekey(L, &k, old);
637
125M
      newcheckedkey(t, &k, gval(old));
638
125M
    }
639
147M
  }
640
53.0M
}
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
53.2M
static void exchangehashpart (Table *t1, Table *t2) {
650
53.2M
  lu_byte lsizenode = t1->lsizenode;
651
53.2M
  Node *node = t1->node;
652
53.2M
  int bitdummy1 = t1->flags & BITDUMMY;
653
53.2M
  t1->lsizenode = t2->lsizenode;
654
53.2M
  t1->node = t2->node;
655
53.2M
  t1->flags = cast_byte((t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY));
656
53.2M
  t2->lsizenode = lsizenode;
657
53.2M
  t2->node = node;
658
53.2M
  t2->flags = cast_byte((t2->flags & NOTBITDUMMY) | bitdummy1);
659
53.2M
}
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
71.6k
                                        unsigned newasize) {
668
71.6k
  unsigned i;
669
390k
  for (i = newasize; i < oldasize; i++) {  /* traverse vanishing slice */
670
319k
    lu_byte tag = *getArrTag(t, i);
671
319k
    if (!tagisempty(tag)) {  /* a non-empty entry? */
672
14.8k
      TValue key, aux;
673
14.8k
      setivalue(&key, l_castU2S(i) + 1);  /* make the key */
674
14.8k
      farr2val(t, i, tag, &aux);  /* copy value into 'aux' */
675
14.8k
      insertkey(t, &key, &aux);  /* insert entry into the hash part */
676
14.8k
    }
677
319k
  }
678
71.6k
}
679
680
681
/*
682
** Clear new slice of the array.
683
*/
684
53.0M
static void clearNewSlice (Table *t, unsigned oldasize, unsigned newasize) {
685
128M
  for (; oldasize < newasize; oldasize++)
686
75.5M
    *getArrTag(t, oldasize) = LUA_VEMPTY;
687
53.0M
}
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
53.0M
                                          unsigned nhsize) {
708
53.0M
  Table newt;  /* to keep the new hash part */
709
53.0M
  unsigned oldasize = t->asize;
710
53.0M
  Value *newarray;
711
53.0M
  if (newasize > MAXASIZE)
712
0
    luaG_runerror(L, "table overflow");
713
  /* create new hash part with appropriate size into 'newt' */
714
53.0M
  newt.flags = 0;
715
53.0M
  setnodevector(L, &newt, nhsize);
716
53.0M
  if (newasize < oldasize) {  /* will array shrink? */
717
    /* re-insert into the new hash the elements from vanishing slice */
718
71.6k
    exchangehashpart(t, &newt);  /* pretend table has new hash */
719
71.6k
    reinsertOldSlice(t, oldasize, newasize);
720
71.6k
    exchangehashpart(t, &newt);  /* restore old hash (in case of errors) */
721
71.6k
  }
722
  /* allocate new array */
723
53.0M
  newarray = resizearray(L, t, oldasize, newasize);
724
53.0M
  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
53.0M
  exchangehashpart(t, &newt);  /* 't' has the new hash ('newt' has the old) */
730
53.0M
  t->array = newarray;  /* set new array part */
731
53.0M
  t->asize = newasize;
732
53.0M
  if (newarray != NULL)
733
6.96M
    *lenhint(t) = newasize / 2u;  /* set an initial hint */
734
53.0M
  clearNewSlice(t, oldasize, newasize);
735
  /* re-insert elements from old hash part into new parts */
736
53.0M
  reinserthash(L, &newt, t);  /* 'newt' now has the old hash */
737
53.0M
  freehash(L, &newt);  /* free old hash part */
738
53.0M
}
739
740
741
132k
void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
742
132k
  unsigned nsize = allocsizenode(t);
743
132k
  luaH_resize(L, t, nasize, nsize);
744
132k
}
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
44.5M
static void rehash (lua_State *L, Table *t, const TValue *ek) {
753
44.5M
  unsigned asize;  /* optimal size for array part */
754
44.5M
  Counters ct;
755
44.5M
  unsigned i;
756
44.5M
  unsigned nsize;  /* size for the hash part */
757
  /* reset counts */
758
1.46G
  for (i = 0; i <= MAXABITS; i++) ct.nums[i] = 0;
759
44.5M
  ct.na = 0;
760
44.5M
  ct.deleted = 0;
761
44.5M
  ct.total = 1;  /* count extra key */
762
44.5M
  if (ttisinteger(ek))
763
1.32M
    countint(ivalue(ek), &ct);  /* extra key may go to array */
764
44.5M
  numusehash(t, &ct);  /* count keys in hash part */
765
44.5M
  if (ct.na == 0) {
766
    /* no new keys to enter array part; keep it with the same size */
767
42.8M
    asize = t->asize;
768
42.8M
  }
769
1.64M
  else {  /* compute best size for array part */
770
1.64M
    numusearray(t, &ct);  /* count keys in array part */
771
1.64M
    asize = computesizes(&ct);  /* compute new size for array part */
772
1.64M
  }
773
  /* all keys not in the array part go to the hash part */
774
44.5M
  nsize = ct.total - ct.na;
775
44.5M
  if (ct.deleted) {  /* table has deleted entries? */
776
    /* insertion-deletion-insertion: give hash some extra size to
777
       avoid repeated resizings */
778
13.1M
    nsize += nsize >> 2;
779
13.1M
  }
780
  /* resize the table to new computed sizes */
781
44.5M
  luaH_resize(L, t, asize, nsize);
782
44.5M
}
783
784
/*
785
** }=============================================================
786
*/
787
788
789
41.5M
Table *luaH_new (lua_State *L) {
790
41.5M
  GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
791
41.5M
  Table *t = gco2t(o);
792
0
  t->metatable = NULL;
793
41.5M
  t->flags = maskflags;  /* table has no metamethod fields */
794
41.5M
  t->array = NULL;
795
41.5M
  t->asize = 0;
796
41.5M
  setnodevector(L, t, 0);
797
41.5M
  return t;
798
41.5M
}
799
800
801
61.6M
lu_mem luaH_size (Table *t) {
802
61.6M
  lu_mem sz = cast(lu_mem, sizeof(Table)) + concretesize(t->asize);
803
61.6M
  if (!isdummy(t))
804
30.1M
    sz += sizehash(t);
805
61.6M
  return sz;
806
61.6M
}
807
808
809
/*
810
** Frees a table.
811
*/
812
41.5M
void luaH_free (lua_State *L, Table *t) {
813
41.5M
  freehash(L, t);
814
41.5M
  resizearray(L, t, t->asize, 0);
815
41.5M
  luaM_free(L, t);
816
41.5M
}
817
818
819
183M
static Node *getfreepos (Table *t) {
820
183M
  if (haslastfree(t)) {  /* does it have 'lastfree' information? */
821
    /* look for a spot before 'lastfree', updating 'lastfree' */
822
161M
    while (getlastfree(t) > t->node) {
823
151M
      Node *free = --getlastfree(t);
824
151M
      if (keyisnil(free))
825
78.4M
        return free;
826
151M
    }
827
89.2M
  }
828
93.9M
  else {  /* no 'lastfree' information */
829
93.9M
    unsigned i = sizenode(t);
830
245M
    while (i--) {  /* do a linear search */
831
170M
      Node *free = gnode(t, i);
832
170M
      if (keyisnil(free))
833
18.1M
        return free;
834
170M
    }
835
93.9M
  }
836
86.6M
  return NULL;  /* could not find a free place */
837
183M
}
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
341M
static int insertkey (Table *t, const TValue *key, TValue *value) {
850
341M
  Node *mp = mainpositionTV(t, key);
851
  /* table cannot already contain the key */
852
341M
  lua_assert(isabstkey(getgeneric(t, key, 0)));
853
341M
  if (!isempty(gval(mp)) || isdummy(t)) {  /* main position is taken? */
854
183M
    Node *othern;
855
183M
    Node *f = getfreepos(t);  /* get a free place */
856
183M
    if (f == NULL)  /* cannot find a free place? */
857
86.6M
      return 0;
858
96.5M
    lua_assert(!isdummy(t));
859
96.5M
    othern = mainpositionfromnode(t, mp);
860
96.5M
    if (othern != mp) {  /* is colliding node out of its main position? */
861
      /* yes; move colliding node into free position */
862
23.7M
      while (othern + gnext(othern) != mp)  /* find previous */
863
3.60M
        othern += gnext(othern);
864
20.0M
      gnext(othern) = cast_int(f - othern);  /* rechain to point to 'f' */
865
20.0M
      *f = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
866
20.0M
      if (gnext(mp) != 0) {
867
3.05M
        gnext(f) += cast_int(mp - f);  /* correct 'next' */
868
3.05M
        gnext(mp) = 0;  /* now 'mp' is free */
869
3.05M
      }
870
20.0M
      setempty(gval(mp));
871
20.0M
    }
872
76.4M
    else {  /* colliding node is in its own main position */
873
      /* new node will go into free position */
874
76.4M
      if (gnext(mp) != 0)
875
16.5M
        gnext(f) = cast_int((mp + gnext(mp)) - f);  /* chain new position */
876
76.4M
      else lua_assert(gnext(f) == 0);
877
76.4M
      gnext(mp) = cast_int(f - mp);
878
76.4M
      mp = f;
879
76.4M
    }
880
96.5M
  }
881
254M
  setnodekey(mp, key);
882
254M
  lua_assert(isempty(gval(mp)));
883
509M
  setobj2t(cast(lua_State *, 0), gval(mp), value);
884
254M
  return 1;
885
509M
}
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
170M
static void newcheckedkey (Table *t, const TValue *key, TValue *value) {
893
170M
  unsigned i = keyinarray(t, key);
894
170M
  if (i > 0)  /* is key in the array part? */
895
785k
    obj2arr(t, i - 1, value);  /* set value in the array */
896
169M
  else {
897
169M
    int done = insertkey(t, key, value);  /* insert key in the hash part */
898
169M
    lua_assert(done);  /* it cannot fail */
899
169M
    cast(void, done);  /* to avoid warnings */
900
169M
  }
901
170M
}
902
903
904
static void luaH_newkey (lua_State *L, Table *t, const TValue *key,
905
54.8M
                                                 TValue *value) {
906
54.8M
  if (!ttisnil(value)) {  /* do not insert nil values */
907
51.6M
    int done = insertkey(t, key, value);
908
51.6M
    if (!done) {  /* could not find a free place? */
909
44.5M
      rehash(L, t, key);  /* grow table */
910
44.5M
      newcheckedkey(t, key, value);  /* insert key in grown table */
911
44.5M
    }
912
51.6M
    luaC_barrierback(L, obj2gco(t), key);
913
    /* for debugging only: any new key may force an emergency collection */
914
51.6M
    condchangemem(L, (void)0, (void)0, 1);
915
51.6M
  }
916
54.8M
}
917
918
919
28.5M
static const TValue *getintfromhash (Table *t, lua_Integer key) {
920
28.5M
  Node *n = hashint(t, key);
921
28.5M
  lua_assert(!ikeyinarray(t, key));
922
34.2M
  for (;;) {  /* check whether 'key' is somewhere in the chain */
923
34.2M
    if (keyisinteger(n) && keyival(n) == key)
924
7.21M
      return gval(n);  /* that's it */
925
27.0M
    else {
926
27.0M
      int nx = gnext(n);
927
27.0M
      if (nx == 0) break;
928
5.76M
      n += nx;
929
5.76M
    }
930
34.2M
  }
931
21.3M
  return &absentkey;
932
28.5M
}
933
934
935
8.89M
static int hashkeyisempty (Table *t, lua_Unsigned key) {
936
8.89M
  const TValue *val = getintfromhash(t, l_castU2S(key));
937
8.89M
  return isempty(val);
938
8.89M
}
939
940
941
673M
static lu_byte finishnodeget (const TValue *val, TValue *res) {
942
673M
  if (!ttisnil(val)) {
943
520M
    setobj(((lua_State*)NULL), res, val);
944
520M
  }
945
673M
  return ttypetag(val);
946
673M
}
947
948
949
17.6M
lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res) {
950
17.6M
  unsigned k = ikeyinarray(t, key);
951
17.6M
  if (k > 0) {
952
5.62M
    lu_byte tag = *getArrTag(t, k - 1);
953
5.62M
    if (!tagisempty(tag))
954
5.60M
      farr2val(t, k - 1, tag, res);
955
5.62M
    return tag;
956
5.62M
  }
957
12.0M
  else
958
12.0M
    return finishnodeget(getintfromhash(t, key), res);
959
17.6M
}
960
961
962
/*
963
** search function for short strings
964
*/
965
944M
const TValue *luaH_Hgetshortstr (Table *t, TString *key) {
966
944M
  Node *n = hashstr(t, key);
967
944M
  lua_assert(strisshr(key));
968
1.20G
  for (;;) {  /* check whether 'key' is somewhere in the chain */
969
1.20G
    if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
970
635M
      return gval(n);  /* that's it */
971
572M
    else {
972
572M
      int nx = gnext(n);
973
572M
      if (nx == 0)
974
308M
        return &absentkey;  /* not found */
975
263M
      n += nx;
976
263M
    }
977
1.20G
  }
978
944M
}
979
980
981
292M
lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res) {
982
292M
  return finishnodeget(luaH_Hgetshortstr(t, key), res);
983
292M
}
984
985
986
2.82M
static const TValue *Hgetlongstr (Table *t, TString *key) {
987
2.82M
  TValue ko;
988
2.82M
  lua_assert(!strisshr(key));
989
5.64M
  setsvalue(cast(lua_State *, NULL), &ko, key);
990
2.82M
  return getgeneric(t, &ko, 0);  /* for long strings, use generic case */
991
5.64M
}
992
993
994
206M
static const TValue *Hgetstr (Table *t, TString *key) {
995
206M
  if (strisshr(key))
996
204M
    return luaH_Hgetshortstr(t, key);
997
2.82M
  else
998
2.82M
    return Hgetlongstr(t, key);
999
206M
}
1000
1001
1002
206M
lu_byte luaH_getstr (Table *t, TString *key, TValue *res) {
1003
206M
  return finishnodeget(Hgetstr(t, key), res);
1004
206M
}
1005
1006
1007
/*
1008
** main search function
1009
*/
1010
174M
lu_byte luaH_get (Table *t, const TValue *key, TValue *res) {
1011
174M
  const TValue *slot;
1012
174M
  switch (ttypetag(key)) {
1013
148M
    case LUA_VSHRSTR:
1014
148M
      slot = luaH_Hgetshortstr(t, tsvalue(key));
1015
0
      break;
1016
11.9M
    case LUA_VNUMINT:
1017
11.9M
      return luaH_getint(t, ivalue(key), res);
1018
13.8k
    case LUA_VNIL:
1019
13.8k
      slot = &absentkey;
1020
13.8k
      break;
1021
6.06M
    case LUA_VNUMFLT: {
1022
6.06M
      lua_Integer k;
1023
6.06M
      if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
1024
11.2k
        return luaH_getint(t, k, res);  /* use specialized version */
1025
      /* else... */
1026
6.06M
    }  /* FALLTHROUGH */
1027
13.6M
    default:
1028
13.6M
      slot = getgeneric(t, key, 0);
1029
13.6M
      break;
1030
174M
  }
1031
162M
  return finishnodeget(slot, res);
1032
174M
}
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
55.7M
static int retpsetcode (Table *t, const TValue *slot) {
1040
55.7M
  if (isabstkey(slot))
1041
54.9M
    return HNOTFOUND;  /* no slot with that key */
1042
840k
  else  /* return node encoded */
1043
840k
    return cast_int((cast(Node*, slot) - t->node)) + HFIRSTNODE;
1044
55.7M
}
1045
1046
1047
15.0M
static int finishnodeset (Table *t, const TValue *slot, TValue *val) {
1048
15.0M
  if (!ttisnil(slot)) {
1049
2.91M
    setobj(((lua_State*)NULL), cast(TValue*, slot), val);
1050
2.91M
    return HOK;  /* success */
1051
2.91M
  }
1052
12.1M
  else
1053
12.1M
    return retpsetcode(t, slot);
1054
15.0M
}
1055
1056
1057
568k
static int rawfinishnodeset (const TValue *slot, TValue *val) {
1058
568k
  if (isabstkey(slot))
1059
204k
    return 0;  /* no slot with that key */
1060
363k
  else {
1061
363k
    setobj(((lua_State*)NULL), cast(TValue*, slot), val);
1062
363k
    return 1;  /* success */
1063
363k
  }
1064
568k
}
1065
1066
1067
6.99M
int luaH_psetint (Table *t, lua_Integer key, TValue *val) {
1068
6.99M
  lua_assert(!ikeyinarray(t, key));
1069
6.99M
  return finishnodeset(t, getintfromhash(t, key), val);
1070
6.99M
}
1071
1072
1073
1.98M
static int psetint (Table *t, lua_Integer key, TValue *val) {
1074
1.98M
  int hres;
1075
1.98M
  luaH_fastseti(t, key, val, hres);
1076
1.98M
  return hres;
1077
1.98M
}
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
198M
int luaH_psetshortstr (Table *t, TString *key, TValue *val) {
1089
198M
  const TValue *slot = luaH_Hgetshortstr(t, key);
1090
198M
  if (!ttisnil(slot)) {  /* key already has a value? (all too common) */
1091
27.5M
    setobj(((lua_State*)NULL), cast(TValue*, slot), val);  /* update it */
1092
27.5M
    return HOK;  /* done */
1093
27.5M
  }
1094
170M
  else if (checknoTM(t->metatable, TM_NEWINDEX)) {  /* no metamethod? */
1095
170M
    if (ttisnil(val))  /* new value is nil? */
1096
48.9M
      return HOK;  /* done (value is already nil/absent) */
1097
121M
    if (isabstkey(slot) &&  /* key is absent? */
1098
121M
       !(isblack(t) && iswhite(key))) {  /* and don't need barrier? */
1099
120M
      TValue tk;  /* key as a TValue */
1100
120M
      setsvalue(cast(lua_State *, NULL), &tk, key);
1101
120M
      if (insertkey(t, &tk, val)) {  /* insert key, if there is space */
1102
78.2M
        invalidateTMcache(t);
1103
78.2M
        return HOK;
1104
78.2M
      }
1105
120M
    }
1106
121M
  }
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
43.6M
  return retpsetcode(t, slot);
1111
198M
}
1112
1113
1114
70.9M
int luaH_psetstr (Table *t, TString *key, TValue *val) {
1115
70.9M
  if (strisshr(key))
1116
70.9M
    return luaH_psetshortstr(t, key, val);
1117
70
  else
1118
70
    return finishnodeset(t, Hgetlongstr(t, key), val);
1119
70.9M
}
1120
1121
1122
54.8M
int luaH_pset (Table *t, const TValue *key, TValue *val) {
1123
54.8M
  switch (ttypetag(key)) {
1124
44.7M
    case LUA_VSHRSTR: return luaH_psetshortstr(t, tsvalue(key), val);
1125
1.78M
    case LUA_VNUMINT: return psetint(t, ivalue(key), val);
1126
109k
    case LUA_VNIL: return HNOTFOUND;
1127
3.34M
    case LUA_VNUMFLT: {
1128
3.34M
      lua_Integer k;
1129
3.34M
      if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
1130
200k
        return psetint(t, k, val);  /* use specialized version */
1131
      /* else... */
1132
3.34M
    }  /* FALLTHROUGH */
1133
8.05M
    default:
1134
8.05M
      return finishnodeset(t, getgeneric(t, key, 0), val);
1135
54.8M
  }
1136
54.8M
}
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
55.5M
                                    TValue *value, int hres) {
1146
55.5M
  lua_assert(hres != HOK);
1147
55.5M
  if (hres == HNOTFOUND) {
1148
54.7M
    TValue aux;
1149
54.7M
    if (l_unlikely(ttisnil(key)))
1150
11.2k
      luaG_runerror(L, "table index is nil");
1151
54.6M
    else if (ttisfloat(key)) {
1152
3.22M
      lua_Number f = fltvalue(key);
1153
0
      lua_Integer k;
1154
3.22M
      if (luaV_flttointeger(f, &k, F2Ieq)) {
1155
92.6k
        setivalue(&aux, k);  /* key is equal to an integer */
1156
92.6k
        key = &aux;  /* insert it as an integer */
1157
92.6k
      }
1158
3.13M
      else if (l_unlikely(luai_numisnan(f)))
1159
488
        luaG_runerror(L, "table index is NaN");
1160
3.22M
    }
1161
54.6M
    luaH_newkey(L, t, key, value);
1162
54.6M
  }
1163
846k
  else if (hres > 0) {  /* regular Node? */
1164
816k
    setobj2t(L, gval(gnode(t, hres - HFIRSTNODE)), value);
1165
816k
  }
1166
30.3k
  else {  /* array entry */
1167
30.3k
    hres = ~hres;  /* real index */
1168
30.3k
    obj2arr(t, cast_uint(hres), value);
1169
30.3k
  }
1170
55.5M
}
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
49.5M
void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
1178
49.5M
  int hres = luaH_pset(t, key, value);
1179
49.5M
  if (hres != HOK)
1180
27.3M
    luaH_finishset(L, t, key, value, hres);
1181
49.5M
}
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.61M
void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
1189
1.61M
  unsigned ik = ikeyinarray(t, key);
1190
1.61M
  if (ik > 0)
1191
1.04M
    obj2arr(t, ik - 1, value);
1192
568k
  else {
1193
568k
    int ok = rawfinishnodeset(getintfromhash(t, key), value);
1194
568k
    if (!ok) {
1195
204k
      TValue k;
1196
204k
      setivalue(&k, key);
1197
204k
      luaH_newkey(L, t, &k, value);
1198
204k
    }
1199
568k
  }
1200
1.61M
}
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
470k
static lua_Unsigned hash_search (Table *t, lua_Unsigned j) {
1217
470k
  lua_Unsigned i;
1218
470k
  if (j == 0) j++;  /* the caller ensures 'j + 1' is present */
1219
580k
  do {
1220
580k
    i = j;  /* 'i' is a present index */
1221
580k
    if (j <= l_castS2U(LUA_MAXINTEGER) / 2)
1222
580k
      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
580k
  } while (!hashkeyisempty(t, j));  /* repeat until an absent t[j] */
1231
  /* i < j  &&  t[i] present  &&  t[j] absent */
1232
6.97M
  while (j - i > 1u) {  /* do a binary search between them */
1233
6.49M
    lua_Unsigned m = (i + j) / 2;
1234
6.49M
    if (hashkeyisempty(t, m)) j = m;
1235
2.76M
    else i = m;
1236
6.49M
  }
1237
470k
  return i;
1238
470k
}
1239
1240
1241
94.5k
static unsigned int binsearch (Table *array, unsigned int i, unsigned int j) {
1242
94.5k
  lua_assert(i <= j);
1243
104k
  while (j - i > 1u) {  /* binary search */
1244
9.64k
    unsigned int m = (i + j) / 2;
1245
9.64k
    if (arraykeyisempty(array, m)) j = m;
1246
3.10k
    else i = m;
1247
9.64k
  }
1248
94.5k
  return i;
1249
94.5k
}
1250
1251
1252
/* return a border, saving it as a hint for next call */
1253
6.85M
static lua_Unsigned newhint (Table *t, unsigned hint) {
1254
6.85M
  lua_assert(hint <= t->asize);
1255
6.85M
  *lenhint(t) = hint;
1256
6.85M
  return hint;
1257
6.85M
}
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
11.5M
lua_Unsigned luaH_getn (Table *t) {
1272
11.5M
  unsigned asize = t->asize;
1273
11.5M
  if (asize > 0) {  /* is there an array part? */
1274
7.40M
    const unsigned maxvicinity = 4;
1275
7.40M
    unsigned limit = *lenhint(t);  /* start with the hint */
1276
7.40M
    if (limit == 0)
1277
124k
      limit = 1;  /* make limit a valid index in the array */
1278
7.40M
    if (arraykeyisempty(t, limit)) {  /* t[limit] empty? */
1279
      /* there must be a border before 'limit' */
1280
144k
      unsigned i;
1281
      /* look for a border in the vicinity of the hint */
1282
158k
      for (i = 0; i < maxvicinity && limit > 1; i++) {
1283
64.8k
        limit--;
1284
64.8k
        if (!arraykeyisempty(t, limit))
1285
51.3k
          return newhint(t, limit);  /* 'limit' is a border */
1286
64.8k
      }
1287
      /* t[limit] still empty; search for a border in [0, limit) */
1288
93.4k
      return newhint(t, binsearch(t, 0, limit));
1289
144k
    }
1290
7.26M
    else {  /* 'limit' is present in table; look for a border after it */
1291
7.26M
      unsigned i;
1292
      /* look for a border in the vicinity of the hint */
1293
11.6M
      for (i = 0; i < maxvicinity && limit < asize; i++) {
1294
11.1M
        limit++;
1295
11.1M
        if (arraykeyisempty(t, limit))
1296
6.71M
          return newhint(t, limit - 1);  /* 'limit - 1' is a border */
1297
11.1M
      }
1298
550k
      if (arraykeyisempty(t, asize)) {  /* last element empty? */
1299
        /* t[limit] not empty; search for a border in [limit, asize) */
1300
1.10k
        return newhint(t, binsearch(t, limit, asize));
1301
1.10k
      }
1302
550k
    }
1303
    /* last element non empty; set a hint to speed up finding that again */
1304
    /* (keys in the hash part cannot be hints) */
1305
549k
    *lenhint(t) = asize;
1306
549k
  }
1307
  /* no array part or t[asize] is not empty; check the hash part */
1308
4.64M
  lua_assert(asize == 0 || !arraykeyisempty(t, asize));
1309
4.64M
  if (isdummy(t) || hashkeyisempty(t, asize + 1))
1310
4.17M
    return asize;  /* 'asize + 1' is empty */
1311
470k
  else  /* 'asize + 1' is also non empty */
1312
470k
    return hash_search(t, asize);
1313
4.64M
}
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