2
0

lstrlib.c 56 KB

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