ltablib.c 13 KB

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