lstrlib.c 55 KB

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