lstrlib.c 55 KB

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