lstrlib.c 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  1. /*
  2. ** $Id: lstrlib.c $
  3. ** Standard library for string operations and pattern-matching
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lstrlib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #include <ctype.h>
  10. #include <float.h>
  11. #include <limits.h>
  12. #include <locale.h>
  13. #include <math.h>
  14. #include <stddef.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include "lua.h"
  19. #include "lauxlib.h"
  20. #include "lualib.h"
  21. #include "llimits.h"
  22. /*
  23. ** maximum number of captures that a pattern can do during
  24. ** pattern-matching. This limit is arbitrary, but must fit in
  25. ** an unsigned char.
  26. */
  27. #if !defined(LUA_MAXCAPTURES)
  28. #define LUA_MAXCAPTURES 32
  29. #endif
  30. static int str_len (lua_State *L) {
  31. size_t l;
  32. luaL_checklstring(L, 1, &l);
  33. lua_pushinteger(L, (lua_Integer)l);
  34. return 1;
  35. }
  36. /*
  37. ** translate a relative initial string position
  38. ** (negative means back from end): clip result to [1, inf).
  39. ** The length of any string in Lua must fit in a lua_Integer,
  40. ** so there are no overflows in the casts.
  41. ** The inverted comparison avoids a possible overflow
  42. ** computing '-pos'.
  43. */
  44. static size_t posrelatI (lua_Integer pos, size_t len) {
  45. if (pos > 0)
  46. return (size_t)pos;
  47. else if (pos == 0)
  48. return 1;
  49. else if (pos < -(lua_Integer)len) /* inverted comparison */
  50. return 1; /* clip to 1 */
  51. else return len + (size_t)pos + 1;
  52. }
  53. /*
  54. ** Gets an optional ending string position from argument 'arg',
  55. ** with default value 'def'.
  56. ** Negative means back from end: clip result to [0, len]
  57. */
  58. static size_t getendpos (lua_State *L, int arg, lua_Integer def,
  59. size_t len) {
  60. lua_Integer pos = luaL_optinteger(L, arg, def);
  61. if (pos > (lua_Integer)len)
  62. return len;
  63. else if (pos >= 0)
  64. return (size_t)pos;
  65. else if (pos < -(lua_Integer)len)
  66. return 0;
  67. else return len + (size_t)pos + 1;
  68. }
  69. static int str_sub (lua_State *L) {
  70. size_t l;
  71. const char *s = luaL_checklstring(L, 1, &l);
  72. size_t start = posrelatI(luaL_checkinteger(L, 2), l);
  73. size_t end = getendpos(L, 3, -1, l);
  74. if (start <= end)
  75. lua_pushlstring(L, s + start - 1, (end - start) + 1);
  76. else lua_pushliteral(L, "");
  77. return 1;
  78. }
  79. static int str_reverse (lua_State *L) {
  80. size_t l, i;
  81. luaL_Buffer b;
  82. const char *s = luaL_checklstring(L, 1, &l);
  83. char *p = luaL_buffinitsize(L, &b, l);
  84. for (i = 0; i < l; i++)
  85. p[i] = s[l - i - 1];
  86. luaL_pushresultsize(&b, l);
  87. return 1;
  88. }
  89. static int str_lower (lua_State *L) {
  90. size_t l;
  91. size_t i;
  92. luaL_Buffer b;
  93. const char *s = luaL_checklstring(L, 1, &l);
  94. char *p = luaL_buffinitsize(L, &b, l);
  95. for (i=0; i<l; i++)
  96. p[i] = cast_char(tolower(cast_uchar(s[i])));
  97. luaL_pushresultsize(&b, l);
  98. return 1;
  99. }
  100. static int str_upper (lua_State *L) {
  101. size_t l;
  102. size_t i;
  103. luaL_Buffer b;
  104. const char *s = luaL_checklstring(L, 1, &l);
  105. char *p = luaL_buffinitsize(L, &b, l);
  106. for (i=0; i<l; i++)
  107. p[i] = cast_char(toupper(cast_uchar(s[i])));
  108. luaL_pushresultsize(&b, l);
  109. return 1;
  110. }
  111. static int str_rep (lua_State *L) {
  112. size_t l, lsep;
  113. const char *s = luaL_checklstring(L, 1, &l);
  114. lua_Integer n = luaL_checkinteger(L, 2);
  115. const char *sep = luaL_optlstring(L, 3, "", &lsep);
  116. if (n <= 0)
  117. lua_pushliteral(L, "");
  118. else if (l_unlikely(l + lsep < l || l + lsep > MAX_SIZE / cast_sizet(n)))
  119. return luaL_error(L, "resulting string too large");
  120. else {
  121. size_t totallen = ((size_t)n * (l + lsep)) - lsep;
  122. luaL_Buffer b;
  123. char *p = luaL_buffinitsize(L, &b, totallen);
  124. while (n-- > 1) { /* first n-1 copies (followed by separator) */
  125. memcpy(p, s, l * sizeof(char)); p += l;
  126. if (lsep > 0) { /* empty 'memcpy' is not that cheap */
  127. memcpy(p, sep, lsep * sizeof(char));
  128. p += lsep;
  129. }
  130. }
  131. memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
  132. luaL_pushresultsize(&b, totallen);
  133. }
  134. return 1;
  135. }
  136. static int str_byte (lua_State *L) {
  137. size_t l;
  138. const char *s = luaL_checklstring(L, 1, &l);
  139. lua_Integer pi = luaL_optinteger(L, 2, 1);
  140. size_t posi = posrelatI(pi, l);
  141. size_t pose = getendpos(L, 3, pi, l);
  142. int n, i;
  143. if (posi > pose) return 0; /* empty interval; return no values */
  144. if (l_unlikely(pose - posi >= (size_t)INT_MAX)) /* arithmetic overflow? */
  145. return luaL_error(L, "string slice too long");
  146. n = (int)(pose - posi) + 1;
  147. luaL_checkstack(L, n, "string slice too long");
  148. for (i=0; i<n; i++)
  149. lua_pushinteger(L, cast_uchar(s[posi + cast_uint(i) - 1]));
  150. return n;
  151. }
  152. static int str_char (lua_State *L) {
  153. int n = lua_gettop(L); /* number of arguments */
  154. int i;
  155. luaL_Buffer b;
  156. char *p = luaL_buffinitsize(L, &b, cast_uint(n));
  157. for (i=1; i<=n; i++) {
  158. lua_Unsigned c = (lua_Unsigned)luaL_checkinteger(L, i);
  159. luaL_argcheck(L, c <= (lua_Unsigned)UCHAR_MAX, i, "value out of range");
  160. p[i - 1] = cast_char(cast_uchar(c));
  161. }
  162. luaL_pushresultsize(&b, cast_uint(n));
  163. return 1;
  164. }
  165. /*
  166. ** Buffer to store the result of 'string.dump'. It must be initialized
  167. ** after the call to 'lua_dump', to ensure that the function is on the
  168. ** top of the stack when 'lua_dump' is called. ('luaL_buffinit' might
  169. ** push stuff.)
  170. */
  171. struct str_Writer {
  172. int init; /* true iff buffer has been initialized */
  173. luaL_Buffer B;
  174. };
  175. static int writer (lua_State *L, const void *b, size_t size, void *ud) {
  176. struct str_Writer *state = (struct str_Writer *)ud;
  177. if (!state->init) {
  178. state->init = 1;
  179. luaL_buffinit(L, &state->B);
  180. }
  181. if (b == NULL) { /* finishing dump? */
  182. luaL_pushresult(&state->B); /* push result */
  183. lua_replace(L, 1); /* move it to reserved slot */
  184. }
  185. else
  186. luaL_addlstring(&state->B, (const char *)b, size);
  187. return 0;
  188. }
  189. static int str_dump (lua_State *L) {
  190. struct str_Writer state;
  191. int strip = lua_toboolean(L, 2);
  192. luaL_argcheck(L, lua_type(L, 1) == LUA_TFUNCTION && !lua_iscfunction(L, 1),
  193. 1, "Lua function expected");
  194. /* ensure function is on the top of the stack and vacate slot 1 */
  195. lua_pushvalue(L, 1);
  196. state.init = 0;
  197. lua_dump(L, writer, &state, strip);
  198. lua_settop(L, 1); /* leave final result on top */
  199. return 1;
  200. }
  201. /*
  202. ** {======================================================
  203. ** METAMETHODS
  204. ** =======================================================
  205. */
  206. #if defined(LUA_NOCVTS2N) /* { */
  207. /* no coercion from strings to numbers */
  208. static const luaL_Reg stringmetamethods[] = {
  209. {"__index", NULL}, /* placeholder */
  210. {NULL, NULL}
  211. };
  212. #else /* }{ */
  213. static int tonum (lua_State *L, int arg) {
  214. if (lua_type(L, arg) == LUA_TNUMBER) { /* already a number? */
  215. lua_pushvalue(L, arg);
  216. return 1;
  217. }
  218. else { /* check whether it is a numerical string */
  219. size_t len;
  220. const char *s = lua_tolstring(L, arg, &len);
  221. return (s != NULL && lua_stringtonumber(L, s) == len + 1);
  222. }
  223. }
  224. static void trymt (lua_State *L, const char *mtname) {
  225. lua_settop(L, 2); /* back to the original arguments */
  226. if (l_unlikely(lua_type(L, 2) == LUA_TSTRING ||
  227. !luaL_getmetafield(L, 2, mtname)))
  228. luaL_error(L, "attempt to %s a '%s' with a '%s'", mtname + 2,
  229. luaL_typename(L, -2), luaL_typename(L, -1));
  230. lua_insert(L, -3); /* put metamethod before arguments */
  231. lua_call(L, 2, 1); /* call metamethod */
  232. }
  233. static int arith (lua_State *L, int op, const char *mtname) {
  234. if (tonum(L, 1) && tonum(L, 2))
  235. lua_arith(L, op); /* result will be on the top */
  236. else
  237. trymt(L, mtname);
  238. return 1;
  239. }
  240. static int arith_add (lua_State *L) {
  241. return arith(L, LUA_OPADD, "__add");
  242. }
  243. static int arith_sub (lua_State *L) {
  244. return arith(L, LUA_OPSUB, "__sub");
  245. }
  246. static int arith_mul (lua_State *L) {
  247. return arith(L, LUA_OPMUL, "__mul");
  248. }
  249. static int arith_mod (lua_State *L) {
  250. return arith(L, LUA_OPMOD, "__mod");
  251. }
  252. static int arith_pow (lua_State *L) {
  253. return arith(L, LUA_OPPOW, "__pow");
  254. }
  255. static int arith_div (lua_State *L) {
  256. return arith(L, LUA_OPDIV, "__div");
  257. }
  258. static int arith_idiv (lua_State *L) {
  259. return arith(L, LUA_OPIDIV, "__idiv");
  260. }
  261. static int arith_unm (lua_State *L) {
  262. return arith(L, LUA_OPUNM, "__unm");
  263. }
  264. static const luaL_Reg stringmetamethods[] = {
  265. {"__add", arith_add},
  266. {"__sub", arith_sub},
  267. {"__mul", arith_mul},
  268. {"__mod", arith_mod},
  269. {"__pow", arith_pow},
  270. {"__div", arith_div},
  271. {"__idiv", arith_idiv},
  272. {"__unm", arith_unm},
  273. {"__index", NULL}, /* placeholder */
  274. {NULL, NULL}
  275. };
  276. #endif /* } */
  277. /* }====================================================== */
  278. /*
  279. ** {======================================================
  280. ** PATTERN MATCHING
  281. ** =======================================================
  282. */
  283. #define CAP_UNFINISHED (-1)
  284. #define CAP_POSITION (-2)
  285. typedef struct MatchState {
  286. const char *src_init; /* init of source string */
  287. const char *src_end; /* end ('\0') of source string */
  288. const char *p_end; /* end ('\0') of pattern */
  289. lua_State *L;
  290. int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
  291. int level; /* total number of captures (finished or unfinished) */
  292. struct {
  293. const char *init;
  294. ptrdiff_t len; /* length or special value (CAP_*) */
  295. } capture[LUA_MAXCAPTURES];
  296. } MatchState;
  297. /* recursive function */
  298. static const char *match (MatchState *ms, const char *s, const char *p);
  299. /* maximum recursion depth for 'match' */
  300. #if !defined(MAXCCALLS)
  301. #define MAXCCALLS 200
  302. #endif
  303. #define L_ESC '%'
  304. #define SPECIALS "^$*+?.([%-"
  305. static int check_capture (MatchState *ms, int l) {
  306. l -= '1';
  307. if (l_unlikely(l < 0 || l >= ms->level ||
  308. ms->capture[l].len == CAP_UNFINISHED))
  309. return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
  310. return l;
  311. }
  312. static int capture_to_close (MatchState *ms) {
  313. int level = ms->level;
  314. for (level--; level>=0; level--)
  315. if (ms->capture[level].len == CAP_UNFINISHED) return level;
  316. return luaL_error(ms->L, "invalid pattern capture");
  317. }
  318. static const char *classend (MatchState *ms, const char *p) {
  319. switch (*p++) {
  320. case L_ESC: {
  321. if (l_unlikely(p == ms->p_end))
  322. luaL_error(ms->L, "malformed pattern (ends with '%%')");
  323. return p+1;
  324. }
  325. case '[': {
  326. if (*p == '^') p++;
  327. do { /* look for a ']' */
  328. if (l_unlikely(p == ms->p_end))
  329. luaL_error(ms->L, "malformed pattern (missing ']')");
  330. if (*(p++) == L_ESC && p < ms->p_end)
  331. p++; /* skip escapes (e.g. '%]') */
  332. } while (*p != ']');
  333. return p+1;
  334. }
  335. default: {
  336. return p;
  337. }
  338. }
  339. }
  340. static int match_class (int c, int cl) {
  341. int res;
  342. switch (tolower(cl)) {
  343. case 'a' : res = isalpha(c); break;
  344. case 'c' : res = iscntrl(c); break;
  345. case 'd' : res = isdigit(c); break;
  346. case 'g' : res = isgraph(c); break;
  347. case 'l' : res = islower(c); break;
  348. case 'p' : res = ispunct(c); break;
  349. case 's' : res = isspace(c); break;
  350. case 'u' : res = isupper(c); break;
  351. case 'w' : res = isalnum(c); break;
  352. case 'x' : res = isxdigit(c); break;
  353. case 'z' : res = (c == 0); break; /* deprecated option */
  354. default: return (cl == c);
  355. }
  356. return (islower(cl) ? res : !res);
  357. }
  358. static int matchbracketclass (int c, const char *p, const char *ec) {
  359. int sig = 1;
  360. if (*(p+1) == '^') {
  361. sig = 0;
  362. p++; /* skip the '^' */
  363. }
  364. while (++p < ec) {
  365. if (*p == L_ESC) {
  366. p++;
  367. if (match_class(c, cast_uchar(*p)))
  368. return sig;
  369. }
  370. else if ((*(p+1) == '-') && (p+2 < ec)) {
  371. p+=2;
  372. if (cast_uchar(*(p-2)) <= c && c <= cast_uchar(*p))
  373. return sig;
  374. }
  375. else if (cast_uchar(*p) == c) return sig;
  376. }
  377. return !sig;
  378. }
  379. static int singlematch (MatchState *ms, const char *s, const char *p,
  380. const char *ep) {
  381. if (s >= ms->src_end)
  382. return 0;
  383. else {
  384. int c = cast_uchar(*s);
  385. switch (*p) {
  386. case '.': return 1; /* matches any char */
  387. case L_ESC: return match_class(c, cast_uchar(*(p+1)));
  388. case '[': return matchbracketclass(c, p, ep-1);
  389. default: return (cast_uchar(*p) == c);
  390. }
  391. }
  392. }
  393. static const char *matchbalance (MatchState *ms, const char *s,
  394. const char *p) {
  395. if (l_unlikely(p >= ms->p_end - 1))
  396. luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
  397. if (*s != *p) return NULL;
  398. else {
  399. int b = *p;
  400. int e = *(p+1);
  401. int cont = 1;
  402. while (++s < ms->src_end) {
  403. if (*s == e) {
  404. if (--cont == 0) return s+1;
  405. }
  406. else if (*s == b) cont++;
  407. }
  408. }
  409. return NULL; /* string ends out of balance */
  410. }
  411. static const char *max_expand (MatchState *ms, const char *s,
  412. const char *p, const char *ep) {
  413. ptrdiff_t i = 0; /* counts maximum expand for item */
  414. while (singlematch(ms, s + i, p, ep))
  415. i++;
  416. /* keeps trying to match with the maximum repetitions */
  417. while (i>=0) {
  418. const char *res = match(ms, (s+i), ep+1);
  419. if (res) return res;
  420. i--; /* else didn't match; reduce 1 repetition to try again */
  421. }
  422. return NULL;
  423. }
  424. static const char *min_expand (MatchState *ms, const char *s,
  425. const char *p, const char *ep) {
  426. for (;;) {
  427. const char *res = match(ms, s, ep+1);
  428. if (res != NULL)
  429. return res;
  430. else if (singlematch(ms, s, p, ep))
  431. s++; /* try with one more repetition */
  432. else return NULL;
  433. }
  434. }
  435. static const char *start_capture (MatchState *ms, const char *s,
  436. const char *p, int what) {
  437. const char *res;
  438. int level = ms->level;
  439. if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
  440. ms->capture[level].init = s;
  441. ms->capture[level].len = what;
  442. ms->level = level+1;
  443. if ((res=match(ms, s, p)) == NULL) /* match failed? */
  444. ms->level--; /* undo capture */
  445. return res;
  446. }
  447. static const char *end_capture (MatchState *ms, const char *s,
  448. const char *p) {
  449. int l = capture_to_close(ms);
  450. const char *res;
  451. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  452. if ((res = match(ms, s, p)) == NULL) /* match failed? */
  453. ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
  454. return res;
  455. }
  456. static const char *match_capture (MatchState *ms, const char *s, int l) {
  457. size_t len;
  458. l = check_capture(ms, l);
  459. len = cast_sizet(ms->capture[l].len);
  460. if ((size_t)(ms->src_end-s) >= len &&
  461. memcmp(ms->capture[l].init, s, len) == 0)
  462. return s+len;
  463. else return NULL;
  464. }
  465. static const char *match (MatchState *ms, const char *s, const char *p) {
  466. if (l_unlikely(ms->matchdepth-- == 0))
  467. luaL_error(ms->L, "pattern too complex");
  468. init: /* using goto to optimize tail recursion */
  469. if (p != ms->p_end) { /* end of pattern? */
  470. switch (*p) {
  471. case '(': { /* start capture */
  472. if (*(p + 1) == ')') /* position capture? */
  473. s = start_capture(ms, s, p + 2, CAP_POSITION);
  474. else
  475. s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
  476. break;
  477. }
  478. case ')': { /* end capture */
  479. s = end_capture(ms, s, p + 1);
  480. break;
  481. }
  482. case '$': {
  483. if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */
  484. goto dflt; /* no; go to default */
  485. s = (s == ms->src_end) ? s : NULL; /* check end of string */
  486. break;
  487. }
  488. case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
  489. switch (*(p + 1)) {
  490. case 'b': { /* balanced string? */
  491. s = matchbalance(ms, s, p + 2);
  492. if (s != NULL) {
  493. p += 4; goto init; /* return match(ms, s, p + 4); */
  494. } /* else fail (s == NULL) */
  495. break;
  496. }
  497. case 'f': { /* frontier? */
  498. const char *ep; char previous;
  499. p += 2;
  500. if (l_unlikely(*p != '['))
  501. luaL_error(ms->L, "missing '[' after '%%f' in pattern");
  502. ep = classend(ms, p); /* points to what is next */
  503. previous = (s == ms->src_init) ? '\0' : *(s - 1);
  504. if (!matchbracketclass(cast_uchar(previous), p, ep - 1) &&
  505. matchbracketclass(cast_uchar(*s), p, ep - 1)) {
  506. p = ep; goto init; /* return match(ms, s, ep); */
  507. }
  508. s = NULL; /* match failed */
  509. break;
  510. }
  511. case '0': case '1': case '2': case '3':
  512. case '4': case '5': case '6': case '7':
  513. case '8': case '9': { /* capture results (%0-%9)? */
  514. s = match_capture(ms, s, cast_uchar(*(p + 1)));
  515. if (s != NULL) {
  516. p += 2; goto init; /* return match(ms, s, p + 2) */
  517. }
  518. break;
  519. }
  520. default: goto dflt;
  521. }
  522. break;
  523. }
  524. default: dflt: { /* pattern class plus optional suffix */
  525. const char *ep = classend(ms, p); /* points to optional suffix */
  526. /* does not match at least once? */
  527. if (!singlematch(ms, s, p, ep)) {
  528. if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
  529. p = ep + 1; goto init; /* return match(ms, s, ep + 1); */
  530. }
  531. else /* '+' or no suffix */
  532. s = NULL; /* fail */
  533. }
  534. else { /* matched once */
  535. switch (*ep) { /* handle optional suffix */
  536. case '?': { /* optional */
  537. const char *res;
  538. if ((res = match(ms, s + 1, ep + 1)) != NULL)
  539. s = res;
  540. else {
  541. p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */
  542. }
  543. break;
  544. }
  545. case '+': /* 1 or more repetitions */
  546. s++; /* 1 match already done */
  547. /* FALLTHROUGH */
  548. case '*': /* 0 or more repetitions */
  549. s = max_expand(ms, s, p, ep);
  550. break;
  551. case '-': /* 0 or more repetitions (minimum) */
  552. s = min_expand(ms, s, p, ep);
  553. break;
  554. default: /* no suffix */
  555. s++; p = ep; goto init; /* return match(ms, s + 1, ep); */
  556. }
  557. }
  558. break;
  559. }
  560. }
  561. }
  562. ms->matchdepth++;
  563. return s;
  564. }
  565. static const char *lmemfind (const char *s1, size_t l1,
  566. const char *s2, size_t l2) {
  567. if (l2 == 0) return s1; /* empty strings are everywhere */
  568. else if (l2 > l1) return NULL; /* avoids a negative 'l1' */
  569. else {
  570. const char *init; /* to search for a '*s2' inside 's1' */
  571. l2--; /* 1st char will be checked by 'memchr' */
  572. l1 = l1-l2; /* 's2' cannot be found after that */
  573. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  574. init++; /* 1st char is already checked */
  575. if (memcmp(init, s2+1, l2) == 0)
  576. return init-1;
  577. else { /* correct 'l1' and 's1' to try again */
  578. l1 -= ct_diff2sz(init - s1);
  579. s1 = init;
  580. }
  581. }
  582. return NULL; /* not found */
  583. }
  584. }
  585. /*
  586. ** get information about the i-th capture. If there are no captures
  587. ** and 'i==0', return information about the whole match, which
  588. ** is the range 's'..'e'. If the capture is a string, return
  589. ** its length and put its address in '*cap'. If it is an integer
  590. ** (a position), push it on the stack and return CAP_POSITION.
  591. */
  592. static ptrdiff_t get_onecapture (MatchState *ms, int i, const char *s,
  593. const char *e, const char **cap) {
  594. if (i >= ms->level) {
  595. if (l_unlikely(i != 0))
  596. luaL_error(ms->L, "invalid capture index %%%d", i + 1);
  597. *cap = s;
  598. return (e - s);
  599. }
  600. else {
  601. ptrdiff_t capl = ms->capture[i].len;
  602. *cap = ms->capture[i].init;
  603. if (l_unlikely(capl == CAP_UNFINISHED))
  604. luaL_error(ms->L, "unfinished capture");
  605. else if (capl == CAP_POSITION)
  606. lua_pushinteger(ms->L,
  607. ct_diff2S(ms->capture[i].init - ms->src_init) + 1);
  608. return capl;
  609. }
  610. }
  611. /*
  612. ** Push the i-th capture on the stack.
  613. */
  614. static void push_onecapture (MatchState *ms, int i, const char *s,
  615. const char *e) {
  616. const char *cap;
  617. ptrdiff_t l = get_onecapture(ms, i, s, e, &cap);
  618. if (l != CAP_POSITION)
  619. lua_pushlstring(ms->L, cap, cast_sizet(l));
  620. /* else position was already pushed */
  621. }
  622. static int push_captures (MatchState *ms, const char *s, const char *e) {
  623. int i;
  624. int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  625. luaL_checkstack(ms->L, nlevels, "too many captures");
  626. for (i = 0; i < nlevels; i++)
  627. push_onecapture(ms, i, s, e);
  628. return nlevels; /* number of strings pushed */
  629. }
  630. /* check whether pattern has no special characters */
  631. static int nospecials (const char *p, size_t l) {
  632. size_t upto = 0;
  633. do {
  634. if (strpbrk(p + upto, SPECIALS))
  635. return 0; /* pattern has a special character */
  636. upto += strlen(p + upto) + 1; /* may have more after \0 */
  637. } while (upto <= l);
  638. return 1; /* no special chars found */
  639. }
  640. static void prepstate (MatchState *ms, lua_State *L,
  641. const char *s, size_t ls, const char *p, size_t lp) {
  642. ms->L = L;
  643. ms->matchdepth = MAXCCALLS;
  644. ms->src_init = s;
  645. ms->src_end = s + ls;
  646. ms->p_end = p + lp;
  647. }
  648. static void reprepstate (MatchState *ms) {
  649. ms->level = 0;
  650. lua_assert(ms->matchdepth == MAXCCALLS);
  651. }
  652. static int str_find_aux (lua_State *L, int find) {
  653. size_t ls, lp;
  654. const char *s = luaL_checklstring(L, 1, &ls);
  655. const char *p = luaL_checklstring(L, 2, &lp);
  656. size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
  657. if (init > ls) { /* start after string's end? */
  658. luaL_pushfail(L); /* cannot find anything */
  659. return 1;
  660. }
  661. /* explicit request or no special characters? */
  662. if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
  663. /* do a plain search */
  664. const char *s2 = lmemfind(s + init, ls - init, p, lp);
  665. if (s2) {
  666. lua_pushinteger(L, ct_diff2S(s2 - s) + 1);
  667. lua_pushinteger(L, cast_st2S(ct_diff2sz(s2 - s) + lp));
  668. return 2;
  669. }
  670. }
  671. else {
  672. MatchState ms;
  673. const char *s1 = s + init;
  674. int anchor = (*p == '^');
  675. if (anchor) {
  676. p++; lp--; /* skip anchor character */
  677. }
  678. prepstate(&ms, L, s, ls, p, lp);
  679. do {
  680. const char *res;
  681. reprepstate(&ms);
  682. if ((res=match(&ms, s1, p)) != NULL) {
  683. if (find) {
  684. lua_pushinteger(L, ct_diff2S(s1 - s) + 1); /* start */
  685. lua_pushinteger(L, ct_diff2S(res - s)); /* end */
  686. return push_captures(&ms, NULL, 0) + 2;
  687. }
  688. else
  689. return push_captures(&ms, s1, res);
  690. }
  691. } while (s1++ < ms.src_end && !anchor);
  692. }
  693. luaL_pushfail(L); /* not found */
  694. return 1;
  695. }
  696. static int str_find (lua_State *L) {
  697. return str_find_aux(L, 1);
  698. }
  699. static int str_match (lua_State *L) {
  700. return str_find_aux(L, 0);
  701. }
  702. /* state for 'gmatch' */
  703. typedef struct GMatchState {
  704. const char *src; /* current position */
  705. const char *p; /* pattern */
  706. const char *lastmatch; /* end of last match */
  707. MatchState ms; /* match state */
  708. } GMatchState;
  709. static int gmatch_aux (lua_State *L) {
  710. GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
  711. const char *src;
  712. gm->ms.L = L;
  713. for (src = gm->src; src <= gm->ms.src_end; src++) {
  714. const char *e;
  715. reprepstate(&gm->ms);
  716. if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {
  717. gm->src = gm->lastmatch = e;
  718. return push_captures(&gm->ms, src, e);
  719. }
  720. }
  721. return 0; /* not found */
  722. }
  723. static int gmatch (lua_State *L) {
  724. size_t ls, lp;
  725. const char *s = luaL_checklstring(L, 1, &ls);
  726. const char *p = luaL_checklstring(L, 2, &lp);
  727. size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
  728. GMatchState *gm;
  729. lua_settop(L, 2); /* keep strings on closure to avoid being collected */
  730. gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);
  731. if (init > ls) /* start after string's end? */
  732. init = ls + 1; /* avoid overflows in 's + init' */
  733. prepstate(&gm->ms, L, s, ls, p, lp);
  734. gm->src = s + init; gm->p = p; gm->lastmatch = NULL;
  735. lua_pushcclosure(L, gmatch_aux, 3);
  736. return 1;
  737. }
  738. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  739. const char *e) {
  740. size_t l;
  741. lua_State *L = ms->L;
  742. const char *news = lua_tolstring(L, 3, &l);
  743. const char *p;
  744. while ((p = (char *)memchr(news, L_ESC, l)) != NULL) {
  745. luaL_addlstring(b, news, ct_diff2sz(p - news));
  746. p++; /* skip ESC */
  747. if (*p == L_ESC) /* '%%' */
  748. luaL_addchar(b, *p);
  749. else if (*p == '0') /* '%0' */
  750. luaL_addlstring(b, s, ct_diff2sz(e - s));
  751. else if (isdigit(cast_uchar(*p))) { /* '%n' */
  752. const char *cap;
  753. ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap);
  754. if (resl == CAP_POSITION)
  755. luaL_addvalue(b); /* add position to accumulated result */
  756. else
  757. luaL_addlstring(b, cap, cast_sizet(resl));
  758. }
  759. else
  760. luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
  761. l -= ct_diff2sz(p + 1 - news);
  762. news = p + 1;
  763. }
  764. luaL_addlstring(b, news, l);
  765. }
  766. /*
  767. ** Add the replacement value to the string buffer 'b'.
  768. ** Return true if the original string was changed. (Function calls and
  769. ** table indexing resulting in nil or false do not change the subject.)
  770. */
  771. static int add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  772. const char *e, int tr) {
  773. lua_State *L = ms->L;
  774. switch (tr) {
  775. case LUA_TFUNCTION: { /* call the function */
  776. int n;
  777. lua_pushvalue(L, 3); /* push the function */
  778. n = push_captures(ms, s, e); /* all captures as arguments */
  779. lua_call(L, n, 1); /* call it */
  780. break;
  781. }
  782. case LUA_TTABLE: { /* index the table */
  783. push_onecapture(ms, 0, s, e); /* first capture is the index */
  784. lua_gettable(L, 3);
  785. break;
  786. }
  787. default: { /* LUA_TNUMBER or LUA_TSTRING */
  788. add_s(ms, b, s, e); /* add value to the buffer */
  789. return 1; /* something changed */
  790. }
  791. }
  792. if (!lua_toboolean(L, -1)) { /* nil or false? */
  793. lua_pop(L, 1); /* remove value */
  794. luaL_addlstring(b, s, ct_diff2sz(e - s)); /* keep original text */
  795. return 0; /* no changes */
  796. }
  797. else if (l_unlikely(!lua_isstring(L, -1)))
  798. return luaL_error(L, "invalid replacement value (a %s)",
  799. luaL_typename(L, -1));
  800. else {
  801. luaL_addvalue(b); /* add result to accumulator */
  802. return 1; /* something changed */
  803. }
  804. }
  805. static int str_gsub (lua_State *L) {
  806. size_t srcl, lp;
  807. const char *src = luaL_checklstring(L, 1, &srcl); /* subject */
  808. const char *p = luaL_checklstring(L, 2, &lp); /* pattern */
  809. const char *lastmatch = NULL; /* end of last match */
  810. int tr = lua_type(L, 3); /* replacement type */
  811. /* max replacements */
  812. lua_Integer max_s = luaL_optinteger(L, 4, cast_st2S(srcl) + 1);
  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, ct_diff2sz(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, unsigned 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] = cast_char(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, unsigned 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. unsigned 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 += cast_uint(l_sprintf(buff + n, sz - n, "p%+d", e)); /* add exponent */
  901. lua_assert(n < sz);
  902. return cast_int(n);
  903. }
  904. }
  905. static int lua_number2strx (lua_State *L, char *buff, unsigned 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] = cast_char(toupper(cast_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(cast_uchar(*s))) {
  962. char buff[10];
  963. if (!isdigit(cast_uchar(*(s+1))))
  964. l_sprintf(buff, sizeof(buff), "\\%d", (int)cast_uchar(*s));
  965. else
  966. l_sprintf(buff, sizeof(buff), "\\%03d", (int)cast_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, '.', cast_uint(nb)) == NULL) { /* no dot? */
  994. char point = lua_getlocaledecpoint(); /* try locale point */
  995. char *ppoint = (char *)memchr(buff, point, cast_uint(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, cast_uint(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(cast_uchar(*s))) {
  1038. s++;
  1039. if (isdigit(cast_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(cast_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. unsigned 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(cast_uint(nb) < maxitem);
  1191. luaL_addsize(&b, cast_uint(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. unsigned 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 size_t getnum (const char **fmt, size_t df) {
  1250. if (!digit(**fmt)) /* no number? */
  1251. return df; /* return default value */
  1252. else {
  1253. size_t a = 0;
  1254. do {
  1255. a = a*10 + cast_uint(*((*fmt)++) - '0');
  1256. } while (digit(**fmt) && a <= (MAX_SIZE - 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 of integers.
  1263. */
  1264. static unsigned getnumlimit (Header *h, const char **fmt, size_t df) {
  1265. size_t sz = getnum(fmt, df);
  1266. if (l_unlikely((sz - 1u) >= MAXINTSIZE))
  1267. return cast_uint(luaL_error(h->L,
  1268. "integral size (%d) out of limits [1,%d]", sz, MAXINTSIZE));
  1269. return cast_uint(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, size_t *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, cast_sizet(-1));
  1305. if (l_unlikely(*size == cast_sizet(-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 size_t 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, const char **fmt,
  1334. size_t *psize, unsigned *ntoalign) {
  1335. KOption opt = getoption(h, fmt, psize);
  1336. size_t 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(!ispow2(align))) { /* not a power of 2? */
  1347. *ntoalign = 0; /* to avoid warnings */
  1348. luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
  1349. }
  1350. else {
  1351. /* 'szmoda' = totalsize % align */
  1352. unsigned szmoda = cast_uint(totalsize & (align - 1));
  1353. *ntoalign = cast_uint((align - szmoda) & (align - 1));
  1354. }
  1355. }
  1356. return opt;
  1357. }
  1358. /*
  1359. ** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
  1360. ** The final 'if' handles the case when 'size' is larger than
  1361. ** the size of a Lua integer, correcting the extra sign-extension
  1362. ** bytes if necessary (by default they would be zeros).
  1363. */
  1364. static void packint (luaL_Buffer *b, lua_Unsigned n,
  1365. int islittle, unsigned size, int neg) {
  1366. char *buff = luaL_prepbuffsize(b, size);
  1367. unsigned i;
  1368. buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */
  1369. for (i = 1; i < size; i++) {
  1370. n >>= NB;
  1371. buff[islittle ? i : size - 1 - i] = (char)(n & MC);
  1372. }
  1373. if (neg && size > SZINT) { /* negative number need sign extension? */
  1374. for (i = SZINT; i < size; i++) /* correct extra bytes */
  1375. buff[islittle ? i : size - 1 - i] = (char)MC;
  1376. }
  1377. luaL_addsize(b, size); /* add result to buffer */
  1378. }
  1379. /*
  1380. ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
  1381. ** given 'islittle' is different from native endianness.
  1382. */
  1383. static void copywithendian (char *dest, const char *src,
  1384. unsigned size, int islittle) {
  1385. if (islittle == nativeendian.little)
  1386. memcpy(dest, src, size);
  1387. else {
  1388. dest += size - 1;
  1389. while (size-- != 0)
  1390. *(dest--) = *(src++);
  1391. }
  1392. }
  1393. static int str_pack (lua_State *L) {
  1394. luaL_Buffer b;
  1395. Header h;
  1396. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1397. int arg = 1; /* current argument to pack */
  1398. size_t totalsize = 0; /* accumulate total size of result */
  1399. initheader(L, &h);
  1400. lua_pushnil(L); /* mark to separate arguments from string buffer */
  1401. luaL_buffinit(L, &b);
  1402. while (*fmt != '\0') {
  1403. unsigned ntoalign;
  1404. size_t size;
  1405. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1406. luaL_argcheck(L, size + ntoalign <= MAX_SIZE - totalsize, arg,
  1407. "result too long");
  1408. totalsize += ntoalign + size;
  1409. while (ntoalign-- > 0)
  1410. luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */
  1411. arg++;
  1412. switch (opt) {
  1413. case Kint: { /* signed integers */
  1414. lua_Integer n = luaL_checkinteger(L, arg);
  1415. if (size < SZINT) { /* need overflow check? */
  1416. lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
  1417. luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
  1418. }
  1419. packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), (n < 0));
  1420. break;
  1421. }
  1422. case Kuint: { /* unsigned integers */
  1423. lua_Integer n = luaL_checkinteger(L, arg);
  1424. if (size < SZINT) /* need overflow check? */
  1425. luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
  1426. arg, "unsigned overflow");
  1427. packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), 0);
  1428. break;
  1429. }
  1430. case Kfloat: { /* C float */
  1431. float f = (float)luaL_checknumber(L, arg); /* get argument */
  1432. char *buff = luaL_prepbuffsize(&b, sizeof(f));
  1433. /* move 'f' to final result, correcting endianness if needed */
  1434. copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
  1435. luaL_addsize(&b, size);
  1436. break;
  1437. }
  1438. case Knumber: { /* Lua float */
  1439. lua_Number f = luaL_checknumber(L, arg); /* get argument */
  1440. char *buff = luaL_prepbuffsize(&b, sizeof(f));
  1441. /* move 'f' to final result, correcting endianness if needed */
  1442. copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
  1443. luaL_addsize(&b, size);
  1444. break;
  1445. }
  1446. case Kdouble: { /* C double */
  1447. double f = (double)luaL_checknumber(L, arg); /* get argument */
  1448. char *buff = luaL_prepbuffsize(&b, sizeof(f));
  1449. /* move 'f' to final result, correcting endianness if needed */
  1450. copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
  1451. luaL_addsize(&b, size);
  1452. break;
  1453. }
  1454. case Kchar: { /* fixed-size string */
  1455. size_t len;
  1456. const char *s = luaL_checklstring(L, arg, &len);
  1457. luaL_argcheck(L, len <= size, arg, "string longer than given size");
  1458. luaL_addlstring(&b, s, len); /* add string */
  1459. if (len < size) { /* does it need padding? */
  1460. size_t psize = size - len; /* pad size */
  1461. char *buff = luaL_prepbuffsize(&b, psize);
  1462. memset(buff, LUAL_PACKPADBYTE, psize);
  1463. luaL_addsize(&b, psize);
  1464. }
  1465. break;
  1466. }
  1467. case Kstring: { /* strings with length count */
  1468. size_t len;
  1469. const char *s = luaL_checklstring(L, arg, &len);
  1470. luaL_argcheck(L, size >= sizeof(lua_Unsigned) ||
  1471. len < ((lua_Unsigned)1 << (size * NB)),
  1472. arg, "string length does not fit in given size");
  1473. /* pack length */
  1474. packint(&b, (lua_Unsigned)len, h.islittle, cast_uint(size), 0);
  1475. luaL_addlstring(&b, s, len);
  1476. totalsize += len;
  1477. break;
  1478. }
  1479. case Kzstr: { /* zero-terminated string */
  1480. size_t len;
  1481. const char *s = luaL_checklstring(L, arg, &len);
  1482. luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
  1483. luaL_addlstring(&b, s, len);
  1484. luaL_addchar(&b, '\0'); /* add zero at the end */
  1485. totalsize += len + 1;
  1486. break;
  1487. }
  1488. case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */
  1489. case Kpaddalign: case Knop:
  1490. arg--; /* undo increment */
  1491. break;
  1492. }
  1493. }
  1494. luaL_pushresult(&b);
  1495. return 1;
  1496. }
  1497. static int str_packsize (lua_State *L) {
  1498. Header h;
  1499. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1500. size_t totalsize = 0; /* accumulate total size of result */
  1501. initheader(L, &h);
  1502. while (*fmt != '\0') {
  1503. unsigned ntoalign;
  1504. size_t size;
  1505. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1506. luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
  1507. "variable-length format");
  1508. size += ntoalign; /* total space used by option */
  1509. luaL_argcheck(L, totalsize <= LUA_MAXINTEGER - size,
  1510. 1, "format result too large");
  1511. totalsize += size;
  1512. }
  1513. lua_pushinteger(L, cast_st2S(totalsize));
  1514. return 1;
  1515. }
  1516. /*
  1517. ** Unpack an integer with 'size' bytes and 'islittle' endianness.
  1518. ** If size is smaller than the size of a Lua integer and integer
  1519. ** is signed, must do sign extension (propagating the sign to the
  1520. ** higher bits); if size is larger than the size of a Lua integer,
  1521. ** it must check the unread bytes to see whether they do not cause an
  1522. ** overflow.
  1523. */
  1524. static lua_Integer unpackint (lua_State *L, const char *str,
  1525. int islittle, int size, int issigned) {
  1526. lua_Unsigned res = 0;
  1527. int i;
  1528. int limit = (size <= SZINT) ? size : SZINT;
  1529. for (i = limit - 1; i >= 0; i--) {
  1530. res <<= NB;
  1531. res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
  1532. }
  1533. if (size < SZINT) { /* real size smaller than lua_Integer? */
  1534. if (issigned) { /* needs sign extension? */
  1535. lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
  1536. res = ((res ^ mask) - mask); /* do sign extension */
  1537. }
  1538. }
  1539. else if (size > SZINT) { /* must check unread bytes */
  1540. int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
  1541. for (i = limit; i < size; i++) {
  1542. if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask))
  1543. luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
  1544. }
  1545. }
  1546. return (lua_Integer)res;
  1547. }
  1548. static int str_unpack (lua_State *L) {
  1549. Header h;
  1550. const char *fmt = luaL_checkstring(L, 1);
  1551. size_t ld;
  1552. const char *data = luaL_checklstring(L, 2, &ld);
  1553. size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
  1554. int n = 0; /* number of results */
  1555. luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
  1556. initheader(L, &h);
  1557. while (*fmt != '\0') {
  1558. unsigned ntoalign;
  1559. size_t size;
  1560. KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
  1561. luaL_argcheck(L, ntoalign + size <= ld - pos, 2,
  1562. "data string too short");
  1563. pos += ntoalign; /* skip alignment */
  1564. /* stack space for item + next position */
  1565. luaL_checkstack(L, 2, "too many results");
  1566. n++;
  1567. switch (opt) {
  1568. case Kint:
  1569. case Kuint: {
  1570. lua_Integer res = unpackint(L, data + pos, h.islittle,
  1571. cast_int(size), (opt == Kint));
  1572. lua_pushinteger(L, res);
  1573. break;
  1574. }
  1575. case Kfloat: {
  1576. float f;
  1577. copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
  1578. lua_pushnumber(L, (lua_Number)f);
  1579. break;
  1580. }
  1581. case Knumber: {
  1582. lua_Number f;
  1583. copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
  1584. lua_pushnumber(L, f);
  1585. break;
  1586. }
  1587. case Kdouble: {
  1588. double f;
  1589. copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
  1590. lua_pushnumber(L, (lua_Number)f);
  1591. break;
  1592. }
  1593. case Kchar: {
  1594. lua_pushlstring(L, data + pos, size);
  1595. break;
  1596. }
  1597. case Kstring: {
  1598. lua_Unsigned len = (lua_Unsigned)unpackint(L, data + pos,
  1599. h.islittle, cast_int(size), 0);
  1600. luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
  1601. lua_pushlstring(L, data + pos + size, len);
  1602. pos += len; /* skip string */
  1603. break;
  1604. }
  1605. case Kzstr: {
  1606. size_t len = strlen(data + pos);
  1607. luaL_argcheck(L, pos + len < ld, 2,
  1608. "unfinished string for format 'z'");
  1609. lua_pushlstring(L, data + pos, len);
  1610. pos += len + 1; /* skip string plus final '\0' */
  1611. break;
  1612. }
  1613. case Kpaddalign: case Kpadding: case Knop:
  1614. n--; /* undo increment */
  1615. break;
  1616. }
  1617. pos += size;
  1618. }
  1619. lua_pushinteger(L, cast_st2S(pos) + 1); /* next position */
  1620. return n + 1;
  1621. }
  1622. /* }====================================================== */
  1623. static const luaL_Reg strlib[] = {
  1624. {"byte", str_byte},
  1625. {"char", str_char},
  1626. {"dump", str_dump},
  1627. {"find", str_find},
  1628. {"format", str_format},
  1629. {"gmatch", gmatch},
  1630. {"gsub", str_gsub},
  1631. {"len", str_len},
  1632. {"lower", str_lower},
  1633. {"match", str_match},
  1634. {"rep", str_rep},
  1635. {"reverse", str_reverse},
  1636. {"sub", str_sub},
  1637. {"upper", str_upper},
  1638. {"pack", str_pack},
  1639. {"packsize", str_packsize},
  1640. {"unpack", str_unpack},
  1641. {NULL, NULL}
  1642. };
  1643. static void createmetatable (lua_State *L) {
  1644. /* table to be metatable for strings */
  1645. luaL_newlibtable(L, stringmetamethods);
  1646. luaL_setfuncs(L, stringmetamethods, 0);
  1647. lua_pushliteral(L, ""); /* dummy string */
  1648. lua_pushvalue(L, -2); /* copy table */
  1649. lua_setmetatable(L, -2); /* set table as metatable for strings */
  1650. lua_pop(L, 1); /* pop dummy string */
  1651. lua_pushvalue(L, -2); /* get string library */
  1652. lua_setfield(L, -2, "__index"); /* metatable.__index = string */
  1653. lua_pop(L, 1); /* pop metatable */
  1654. }
  1655. /*
  1656. ** Open string library
  1657. */
  1658. LUAMOD_API int luaopen_string (lua_State *L) {
  1659. luaL_newlib(L, strlib);
  1660. createmetatable(L);
  1661. return 1;
  1662. }