ltablib.c 13 KB

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