lstrlib.c 56 KB

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