/*1** $Id: ltablib.c $2** Library for Table Manipulation3** See Copyright Notice in lua.h4*/56#define ltablib_c7#define LUA_LIB89#include "lprefix.h"101112#include <limits.h>13#include <stddef.h>14#include <string.h>1516#include "lua.h"1718#include "lauxlib.h"19#include "lualib.h"202122/*23** Operations that an object must define to mimic a table24** (some functions only need some of them)25*/26#define TAB_R 1 /* read */27#define TAB_W 2 /* write */28#define TAB_L 4 /* length */29#define TAB_RW (TAB_R | TAB_W) /* read/write */303132#define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n))333435static int checkfield (lua_State *L, const char *key, int n) {36lua_pushstring(L, key);37return (lua_rawget(L, -n) != LUA_TNIL);38}394041/*42** Check that 'arg' either is a table or can behave like one (that is,43** has a metatable with the required metamethods)44*/45static void checktab (lua_State *L, int arg, int what) {46if (lua_type(L, arg) != LUA_TTABLE) { /* is it not a table? */47int n = 1; /* number of elements to pop */48if (lua_getmetatable(L, arg) && /* must have metatable */49(!(what & TAB_R) || checkfield(L, "__index", ++n)) &&50(!(what & TAB_W) || checkfield(L, "__newindex", ++n)) &&51(!(what & TAB_L) || checkfield(L, "__len", ++n))) {52lua_pop(L, n); /* pop metatable and tested metamethods */53}54else55luaL_checktype(L, arg, LUA_TTABLE); /* force an error */56}57}585960static int tinsert (lua_State *L) {61lua_Integer pos; /* where to insert new element */62lua_Integer e = aux_getn(L, 1, TAB_RW);63e = luaL_intop(+, e, 1); /* first empty element */64switch (lua_gettop(L)) {65case 2: { /* called with only 2 arguments */66pos = e; /* insert new element at the end */67break;68}69case 3: {70lua_Integer i;71pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */72/* check whether 'pos' is in [1, e] */73luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2,74"position out of bounds");75for (i = e; i > pos; i--) { /* move up elements */76lua_geti(L, 1, i - 1);77lua_seti(L, 1, i); /* t[i] = t[i - 1] */78}79break;80}81default: {82return luaL_error(L, "wrong number of arguments to 'insert'");83}84}85lua_seti(L, 1, pos); /* t[pos] = v */86return 0;87}888990static int tremove (lua_State *L) {91lua_Integer size = aux_getn(L, 1, TAB_RW);92lua_Integer pos = luaL_optinteger(L, 2, size);93if (pos != size) /* validate 'pos' if given */94/* check whether 'pos' is in [1, size + 1] */95luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 2,96"position out of bounds");97lua_geti(L, 1, pos); /* result = t[pos] */98for ( ; pos < size; pos++) {99lua_geti(L, 1, pos + 1);100lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */101}102lua_pushnil(L);103lua_seti(L, 1, pos); /* remove entry t[pos] */104return 1;105}106107108/*109** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever110** possible, copy in increasing order, which is better for rehashing.111** "possible" means destination after original range, or smaller112** than origin, or copying to another table.113*/114static int tmove (lua_State *L) {115lua_Integer f = luaL_checkinteger(L, 2);116lua_Integer e = luaL_checkinteger(L, 3);117lua_Integer t = luaL_checkinteger(L, 4);118int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */119checktab(L, 1, TAB_R);120checktab(L, tt, TAB_W);121if (e >= f) { /* otherwise, nothing to move */122lua_Integer n, i;123luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3,124"too many elements to move");125n = e - f + 1; /* number of elements to move */126luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4,127"destination wrap around");128if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) {129for (i = 0; i < n; i++) {130lua_geti(L, 1, f + i);131lua_seti(L, tt, t + i);132}133}134else {135for (i = n - 1; i >= 0; i--) {136lua_geti(L, 1, f + i);137lua_seti(L, tt, t + i);138}139}140}141lua_pushvalue(L, tt); /* return destination table */142return 1;143}144145146static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {147lua_geti(L, 1, i);148if (l_unlikely(!lua_isstring(L, -1)))149luaL_error(L, "invalid value (%s) at index %I in table for 'concat'",150luaL_typename(L, -1), (LUAI_UACINT)i);151luaL_addvalue(b);152}153154155static int tconcat (lua_State *L) {156luaL_Buffer b;157lua_Integer last = aux_getn(L, 1, TAB_R);158size_t lsep;159const char *sep = luaL_optlstring(L, 2, "", &lsep);160lua_Integer i = luaL_optinteger(L, 3, 1);161last = luaL_optinteger(L, 4, last);162luaL_buffinit(L, &b);163for (; i < last; i++) {164addfield(L, &b, i);165luaL_addlstring(&b, sep, lsep);166}167if (i == last) /* add last value (if interval was not empty) */168addfield(L, &b, i);169luaL_pushresult(&b);170return 1;171}172173174/*175** {======================================================176** Pack/unpack177** =======================================================178*/179180static int tpack (lua_State *L) {181int i;182int n = lua_gettop(L); /* number of elements to pack */183lua_createtable(L, n, 1); /* create result table */184lua_insert(L, 1); /* put it at index 1 */185for (i = n; i >= 1; i--) /* assign elements */186lua_seti(L, 1, i);187lua_pushinteger(L, n);188lua_setfield(L, 1, "n"); /* t.n = number of elements */189return 1; /* return table */190}191192193static int tunpack (lua_State *L) {194lua_Unsigned n;195lua_Integer i = luaL_optinteger(L, 2, 1);196lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));197if (i > e) return 0; /* empty range */198n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */199if (l_unlikely(n >= (unsigned int)INT_MAX ||200!lua_checkstack(L, (int)(++n))))201return luaL_error(L, "too many results to unpack");202for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */203lua_geti(L, 1, i);204}205lua_geti(L, 1, e); /* push last element */206return (int)n;207}208209/* }====================================================== */210211212213/*214** {======================================================215** Quicksort216** (based on 'Algorithms in MODULA-3', Robert Sedgewick;217** Addison-Wesley, 1993.)218** =======================================================219*/220221222/* type for array indices */223typedef unsigned int IdxT;224225226/*227** Produce a "random" 'unsigned int' to randomize pivot choice. This228** macro is used only when 'sort' detects a big imbalance in the result229** of a partition. (If you don't want/need this "randomness", ~0 is a230** good choice.)231*/232#if !defined(l_randomizePivot) /* { */233234#include <time.h>235236/* size of 'e' measured in number of 'unsigned int's */237#define sof(e) (sizeof(e) / sizeof(unsigned int))238239/*240** Use 'time' and 'clock' as sources of "randomness". Because we don't241** know the types 'clock_t' and 'time_t', we cannot cast them to242** anything without risking overflows. A safe way to use their values243** is to copy them to an array of a known type and use the array values.244*/245static unsigned int l_randomizePivot (void) {246clock_t c = clock();247time_t t = time(NULL);248unsigned int buff[sof(c) + sof(t)];249unsigned int i, rnd = 0;250memcpy(buff, &c, sof(c) * sizeof(unsigned int));251memcpy(buff + sof(c), &t, sof(t) * sizeof(unsigned int));252for (i = 0; i < sof(buff); i++)253rnd += buff[i];254return rnd;255}256257#endif /* } */258259260/* arrays larger than 'RANLIMIT' may use randomized pivots */261#define RANLIMIT 100u262263264static void set2 (lua_State *L, IdxT i, IdxT j) {265lua_seti(L, 1, i);266lua_seti(L, 1, j);267}268269270/*271** Return true iff value at stack index 'a' is less than the value at272** index 'b' (according to the order of the sort).273*/274static int sort_comp (lua_State *L, int a, int b) {275if (lua_isnil(L, 2)) /* no function? */276return lua_compare(L, a, b, LUA_OPLT); /* a < b */277else { /* function */278int res;279lua_pushvalue(L, 2); /* push function */280lua_pushvalue(L, a-1); /* -1 to compensate function */281lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */282lua_call(L, 2, 1); /* call function */283res = lua_toboolean(L, -1); /* get result */284lua_pop(L, 1); /* pop result */285return res;286}287}288289290/*291** Does the partition: Pivot P is at the top of the stack.292** precondition: a[lo] <= P == a[up-1] <= a[up],293** so it only needs to do the partition from lo + 1 to up - 2.294** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up]295** returns 'i'.296*/297static IdxT partition (lua_State *L, IdxT lo, IdxT up) {298IdxT i = lo; /* will be incremented before first use */299IdxT j = up - 1; /* will be decremented before first use */300/* loop invariant: a[lo .. i] <= P <= a[j .. up] */301for (;;) {302/* next loop: repeat ++i while a[i] < P */303while ((void)lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) {304if (l_unlikely(i == up - 1)) /* a[i] < P but a[up - 1] == P ?? */305luaL_error(L, "invalid order function for sorting");306lua_pop(L, 1); /* remove a[i] */307}308/* after the loop, a[i] >= P and a[lo .. i - 1] < P */309/* next loop: repeat --j while P < a[j] */310while ((void)lua_geti(L, 1, --j), sort_comp(L, -3, -1)) {311if (l_unlikely(j < i)) /* j < i but a[j] > P ?? */312luaL_error(L, "invalid order function for sorting");313lua_pop(L, 1); /* remove a[j] */314}315/* after the loop, a[j] <= P and a[j + 1 .. up] >= P */316if (j < i) { /* no elements out of place? */317/* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */318lua_pop(L, 1); /* pop a[j] */319/* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */320set2(L, up - 1, i);321return i;322}323/* otherwise, swap a[i] - a[j] to restore invariant and repeat */324set2(L, i, j);325}326}327328329/*330** Choose an element in the middle (2nd-3th quarters) of [lo,up]331** "randomized" by 'rnd'332*/333static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) {334IdxT r4 = (up - lo) / 4; /* range/4 */335IdxT p = rnd % (r4 * 2) + (lo + r4);336lua_assert(lo + r4 <= p && p <= up - r4);337return p;338}339340341/*342** Quicksort algorithm (recursive function)343*/344static void auxsort (lua_State *L, IdxT lo, IdxT up,345unsigned int rnd) {346while (lo < up) { /* loop for tail recursion */347IdxT p; /* Pivot index */348IdxT n; /* to be used later */349/* sort elements 'lo', 'p', and 'up' */350lua_geti(L, 1, lo);351lua_geti(L, 1, up);352if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */353set2(L, lo, up); /* swap a[lo] - a[up] */354else355lua_pop(L, 2); /* remove both values */356if (up - lo == 1) /* only 2 elements? */357return; /* already sorted */358if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */359p = (lo + up)/2; /* middle element is a good pivot */360else /* for larger intervals, it is worth a random pivot */361p = choosePivot(lo, up, rnd);362lua_geti(L, 1, p);363lua_geti(L, 1, lo);364if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */365set2(L, p, lo); /* swap a[p] - a[lo] */366else {367lua_pop(L, 1); /* remove a[lo] */368lua_geti(L, 1, up);369if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */370set2(L, p, up); /* swap a[up] - a[p] */371else372lua_pop(L, 2);373}374if (up - lo == 2) /* only 3 elements? */375return; /* already sorted */376lua_geti(L, 1, p); /* get middle element (Pivot) */377lua_pushvalue(L, -1); /* push Pivot */378lua_geti(L, 1, up - 1); /* push a[up - 1] */379set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */380p = partition(L, lo, up);381/* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */382if (p - lo < up - p) { /* lower interval is smaller? */383auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */384n = p - lo; /* size of smaller interval */385lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */386}387else {388auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */389n = up - p; /* size of smaller interval */390up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */391}392if ((up - lo) / 128 > n) /* partition too imbalanced? */393rnd = l_randomizePivot(); /* try a new randomization */394} /* tail call auxsort(L, lo, up, rnd) */395}396397398static int sort (lua_State *L) {399lua_Integer n = aux_getn(L, 1, TAB_RW);400if (n > 1) { /* non-trivial interval? */401luaL_argcheck(L, n < INT_MAX, 1, "array too big");402if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */403luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */404lua_settop(L, 2); /* make sure there are two arguments */405auxsort(L, 1, (IdxT)n, 0);406}407return 0;408}409410/* }====================================================== */411412413static const luaL_Reg tab_funcs[] = {414{"concat", tconcat},415{"insert", tinsert},416{"pack", tpack},417{"unpack", tunpack},418{"remove", tremove},419{"move", tmove},420{"sort", sort},421{NULL, NULL}422};423424425LUAMOD_API int luaopen_table (lua_State *L) {426luaL_newlib(L, tab_funcs);427return 1;428}429430431432