Coverage Report

Created: 2024-04-23 06:32

/src/testdir/build/lua-master/source/ltablib.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
** $Id: ltablib.c $
3
** Library for Table Manipulation
4
** See Copyright Notice in lua.h
5
*/
6
7
#define ltablib_c
8
#define LUA_LIB
9
10
#include "lprefix.h"
11
12
13
#include <limits.h>
14
#include <stddef.h>
15
#include <string.h>
16
17
#include "lua.h"
18
19
#include "lauxlib.h"
20
#include "lualib.h"
21
22
23
/*
24
** Operations that an object must define to mimic a table
25
** (some functions only need some of them)
26
*/
27
0
#define TAB_R 1      /* read */
28
0
#define TAB_W 2      /* write */
29
0
#define TAB_L 4      /* length */
30
#define TAB_RW  (TAB_R | TAB_W)   /* read/write */
31
32
33
0
#define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n))
34
35
36
0
static int checkfield (lua_State *L, const char *key, int n) {
37
0
  lua_pushstring(L, key);
38
0
  return (lua_rawget(L, -n) != LUA_TNIL);
39
0
}
40
41
42
/*
43
** Check that 'arg' either is a table or can behave like one (that is,
44
** has a metatable with the required metamethods)
45
*/
46
0
static void checktab (lua_State *L, int arg, int what) {
47
0
  if (lua_type(L, arg) != LUA_TTABLE) {  /* is it not a table? */
48
0
    int n = 1;  /* number of elements to pop */
49
0
    if (lua_getmetatable(L, arg) &&  /* must have metatable */
50
0
        (!(what & TAB_R) || checkfield(L, "__index", ++n)) &&
51
0
        (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) &&
52
0
        (!(what & TAB_L) || checkfield(L, "__len", ++n))) {
53
0
      lua_pop(L, n);  /* pop metatable and tested metamethods */
54
0
    }
55
0
    else
56
0
      luaL_checktype(L, arg, LUA_TTABLE);  /* force an error */
57
0
  }
58
0
}
59
60
61
0
static int tcreate (lua_State *L) {
62
0
  lua_Unsigned sizeseq = (lua_Unsigned)luaL_checkinteger(L, 1);
63
0
  lua_Unsigned sizerest = (lua_Unsigned)luaL_optinteger(L, 2, 0);
64
0
  luaL_argcheck(L, sizeseq <= UINT_MAX, 1, "out of range");
65
0
  luaL_argcheck(L, sizerest <= UINT_MAX, 2, "out of range");
66
0
  lua_createtable(L, (unsigned)sizeseq, (unsigned)sizerest);
67
0
  return 1;
68
0
}
69
70
71
0
static int tinsert (lua_State *L) {
72
0
  lua_Integer pos;  /* where to insert new element */
73
0
  lua_Integer e = aux_getn(L, 1, TAB_RW);
74
0
  e = luaL_intop(+, e, 1);  /* first empty element */
75
0
  switch (lua_gettop(L)) {
76
0
    case 2: {  /* called with only 2 arguments */
77
0
      pos = e;  /* insert new element at the end */
78
0
      break;
79
0
    }
80
0
    case 3: {
81
0
      lua_Integer i;
82
0
      pos = luaL_checkinteger(L, 2);  /* 2nd argument is the position */
83
      /* check whether 'pos' is in [1, e] */
84
0
      luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2,
85
0
                       "position out of bounds");
86
0
      for (i = e; i > pos; i--) {  /* move up elements */
87
0
        lua_geti(L, 1, i - 1);
88
0
        lua_seti(L, 1, i);  /* t[i] = t[i - 1] */
89
0
      }
90
0
      break;
91
0
    }
92
0
    default: {
93
0
      return luaL_error(L, "wrong number of arguments to 'insert'");
94
0
    }
95
0
  }
96
0
  lua_seti(L, 1, pos);  /* t[pos] = v */
97
0
  return 0;
98
0
}
99
100
101
0
static int tremove (lua_State *L) {
102
0
  lua_Integer size = aux_getn(L, 1, TAB_RW);
103
0
  lua_Integer pos = luaL_optinteger(L, 2, size);
104
0
  if (pos != size)  /* validate 'pos' if given */
105
    /* check whether 'pos' is in [1, size + 1] */
106
0
    luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 2,
107
0
                     "position out of bounds");
108
0
  lua_geti(L, 1, pos);  /* result = t[pos] */
109
0
  for ( ; pos < size; pos++) {
110
0
    lua_geti(L, 1, pos + 1);
111
0
    lua_seti(L, 1, pos);  /* t[pos] = t[pos + 1] */
112
0
  }
113
0
  lua_pushnil(L);
114
0
  lua_seti(L, 1, pos);  /* remove entry t[pos] */
115
0
  return 1;
116
0
}
117
118
119
/*
120
** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever
121
** possible, copy in increasing order, which is better for rehashing.
122
** "possible" means destination after original range, or smaller
123
** than origin, or copying to another table.
124
*/
125
0
static int tmove (lua_State *L) {
126
0
  lua_Integer f = luaL_checkinteger(L, 2);
127
0
  lua_Integer e = luaL_checkinteger(L, 3);
128
0
  lua_Integer t = luaL_checkinteger(L, 4);
129
0
  int tt = !lua_isnoneornil(L, 5) ? 5 : 1;  /* destination table */
130
0
  checktab(L, 1, TAB_R);
131
0
  checktab(L, tt, TAB_W);
132
0
  if (e >= f) {  /* otherwise, nothing to move */
133
0
    lua_Integer n, i;
134
0
    luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3,
135
0
                  "too many elements to move");
136
0
    n = e - f + 1;  /* number of elements to move */
137
0
    luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4,
138
0
                  "destination wrap around");
139
0
    if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) {
140
0
      for (i = 0; i < n; i++) {
141
0
        lua_geti(L, 1, f + i);
142
0
        lua_seti(L, tt, t + i);
143
0
      }
144
0
    }
145
0
    else {
146
0
      for (i = n - 1; i >= 0; i--) {
147
0
        lua_geti(L, 1, f + i);
148
0
        lua_seti(L, tt, t + i);
149
0
      }
150
0
    }
151
0
  }
152
0
  lua_pushvalue(L, tt);  /* return destination table */
153
0
  return 1;
154
0
}
155
156
157
0
static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {
158
0
  lua_geti(L, 1, i);
159
0
  if (l_unlikely(!lua_isstring(L, -1)))
160
0
    luaL_error(L, "invalid value (%s) at index %I in table for 'concat'",
161
0
                  luaL_typename(L, -1), (LUAI_UACINT)i);
162
0
  luaL_addvalue(b);
163
0
}
164
165
166
0
static int tconcat (lua_State *L) {
167
0
  luaL_Buffer b;
168
0
  lua_Integer last = aux_getn(L, 1, TAB_R);
169
0
  size_t lsep;
170
0
  const char *sep = luaL_optlstring(L, 2, "", &lsep);
171
0
  lua_Integer i = luaL_optinteger(L, 3, 1);
172
0
  last = luaL_optinteger(L, 4, last);
173
0
  luaL_buffinit(L, &b);
174
0
  for (; i < last; i++) {
175
0
    addfield(L, &b, i);
176
0
    luaL_addlstring(&b, sep, lsep);
177
0
  }
178
0
  if (i == last)  /* add last value (if interval was not empty) */
179
0
    addfield(L, &b, i);
180
0
  luaL_pushresult(&b);
181
0
  return 1;
182
0
}
183
184
185
/*
186
** {======================================================
187
** Pack/unpack
188
** =======================================================
189
*/
190
191
0
static int tpack (lua_State *L) {
192
0
  int i;
193
0
  int n = lua_gettop(L);  /* number of elements to pack */
194
0
  lua_createtable(L, n, 1);  /* create result table */
195
0
  lua_insert(L, 1);  /* put it at index 1 */
196
0
  for (i = n; i >= 1; i--)  /* assign elements */
197
0
    lua_seti(L, 1, i);
198
0
  lua_pushinteger(L, n);
199
0
  lua_setfield(L, 1, "n");  /* t.n = number of elements */
200
0
  return 1;  /* return table */
201
0
}
202
203
204
0
static int tunpack (lua_State *L) {
205
0
  lua_Unsigned n;
206
0
  lua_Integer i = luaL_optinteger(L, 2, 1);
207
0
  lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
208
0
  if (i > e) return 0;  /* empty range */
209
0
  n = (lua_Unsigned)e - i;  /* number of elements minus 1 (avoid overflows) */
210
0
  if (l_unlikely(n >= (unsigned int)INT_MAX  ||
211
0
                 !lua_checkstack(L, (int)(++n))))
212
0
    return luaL_error(L, "too many results to unpack");
213
0
  for (; i < e; i++) {  /* push arg[i..e - 1] (to avoid overflows) */
214
0
    lua_geti(L, 1, i);
215
0
  }
216
0
  lua_geti(L, 1, e);  /* push last element */
217
0
  return (int)n;
218
0
}
219
220
/* }====================================================== */
221
222
223
224
/*
225
** {======================================================
226
** Quicksort
227
** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
228
**  Addison-Wesley, 1993.)
229
** =======================================================
230
*/
231
232
233
/* type for array indices */
234
typedef unsigned int IdxT;
235
236
237
/*
238
** Produce a "random" 'unsigned int' to randomize pivot choice. This
239
** macro is used only when 'sort' detects a big imbalance in the result
240
** of a partition. (If you don't want/need this "randomness", ~0 is a
241
** good choice.)
242
*/
243
#if !defined(l_randomizePivot)
244
0
#define l_randomizePivot(L) luaL_makeseed(L)
245
#endif          /* } */
246
247
248
/* arrays larger than 'RANLIMIT' may use randomized pivots */
249
0
#define RANLIMIT  100u
250
251
252
0
static void set2 (lua_State *L, IdxT i, IdxT j) {
253
0
  lua_seti(L, 1, i);
254
0
  lua_seti(L, 1, j);
255
0
}
256
257
258
/*
259
** Return true iff value at stack index 'a' is less than the value at
260
** index 'b' (according to the order of the sort).
261
*/
262
0
static int sort_comp (lua_State *L, int a, int b) {
263
0
  if (lua_isnil(L, 2))  /* no function? */
264
0
    return lua_compare(L, a, b, LUA_OPLT);  /* a < b */
265
0
  else {  /* function */
266
0
    int res;
267
0
    lua_pushvalue(L, 2);    /* push function */
268
0
    lua_pushvalue(L, a-1);  /* -1 to compensate function */
269
0
    lua_pushvalue(L, b-2);  /* -2 to compensate function and 'a' */
270
0
    lua_call(L, 2, 1);      /* call function */
271
0
    res = lua_toboolean(L, -1);  /* get result */
272
0
    lua_pop(L, 1);          /* pop result */
273
0
    return res;
274
0
  }
275
0
}
276
277
278
/*
279
** Does the partition: Pivot P is at the top of the stack.
280
** precondition: a[lo] <= P == a[up-1] <= a[up],
281
** so it only needs to do the partition from lo + 1 to up - 2.
282
** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up]
283
** returns 'i'.
284
*/
285
0
static IdxT partition (lua_State *L, IdxT lo, IdxT up) {
286
0
  IdxT i = lo;  /* will be incremented before first use */
287
0
  IdxT j = up - 1;  /* will be decremented before first use */
288
  /* loop invariant: a[lo .. i] <= P <= a[j .. up] */
289
0
  for (;;) {
290
    /* next loop: repeat ++i while a[i] < P */
291
0
    while ((void)lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) {
292
0
      if (l_unlikely(i == up - 1))  /* a[i] < P  but a[up - 1] == P  ?? */
293
0
        luaL_error(L, "invalid order function for sorting");
294
0
      lua_pop(L, 1);  /* remove a[i] */
295
0
    }
296
    /* after the loop, a[i] >= P and a[lo .. i - 1] < P */
297
    /* next loop: repeat --j while P < a[j] */
298
0
    while ((void)lua_geti(L, 1, --j), sort_comp(L, -3, -1)) {
299
0
      if (l_unlikely(j < i))  /* j < i  but  a[j] > P ?? */
300
0
        luaL_error(L, "invalid order function for sorting");
301
0
      lua_pop(L, 1);  /* remove a[j] */
302
0
    }
303
    /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */
304
0
    if (j < i) {  /* no elements out of place? */
305
      /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */
306
0
      lua_pop(L, 1);  /* pop a[j] */
307
      /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */
308
0
      set2(L, up - 1, i);
309
0
      return i;
310
0
    }
311
    /* otherwise, swap a[i] - a[j] to restore invariant and repeat */
312
0
    set2(L, i, j);
313
0
  }
314
0
}
315
316
317
/*
318
** Choose an element in the middle (2nd-3th quarters) of [lo,up]
319
** "randomized" by 'rnd'
320
*/
321
0
static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) {
322
0
  IdxT r4 = (up - lo) / 4;  /* range/4 */
323
0
  IdxT p = (rnd ^ lo ^ up) % (r4 * 2) + (lo + r4);
324
0
  lua_assert(lo + r4 <= p && p <= up - r4);
325
0
  return p;
326
0
}
327
328
329
/*
330
** Quicksort algorithm (recursive function)
331
*/
332
0
static void auxsort (lua_State *L, IdxT lo, IdxT up, unsigned rnd) {
333
0
  while (lo < up) {  /* loop for tail recursion */
334
0
    IdxT p;  /* Pivot index */
335
0
    IdxT n;  /* to be used later */
336
    /* sort elements 'lo', 'p', and 'up' */
337
0
    lua_geti(L, 1, lo);
338
0
    lua_geti(L, 1, up);
339
0
    if (sort_comp(L, -1, -2))  /* a[up] < a[lo]? */
340
0
      set2(L, lo, up);  /* swap a[lo] - a[up] */
341
0
    else
342
0
      lua_pop(L, 2);  /* remove both values */
343
0
    if (up - lo == 1)  /* only 2 elements? */
344
0
      return;  /* already sorted */
345
0
    if (up - lo < RANLIMIT || rnd == 0)  /* small interval or no randomize? */
346
0
      p = (lo + up)/2;  /* middle element is a good pivot */
347
0
    else  /* for larger intervals, it is worth a random pivot */
348
0
      p = choosePivot(lo, up, rnd);
349
0
    lua_geti(L, 1, p);
350
0
    lua_geti(L, 1, lo);
351
0
    if (sort_comp(L, -2, -1))  /* a[p] < a[lo]? */
352
0
      set2(L, p, lo);  /* swap a[p] - a[lo] */
353
0
    else {
354
0
      lua_pop(L, 1);  /* remove a[lo] */
355
0
      lua_geti(L, 1, up);
356
0
      if (sort_comp(L, -1, -2))  /* a[up] < a[p]? */
357
0
        set2(L, p, up);  /* swap a[up] - a[p] */
358
0
      else
359
0
        lua_pop(L, 2);
360
0
    }
361
0
    if (up - lo == 2)  /* only 3 elements? */
362
0
      return;  /* already sorted */
363
0
    lua_geti(L, 1, p);  /* get middle element (Pivot) */
364
0
    lua_pushvalue(L, -1);  /* push Pivot */
365
0
    lua_geti(L, 1, up - 1);  /* push a[up - 1] */
366
0
    set2(L, p, up - 1);  /* swap Pivot (a[p]) with a[up - 1] */
367
0
    p = partition(L, lo, up);
368
    /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */
369
0
    if (p - lo < up - p) {  /* lower interval is smaller? */
370
0
      auxsort(L, lo, p - 1, rnd);  /* call recursively for lower interval */
371
0
      n = p - lo;  /* size of smaller interval */
372
0
      lo = p + 1;  /* tail call for [p + 1 .. up] (upper interval) */
373
0
    }
374
0
    else {
375
0
      auxsort(L, p + 1, up, rnd);  /* call recursively for upper interval */
376
0
      n = up - p;  /* size of smaller interval */
377
0
      up = p - 1;  /* tail call for [lo .. p - 1]  (lower interval) */
378
0
    }
379
0
    if ((up - lo) / 128 > n) /* partition too imbalanced? */
380
0
      rnd = l_randomizePivot(L);  /* try a new randomization */
381
0
  }  /* tail call auxsort(L, lo, up, rnd) */
382
0
}
383
384
385
0
static int sort (lua_State *L) {
386
0
  lua_Integer n = aux_getn(L, 1, TAB_RW);
387
0
  if (n > 1) {  /* non-trivial interval? */
388
0
    luaL_argcheck(L, n < INT_MAX, 1, "array too big");
389
0
    if (!lua_isnoneornil(L, 2))  /* is there a 2nd argument? */
390
0
      luaL_checktype(L, 2, LUA_TFUNCTION);  /* must be a function */
391
0
    lua_settop(L, 2);  /* make sure there are two arguments */
392
0
    auxsort(L, 1, (IdxT)n, 0);
393
0
  }
394
0
  return 0;
395
0
}
396
397
/* }====================================================== */
398
399
400
static const luaL_Reg tab_funcs[] = {
401
  {"concat", tconcat},
402
  {"create", tcreate},
403
  {"insert", tinsert},
404
  {"pack", tpack},
405
  {"unpack", tunpack},
406
  {"remove", tremove},
407
  {"move", tmove},
408
  {"sort", sort},
409
  {NULL, NULL}
410
};
411
412
413
4.53k
LUAMOD_API int luaopen_table (lua_State *L) {
414
4.53k
  luaL_newlib(L, tab_funcs);
415
4.53k
  return 1;
416
4.53k
}
417