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