lstrlib.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894
  1. /*
  2. ** $Id: lstrlib.c $
  3. ** Standard library for string operations and pattern-matching
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lstrlib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #include <ctype.h>
  10. #include <float.h>
  11. #include <limits.h>
  12. #include <locale.h>
  13. #include <math.h>
  14. #include <stddef.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include "lua.h"
  19. #include "lauxlib.h"
  20. #include "lualib.h"
  21. #include "llimits.h"
  22. /*
  23. ** maximum number of captures that a pattern can do during
  24. ** pattern-matching. This limit is arbitrary, but must fit in
  25. ** an unsigned char.
  26. */
  27. #if !defined(LUA_MAXCAPTURES)
  28. #define LUA_MAXCAPTURES 32
  29. #endif
  30. static int str_len (lua_State *L) {
  31. size_t l;
  32. luaL_checklstring(L, 1, &l);
  33. lua_pushinteger(L, (lua_Integer)l);
  34. return 1;
  35. }
  36. /*
  37. ** translate a relative initial string position
  38. ** (negative means back from end): clip result to [1, inf).
  39. ** The length of any string in Lua must fit in a lua_Integer,
  40. ** so there are no overflows in the casts.
  41. ** The inverted comparison avoids a possible overflow
  42. ** computing '-pos'.
  43. */
  44. static size_t posrelatI (lua_Integer pos, size_t len) {
  45. if (pos > 0)
  46. return (size_t)pos;
  47. else if (pos == 0)
  48. return 1;
  49. else if (pos < -(lua_Integer)len) /* inverted comparison */
  50. return 1; /* clip to 1 */
  51. else return len + (size_t)pos + 1;
  52. }
  53. /*
  54. ** Gets an optional ending string position from argument 'arg',
  55. ** with default value 'def'.
  56. ** Negative means back from end: clip result to [0, len]
  57. */
  58. static size_t getendpos (lua_State *L, int arg, lua_Integer def,
  59. size_t len) {
  60. lua_Integer pos = luaL_optinteger(L, arg, def);
  61. if (pos > (lua_Integer)len)
  62. return len;
  63. else if (pos >= 0)
  64. return (size_t)pos;
  65. else if (pos < -(lua_Integer)len)
  66. return 0;
  67. else return len + (size_t)pos + 1;
  68. }
  69. static int str_sub (lua_State *L) {
  70. size_t l;
  71. const char *s = luaL_checklstring(L, 1, &l);
  72. size_t start = posrelatI(luaL_checkinteger(L, 2), l);
  73. size_t end = getendpos(L, 3, -1, l);
  74. if (start <= end)
  75. lua_pushlstring(L, s + start - 1, (end - start) + 1);
  76. else lua_pushliteral(L, "");
  77. return 1;
  78. }
  79. static int str_reverse (lua_State *L) {
  80. size_t l, i;
  81. luaL_Buffer b;
  82. const char *s = luaL_checklstring(L, 1, &l);
  83. char *p = luaL_buffinitsize(L, &b, l);
  84. for (i = 0; i < l; i++)
  85. p[i] = s[l - i - 1];
  86. luaL_pushresultsize(&b, l);
  87. return 1;
  88. }
  89. static int str_lower (lua_State *L) {
  90. size_t l;
  91. size_t i;
  92. luaL_Buffer b;
  93. const char *s = luaL_checklstring(L, 1, &l);
  94. char *p = luaL_buffinitsize(L, &b, l);
  95. for (i=0; i<l; i++)
  96. p[i] = cast_char(tolower(cast_uchar(s[i])));
  97. luaL_pushresultsize(&b, l);
  98. return 1;
  99. }
  100. static int str_upper (lua_State *L) {
  101. size_t l;
  102. size_t i;
  103. luaL_Buffer b;
  104. const char *s = luaL_checklstring(L, 1, &l);
  105. char *p = luaL_buffinitsize(L, &b, l);
  106. for (i=0; i<l; i++)
  107. p[i] = cast_char(toupper(cast_uchar(s[i])));
  108. luaL_pushresultsize(&b, l);
  109. return 1;
  110. }
  111. /*
  112. ** MAX_SIZE is limited both by size_t and lua_Integer.
  113. ** When x <= MAX_SIZE, x can be safely cast to size_t or lua_Integer.
  114. */
  115. static int str_rep (lua_State *L) {
  116. size_t len, lsep;
  117. const char *s = luaL_checklstring(L, 1, &len);
  118. lua_Integer n = luaL_checkinteger(L, 2);
  119. const char *sep = luaL_optlstring(L, 3, "", &lsep);
  120. if (n <= 0)
  121. lua_pushliteral(L, "");
  122. else if (l_unlikely(len > MAX_SIZE - lsep ||
  123. cast_st2S(len + lsep) > cast_st2S(MAX_SIZE) / n))
  124. return luaL_error(L, "resulting string too large");
  125. else {
  126. size_t totallen = (cast_sizet(n) * (len + lsep)) - lsep;
  127. luaL_Buffer b;
  128. char *p = luaL_buffinitsize(L, &b, totallen);
  129. while (n-- > 1) { /* first n-1 copies (followed by separator) */
  130. memcpy(p, s, len * sizeof(char)); p += len;
  131. if (lsep > 0) { /* empty 'memcpy' is not that cheap */
  132. memcpy(p, sep, lsep * sizeof(char)); p += lsep;
  133. }
  134. }
  135. memcpy(p, s, len * sizeof(char)); /* last copy without separator */
  136. luaL_pushresultsize(&b, totallen);
  137. }
  138. return 1;
  139. }
  140. static int str_byte (lua_State *L) {
  141. size_t l;
  142. const char *s = luaL_checklstring(L, 1, &l);
  143. lua_Integer pi = luaL_optinteger(L, 2, 1);
  144. size_t posi = posrelatI(pi, l);
  145. size_t pose = getendpos(L, 3, pi, l);
  146. int n, i;
  147. if (posi > pose) return 0; /* empty interval; return no values */
  148. if (l_unlikely(pose - posi >= (size_t)INT_MAX)) /* arithmetic overflow? */
  149. return luaL_error(L, "string slice too long");
  150. n = (int)(pose - posi) + 1;
  151. luaL_checkstack(L, n, "string slice too long");
  152. for (i=0; i<n; i++)
  153. lua_pushinteger(L, cast_uchar(s[posi + cast_uint(i) - 1]));
  154. return n;
  155. }
  156. static int str_char (lua_State *L) {
  157. int n = lua_gettop(L); /* number of arguments */
  158. int i;
  159. luaL_Buffer b;
  160. char *p = luaL_buffinitsize(L, &b, cast_uint(n));
  161. for (i=1; i<=n; i++) {
  162. lua_Unsigned c = (lua_Unsigned)luaL_checkinteger(L, i);
  163. luaL_argcheck(L, c <= (lua_Unsigned)UCHAR_MAX, i, "value out of range");
  164. p[i - 1] = cast_char(cast_uchar(c));
  165. }
  166. luaL_pushresultsize(&b, cast_uint(n));
  167. return 1;
  168. }
  169. /*
  170. ** Buffer to store the result of 'string.dump'. It must be initialized
  171. ** after the call to 'lua_dump', to ensure that the function is on the
  172. ** top of the stack when 'lua_dump' is called. ('luaL_buffinit' might
  173. ** push stuff.)
  174. */
  175. struct str_Writer {
  176. int init; /* true iff buffer has been initialized */
  177. luaL_Buffer B;
  178. };
  179. static int writer (lua_State *L, const void *b, size_t size, void *ud) {
  180. struct str_Writer *state = (struct str_Writer *)ud;
  181. if (!state->init) {
  182. state->init = 1;
  183. luaL_buffinit(L, &state->B);
  184. }
  185. if (b == NULL) { /* finishing dump? */
  186. luaL_pushresult(&state->B); /* push result */
  187. lua_replace(L, 1); /* move it to reserved slot */
  188. }
  189. else
  190. luaL_addlstring(&state->B, (const char *)b, size);
  191. return 0;
  192. }
  193. static int str_dump (lua_State *L) {
  194. struct str_Writer state;
  195. int strip = lua_toboolean(L, 2);
  196. luaL_argcheck(L, lua_type(L, 1) == LUA_TFUNCTION && !lua_iscfunction(L, 1),
  197. 1, "Lua function expected");
  198. /* ensure function is on the top of the stack and vacate slot 1 */
  199. lua_pushvalue(L, 1);
  200. state.init = 0;
  201. lua_dump(L, writer, &state, strip);
  202. lua_settop(L, 1); /* leave final result on top */
  203. return 1;
  204. }
  205. /*
  206. ** {======================================================
  207. ** METAMETHODS
  208. ** =======================================================
  209. */
  210. #if defined(LUA_NOCVTS2N) /* { */
  211. /* no coercion from strings to numbers */
  212. static const luaL_Reg stringmetamethods[] = {
  213. {"__index", NULL}, /* placeholder */
  214. {NULL, NULL}
  215. };
  216. #else /* }{ */
  217. static int tonum (lua_State *L, int arg) {
  218. if (lua_type(L, arg) == LUA_TNUMBER) { /* already a number? */
  219. lua_pushvalue(L, arg);
  220. return 1;
  221. }
  222. else { /* check whether it is a numerical string */
  223. size_t len;
  224. const char *s = lua_tolstring(L, arg, &len);
  225. return (s != NULL && lua_stringtonumber(L, s) == len + 1);
  226. }
  227. }
  228. /*
  229. ** To be here, either the first operand was a string or the first
  230. ** operand didn't have a corresponding metamethod. (Otherwise, that
  231. ** other metamethod would have been called.) So, if this metamethod
  232. ** doesn't work, the only other option would be for the second
  233. ** operand to have a different metamethod.
  234. */
  235. static void trymt (lua_State *L, const char *mtkey, const char *opname) {
  236. lua_settop(L, 2); /* back to the original arguments */
  237. if (l_unlikely(lua_type(L, 2) == LUA_TSTRING ||
  238. !luaL_getmetafield(L, 2, mtkey)))
  239. luaL_error(L, "attempt to %s a '%s' with a '%s'", opname,
  240. luaL_typename(L, -2), luaL_typename(L, -1));
  241. lua_insert(L, -3); /* put metamethod before arguments */
  242. lua_call(L, 2, 1); /* call metamethod */
  243. }
  244. static int arith (lua_State *L, int op, const char *mtname) {
  245. if (tonum(L, 1) && tonum(L, 2))
  246. lua_arith(L, op); /* result will be on the top */
  247. else
  248. trymt(L, mtname, mtname + 2);
  249. return 1;
  250. }
  251. static int arith_add (lua_State *L) {
  252. return arith(L, LUA_OPADD, "__add");
  253. }
  254. static int arith_sub (lua_State *L) {
  255. return arith(L, LUA_OPSUB, "__sub");
  256. }
  257. static int arith_mul (lua_State *L) {
  258. return arith(L, LUA_OPMUL, "__mul");
  259. }
  260. static int arith_mod (lua_State *L) {
  261. return arith(L, LUA_OPMOD, "__mod");
  262. }
  263. static int arith_pow (lua_State *L) {
  264. return arith(L, LUA_OPPOW, "__pow");
  265. }
  266. static int arith_div (lua_State *L) {
  267. return arith(L, LUA_OPDIV, "__div");
  268. }
  269. static int arith_idiv (lua_State *L) {
  270. return arith(L, LUA_OPIDIV, "__idiv");
  271. }
  272. static int arith_unm (lua_State *L) {
  273. return arith(L, LUA_OPUNM, "__unm");
  274. }
  275. static const luaL_Reg stringmetamethods[] = {
  276. {"__add", arith_add},
  277. {"__sub", arith_sub},
  278. {"__mul", arith_mul},
  279. {"__mod", arith_mod},
  280. {"__pow", arith_pow},
  281. {"__div", arith_div},
  282. {"__idiv", arith_idiv},
  283. {"__unm", arith_unm},
  284. {"__index", NULL}, /* placeholder */
  285. {NULL, NULL}
  286. };
  287. #endif /* } */
  288. /* }====================================================== */
  289. /*
  290. ** {======================================================
  291. ** PATTERN MATCHING
  292. ** =======================================================
  293. */
  294. #define CAP_UNFINISHED (-1)
  295. #define CAP_POSITION (-2)
  296. typedef struct MatchState {
  297. const char *src_init; /* init of source string */
  298. const char *src_end; /* end ('\0') of source string */
  299. const char *p_end; /* end ('\0') of pattern */
  300. lua_State *L;
  301. int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
  302. int level; /* total number of captures (finished or unfinished) */
  303. struct {
  304. const char *init;
  305. ptrdiff_t len; /* length or special value (CAP_*) */
  306. } capture[LUA_MAXCAPTURES];
  307. } MatchState;
  308. /* recursive function */
  309. static const char *match (MatchState *ms, const char *s, const char *p);
  310. /* maximum recursion depth for 'match' */
  311. #if !defined(MAXCCALLS)
  312. #define MAXCCALLS 200
  313. #endif
  314. #define L_ESC '%'
  315. #define SPECIALS "^$*+?.([%-"
  316. static int check_capture (MatchState *ms, int l) {
  317. l -= '1';
  318. if (l_unlikely(l < 0 || l >= ms->level ||
  319. ms->capture[l].len == CAP_UNFINISHED))
  320. return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
  321. return l;
  322. }
  323. static int capture_to_close (MatchState *ms) {
  324. int level = ms->level;
  325. for (level--; level>=0; level--)
  326. if (ms->capture[level].len == CAP_UNFINISHED) return level;
  327. return luaL_error(ms->L, "invalid pattern capture");
  328. }
  329. static const char *classend (MatchState *ms, const char *p) {
  330. switch (*p++) {
  331. case L_ESC: {
  332. if (l_unlikely(p == ms->p_end))
  333. luaL_error(ms->L, "malformed pattern (ends with '%%')");
  334. return p+1;
  335. }
  336. case '[': {
  337. if (*p == '^') p++;
  338. do { /* look for a ']' */
  339. if (l_unlikely(p == ms->p_end))
  340. luaL_error(ms->L, "malformed pattern (missing ']')");
  341. if (*(p++) == L_ESC && p < ms->p_end)
  342. p++; /* skip escapes (e.g. '%]') */
  343. } while (*p != ']');
  344. return p+1;
  345. }
  346. default: {
  347. return p;
  348. }
  349. }
  350. }
  351. static int match_class (int c, int cl) {
  352. int res;
  353. switch (tolower(cl)) {
  354. case 'a' : res = isalpha(c); break;
  355. case 'c' : res = iscntrl(c); break;
  356. case 'd' : res = isdigit(c); break;
  357. case 'g' : res = isgraph(c); break;
  358. case 'l' : res = islower(c); break;
  359. case 'p' : res = ispunct(c); break;
  360. case 's' : res = isspace(c); break;
  361. case 'u' : res = isupper(c); break;
  362. case 'w' : res = isalnum(c); break;
  363. case 'x' : res = isxdigit(c); break;
  364. case 'z' : res = (c == 0); break; /* deprecated option */
  365. default: return (cl == c);
  366. }
  367. return (islower(cl) ? res : !res);
  368. }
  369. static int matchbracketclass (int c, const char *p, const char *ec) {
  370. int sig = 1;
  371. if (*(p+1) == '^') {
  372. sig = 0;
  373. p++; /* skip the '^' */
  374. }
  375. while (++p < ec) {
  376. if (*p == L_ESC) {
  377. p++;
  378. if (match_class(c, cast_uchar(*p)))
  379. return sig;
  380. }
  381. else if ((*(p+1) == '-') && (p+2 < ec)) {
  382. p+=2;
  383. if (cast_uchar(*(p-2)) <= c && c <= cast_uchar(*p))
  384. return sig;
  385. }
  386. else if (cast_uchar(*p) == c) return sig;
  387. }
  388. return !sig;
  389. }
  390. static int singlematch (MatchState *ms, const char *s, const char *p,
  391. const char *ep) {
  392. if (s >= ms->src_end)
  393. return 0;
  394. else {
  395. int c = cast_uchar(*s);
  396. switch (*p) {
  397. case '.': return 1; /* matches any char */
  398. case L_ESC: return match_class(c, cast_uchar(*(p+1)));
  399. case '[': return matchbracketclass(c, p, ep-1);
  400. default: return (cast_uchar(*p) == c);
  401. }
  402. }
  403. }
  404. static const char *matchbalance (MatchState *ms, const char *s,
  405. const char *p) {
  406. if (l_unlikely(p >= ms->p_end - 1))
  407. luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
  408. if (*s != *p) return NULL;
  409. else {
  410. int b = *p;
  411. int e = *(p+1);
  412. int cont = 1;
  413. while (++s < ms->src_end) {
  414. if (*s == e) {
  415. if (--cont == 0) return s+1;
  416. }
  417. else if (*s == b) cont++;
  418. }
  419. }
  420. return NULL; /* string ends out of balance */
  421. }
  422. static const char *max_expand (MatchState *ms, const char *s,
  423. const char *p, const char *ep) {
  424. ptrdiff_t i = 0; /* counts maximum expand for item */
  425. while (singlematch(ms, s + i, p, ep))
  426. i++;
  427. /* keeps trying to match with the maximum repetitions */
  428. while (i>=0) {
  429. const char *res = match(ms, (s+i), ep+1);
  430. if (res) return res;
  431. i--; /* else didn't match; reduce 1 repetition to try again */
  432. }
  433. return NULL;
  434. }
  435. static const char *min_expand (MatchState *ms, const char *s,
  436. const char *p, const char *ep) {
  437. for (;;) {
  438. const char *res = match(ms, s, ep+1);
  439. if (res != NULL)
  440. return res;
  441. else if (singlematch(ms, s, p, ep))
  442. s++; /* try with one more repetition */
  443. else return NULL;
  444. }
  445. }
  446. static const char *start_capture (MatchState *ms, const char *s,
  447. const char *p, int what) {
  448. const char *res;
  449. int level = ms->level;
  450. if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
  451. ms->capture[level].init = s;
  452. ms->capture[level].len = what;
  453. ms->level = level+1;
  454. if ((res=match(ms, s, p)) == NULL) /* match failed? */
  455. ms->level--; /* undo capture */
  456. return res;
  457. }
  458. static const char *end_capture (MatchState *ms, const char *s,
  459. const char *p) {
  460. int l = capture_to_close(ms);
  461. const char *res;
  462. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  463. if ((res = match(ms, s, p)) == NULL) /* match failed? */
  464. ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
  465. return res;
  466. }
  467. static const char *match_capture (MatchState *ms, const char *s, int l) {
  468. size_t len;
  469. l = check_capture(ms, l);
  470. len = cast_sizet(ms->capture[l].len);
  471. if ((size_t)(ms->src_end-s) >= len &&
  472. memcmp(ms->capture[l].init, s, len) == 0)
  473. return s+len;
  474. else return NULL;
  475. }
  476. static const char *match (MatchState *ms, const char *s, const char *p) {
  477. if (l_unlikely(ms->matchdepth-- == 0))
  478. luaL_error(ms->L, "pattern too complex");
  479. init: /* using goto to optimize tail recursion */
  480. if (p != ms->p_end) { /* end of pattern? */
  481. switch (*p) {
  482. case '(': { /* start capture */
  483. if (*(p + 1) == ')') /* position capture? */
  484. s = start_capture(ms, s, p + 2, CAP_POSITION);
  485. else
  486. s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
  487. break;
  488. }
  489. case ')': { /* end capture */
  490. s = end_capture(ms, s, p + 1);
  491. break;
  492. }
  493. case '$': {
  494. if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */
  495. goto dflt; /* no; go to default */
  496. s = (s == ms->src_end) ? s : NULL; /* check end of string */
  497. break;
  498. }
  499. case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
  500. switch (*(p + 1)) {
  501. case 'b': { /* balanced string? */
  502. s = matchbalance(ms, s, p + 2);
  503. if (s != NULL) {
  504. p += 4; goto init; /* return match(ms, s, p + 4); */
  505. } /* else fail (s == NULL) */
  506. break;
  507. }
  508. case 'f': { /* frontier? */
  509. const char *ep; char previous;
  510. p += 2;
  511. if (l_unlikely(*p != '['))
  512. luaL_error(ms->L, "missing '[' after '%%f' in pattern");
  513. ep = classend(ms, p); /* points to what is next */
  514. previous = (s == ms->src_init) ? '\0' : *(s - 1);
  515. if (!matchbracketclass(cast_uchar(previous), p, ep - 1) &&
  516. matchbracketclass(cast_uchar(*s), p, ep - 1)) {
  517. p = ep; goto init; /* return match(ms, s, ep); */
  518. }
  519. s = NULL; /* match failed */
  520. break;
  521. }
  522. case '0': case '1': case '2': case '3':
  523. case '4': case '5': case '6': case '7':
  524. case '8': case '9': { /* capture results (%0-%9)? */
  525. s = match_capture(ms, s, cast_uchar(*(p + 1)));
  526. if (s != NULL) {
  527. p += 2; goto init; /* return match(ms, s, p + 2) */
  528. }
  529. break;
  530. }
  531. default: goto dflt;
  532. }
  533. break;
  534. }
  535. default: dflt: { /* pattern class plus optional suffix */
  536. const char *ep = classend(ms, p); /* points to optional suffix */
  537. /* does not match at least once? */
  538. if (!singlematch(ms, s, p, ep)) {
  539. if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
  540. p = ep + 1; goto init; /* return match(ms, s, ep + 1); */
  541. }
  542. else /* '+' or no suffix */
  543. s = NULL; /* fail */
  544. }
  545. else { /* matched once */
  546. switch (*ep) { /* handle optional suffix */
  547. case '?': { /* optional */
  548. const char *res;
  549. if ((res = match(ms, s + 1, ep + 1)) != NULL)
  550. s = res;
  551. else {
  552. p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */
  553. }
  554. break;
  555. }
  556. case '+': /* 1 or more repetitions */
  557. s++; /* 1 match already done */
  558. /* FALLTHROUGH */
  559. case '*': /* 0 or more repetitions */
  560. s = max_expand(ms, s, p, ep);
  561. break;
  562. case '-': /* 0 or more repetitions (minimum) */
  563. s = min_expand(ms, s, p, ep);
  564. break;
  565. default: /* no suffix */
  566. s++; p = ep; goto init; /* return match(ms, s + 1, ep); */
  567. }
  568. }
  569. break;
  570. }
  571. }
  572. }
  573. ms->matchdepth++;
  574. return s;
  575. }
  576. static const char *lmemfind (const char *s1, size_t l1,
  577. const char *s2, size_t l2) {
  578. if (l2 == 0) return s1; /* empty strings are everywhere */
  579. else if (l2 > l1) return NULL; /* avoids a negative 'l1' */
  580. else {
  581. const char *init; /* to search for a '*s2' inside 's1' */
  582. l2--; /* 1st char will be checked by 'memchr' */
  583. l1 = l1-l2; /* 's2' cannot be found after that */
  584. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  585. init++; /* 1st char is already checked */
  586. if (memcmp(init, s2+1, l2) == 0)
  587. return init-1;
  588. else { /* correct 'l1' and 's1' to try again */
  589. l1 -= ct_diff2sz(init - s1);
  590. s1 = init;
  591. }
  592. }
  593. return NULL; /* not found */
  594. }
  595. }
  596. /*
  597. ** get information about the i-th capture. If there are no captures
  598. ** and 'i==0', return information about the whole match, which
  599. ** is the range 's'..'e'. If the capture is a string, return
  600. ** its length and put its address in '*cap'. If it is an integer
  601. ** (a position), push it on the stack and return CAP_POSITION.
  602. */
  603. static ptrdiff_t get_onecapture (MatchState *ms, int i, const char *s,
  604. const char *e, const char **cap) {
  605. if (i >= ms->level) {
  606. if (l_unlikely(i != 0))
  607. luaL_error(ms->L, "invalid capture index %%%d", i + 1);
  608. *cap = s;
  609. return (e - s);
  610. }
  611. else {
  612. ptrdiff_t capl = ms->capture[i].len;
  613. *cap = ms->capture[i].init;
  614. if (l_unlikely(capl == CAP_UNFINISHED))
  615. luaL_error(ms->L, "unfinished capture");
  616. else if (capl == CAP_POSITION)
  617. lua_pushinteger(ms->L,
  618. ct_diff2S(ms->capture[i].init - ms->src_init) + 1);
  619. return capl;
  620. }
  621. }
  622. /*
  623. ** Push the i-th capture on the stack.
  624. */
  625. static void push_onecapture (MatchState *ms, int i, const char *s,
  626. const char *e) {
  627. const char *cap;
  628. ptrdiff_t l = get_onecapture(ms, i, s, e, &cap);
  629. if (l != CAP_POSITION)
  630. lua_pushlstring(ms->L, cap, cast_sizet(l));
  631. /* else position was already pushed */
  632. }
  633. static int push_captures (MatchState *ms, const char *s, const char *e) {
  634. int i;
  635. int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  636. luaL_checkstack(ms->L, nlevels, "too many captures");
  637. for (i = 0; i < nlevels; i++)
  638. push_onecapture(ms, i, s, e);
  639. return nlevels; /* number of strings pushed */
  640. }
  641. /* check whether pattern has no special characters */
  642. static int nospecials (const char *p, size_t l) {
  643. size_t upto = 0;
  644. do {
  645. if (strpbrk(p + upto, SPECIALS))
  646. return 0; /* pattern has a special character */
  647. upto += strlen(p + upto) + 1; /* may have more after \0 */
  648. } while (upto <= l);
  649. return 1; /* no special chars found */
  650. }
  651. static void prepstate (MatchState *ms, lua_State *L,
  652. const char *s, size_t ls, const char *p, size_t lp) {
  653. ms->L = L;
  654. ms->matchdepth = MAXCCALLS;
  655. ms->src_init = s;
  656. ms->src_end = s + ls;
  657. ms->p_end = p + lp;
  658. }
  659. static void reprepstate (MatchState *ms) {
  660. ms->level = 0;
  661. lua_assert(ms->matchdepth == MAXCCALLS);
  662. }
  663. static int str_find_aux (lua_State *L, int find) {
  664. size_t ls, lp;
  665. const char *s = luaL_checklstring(L, 1, &ls);
  666. const char *p = luaL_checklstring(L, 2, &lp);
  667. size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
  668. if (init > ls) { /* start after string's end? */
  669. luaL_pushfail(L); /* cannot find anything */
  670. return 1;
  671. }
  672. /* explicit request or no special characters? */
  673. if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
  674. /* do a plain search */
  675. const char *s2 = lmemfind(s + init, ls - init, p, lp);
  676. if (s2) {
  677. lua_pushinteger(L, ct_diff2S(s2 - s) + 1);
  678. lua_pushinteger(L, cast_st2S(ct_diff2sz(s2 - s) + lp));
  679. return 2;
  680. }
  681. }
  682. else {
  683. MatchState ms;
  684. const char *s1 = s + init;
  685. int anchor = (*p == '^');
  686. if (anchor) {
  687. p++; lp--; /* skip anchor character */
  688. }
  689. prepstate(&ms, L, s, ls, p, lp);
  690. do {
  691. const char *res;
  692. reprepstate(&ms);
  693. if ((res=match(&ms, s1, p)) != NULL) {
  694. if (find) {
  695. lua_pushinteger(L, ct_diff2S(s1 - s) + 1); /* start */
  696. lua_pushinteger(L, ct_diff2S(res - s)); /* end */
  697. return push_captures(&ms, NULL, 0) + 2;
  698. }
  699. else
  700. return push_captures(&ms, s1, res);
  701. }
  702. } while (s1++ < ms.src_end && !anchor);
  703. }
  704. luaL_pushfail(L); /* not found */
  705. return 1;
  706. }
  707. static int str_find (lua_State *L) {
  708. return str_find_aux(L, 1);
  709. }
  710. static int str_match (lua_State *L) {
  711. return str_find_aux(L, 0);
  712. }
  713. /* state for 'gmatch' */
  714. typedef struct GMatchState {
  715. const char *src; /* current position */
  716. const char *p; /* pattern */
  717. const char *lastmatch; /* end of last match */
  718. MatchState ms; /* match state */
  719. } GMatchState;
  720. static int gmatch_aux (lua_State *L) {
  721. GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
  722. const char *src;
  723. gm->ms.L = L;
  724. for (src = gm->src; src <= gm->ms.src_end; src++) {
  725. const char *e;
  726. reprepstate(&gm->ms);
  727. if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {
  728. gm->src = gm->lastmatch = e;
  729. return push_captures(&gm->ms, src, e);
  730. }
  731. }
  732. return 0; /* not found */
  733. }
  734. static int gmatch (lua_State *L) {
  735. size_t ls, lp;
  736. const char *s = luaL_checklstring(L, 1, &ls);
  737. const char *p = luaL_checklstring(L, 2, &lp);
  738. size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
  739. GMatchState *gm;
  740. lua_settop(L, 2); /* keep strings on closure to avoid being collected */
  741. gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);
  742. if (init > ls) /* start after string's end? */
  743. init = ls + 1; /* avoid overflows in 's + init' */
  744. prepstate(&gm->ms, L, s, ls, p, lp);
  745. gm->src = s + init; gm->p = p; gm->lastmatch = NULL;
  746. lua_pushcclosure(L, gmatch_aux, 3);
  747. return 1;
  748. }
  749. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  750. const char *e) {
  751. size_t l;
  752. lua_State *L = ms->L;
  753. const char *news = lua_tolstring(L, 3, &l);
  754. const char *p;
  755. while ((p = (char *)memchr(news, L_ESC, l)) != NULL) {
  756. luaL_addlstring(b, news, ct_diff2sz(p - news));
  757. p++; /* skip ESC */
  758. if (*p == L_ESC) /* '%%' */
  759. luaL_addchar(b, *p);
  760. else if (*p == '0') /* '%0' */
  761. luaL_addlstring(b, s, ct_diff2sz(e - s));
  762. else if (isdigit(cast_uchar(*p))) { /* '%n' */
  763. const char *cap;
  764. ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap);
  765. if (resl == CAP_POSITION)
  766. luaL_addvalue(b); /* add position to accumulated result */
  767. else
  768. luaL_addlstring(b, cap, cast_sizet(resl));
  769. }
  770. else
  771. luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
  772. l -= ct_diff2sz(p + 1 - news);
  773. news = p + 1;
  774. }
  775. luaL_addlstring(b, news, l);
  776. }
  777. /*
  778. ** Add the replacement value to the string buffer 'b'.
  779. ** Return true if the original string was changed. (Function calls and
  780. ** table indexing resulting in nil or false do not change the subject.)
  781. */
  782. static int add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  783. const char *e, int tr) {
  784. lua_State *L = ms->L;
  785. switch (tr) {
  786. case LUA_TFUNCTION: { /* call the function */
  787. int n;
  788. lua_pushvalue(L, 3); /* push the function */
  789. n = push_captures(ms, s, e); /* all captures as arguments */
  790. lua_call(L, n, 1); /* call it */
  791. break;
  792. }
  793. case LUA_TTABLE: { /* index the table */
  794. push_onecapture(ms, 0, s, e); /* first capture is the index */
  795. lua_gettable(L, 3);
  796. break;
  797. }
  798. default: { /* LUA_TNUMBER or LUA_TSTRING */
  799. add_s(ms, b, s, e); /* add value to the buffer */
  800. return 1; /* something changed */
  801. }
  802. }
  803. if (!lua_toboolean(L, -1)) { /* nil or false? */
  804. lua_pop(L, 1); /* remove value */
  805. luaL_addlstring(b, s, ct_diff2sz(e - s)); /* keep original text */
  806. return 0; /* no changes */
  807. }
  808. else if (l_unlikely(!lua_isstring(L, -1)))
  809. return luaL_error(L, "invalid replacement value (a %s)",
  810. luaL_typename(L, -1));
  811. else {
  812. luaL_addvalue(b); /* add result to accumulator */
  813. return 1; /* something changed */
  814. }
  815. }
  816. static int str_gsub (lua_State *L) {
  817. size_t srcl, lp;
  818. const char *src = luaL_checklstring(L, 1, &srcl); /* subject */
  819. const char *p = luaL_checklstring(L, 2, &lp); /* pattern */
  820. const char *lastmatch = NULL; /* end of last match */
  821. int tr = lua_type(L, 3); /* replacement type */
  822. /* max replacements */
  823. lua_Integer max_s = luaL_optinteger(L, 4, cast_st2S(srcl) + 1);
  824. int anchor = (*p == '^');
  825. lua_Integer n = 0; /* replacement count */
  826. int changed = 0; /* change flag */
  827. MatchState ms;
  828. luaL_Buffer b;
  829. luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  830. tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
  831. "string/function/table");
  832. luaL_buffinit(L, &b);
  833. if (anchor) {
  834. p++; lp--; /* skip anchor character */
  835. }
  836. prepstate(&ms, L, src, srcl, p, lp);
  837. while (n < max_s) {
  838. const char *e;
  839. reprepstate(&ms); /* (re)prepare state for new match */
  840. if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */
  841. n++;
  842. changed = add_value(&ms, &b, src, e, tr) | changed;
  843. src = lastmatch = e;
  844. }
  845. else if (src < ms.src_end) /* otherwise, skip one character */
  846. luaL_addchar(&b, *src++);
  847. else break; /* end of subject */
  848. if (anchor) break;
  849. }
  850. if (!changed) /* no changes? */
  851. lua_pushvalue(L, 1); /* return original string */
  852. else { /* something changed */
  853. luaL_addlstring(&b, src, ct_diff2sz(ms.src_end - src));
  854. luaL_pushresult(&b); /* create and return new string */
  855. }
  856. lua_pushinteger(L, n); /* number of substitutions */
  857. return 2;
  858. }
  859. /* }====================================================== */
  860. /*
  861. ** {======================================================
  862. ** STRING FORMAT
  863. ** =======================================================
  864. */
  865. #if !defined(lua_number2strx) /* { */
  866. /*
  867. ** Hexadecimal floating-point formatter
  868. */
  869. #define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char))
  870. /*
  871. ** Number of bits that goes into the first digit. It can be any value
  872. ** between 1 and 4; the following definition tries to align the number
  873. ** to nibble boundaries by making what is left after that first digit a
  874. ** multiple of 4.
  875. */
  876. #define L_NBFD ((l_floatatt(MANT_DIG) - 1)%4 + 1)
  877. /*
  878. ** Add integer part of 'x' to buffer and return new 'x'
  879. */
  880. static lua_Number adddigit (char *buff, unsigned n, lua_Number x) {
  881. lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */
  882. int d = (int)dd;
  883. buff[n] = cast_char(d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */
  884. return x - dd; /* return what is left */
  885. }
  886. static int num2straux (char *buff, unsigned sz, lua_Number x) {
  887. /* if 'inf' or 'NaN', format it like '%g' */
  888. if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL)
  889. return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x);
  890. else if (x == 0) { /* can be -0... */
  891. /* create "0" or "-0" followed by exponent */
  892. return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x);
  893. }
  894. else {
  895. int e;
  896. lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */
  897. unsigned n = 0; /* character count */
  898. if (m < 0) { /* is number negative? */
  899. buff[n++] = '-'; /* add sign */
  900. m = -m; /* make it positive */
  901. }
  902. buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */
  903. m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */
  904. e -= L_NBFD; /* this digit goes before the radix point */
  905. if (m > 0) { /* more digits? */
  906. buff[n++] = lua_getlocaledecpoint(); /* add radix point */
  907. do { /* add as many digits as needed */
  908. m = adddigit(buff, n++, m * 16);
  909. } while (m > 0);
  910. }
  911. n += cast_uint(l_sprintf(buff + n, sz - n, "p%+d", e)); /* add exponent */
  912. lua_assert(n < sz);
  913. return cast_int(n);
  914. }
  915. }
  916. static int lua_number2strx (lua_State *L, char *buff, unsigned sz,
  917. const char *fmt, lua_Number x) {
  918. int n = num2straux(buff, sz, x);
  919. if (fmt[SIZELENMOD] == 'A') {
  920. int i;
  921. for (i = 0; i < n; i++)
  922. buff[i] = cast_char(toupper(cast_uchar(buff[i])));
  923. }
  924. else if (l_unlikely(fmt[SIZELENMOD] != 'a'))
  925. return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented");
  926. return n;
  927. }
  928. #endif /* } */
  929. /*
  930. ** Maximum size for items formatted with '%f'. This size is produced
  931. ** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.',
  932. ** and '\0') + number of decimal digits to represent maxfloat (which
  933. ** is maximum exponent + 1). (99+3+1, adding some extra, 110)
  934. */
  935. #define MAX_ITEMF (110 + l_floatatt(MAX_10_EXP))
  936. /*
  937. ** All formats except '%f' do not need that large limit. The other
  938. ** float formats use exponents, so that they fit in the 99 limit for
  939. ** significant digits; 's' for large strings and 'q' add items directly
  940. ** to the buffer; all integer formats also fit in the 99 limit. The
  941. ** worst case are floats: they may need 99 significant digits, plus
  942. ** '0x', '-', '.', 'e+XXXX', and '\0'. Adding some extra, 120.
  943. */
  944. #define MAX_ITEM 120
  945. /* valid flags in a format specification */
  946. #if !defined(L_FMTFLAGSF)
  947. /* valid flags for a, A, e, E, f, F, g, and G conversions */
  948. #define L_FMTFLAGSF "-+#0 "
  949. /* valid flags for o, x, and X conversions */
  950. #define L_FMTFLAGSX "-#0"
  951. /* valid flags for d and i conversions */
  952. #define L_FMTFLAGSI "-+0 "
  953. /* valid flags for u conversions */
  954. #define L_FMTFLAGSU "-0"
  955. /* valid flags for c, p, and s conversions */
  956. #define L_FMTFLAGSC "-"
  957. #endif
  958. /*
  959. ** Maximum size of each format specification (such as "%-099.99d"):
  960. ** Initial '%', flags (up to 5), width (2), period, precision (2),
  961. ** length modifier (8), conversion specifier, and final '\0', plus some
  962. ** extra.
  963. */
  964. #define MAX_FORMAT 32
  965. static void addquoted (luaL_Buffer *b, const char *s, size_t len) {
  966. luaL_addchar(b, '"');
  967. while (len--) {
  968. if (*s == '"' || *s == '\\' || *s == '\n') {
  969. luaL_addchar(b, '\\');
  970. luaL_addchar(b, *s);
  971. }
  972. else if (iscntrl(cast_uchar(*s))) {
  973. char buff[10];
  974. if (!isdigit(cast_uchar(*(s+1))))
  975. l_sprintf(buff, sizeof(buff), "\\%d", (int)cast_uchar(*s));
  976. else
  977. l_sprintf(buff, sizeof(buff), "\\%03d", (int)cast_uchar(*s));
  978. luaL_addstring(b, buff);
  979. }
  980. else
  981. luaL_addchar(b, *s);
  982. s++;
  983. }
  984. luaL_addchar(b, '"');
  985. }
  986. /*
  987. ** Serialize a floating-point number in such a way that it can be
  988. ** scanned back by Lua. Use hexadecimal format for "common" numbers
  989. ** (to preserve precision); inf, -inf, and NaN are handled separately.
  990. ** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.)
  991. */
  992. static int quotefloat (lua_State *L, char *buff, lua_Number n) {
  993. const char *s; /* for the fixed representations */
  994. if (n == (lua_Number)HUGE_VAL) /* inf? */
  995. s = "1e9999";
  996. else if (n == -(lua_Number)HUGE_VAL) /* -inf? */
  997. s = "-1e9999";
  998. else if (n != n) /* NaN? */
  999. s = "(0/0)";
  1000. else { /* format number as hexadecimal */
  1001. int nb = lua_number2strx(L, buff, MAX_ITEM,
  1002. "%" LUA_NUMBER_FRMLEN "a", n);
  1003. /* ensures that 'buff' string uses a dot as the radix character */
  1004. if (memchr(buff, '.', cast_uint(nb)) == NULL) { /* no dot? */
  1005. char point = lua_getlocaledecpoint(); /* try locale point */
  1006. char *ppoint = (char *)memchr(buff, point, cast_uint(nb));
  1007. if (ppoint) *ppoint = '.'; /* change it to a dot */
  1008. }
  1009. return nb;
  1010. }
  1011. /* for the fixed representations */
  1012. return l_sprintf(buff, MAX_ITEM, "%s", s);
  1013. }
  1014. static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
  1015. switch (lua_type(L, arg)) {
  1016. case LUA_TSTRING: {
  1017. size_t len;
  1018. const char *s = lua_tolstring(L, arg, &len);
  1019. addquoted(b, s, len);
  1020. break;
  1021. }
  1022. case LUA_TNUMBER: {
  1023. char *buff = luaL_prepbuffsize(b, MAX_ITEM);
  1024. int nb;
  1025. if (!lua_isinteger(L, arg)) /* float? */
  1026. nb = quotefloat(L, buff, lua_tonumber(L, arg));
  1027. else { /* integers */
  1028. lua_Integer n = lua_tointeger(L, arg);
  1029. const char *format = (n == LUA_MININTEGER) /* corner case? */
  1030. ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hex */
  1031. : LUA_INTEGER_FMT; /* else use default format */
  1032. nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);
  1033. }
  1034. luaL_addsize(b, cast_uint(nb));
  1035. break;
  1036. }
  1037. case LUA_TNIL: case LUA_TBOOLEAN: {
  1038. luaL_tolstring(L, arg, NULL);
  1039. luaL_addvalue(b);
  1040. break;
  1041. }
  1042. default: {
  1043. luaL_argerror(L, arg, "value has no literal form");
  1044. }
  1045. }
  1046. }
  1047. static const char *get2digits (const char *s) {
  1048. if (isdigit(cast_uchar(*s))) {
  1049. s++;
  1050. if (isdigit(cast_uchar(*s))) s++; /* (2 digits at most) */
  1051. }
  1052. return s;
  1053. }
  1054. /*
  1055. ** Check whether a conversion specification is valid. When called,
  1056. ** first character in 'form' must be '%' and last character must
  1057. ** be a valid conversion specifier. 'flags' are the accepted flags;
  1058. ** 'precision' signals whether to accept a precision.
  1059. */
  1060. static void checkformat (lua_State *L, const char *form, const char *flags,
  1061. int precision) {
  1062. const char *spec = form + 1; /* skip '%' */
  1063. spec += strspn(spec, flags); /* skip flags */
  1064. if (*spec != '0') { /* a width cannot start with '0' */
  1065. spec = get2digits(spec); /* skip width */
  1066. if (*spec == '.' && precision) {
  1067. spec++;
  1068. spec = get2digits(spec); /* skip precision */
  1069. }
  1070. }
  1071. if (!isalpha(cast_uchar(*spec))) /* did not go to the end? */
  1072. luaL_error(L, "invalid conversion specification: '%s'", form);
  1073. }
  1074. /*
  1075. ** Get a conversion specification and copy it to 'form'.
  1076. ** Return the address of its last character.
  1077. */
  1078. static const char *getformat (lua_State *L, const char *strfrmt,
  1079. char *form) {
  1080. /* spans flags, width, and precision ('0' is included as a flag) */
  1081. size_t len = strspn(strfrmt, L_FMTFLAGSF "123456789.");
  1082. len++; /* adds following character (should be the specifier) */
  1083. /* still needs space for '%', '\0', plus a length modifier */
  1084. if (len >= MAX_FORMAT - 10)
  1085. luaL_error(L, "invalid format (too long)");
  1086. *(form++) = '%';
  1087. memcpy(form, strfrmt, len * sizeof(char));
  1088. *(form + len) = '\0';
  1089. return strfrmt + len - 1;
  1090. }
  1091. /*
  1092. ** add length modifier into formats
  1093. */
  1094. static void addlenmod (char *form, const char *lenmod) {
  1095. size_t l = strlen(form);
  1096. size_t lm = strlen(lenmod);
  1097. char spec = form[l - 1];
  1098. strcpy(form + l - 1, lenmod);
  1099. form[l + lm - 1] = spec;
  1100. form[l + lm] = '\0';
  1101. }
  1102. static int str_format (lua_State *L) {
  1103. int top = lua_gettop(L);
  1104. int arg = 1;
  1105. size_t sfl;
  1106. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  1107. const char *strfrmt_end = strfrmt+sfl;
  1108. const char *flags;
  1109. luaL_Buffer b;
  1110. luaL_buffinit(L, &b);
  1111. while (strfrmt < strfrmt_end) {
  1112. if (*strfrmt != L_ESC)
  1113. luaL_addchar(&b, *strfrmt++);
  1114. else if (*++strfrmt == L_ESC)
  1115. luaL_addchar(&b, *strfrmt++); /* %% */
  1116. else { /* format item */
  1117. char form[MAX_FORMAT]; /* to store the format ('%...') */
  1118. unsigned maxitem = MAX_ITEM; /* maximum length for the result */
  1119. char *buff = luaL_prepbuffsize(&b, maxitem); /* to put result */
  1120. int nb = 0; /* number of bytes in result */
  1121. if (++arg > top)
  1122. return luaL_argerror(L, arg, "no value");
  1123. strfrmt = getformat(L, strfrmt, form);
  1124. switch (*strfrmt++) {
  1125. case 'c': {
  1126. checkformat(L, form, L_FMTFLAGSC, 0);
  1127. nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg));
  1128. break;
  1129. }
  1130. case 'd': case 'i':
  1131. flags = L_FMTFLAGSI;
  1132. goto intcase;
  1133. case 'u':
  1134. flags = L_FMTFLAGSU;
  1135. goto intcase;
  1136. case 'o': case 'x': case 'X':
  1137. flags = L_FMTFLAGSX;
  1138. intcase: {
  1139. lua_Integer n = luaL_checkinteger(L, arg);
  1140. checkformat(L, form, flags, 1);
  1141. addlenmod(form, LUA_INTEGER_FRMLEN);
  1142. nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n);
  1143. break;
  1144. }
  1145. case 'a': case 'A':
  1146. checkformat(L, form, L_FMTFLAGSF, 1);
  1147. addlenmod(form, LUA_NUMBER_FRMLEN);
  1148. nb = lua_number2strx(L, buff, maxitem, form,
  1149. luaL_checknumber(L, arg));
  1150. break;
  1151. case 'f':
  1152. maxitem = MAX_ITEMF; /* extra space for '%f' */
  1153. buff = luaL_prepbuffsize(&b, maxitem);
  1154. /* FALLTHROUGH */
  1155. case 'e': case 'E': case 'g': case 'G': {
  1156. lua_Number n = luaL_checknumber(L, arg);
  1157. checkformat(L, form, L_FMTFLAGSF, 1);
  1158. addlenmod(form, LUA_NUMBER_FRMLEN);
  1159. nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n);
  1160. break;
  1161. }
  1162. case 'p': {
  1163. const void *p = lua_topointer(L, arg);
  1164. checkformat(L, form, L_FMTFLAGSC, 0);
  1165. if (p == NULL) { /* avoid calling 'printf' with argument NULL */
  1166. p = "(null)"; /* result */
  1167. form[strlen(form) - 1] = 's'; /* format it as a string */
  1168. }
  1169. nb = l_sprintf(buff, maxitem, form, p);
  1170. break;
  1171. }
  1172. case 'q': {
  1173. if (form[2] != '\0') /* modifiers? */
  1174. return luaL_error(L, "specifier '%%q' cannot have modifiers");
  1175. addliteral(L, &b, arg);
  1176. break;
  1177. }
  1178. case 's': {
  1179. size_t l;
  1180. const char *s = luaL_tolstring(L, arg, &l);
  1181. if (form[2] == '\0') /* no modifiers? */
  1182. luaL_addvalue(&b); /* keep entire string */
  1183. else {
  1184. luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
  1185. checkformat(L, form, L_FMTFLAGSC, 1);
  1186. if (strchr(form, '.') == NULL && l >= 100) {
  1187. /* no precision and string is too long to be formatted */
  1188. luaL_addvalue(&b); /* keep entire string */
  1189. }
  1190. else { /* format the string into 'buff' */
  1191. nb = l_sprintf(buff, maxitem, form, s);
  1192. lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
  1193. }
  1194. }
  1195. break;
  1196. }
  1197. default: { /* also treat cases 'pnLlh' */
  1198. return luaL_error(L, "invalid conversion '%s' to 'format'", form);
  1199. }
  1200. }
  1201. lua_assert(cast_uint(nb) < maxitem);
  1202. luaL_addsize(&b, cast_uint(nb));
  1203. }
  1204. }
  1205. luaL_pushresult(&b);
  1206. return 1;
  1207. }
  1208. /* }====================================================== */
  1209. /*
  1210. ** {======================================================
  1211. ** PACK/UNPACK
  1212. ** =======================================================
  1213. */
  1214. /* value used for padding */
  1215. #if !defined(LUAL_PACKPADBYTE)
  1216. #define LUAL_PACKPADBYTE 0x00
  1217. #endif
  1218. /* maximum size for the binary representation of an integer */
  1219. #define MAXINTSIZE 16
  1220. /* number of bits in a character */
  1221. #define NB CHAR_BIT
  1222. /* mask for one character (NB 1's) */
  1223. #define MC ((1 << NB) - 1)
  1224. /* size of a lua_Integer */
  1225. #define SZINT ((int)sizeof(lua_Integer))
  1226. /* dummy union to get native endianness */
  1227. static const union {
  1228. int dummy;
  1229. char little; /* true iff machine is little endian */
  1230. } nativeendian = {1};
  1231. /*
  1232. ** information to pack/unpack stuff
  1233. */
  1234. typedef struct Header {
  1235. lua_State *L;
  1236. int islittle;
  1237. unsigned maxalign;
  1238. } Header;
  1239. /*
  1240. ** options for pack/unpack
  1241. */
  1242. typedef enum KOption {
  1243. Kint, /* signed integers */
  1244. Kuint, /* unsigned integers */
  1245. Kfloat, /* single-precision floating-point numbers */
  1246. Knumber, /* Lua "native" floating-point numbers */
  1247. Kdouble, /* double-precision floating-point numbers */
  1248. Kchar, /* fixed-length strings */
  1249. Kstring, /* strings with prefixed length */
  1250. Kzstr, /* zero-terminated strings */
  1251. Kpadding, /* padding */
  1252. Kpaddalign, /* padding for alignment */
  1253. Knop /* no-op (configuration or spaces) */
  1254. } KOption;
  1255. /*
  1256. ** Read an integer numeral from string 'fmt' or return 'df' if
  1257. ** there is no numeral
  1258. */
  1259. static int digit (int c) { return '0' <= c && c <= '9'; }
  1260. static size_t getnum (const char **fmt, size_t df) {
  1261. if (!digit(**fmt)) /* no number? */
  1262. return df; /* return default value */
  1263. else {
  1264. size_t a = 0;
  1265. do {
  1266. a = a*10 + cast_uint(*((*fmt)++) - '0');
  1267. } while (digit(**fmt) && a <= (MAX_SIZE - 9)/10);
  1268. return a;
  1269. }
  1270. }
  1271. /*
  1272. ** Read an integer numeral and raises an error if it is larger
  1273. ** than the maximum size of integers.
  1274. */
  1275. static unsigned getnumlimit (Header *h, const char **fmt, size_t df) {
  1276. size_t sz = getnum(fmt, df);
  1277. if (l_unlikely((sz - 1u) >= MAXINTSIZE))
  1278. return cast_uint(luaL_error(h->L,
  1279. "integral size (%d) out of limits [1,%d]", sz, MAXINTSIZE));
  1280. return cast_uint(sz);
  1281. }
  1282. /*
  1283. ** Initialize Header
  1284. */
  1285. static void initheader (lua_State *L, Header *h) {
  1286. h->L = L;
  1287. h->islittle = nativeendian.little;
  1288. h->maxalign = 1;
  1289. }
  1290. /*
  1291. ** Read and classify next option. 'size' is filled with option's size.
  1292. */
  1293. static KOption getoption (Header *h, const char **fmt, size_t *size) {
  1294. /* dummy structure to get native alignment requirements */
  1295. struct cD { char c; union { LUAI_MAXALIGN; } u; };
  1296. int opt = *((*fmt)++);
  1297. *size = 0; /* default */
  1298. switch (opt) {
  1299. case 'b': *size = sizeof(char); return Kint;
  1300. case 'B': *size = sizeof(char); return Kuint;
  1301. case 'h': *size = sizeof(short); return Kint;
  1302. case 'H': *size = sizeof(short); return Kuint;
  1303. case 'l': *size = sizeof(long); return Kint;
  1304. case 'L': *size = sizeof(long); return Kuint;
  1305. case 'j': *size = sizeof(lua_Integer); return Kint;
  1306. case 'J': *size = sizeof(lua_Integer); return Kuint;
  1307. case 'T': *size = sizeof(size_t); return Kuint;
  1308. case 'f': *size = sizeof(float); return Kfloat;
  1309. case 'n': *size = sizeof(lua_Number); return Knumber;
  1310. case 'd': *size = sizeof(double); return Kdouble;
  1311. case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
  1312. case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
  1313. case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
  1314. case 'c':
  1315. *size = getnum(fmt, cast_sizet(-1));
  1316. if (l_unlikely(*size == cast_sizet(-1)))
  1317. luaL_error(h->L, "missing size for format option 'c'");
  1318. return Kchar;
  1319. case 'z': return Kzstr;
  1320. case 'x': *size = 1; return Kpadding;
  1321. case 'X': return Kpaddalign;
  1322. case ' ': break;
  1323. case '<': h->islittle = 1; break;
  1324. case '>': h->islittle = 0; break;
  1325. case '=': h->islittle = nativeendian.little; break;
  1326. case '!': {
  1327. const size_t maxalign = offsetof(struct cD, u);
  1328. h->maxalign = getnumlimit(h, fmt, maxalign);
  1329. break;
  1330. }
  1331. default: luaL_error(h->L, "invalid format option '%c'", opt);
  1332. }
  1333. return Knop;
  1334. }
  1335. /*
  1336. ** Read, classify, and fill other details about the next option.
  1337. ** 'psize' is filled with option's size, 'notoalign' with its
  1338. ** alignment requirements.
  1339. ** Local variable 'size' gets the size to be aligned. (Kpadal option
  1340. ** always gets its full alignment, other options are limited by
  1341. ** the maximum alignment ('maxalign'). Kchar option needs no alignment
  1342. ** despite its size.
  1343. */
  1344. static KOption getdetails (Header *h, size_t totalsize, const char **fmt,
  1345. size_t *psize, unsigned *ntoalign) {
  1346. KOption opt = getoption(h, fmt, psize);
  1347. size_t align = *psize; /* usually, alignment follows size */
  1348. if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
  1349. if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
  1350. luaL_argerror(h->L, 1, "invalid next option for option 'X'");
  1351. }
  1352. if (align <= 1 || opt == Kchar) /* need no alignment? */
  1353. *ntoalign = 0;
  1354. else {
  1355. if (align > h->maxalign) /* enforce maximum alignment */
  1356. align = h->maxalign;
  1357. if (l_unlikely(!ispow2(align))) { /* not a power of 2? */
  1358. *ntoalign = 0; /* to avoid warnings */
  1359. luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
  1360. }
  1361. else {
  1362. /* 'szmoda' = totalsize % align */
  1363. unsigned szmoda = cast_uint(totalsize & (align - 1));
  1364. *ntoalign = cast_uint((align - szmoda) & (align - 1));
  1365. }
  1366. }
  1367. return opt;
  1368. }
  1369. /*
  1370. ** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
  1371. ** The final 'if' handles the case when 'size' is larger than
  1372. ** the size of a Lua integer, correcting the extra sign-extension
  1373. ** bytes if necessary (by default they would be zeros).
  1374. */
  1375. static void packint (luaL_Buffer *b, lua_Unsigned n,
  1376. int islittle, unsigned size, int neg) {
  1377. char *buff = luaL_prepbuffsize(b, size);
  1378. unsigned i;
  1379. buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */
  1380. for (i = 1; i < size; i++) {
  1381. n >>= NB;
  1382. buff[islittle ? i : size - 1 - i] = (char)(n & MC);
  1383. }
  1384. if (neg && size > SZINT) { /* negative number need sign extension? */
  1385. for (i = SZINT; i < size; i++) /* correct extra bytes */
  1386. buff[islittle ? i : size - 1 - i] = (char)MC;
  1387. }
  1388. luaL_addsize(b, size); /* add result to buffer */
  1389. }
  1390. /*
  1391. ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
  1392. ** given 'islittle' is different from native endianness.
  1393. */
  1394. static void copywithendian (char *dest, const char *src,
  1395. unsigned size, int islittle) {
  1396. if (islittle == nativeendian.little)
  1397. memcpy(dest, src, size);
  1398. else {
  1399. dest += size - 1;
  1400. while (size-- != 0)
  1401. *(dest--) = *(src++);
  1402. }
  1403. }
  1404. static int str_pack (lua_State *L) {
  1405. luaL_Buffer b;
  1406. Header h;
  1407. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1408. int arg = 1; /* current argument to pack */
  1409. size_t totalsize = 0; /* accumulate total size of result */
  1410. initheader(L, &h);
  1411. lua_pushnil(L); /* mark to separate arguments from string buffer */
  1412. luaL_buffinit(L, &b);
  1413. while (*fmt != '\0') {
  1414. unsigned ntoalign;
  1415. size_t size;
  1416. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1417. luaL_argcheck(L, size + ntoalign <= MAX_SIZE - totalsize, arg,
  1418. "result too long");
  1419. totalsize += ntoalign + size;
  1420. while (ntoalign-- > 0)
  1421. luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */
  1422. arg++;
  1423. switch (opt) {
  1424. case Kint: { /* signed integers */
  1425. lua_Integer n = luaL_checkinteger(L, arg);
  1426. if (size < SZINT) { /* need overflow check? */
  1427. lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
  1428. luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
  1429. }
  1430. packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), (n < 0));
  1431. break;
  1432. }
  1433. case Kuint: { /* unsigned integers */
  1434. lua_Integer n = luaL_checkinteger(L, arg);
  1435. if (size < SZINT) /* need overflow check? */
  1436. luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
  1437. arg, "unsigned overflow");
  1438. packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), 0);
  1439. break;
  1440. }
  1441. case Kfloat: { /* C float */
  1442. float f = (float)luaL_checknumber(L, arg); /* get argument */
  1443. char *buff = luaL_prepbuffsize(&b, sizeof(f));
  1444. /* move 'f' to final result, correcting endianness if needed */
  1445. copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
  1446. luaL_addsize(&b, size);
  1447. break;
  1448. }
  1449. case Knumber: { /* Lua float */
  1450. lua_Number f = luaL_checknumber(L, arg); /* get argument */
  1451. char *buff = luaL_prepbuffsize(&b, sizeof(f));
  1452. /* move 'f' to final result, correcting endianness if needed */
  1453. copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
  1454. luaL_addsize(&b, size);
  1455. break;
  1456. }
  1457. case Kdouble: { /* C double */
  1458. double f = (double)luaL_checknumber(L, arg); /* get argument */
  1459. char *buff = luaL_prepbuffsize(&b, sizeof(f));
  1460. /* move 'f' to final result, correcting endianness if needed */
  1461. copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
  1462. luaL_addsize(&b, size);
  1463. break;
  1464. }
  1465. case Kchar: { /* fixed-size string */
  1466. size_t len;
  1467. const char *s = luaL_checklstring(L, arg, &len);
  1468. luaL_argcheck(L, len <= size, arg, "string longer than given size");
  1469. luaL_addlstring(&b, s, len); /* add string */
  1470. if (len < size) { /* does it need padding? */
  1471. size_t psize = size - len; /* pad size */
  1472. char *buff = luaL_prepbuffsize(&b, psize);
  1473. memset(buff, LUAL_PACKPADBYTE, psize);
  1474. luaL_addsize(&b, psize);
  1475. }
  1476. break;
  1477. }
  1478. case Kstring: { /* strings with length count */
  1479. size_t len;
  1480. const char *s = luaL_checklstring(L, arg, &len);
  1481. luaL_argcheck(L, size >= sizeof(lua_Unsigned) ||
  1482. len < ((lua_Unsigned)1 << (size * NB)),
  1483. arg, "string length does not fit in given size");
  1484. /* pack length */
  1485. packint(&b, (lua_Unsigned)len, h.islittle, cast_uint(size), 0);
  1486. luaL_addlstring(&b, s, len);
  1487. totalsize += len;
  1488. break;
  1489. }
  1490. case Kzstr: { /* zero-terminated string */
  1491. size_t len;
  1492. const char *s = luaL_checklstring(L, arg, &len);
  1493. luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
  1494. luaL_addlstring(&b, s, len);
  1495. luaL_addchar(&b, '\0'); /* add zero at the end */
  1496. totalsize += len + 1;
  1497. break;
  1498. }
  1499. case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */
  1500. case Kpaddalign: case Knop:
  1501. arg--; /* undo increment */
  1502. break;
  1503. }
  1504. }
  1505. luaL_pushresult(&b);
  1506. return 1;
  1507. }
  1508. static int str_packsize (lua_State *L) {
  1509. Header h;
  1510. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1511. size_t totalsize = 0; /* accumulate total size of result */
  1512. initheader(L, &h);
  1513. while (*fmt != '\0') {
  1514. unsigned ntoalign;
  1515. size_t size;
  1516. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1517. luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
  1518. "variable-length format");
  1519. size += ntoalign; /* total space used by option */
  1520. luaL_argcheck(L, totalsize <= LUA_MAXINTEGER - size,
  1521. 1, "format result too large");
  1522. totalsize += size;
  1523. }
  1524. lua_pushinteger(L, cast_st2S(totalsize));
  1525. return 1;
  1526. }
  1527. /*
  1528. ** Unpack an integer with 'size' bytes and 'islittle' endianness.
  1529. ** If size is smaller than the size of a Lua integer and integer
  1530. ** is signed, must do sign extension (propagating the sign to the
  1531. ** higher bits); if size is larger than the size of a Lua integer,
  1532. ** it must check the unread bytes to see whether they do not cause an
  1533. ** overflow.
  1534. */
  1535. static lua_Integer unpackint (lua_State *L, const char *str,
  1536. int islittle, int size, int issigned) {
  1537. lua_Unsigned res = 0;
  1538. int i;
  1539. int limit = (size <= SZINT) ? size : SZINT;
  1540. for (i = limit - 1; i >= 0; i--) {
  1541. res <<= NB;
  1542. res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
  1543. }
  1544. if (size < SZINT) { /* real size smaller than lua_Integer? */
  1545. if (issigned) { /* needs sign extension? */
  1546. lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
  1547. res = ((res ^ mask) - mask); /* do sign extension */
  1548. }
  1549. }
  1550. else if (size > SZINT) { /* must check unread bytes */
  1551. int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
  1552. for (i = limit; i < size; i++) {
  1553. if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask))
  1554. luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
  1555. }
  1556. }
  1557. return (lua_Integer)res;
  1558. }
  1559. static int str_unpack (lua_State *L) {
  1560. Header h;
  1561. const char *fmt = luaL_checkstring(L, 1);
  1562. size_t ld;
  1563. const char *data = luaL_checklstring(L, 2, &ld);
  1564. size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
  1565. int n = 0; /* number of results */
  1566. luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
  1567. initheader(L, &h);
  1568. while (*fmt != '\0') {
  1569. unsigned ntoalign;
  1570. size_t size;
  1571. KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
  1572. luaL_argcheck(L, ntoalign + size <= ld - pos, 2,
  1573. "data string too short");
  1574. pos += ntoalign; /* skip alignment */
  1575. /* stack space for item + next position */
  1576. luaL_checkstack(L, 2, "too many results");
  1577. n++;
  1578. switch (opt) {
  1579. case Kint:
  1580. case Kuint: {
  1581. lua_Integer res = unpackint(L, data + pos, h.islittle,
  1582. cast_int(size), (opt == Kint));
  1583. lua_pushinteger(L, res);
  1584. break;
  1585. }
  1586. case Kfloat: {
  1587. float f;
  1588. copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
  1589. lua_pushnumber(L, (lua_Number)f);
  1590. break;
  1591. }
  1592. case Knumber: {
  1593. lua_Number f;
  1594. copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
  1595. lua_pushnumber(L, f);
  1596. break;
  1597. }
  1598. case Kdouble: {
  1599. double f;
  1600. copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
  1601. lua_pushnumber(L, (lua_Number)f);
  1602. break;
  1603. }
  1604. case Kchar: {
  1605. lua_pushlstring(L, data + pos, size);
  1606. break;
  1607. }
  1608. case Kstring: {
  1609. lua_Unsigned len = (lua_Unsigned)unpackint(L, data + pos,
  1610. h.islittle, cast_int(size), 0);
  1611. luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
  1612. lua_pushlstring(L, data + pos + size, cast_sizet(len));
  1613. pos += cast_sizet(len); /* skip string */
  1614. break;
  1615. }
  1616. case Kzstr: {
  1617. size_t len = strlen(data + pos);
  1618. luaL_argcheck(L, pos + len < ld, 2,
  1619. "unfinished string for format 'z'");
  1620. lua_pushlstring(L, data + pos, len);
  1621. pos += len + 1; /* skip string plus final '\0' */
  1622. break;
  1623. }
  1624. case Kpaddalign: case Kpadding: case Knop:
  1625. n--; /* undo increment */
  1626. break;
  1627. }
  1628. pos += size;
  1629. }
  1630. lua_pushinteger(L, cast_st2S(pos) + 1); /* next position */
  1631. return n + 1;
  1632. }
  1633. /* }====================================================== */
  1634. static const luaL_Reg strlib[] = {
  1635. {"byte", str_byte},
  1636. {"char", str_char},
  1637. {"dump", str_dump},
  1638. {"find", str_find},
  1639. {"format", str_format},
  1640. {"gmatch", gmatch},
  1641. {"gsub", str_gsub},
  1642. {"len", str_len},
  1643. {"lower", str_lower},
  1644. {"match", str_match},
  1645. {"rep", str_rep},
  1646. {"reverse", str_reverse},
  1647. {"sub", str_sub},
  1648. {"upper", str_upper},
  1649. {"pack", str_pack},
  1650. {"packsize", str_packsize},
  1651. {"unpack", str_unpack},
  1652. {NULL, NULL}
  1653. };
  1654. static void createmetatable (lua_State *L) {
  1655. /* table to be metatable for strings */
  1656. luaL_newlibtable(L, stringmetamethods);
  1657. luaL_setfuncs(L, stringmetamethods, 0);
  1658. lua_pushliteral(L, ""); /* dummy string */
  1659. lua_pushvalue(L, -2); /* copy table */
  1660. lua_setmetatable(L, -2); /* set table as metatable for strings */
  1661. lua_pop(L, 1); /* pop dummy string */
  1662. lua_pushvalue(L, -2); /* get string library */
  1663. lua_setfield(L, -2, "__index"); /* metatable.__index = string */
  1664. lua_pop(L, 1); /* pop metatable */
  1665. }
  1666. /*
  1667. ** Open string library
  1668. */
  1669. LUAMOD_API int luaopen_string (lua_State *L) {
  1670. luaL_newlib(L, strlib);
  1671. createmetatable(L);
  1672. return 1;
  1673. }