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