Coverage Report

Created: 2025-07-18 07:03

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