1 /*
2 ** $Lua: ltablib.c,v 1.80 2015/01/13 16:27:29 roberto Exp $
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 
16 #include "lua.h"
17 
18 #include "lauxlib.h"
19 #include "lualib.h"
20 
21 
22 
23 /*
24 ** Structure with table-access functions
25 */
26 typedef struct {
27   int (*geti) (lua_State *L, int idx, lua_Integer n);
28   void (*seti) (lua_State *L, int idx, lua_Integer n);
29 } TabA;
30 
31 
32 /*
33 ** Check that 'arg' has a table and set access functions in 'ta' to raw
34 ** or non-raw according to the presence of corresponding metamethods.
35 */
checktab(lua_State * L,int arg,TabA * ta)36 static void checktab (lua_State *L, int arg, TabA *ta) {
37   ta->geti = NULL; ta->seti = NULL;
38   if (lua_getmetatable(L, arg)) {
39     lua_pushliteral(L, "__index");  /* 'index' metamethod */
40     if (lua_rawget(L, -2) != LUA_TNIL)
41       ta->geti = lua_geti;
42     lua_pushliteral(L, "__newindex");  /* 'newindex' metamethod */
43     if (lua_rawget(L, -3) != LUA_TNIL)
44       ta->seti = lua_seti;
45     lua_pop(L, 3);  /* pop metatable plus both metamethods */
46   }
47   if (ta->geti == NULL || ta->seti == NULL) {
48     luaL_checktype(L, arg, LUA_TTABLE);  /* must be table for raw methods */
49     if (ta->geti == NULL) ta->geti = lua_rawgeti;
50     if (ta->seti == NULL) ta->seti = lua_rawseti;
51   }
52 }
53 
54 
55 #define aux_getn(L,n,ta)	(checktab(L, n, ta), luaL_len(L, n))
56 
57 
58 #if defined(LUA_COMPAT_MAXN)
maxn(lua_State * L)59 static int maxn (lua_State *L) {
60   lua_Number max = 0;
61   luaL_checktype(L, 1, LUA_TTABLE);
62   lua_pushnil(L);  /* first key */
63   while (lua_next(L, 1)) {
64     lua_pop(L, 1);  /* remove value */
65     if (lua_type(L, -1) == LUA_TNUMBER) {
66       lua_Number v = lua_tonumber(L, -1);
67       if (v > max) max = v;
68     }
69   }
70   lua_pushnumber(L, max);
71   return 1;
72 }
73 #endif
74 
75 
tinsert(lua_State * L)76 static int tinsert (lua_State *L) {
77   TabA ta;
78   lua_Integer e = aux_getn(L, 1, &ta) + 1;  /* first empty element */
79   lua_Integer pos;  /* where to insert new element */
80   switch (lua_gettop(L)) {
81     case 2: {  /* called with only 2 arguments */
82       pos = e;  /* insert new element at the end */
83       break;
84     }
85     case 3: {
86       lua_Integer i;
87       pos = luaL_checkinteger(L, 2);  /* 2nd argument is the position */
88       luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds");
89       for (i = e; i > pos; i--) {  /* move up elements */
90         (*ta.geti)(L, 1, i - 1);
91         (*ta.seti)(L, 1, i);  /* t[i] = t[i - 1] */
92       }
93       break;
94     }
95     default: {
96       return luaL_error(L, "wrong number of arguments to 'insert'");
97     }
98   }
99   (*ta.seti)(L, 1, pos);  /* t[pos] = v */
100   return 0;
101 }
102 
103 
tremove(lua_State * L)104 static int tremove (lua_State *L) {
105   TabA ta;
106   lua_Integer size = aux_getn(L, 1, &ta);
107   lua_Integer pos = luaL_optinteger(L, 2, size);
108   if (pos != size)  /* validate 'pos' if given */
109     luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds");
110   (*ta.geti)(L, 1, pos);  /* result = t[pos] */
111   for ( ; pos < size; pos++) {
112     (*ta.geti)(L, 1, pos + 1);
113     (*ta.seti)(L, 1, pos);  /* t[pos] = t[pos + 1] */
114   }
115   lua_pushnil(L);
116   (*ta.seti)(L, 1, pos);  /* t[pos] = nil */
117   return 1;
118 }
119 
120 
tmove(lua_State * L)121 static int tmove (lua_State *L) {
122   TabA ta;
123   lua_Integer f = luaL_checkinteger(L, 2);
124   lua_Integer e = luaL_checkinteger(L, 3);
125   lua_Integer t = luaL_checkinteger(L, 4);
126   int tt = !lua_isnoneornil(L, 5) ? 5 : 1;  /* destination table */
127   if (e >= f) {  /* otherwise, nothing to move */
128     lua_Integer n, i;
129     ta.geti = (luaL_getmetafield(L, 1, "__index") == LUA_TNIL)
130       ? (luaL_checktype(L, 1, LUA_TTABLE), lua_rawgeti)
131       : lua_geti;
132     ta.seti = (luaL_getmetafield(L, tt, "__newindex") == LUA_TNIL)
133       ? (luaL_checktype(L, tt, LUA_TTABLE), lua_rawseti)
134       : lua_seti;
135     luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3,
136                   "too many elements to move");
137     n = e - f + 1;  /* number of elements to move */
138     luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4,
139                   "destination wrap around");
140     if (t > f) {
141       for (i = n - 1; i >= 0; i--) {
142         (*ta.geti)(L, 1, f + i);
143         (*ta.seti)(L, tt, t + i);
144       }
145     }
146     else {
147       for (i = 0; i < n; i++) {
148         (*ta.geti)(L, 1, f + i);
149         (*ta.seti)(L, tt, t + i);
150       }
151     }
152   }
153   lua_pushvalue(L, tt);  /* return "to table" */
154   return 1;
155 }
156 
157 
addfield(lua_State * L,luaL_Buffer * b,TabA * ta,lua_Integer i)158 static void addfield (lua_State *L, luaL_Buffer *b, TabA *ta, lua_Integer i) {
159   (*ta->geti)(L, 1, i);
160   if (!lua_isstring(L, -1))
161     luaL_error(L, "invalid value (%s) at index %d in table for 'concat'",
162                   luaL_typename(L, -1), i);
163   luaL_addvalue(b);
164 }
165 
166 
tconcat(lua_State * L)167 static int tconcat (lua_State *L) {
168   TabA ta;
169   luaL_Buffer b;
170   size_t lsep;
171   lua_Integer i, last;
172   const char *sep = luaL_optlstring(L, 2, "", &lsep);
173   checktab(L, 1, &ta);
174   i = luaL_optinteger(L, 3, 1);
175   last = luaL_opt(L, luaL_checkinteger, 4, luaL_len(L, 1));
176   luaL_buffinit(L, &b);
177   for (; i < last; i++) {
178     addfield(L, &b, &ta, i);
179     luaL_addlstring(&b, sep, lsep);
180   }
181   if (i == last)  /* add last value (if interval was not empty) */
182     addfield(L, &b, &ta, i);
183   luaL_pushresult(&b);
184   return 1;
185 }
186 
187 
188 /*
189 ** {======================================================
190 ** Pack/unpack
191 ** =======================================================
192 */
193 
pack(lua_State * L)194 static int pack (lua_State *L) {
195   int i;
196   int n = lua_gettop(L);  /* number of elements to pack */
197   lua_createtable(L, n, 1);  /* create result table */
198   lua_insert(L, 1);  /* put it at index 1 */
199   for (i = n; i >= 1; i--)  /* assign elements */
200     lua_rawseti(L, 1, i);
201   lua_pushinteger(L, n);
202   lua_setfield(L, 1, "n");  /* t.n = number of elements */
203   return 1;  /* return table */
204 }
205 
206 
unpack(lua_State * L)207 static int unpack (lua_State *L) {
208   TabA ta;
209   lua_Integer i, e;
210   lua_Unsigned n;
211   checktab(L, 1, &ta);
212   i = luaL_optinteger(L, 2, 1);
213   e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
214   if (i > e) return 0;  /* empty range */
215   n = (lua_Unsigned)e - i;  /* number of elements minus 1 (avoid overflows) */
216   if (n >= (unsigned int)INT_MAX  || !lua_checkstack(L, (int)(++n)))
217     return luaL_error(L, "too many results to unpack");
218   do {  /* must have at least one element */
219     (*ta.geti)(L, 1, i);  /* push arg[i..e] */
220   } while (i++ < e);
221 
222   return (int)n;
223 }
224 
225 /* }====================================================== */
226 
227 
228 
229 /*
230 ** {======================================================
231 ** Quicksort
232 ** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
233 **  Addison-Wesley, 1993.)
234 ** =======================================================
235 */
236 
237 
set2(lua_State * L,TabA * ta,int i,int j)238 static void set2 (lua_State *L, TabA *ta, int i, int j) {
239   (*ta->seti)(L, 1, i);
240   (*ta->seti)(L, 1, j);
241 }
242 
sort_comp(lua_State * L,int a,int b)243 static int sort_comp (lua_State *L, int a, int b) {
244   if (!lua_isnil(L, 2)) {  /* function? */
245     int res;
246     lua_pushvalue(L, 2);
247     lua_pushvalue(L, a-1);  /* -1 to compensate function */
248     lua_pushvalue(L, b-2);  /* -2 to compensate function and 'a' */
249     lua_call(L, 2, 1);
250     res = lua_toboolean(L, -1);
251     lua_pop(L, 1);
252     return res;
253   }
254   else  /* a < b? */
255     return lua_compare(L, a, b, LUA_OPLT);
256 }
257 
auxsort(lua_State * L,TabA * ta,int l,int u)258 static void auxsort (lua_State *L, TabA *ta, int l, int u) {
259   while (l < u) {  /* for tail recursion */
260     int i, j;
261     /* sort elements a[l], a[(l+u)/2] and a[u] */
262     (*ta->geti)(L, 1, l);
263     (*ta->geti)(L, 1, u);
264     if (sort_comp(L, -1, -2))  /* a[u] < a[l]? */
265       set2(L, ta, l, u);  /* swap a[l] - a[u] */
266     else
267       lua_pop(L, 2);
268     if (u-l == 1) break;  /* only 2 elements */
269     i = (l+u)/2;
270     (*ta->geti)(L, 1, i);
271     (*ta->geti)(L, 1, l);
272     if (sort_comp(L, -2, -1))  /* a[i]<a[l]? */
273       set2(L, ta, i, l);
274     else {
275       lua_pop(L, 1);  /* remove a[l] */
276       (*ta->geti)(L, 1, u);
277       if (sort_comp(L, -1, -2))  /* a[u]<a[i]? */
278         set2(L, ta, i, u);
279       else
280         lua_pop(L, 2);
281     }
282     if (u-l == 2) break;  /* only 3 elements */
283     (*ta->geti)(L, 1, i);  /* Pivot */
284     lua_pushvalue(L, -1);
285     (*ta->geti)(L, 1, u-1);
286     set2(L, ta, i, u-1);
287     /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
288     i = l; j = u-1;
289     for (;;) {  /* invariant: a[l..i] <= P <= a[j..u] */
290       /* repeat ++i until a[i] >= P */
291       while ((*ta->geti)(L, 1, ++i), sort_comp(L, -1, -2)) {
292         if (i>=u) luaL_error(L, "invalid order function for sorting");
293         lua_pop(L, 1);  /* remove a[i] */
294       }
295       /* repeat --j until a[j] <= P */
296       while ((*ta->geti)(L, 1, --j), sort_comp(L, -3, -1)) {
297         if (j<=l) luaL_error(L, "invalid order function for sorting");
298         lua_pop(L, 1);  /* remove a[j] */
299       }
300       if (j<i) {
301         lua_pop(L, 3);  /* pop pivot, a[i], a[j] */
302         break;
303       }
304       set2(L, ta, i, j);
305     }
306     (*ta->geti)(L, 1, u-1);
307     (*ta->geti)(L, 1, i);
308     set2(L, ta, u-1, i);  /* swap pivot (a[u-1]) with a[i] */
309     /* a[l..i-1] <= a[i] == P <= a[i+1..u] */
310     /* adjust so that smaller half is in [j..i] and larger one in [l..u] */
311     if (i-l < u-i) {
312       j=l; i=i-1; l=i+2;
313     }
314     else {
315       j=i+1; i=u; u=j-2;
316     }
317     auxsort(L, ta, j, i);  /* call recursively the smaller one */
318   }  /* repeat the routine for the larger one */
319 }
320 
sort(lua_State * L)321 static int sort (lua_State *L) {
322   TabA ta;
323   int n = (int)aux_getn(L, 1, &ta);
324   luaL_checkstack(L, 50, "");  /* assume array is smaller than 2^50 */
325   if (!lua_isnoneornil(L, 2))  /* is there a 2nd argument? */
326     luaL_checktype(L, 2, LUA_TFUNCTION);
327   lua_settop(L, 2);  /* make sure there are two arguments */
328   auxsort(L, &ta, 1, n);
329   return 0;
330 }
331 
332 /* }====================================================== */
333 
334 
335 static const luaL_Reg tab_funcs[] = {
336   {"concat", tconcat},
337 #if defined(LUA_COMPAT_MAXN)
338   {"maxn", maxn},
339 #endif
340   {"insert", tinsert},
341   {"pack", pack},
342   {"unpack", unpack},
343   {"remove", tremove},
344   {"move", tmove},
345   {"sort", sort},
346   {NULL, NULL}
347 };
348 
349 
luaopen_table(lua_State * L)350 LUAMOD_API int luaopen_table (lua_State *L) {
351   luaL_newlib(L, tab_funcs);
352 #if defined(LUA_COMPAT_UNPACK)
353   /* _G.unpack = table.unpack */
354   lua_getfield(L, -1, "unpack");
355   lua_setglobal(L, "unpack");
356 #endif
357   return 1;
358 }
359 
360