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