Coverage Report

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